From d44c2b27df31e356141556067287ebf560331db5 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 03:10:27 +0000 Subject: [PATCH 01/92] fix(release): retain published 1.x contracts for 1.14.0 Preserve legacy unit encoding, public model literals, TypeScript syntax, live units and customer-visible diagnostics. Keep agreed targeting contracts and version the SDK agent. Co-Authored-By: Claude Opus 5.5 --- .prettierignore | 2 + CHANGELOG.md | 58 ++++++++++ README.md | 58 +++------- src/__tests__/client.test.js | 32 ++---- src/__tests__/context.test.js | 117 ++++++++++---------- src/__tests__/release-compatibility.test.js | 54 +++++++++ src/__tests__/sdk.test.js | 5 +- src/__tests__/utils.test.js | 114 +++---------------- src/client.ts | 29 ++--- src/context.ts | 60 ++++------ src/jsonexpr/evaluator.ts | 2 +- src/matcher.ts | 2 +- src/provider.ts | 2 +- src/publisher.ts | 5 +- src/sdk.ts | 15 +-- src/utils.ts | 47 ++++---- 16 files changed, 286 insertions(+), 316 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 src/__tests__/release-compatibility.test.js diff --git a/.prettierignore b/.prettierignore index 92641fe..0d3fc0b 100644 --- a/.prettierignore +++ b/.prettierignore @@ -6,3 +6,5 @@ js lib types package-lock.json + +.claude diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..05f17b8 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,58 @@ +# Changelog + +## 1.14.0 + +### Added + +- `ABsmartly` alias for `SDK`, `readyError()`, `getSDK()`, `getOptions()`, and client + application/environment/agent getters; existing names remain supported. +- Optional `assignmentRules`, holdout models and variant names in context data. +- Semantic-version expression operators (`semver_eq/gt/gte/lt/lte`) and + `Evaluator.versionCompare`; old expression operators keep their conversion rules. +- Optional `includeSystemAttributes` publishes `sdk_name` and `sdk_version` only. +- Tag-driven npm Trusted Publishing and a manual publish dry run. + +### Changed + +- Assignment rules take precedence over traffic, audience, custom assignment and + holdout suppression (explicit overrides still win). A rule win publishes + `ruleOverride: true`; every other exposure publishes `ruleOverride: false`. + Affected: experiments configured with rules, and custom publishers/event loggers + or wire consumers comparing complete exposure shapes. The type field is optional + so existing customer-authored `Exposure` literals still compile. +- Audiences and rule conditions always see configured non-empty `application` and + `environment`; explicit user attributes win. Rule environment scope uses the + configured environment. No synthetic `app_version` is injected or published; + explicitly set values remain valid and published. Affected: running experiments + with system-name conditions, including strict/full-on audiences previously forced + to control. This is the agreed cross-SDK contract, not an opt-in. +- Holdout-covered experiments suppress ordinary experiment exposure when held out; + holdout exposures are deduplicated, and suppressed variable reads use control. + Affected: applications whose context payload links experiments to holdouts. +- The default SDK `X-Agent` is `absmartly-javascript-sdk/1.14.0` instead of + `absmartly-javascript-sdk`. Affected: export/dashboard filters matching the old + agent exactly. Explicit customer agent strings are preserved. +- `GET /context` sends SDK authentication/metadata headers as well as the existing + query parameters, like PUT. Explicit `getUnauthed()` retains its old behaviour. + `X-Application-Version` sends only 1–18 ASCII digits (trimmed), or `0` otherwise. + Affected: proxies inspecting GET headers and apps configuring invalid version + headers that previously caused collector HTTP 400 errors. +- Shared variable keys retain experiment-id priority and fall through unassigned + experiments or variants missing the key; peek queues no exposures. The existing + `variableKeys()` map-of-lists return shape is unchanged. + +### Fixed + +- Failed publishes retain queued events in order; failed finalize stays open and + can be retried. Concurrent flush/finalize waits for in-flight delivery. +- Custom publisher failures and throwing event loggers no longer strand lifecycle + promises or lose/duplicate successfully delivered events. +- Malformed variant configs are isolated rather than failing the entire context; + audience evaluation exceptions fail strict audiences closed. +- Per-request timeouts now govern the retry budget consistently; zero explicitly + disables the deadline. Affected: callers overriding timeouts or using zero, whose + configured limit was previously ignored by part of the retry path. +- Query keys are encoded and unmatched query surrogates no longer throw URIError. +- Preserve published 1.13.4 error strings, custom-field console diagnostics, + live `getUnits()` return, legacy unit hashing, old TypeScript parser support, + and existing model literals rather than shipping main-era compatibility breaks. diff --git a/README.md b/README.md index 2b47e7d..b8ad077 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ The A/B Smartly JavaScript SDK is an isomorphic library for Node.js (CommonJS an ### npm ```shell -npm install @absmartly/javascript-sdk --save +npm install @absmartly/javascript-sdk@1.14.0 --save ``` ### Import in your JavaScript application @@ -32,10 +32,10 @@ import absmartly from "@absmartly/javascript-sdk"; You can include an optimized and pre-built package directly in your HTML code through [unpkg.com](https://www.unpkg.com). -Simply add the following code to your `head` section to include the latest published version. +Simply add the following code to your `head` section to include version 1.14.0. ```html - + ``` ## Getting Started @@ -55,7 +55,7 @@ const sdk = new absmartly.SDK({ }); ``` -The `application` option can also be an object with `name` and `version` to track which version of your application is generating events. The version can be a number or a semver string: +The `application` option can also be an object with `name` and `version` to track which version of your application is generating events. The configured version can be a number or a string. The collector accepts only 1–18 ASCII digits in `X-Application-Version`; other values are sent as `0`. The getter retains the original configured value: ```javascript const sdk = new absmartly.SDK({ endpoint: 'https://sandbox.absmartly.io/v1', @@ -512,47 +512,21 @@ document.getElementById("checkout-btn").addEventListener("click", () => { }); ``` -## Migration Guide (1.13.x → 1.14.0) +## Upgrading from 1.13.4 -Version 1.14.0 contains a few breaking changes. Most applications will not need code changes, but review the items below. +1.14.0 retains the 1.x API, error strings and unit hashing (including legacy surrogate +encoding), Node 6 / npm 3 runtime floor and IE 10 browser target. The build and publish +toolchain uses modern Node; that does not raise the consumer runtime floor. -### `ready()` no longer resolves with the Error object on failure +See [CHANGELOG.md](CHANGELOG.md) for the agreed targeting and wire changes and who is +affected. `ready()` remains a wait signal (it resolves `true` even when loading fails); +use `isFailed()` and the additive `readyError()` for diagnostics. The 1.13.4 implementation +already behaved this way; earlier README migration text describing a changed return +value was incorrect. -**Before:** `ready()` resolved with the Error object on failure (e.g., `const result = await context.ready()` would give you the Error). - -**After:** `ready()` always resolves with `true`. It is a "wait for initialization" signal — you should always proceed with experiment code after it settles, even on failure. The SDK returns control variants (`0`) and default values gracefully when the API is down. Use `isFailed()` and `readyError()` to check for errors if needed. - -```javascript -await context.ready(); -if (context.isFailed()) { - console.error("Context failed:", context.readyError()); -} -const variant = context.treatment("exp_test"); // returns 0 (control) on failure -``` - -**When this might be a problem:** If your code used the return value as the Error object (e.g., `const err = await context.ready(); logError(err)`), it will now receive `true` instead. Use `context.readyError()` to access the error instead. - -### Unit IDs containing astral characters now hash to canonical UTF-8 - -**Before:** `stringToUint8Array` (used to hash unit IDs for variant assignment) encoded each UTF-16 code unit independently. A character outside the Basic Multilingual Plane (≥ U+10000, e.g. an emoji) was encoded as an invalid CESU-8 byte sequence rather than canonical UTF-8. - -**After:** Unit IDs are encoded as canonical 4-byte UTF-8, matching the A/B Smartly collector (which hashes with `UTF_8`). - -**When this might be a problem:** A unit ID that contains an astral character (emoji, rare CJK, etc.) may now be assigned a **different variant** than it was in earlier versions. **Unit IDs composed entirely of BMP characters (≤ U+FFFF) — which covers essentially all typical session IDs, UUIDs, and user IDs — are unaffected.** This only changes assignment for units whose IDs contain astral characters. - -### `audienceMismatch` cache invalidation on indeterminate audiences - -When an audience cannot be evaluated to a boolean (a malformed or non-boolean filter), the cached assignment's `audienceMismatch` flag is now left unchanged instead of being reset to `false`. This keeps a previously valid cached assignment from being needlessly invalidated. Assignment results for well-formed audiences are unchanged. - -An audience filter that throws while being evaluated is treated as a mismatch, so with `audienceStrict` the unit gets variant 0. - -### Audiences always see `application` and `environment`; the automatic `app_version` is gone - -**Before:** audience filters and assignment-rule conditions saw only the attributes you set (and, in pre-releases of 1.14.0, `application`, `environment` and `app_version` when `includeSystemAttributes` was on). The Web Console offers `application` and `environment` as attributes because the collector adds them to every event, but the SDK never had them, so a condition on either evaluated against a missing value and never matched. - -**After:** the SDK always evaluates audiences and assignment-rule conditions with `application` and `environment` set to the names configured in the SDK. An attribute you set with the same name, at any time, overrides them. Names that are not configured or empty are left out. They are not published. The SDK no longer adds `app_version` for audiences or rules (one you set yourself with `context.attribute("app_version", ...)` is still used and published like any other attribute), and `includeSystemAttributes` now only adds `sdk_name` and `sdk_version` to the publish payload; the option is still accepted. - -**This changes assignment for running experiments.** In an experiment with Audience enforced (`audienceStrict`) and an `environment` or `application` condition, a unit whose context does not set that attribute itself currently gets variant 0, even when the configured name matches the condition and even when the experiment is full-on. After upgrading, such a unit is randomised normally (or gets the full-on variant) when the configured name matches. Those units are misassigned today; this release fixes them, but their exposures will change. An attribute your context sets itself still overrides the configured name, so its matching does not change. This protection is per attribute: if an audience uses both `application` and `environment` and the context sets only one of them, the configured name for the other can still change the result. An audience or rule on `app_version` no longer matches unless you set `app_version` yourself. +All other API modernization is deferred to 2.0, preserved on `next/major`. After 2.0, +1.x receives bug fixes for 12 months. Documentation-site updates wait for all SDK 2.0 +releases; this release changes only this repository's documentation. ## About A/B Smartly diff --git a/src/__tests__/client.test.js b/src/__tests__/client.test.js index ca943c4..fa01020 100644 --- a/src/__tests__/client.test.js +++ b/src/__tests__/client.test.js @@ -4,7 +4,6 @@ import fetch from "../fetch"; // eslint-disable-next-line no-shadow import { AbortController } from "../abort"; import { AbortError, RetryError, TimeoutError } from "../errors"; //eslint-disable-line no-shadow -import { SDK_VERSION } from "../version"; jest.mock("../fetch"); @@ -837,7 +836,7 @@ describe("Client", () => { }); }); - it("request() should still send headers when auth is explicitly true (deprecated)", (done) => { + it("request() should send headers without a warning when auth is explicitly true", (done) => { fetch.mockResolvedValueOnce(responseMock(200, "OK", defaultMockResponse)); const warnSpy = jest.spyOn(console, "warn").mockImplementation(); @@ -866,9 +865,7 @@ describe("Client", () => { signal: expect.any(Object), }); - expect(warnSpy).toHaveBeenCalledWith( - "[ABsmartly] The `auth` option is deprecated. Auth headers are now sent by default. Remove `auth: true` from your request options." - ); + expect(warnSpy).not.toHaveBeenCalled(); expect(response).toEqual(defaultMockResponse); @@ -934,7 +931,7 @@ describe("Client", () => { }); }); - it("getUnauthed() should forward to get()", (done) => { + it("getUnauthed() should retain its unauthenticated 1.13 behaviour", (done) => { fetch.mockResolvedValueOnce(responseMock(200, "OK", defaultMockResponse)); const client = new Client(clientOptions); @@ -948,14 +945,7 @@ describe("Client", () => { expect(fetch).toHaveBeenCalledTimes(1); expect(fetch).toHaveBeenLastCalledWith(`${endpoint}/context?application=test_app&environment=test`, { method: "GET", - headers: { - "Content-Type": "application/json", - "X-API-Key": apiKey, - "X-Agent": "javascript-client", - "X-Environment": "test", - "X-Application": "test_app", - "X-Application-Version": 1000000, - }, + body: undefined, keepalive: true, signal: expect.any(Object), }); @@ -975,7 +965,7 @@ describe("Client", () => { .publish({ units, publishedAt, - sdkVersion: SDK_VERSION, + goals, exposures, attributes, @@ -996,7 +986,7 @@ describe("Client", () => { body: JSON.stringify({ units, publishedAt, - sdkVersion: SDK_VERSION, + goals, exposures, attributes, @@ -1019,7 +1009,7 @@ describe("Client", () => { .publish({ units, publishedAt, - sdkVersion: SDK_VERSION, + goals: [], exposures: [], }) @@ -1039,7 +1029,6 @@ describe("Client", () => { body: JSON.stringify({ units, publishedAt, - sdkVersion: SDK_VERSION, }), signal: expect.any(Object), }); @@ -1059,7 +1048,7 @@ describe("Client", () => { client .publish({ units, - sdkVersion: SDK_VERSION, + goals: [], exposures: [], }) @@ -1079,7 +1068,6 @@ describe("Client", () => { body: JSON.stringify({ units, publishedAt: publishedAt + 100, - sdkVersion: SDK_VERSION, }), signal: expect.any(Object), }); @@ -1122,7 +1110,7 @@ describe("Client", () => { }); }); - it("publish() should include sdkVersion in body", (done) => { + it("publish() should retain the 1.13 body shape even for extra input metadata", (done) => { fetch.mockResolvedValueOnce(responseMock(200, "OK", defaultMockResponse)); const client = new Client(clientOptions); @@ -1137,7 +1125,7 @@ describe("Client", () => { }) .then(() => { const body = JSON.parse(fetch.mock.calls[0][1].body); - expect(body.sdkVersion).toEqual("1.2.3"); + expect(body).not.toHaveProperty("sdkVersion"); done(); }); diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 7497958..4706d0d 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -612,12 +612,12 @@ describe("Context", () => { expect(context.isFinalized()).toEqual(false); expect(() => context.data()).toThrow(); - expect(() => context.treatment("test")).toThrow("ABsmartly Context is not yet ready."); - expect(() => context.peek("test")).toThrow("ABsmartly Context is not yet ready."); - expect(() => context.experiments()).toThrow("ABsmartly Context is not yet ready."); - expect(() => context.variableKeys()).toThrow("ABsmartly Context is not yet ready."); - expect(() => context.variableValue("a", 17)).toThrow("ABsmartly Context is not yet ready."); - expect(() => context.peekVariableValue("a", 17)).toThrow("ABsmartly Context is not yet ready."); + expect(() => context.treatment("test")).toThrow("ABSmartly Context is not yet ready."); + expect(() => context.peek("test")).toThrow("ABSmartly Context is not yet ready."); + expect(() => context.experiments()).toThrow("ABSmartly Context is not yet ready."); + expect(() => context.variableKeys()).toThrow("ABSmartly Context is not yet ready."); + expect(() => context.variableValue("a", 17)).toThrow("ABSmartly Context is not yet ready."); + expect(() => context.peekVariableValue("a", 17)).toThrow("ABSmartly Context is not yet ready."); done(); }); @@ -750,7 +750,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -865,7 +865,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -1529,7 +1529,7 @@ describe("Context", () => { const context = new Context(sdk, contextOptions, contextParams, Promise.resolve(getContextResponse)); expect(context.isReady()).toEqual(false); - expect(() => context.peek("exp_test_ab")).toThrow("ABsmartly Context is not yet ready."); + expect(() => context.peek("exp_test_ab")).toThrow("ABSmartly Context is not yet ready."); done(); }); @@ -1541,12 +1541,12 @@ describe("Context", () => { context.treatment("exp_test_ab"); context.finalize().then(() => { - expect(() => context.peek("exp_test_ab")).toThrow("ABsmartly Context is finalized."); + expect(() => context.peek("exp_test_ab")).toThrow("ABSmartly Context is finalized."); done(); }); expect(context.isFinalizing()).toEqual(true); - expect(() => context.peek("exp_test_ab")).toThrow("ABsmartly Context is finalizing."); + expect(() => context.peek("exp_test_ab")).toThrow("ABSmartly Context is finalizing."); }); }); @@ -1575,7 +1575,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -1744,7 +1744,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 0, @@ -1787,7 +1787,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + attributes: [ { name: "age", @@ -1836,7 +1836,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -1878,7 +1878,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -1941,7 +1941,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -1991,13 +1991,13 @@ describe("Context", () => { expect(context.pending()).toEqual(1); context.finalize().then(() => { - expect(() => context.treatment("exp_test_ab")).toThrow("ABsmartly Context is finalized."); + expect(() => context.treatment("exp_test_ab")).toThrow("ABSmartly Context is finalized."); done(); }); expect(context.isFinalizing()).toEqual(true); - expect(() => context.treatment("exp_test_ab")).toThrow("ABsmartly Context is finalizing."); + expect(() => context.treatment("exp_test_ab")).toThrow("ABSmartly Context is finalizing."); }); it("should re-evaluate audience expression when attributes change in strict mode", (done) => { @@ -2233,7 +2233,7 @@ describe("Context", () => { const context = new Context(sdk, contextOptions, contextParams, Promise.resolve(getContextResponse)); expect(context.isReady()).toEqual(false); - expect(() => context.treatment("exp_test_ab")).toThrow("ABsmartly Context is not yet ready."); + expect(() => context.treatment("exp_test_ab")).toThrow("ABSmartly Context is not yet ready."); done(); }); @@ -6339,7 +6339,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -6569,7 +6569,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + attributes: [ { name: "age", @@ -6618,7 +6618,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -6660,7 +6660,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -6696,13 +6696,13 @@ describe("Context", () => { expect(context.pending()).toEqual(1); context.finalize().then(() => { - expect(() => context.variableValue("button.color", 17)).toThrow("ABsmartly Context is finalized."); + expect(() => context.variableValue("button.color", 17)).toThrow("ABSmartly Context is finalized."); done(); }); expect(context.isFinalizing()).toEqual(true); - expect(() => context.variableValue("button.color", 17)).toThrow("ABsmartly Context is finalizing."); + expect(() => context.variableValue("button.color", 17)).toThrow("ABSmartly Context is finalizing."); }); }); @@ -6856,7 +6856,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + goals: [ { achievedAt: 1611141535729, @@ -7015,7 +7015,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + goals: [ { name: "goal1", @@ -7123,7 +7123,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -7247,7 +7247,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + goals: [ { name: "goal1", @@ -7301,7 +7301,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + goals: [ { achievedAt: 1611141535729, @@ -7362,7 +7362,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -7443,7 +7443,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + goals: [ { name: "goal2", @@ -7666,7 +7666,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -7718,7 +7718,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -7869,7 +7869,7 @@ describe("Context", () => { expect(context.pending()).toEqual(0); expect(context.isFinalizing()).toEqual(false); expect(context.isFinalized()).toEqual(true); - expect(consoleErrorSpy).toHaveBeenCalled(); + expect(consoleErrorSpy).not.toHaveBeenCalled(); consoleErrorSpy.mockRestore(); done(); @@ -8290,7 +8290,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -8358,7 +8358,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -8435,7 +8435,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 2, @@ -8484,7 +8484,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 3, @@ -8556,7 +8556,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -8688,28 +8688,27 @@ describe("Context", () => { expect(context.customFieldValue("exp_test_custom_fields", "false_boolean_field")).toEqual(false); }); - it("should log an error through eventLogger when JSON cannot be parsed", () => { - const eventLogger = jest.fn(); - const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, getContextResponse); + it("should console an error when JSON cannot be parsed", () => { + const errorSpy = jest.spyOn(console, "error"); + const context = new Context(sdk, contextOptions, contextParams, getContextResponse); expect(context.pending()).toEqual(0); expect(context.customFieldValue("exp_test_abc", "json_invalid")).toEqual(null); - expect(eventLogger).toHaveBeenCalledWith(context, "error", expect.any(Error)); + expect(errorSpy).toHaveBeenCalledTimes(1); + expect(errorSpy).toHaveBeenCalledWith( + "Failed to parse JSON custom field value 'json_invalid' for experiment 'exp_test_abc'" + ); }); - it("should log an error through eventLogger when a field type is invalid", () => { - const eventLogger = jest.fn(); - const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, getContextResponse); + it("should console an error when a field type is invalid", () => { + const errorSpy = jest.spyOn(console, "error"); + const context = new Context(sdk, contextOptions, contextParams, getContextResponse); expect(context.pending()).toEqual(0); expect(context.customFieldValue("exp_test_custom_fields", "invalid_type_field")).toEqual(null); - expect(eventLogger).toHaveBeenCalledWith( - context, - "error", - expect.objectContaining({ - message: - "Unknown custom field type 'invalid' for experiment 'exp_test_custom_fields' and key 'invalid_type_field' - you may need to upgrade to the latest SDK version", - }) + expect(errorSpy).toHaveBeenCalledTimes(1); + expect(errorSpy).toHaveBeenCalledWith( + "Unknown custom field type 'invalid' for experiment 'exp_test_custom_fields' and key 'invalid_type_field' - you may need to upgrade to the latest SDK version" ); }); }); @@ -9343,7 +9342,7 @@ describe("Context input handling and lifecycle regressions", () => { }); describe("error logging routed through eventLogger", () => { - it("should not call console.error directly for custom field parse errors", () => { + it("should preserve custom field console diagnostics without new error events", () => { const eventLogger = jest.fn(); const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); @@ -9377,8 +9376,10 @@ describe("Context input handling and lifecycle regressions", () => { ); context.customFieldValue("exp", "bad_json"); - expect(errorSpy).not.toHaveBeenCalled(); - expect(eventLogger).toHaveBeenCalledWith(context, "error", expect.any(Error)); + expect(errorSpy).toHaveBeenCalledWith( + "Failed to parse JSON custom field value 'bad_json' for experiment 'exp'" + ); + expect(eventLogger.mock.calls.filter(([, eventName]) => eventName === "error")).toHaveLength(0); errorSpy.mockRestore(); }); diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js new file mode 100644 index 0000000..30670c8 --- /dev/null +++ b/src/__tests__/release-compatibility.test.js @@ -0,0 +1,54 @@ +import SDK from "../sdk"; +import { SDK_VERSION } from "../version"; +import Client from "../client"; +import sdkFetch from "../fetch"; + +jest.mock("../fetch"); + +const options = { endpoint: "https://collector/v1", apiKey: "k", application: "web", environment: "prod" }; + +describe("1.13.4 source and behaviour compatibility", () => { + it("keeps the live units map and released error strings", async () => { + const sdk = new SDK(options); + const context = sdk.createContextWith({ units: { user: "one" } }, { experiments: [] }); + const units = context.getUnits(); + units.session = "two"; + expect(context.getUnit("session")).toBe("two"); + expect(context.getUnits()).toBe(units); + await context.finalize(); + expect(() => context.treatment("e")).toThrow("ABSmartly Context is finalized."); + }); + + it("accepts a released duck-typed custom client without new getters", () => { + const client = { getContext: () => Promise.resolve({ experiments: [] }), publish: () => Promise.resolve() }; + const sdk = new SDK({ ...options, client }); + const context = sdk.createContextWith({ units: { user: "one" } }, { experiments: [] }); + expect(context.isReady()).toBe(true); + expect(context.treatment("e")).toBe(0); + }); + + it.each([null, "", 1004, " 1004 ", "3.2.1", -1, "١٠٠٤", "1234567890123456789"])( + "normalizes collector application-version headers on GET and PUT: %p", + async (version) => { + sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({}) }); + const sdk = new SDK({ ...options, application: { name: "web", version } }); + await sdk.getClient().getContext(); + await sdk.getClient().publish({ units: [], hashed: true, publishedAt: 1 }); + const expected = version === 1004 ? 1004 : version === " 1004 " ? "1004" : 0; + for (const [, request] of sdkFetch.mock.calls) { + expect(request.headers["X-Application-Version"]).toBe(expected); + expect(request.headers["X-Agent"]).toBe(`absmartly-javascript-sdk/${SDK_VERSION}`); + } + expect(sdk.getClient().getApplication().version).toBe(version); + } + ); + + it("preserves explicit custom agents and the unauthenticated helper", async () => { + sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({}) }); + const client = new Client({ ...options, agent: "customer-agent" }); + await client.get({ path: "/custom" }); + expect(sdkFetch.mock.calls[0][1].headers["X-Agent"]).toBe("customer-agent"); + await client.getUnauthed({ path: "/custom", auth: true }); + expect(sdkFetch.mock.calls[1][1]).not.toHaveProperty("headers"); + }); +}); diff --git a/src/__tests__/sdk.test.js b/src/__tests__/sdk.test.js index 7a0ad73..035c6c4 100644 --- a/src/__tests__/sdk.test.js +++ b/src/__tests__/sdk.test.js @@ -1,3 +1,4 @@ +import { SDK_VERSION } from "../version"; import Client from "../client"; import SDK from "../sdk"; import Context from "../context"; @@ -40,7 +41,7 @@ describe("SDK", () => { expect(sdk.getEventLogger()).toBe(SDK.defaultEventLogger); expect(Client).toHaveBeenCalledTimes(1); expect(Client).toHaveBeenCalledWith({ - agent: "absmartly-javascript-sdk", + agent: `absmartly-javascript-sdk/${SDK_VERSION}`, }); expect(ContextDataProvider).toHaveBeenCalledTimes(1); @@ -117,7 +118,7 @@ describe("SDK", () => { Object.assign( {}, { - agent: "absmartly-javascript-sdk", + agent: `absmartly-javascript-sdk/${SDK_VERSION}`, }, options ) diff --git a/src/__tests__/utils.test.js b/src/__tests__/utils.test.js index 0331d0c..013073a 100644 --- a/src/__tests__/utils.test.js +++ b/src/__tests__/utils.test.js @@ -237,11 +237,10 @@ describe("hashUnit()", () => { done(); }); - it("should hash astral/multibyte characters correctly", (done) => { - // Characters outside the BMP are stored as UTF-16 surrogate pairs and must - // encode to 4-byte UTF-8; these canonical hashes are shared across all SDKs. - expect(hashUnit("😀")).toBe("KgLqw51xanDs83V5GFkntg"); - expect(hashUnit("😀😁")).toBe("ZJuDalvUWRJnVtkspj-2bQ"); + it("should preserve 1.13 astral/multibyte hashes", (done) => { + // 1.x keeps the released code-unit encoding to avoid reassigning existing units. + expect(hashUnit("😀")).toBe("-Z9RwqljCn9rjBPBgYvAwg"); + expect(hashUnit("😀😁")).toBe("OkTK8v8Dc9YXARX-1b6CmA"); expect(hashUnit("世界你好")).toBe("v2CJG7YcjjWncKOSCzF2GA"); expect(hashUnit("user_世界_123")).toBe("SCgk4OzXlFMvo1UMsP88fA"); @@ -316,101 +315,18 @@ describe("stringToUint8Array()", () => { done(); }); - describe("unmatched surrogates", () => { - // Unmatched surrogate code units are not valid UTF-8 code points; both TextEncoder - // and the manual fallback must emit U+FFFD (ef bf bd) for each one, matching the - // canonical UTF-8 replacement-character behavior. - const testCases = [ - ["lone high surrogate at end of string", "\uD800", Uint8Array.from([0xef, 0xbf, 0xbd])], - ["lone low surrogate", "\uDC00", Uint8Array.from([0xef, 0xbf, 0xbd])], - ["high surrogate followed by non-surrogate", "\uD800X", Uint8Array.from([0xef, 0xbf, 0xbd, 0x58])], - [ - "two consecutive lone high surrogates", - "\uD800\uD800", - Uint8Array.from([0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd]), - ], - [ - "two consecutive lone low surrogates", - "\uDC00\uDC00", - Uint8Array.from([0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd]), - ], - [ - "low surrogate followed by high surrogate (wrong order)", - "\uDC00\uD800", - Uint8Array.from([0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd]), - ], - ["lone high surrogate after ascii", "a\uD800", Uint8Array.from([0x61, 0xef, 0xbf, 0xbd])], - ["lone low surrogate before ascii", "\uDC00b", Uint8Array.from([0xef, 0xbf, 0xbd, 0x62])], + it("should preserve the 1.13 encoding for every surrogate code unit", () => { + const cases = [ + ["\uD800", [0xed, 0xa0, 0x80]], + ["\uDC00", [0xed, 0xb0, 0x80]], + ["😀", [0xed, 0xa0, 0xbd, 0xed, 0xb8, 0x80]], + ["a\uD800b", [97, 0xed, 0xa0, 0x80, 98]], ]; - - it("should emit U+FFFD for unmatched surrogates via the built-in TextEncoder", (done) => { - for (const [, input, expected] of testCases) { - const array = stringToUint8Array(input); - expect(Array.from(array)).toEqual(Array.from(expected)); - } - done(); - }); - - it("should emit U+FFFD for unmatched surrogates via the manual fallback", (done) => { - const OriginalTextEncoder = global.TextEncoder; - // eslint-disable-next-line no-global-assign - delete global.TextEncoder; - - try { - for (const [, input, expected] of testCases) { - const array = stringToUint8Array(input); - expect(Array.from(array)).toEqual(Array.from(expected)); - } - } finally { - global.TextEncoder = OriginalTextEncoder; - } - done(); - }); - - it("should copy bytes from a TextEncoder view with an oversized backing buffer", (done) => { - const OriginalTextEncoder = global.TextEncoder; - const expected = hashUnit("session_abc123"); - - // eslint-disable-next-line no-global-assign - global.TextEncoder = class { - encode(value) { - const bytes = OriginalTextEncoder - ? new OriginalTextEncoder().encode(value) - : Uint8Array.from([115, 101, 115, 115, 105, 111, 110, 95, 97, 98, 99, 49, 50, 51]); - const buffer = new ArrayBuffer(bytes.byteLength + 16); - const view = new Uint8Array(buffer, 8, bytes.byteLength); - view.set(bytes); - return view; - } - }; - - try { - const bytes = stringToUint8Array("session_abc123"); - expect(bytes.byteOffset).toBe(0); - expect(bytes.byteLength).toBe(bytes.buffer.byteLength); - expect(hashUnit("session_abc123")).toBe(expected); - } finally { - global.TextEncoder = OriginalTextEncoder; - } - - done(); - }); - - it("should produce identical hashUnit results for both code paths", (done) => { - const OriginalTextEncoder = global.TextEncoder; - - for (const [, input] of testCases) { - const nativeHash = hashUnit(input); - - // eslint-disable-next-line no-global-assign - delete global.TextEncoder; - const fallbackHash = hashUnit(input); - global.TextEncoder = OriginalTextEncoder; - - expect(fallbackHash).toBe(nativeHash); - } - done(); - }); + for (const [input, bytes] of cases) { + const encoded = stringToUint8Array(input); + expect(Array.from(encoded)).toEqual(bytes); + expect(encoded.byteLength).toBe(encoded.buffer.byteLength); + } }); }); diff --git a/src/client.ts b/src/client.ts index c0f5fe1..10f9e86 100644 --- a/src/client.ts +++ b/src/client.ts @@ -4,9 +4,9 @@ import { AbortController } from "./abort"; // eslint-disable-next-line no-shadow import { AbortError, RetryError, TimeoutError } from "./errors"; -import { type AbortSignal as ABsmartlyAbortSignal } from "./abort-controller-shim"; -import { type ContextOptions, type ContextParams } from "./context"; -import { type PublishParams } from "./publisher"; +import { AbortSignal as ABsmartlyAbortSignal } from "./abort-controller-shim"; +import { ContextOptions, ContextParams } from "./context"; +import { PublishParams } from "./publisher"; import { toWellFormedString } from "./utils"; export type FetchResponse = { @@ -45,6 +45,16 @@ export type ClientOptions = { keepalive?: boolean; }; +// The collector reads X-Application-Version as a 64-bit integer and rejects anything else with a 400, +// so only a whole number of 1 to 18 digits is sent as-is; anything else (e.g. "1.2.3") is sent as 0. +function applicationVersionHeader(version: number | string): number | string { + if (typeof version === "number") { + return /^[0-9]{1,18}$/.test(String(version)) ? version : 0; + } + const trimmed = typeof version === "string" ? version.trim() : ""; + return /^[0-9]{1,18}$/.test(trimmed) ? trimmed : 0; +} + type NormalizedClientOptions = Omit, "application"> & { application: ApplicationObject; }; @@ -123,7 +133,6 @@ export default class Client { units: params.units, hashed: params.hashed, publishedAt: params.publishedAt || Date.now(), - sdkVersion: params.sdkVersion, }; if (Array.isArray(params.goals) && params.goals.length > 0) { @@ -174,12 +183,6 @@ export default class Client { keepalive: this._opts.keepalive, }; - if (options.auth === true) { - console.warn( - "[ABsmartly] The `auth` option is deprecated. Auth headers are now sent by default. Remove `auth: true` from your request options." - ); - } - if (options.auth !== false) { opts.headers = { "Content-Type": "application/json", @@ -187,7 +190,7 @@ export default class Client { "X-Agent": this._opts.agent, "X-Environment": this._opts.environment, "X-Application": this._opts.application.name, - "X-Application-Version": this._opts.application.version, + "X-Application-Version": applicationVersionHeader(this._opts.application.version), }; } @@ -330,8 +333,8 @@ export default class Client { }); } - /** @deprecated Use get() instead. */ + /** GET without authentication, retained for 1.x consumers. Use get() for SDK headers. */ getUnauthed(options: ClientRequestOptions) { - return this.get(options); + return this.get({ ...options, auth: false }); } } diff --git a/src/context.ts b/src/context.ts index 09ccce7..186c700 100644 --- a/src/context.ts +++ b/src/context.ts @@ -2,10 +2,10 @@ import { arrayEqualsShallow, hashUnit, isObject, isPromise } from "./utils"; import { VariantAssigner } from "./assigner"; import { AudienceMatcher } from "./matcher"; import { insertUniqueSorted } from "./algorithm"; -import SDK, { type EventLogger, type EventName } from "./sdk"; -import { ContextPublisher, type PublishParams } from "./publisher"; +import SDK, { EventLogger, EventName } from "./sdk"; +import { ContextPublisher, PublishParams } from "./publisher"; import { ContextDataProvider } from "./provider"; -import { type ClientRequestOptions } from "./client"; +import { ClientRequestOptions } from "./client"; import { SDK_VERSION } from "./version"; type JSONPrimitive = string | number | boolean | null; @@ -119,7 +119,7 @@ export type Exposure = { fullOn: boolean; custom: boolean; audienceMismatch: boolean; - ruleOverride: boolean; + ruleOverride?: boolean; }; export type Attribute = { @@ -275,7 +275,7 @@ export default class Context { return this._failedError; } - ready() { + ready(): Promise { if (this.isReady()) { return Promise.resolve(true); } @@ -379,8 +379,8 @@ export default class Context { } } - getUnits() { - return { ...this._units }; + getUnits(): Units { + return this._units; } units(units: Record) { @@ -389,7 +389,8 @@ export default class Context { } } - getAttribute(attrName: string) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + getAttribute(attrName: string): any { for (let i = this._attrs.length - 1; i >= 0; i--) { if (this._attrs[i].name === attrName) return this._attrs[i].value; } @@ -508,9 +509,9 @@ export default class Context { private _checkNotFinalized() { if (this.isFinalized()) { - throw new Error("ABsmartly Context is finalized."); + throw new Error("ABSmartly Context is finalized."); } else if (this.isFinalizing()) { - throw new Error("ABsmartly Context is finalizing."); + throw new Error("ABSmartly Context is finalizing."); } } @@ -542,7 +543,7 @@ export default class Context { private _checkReady(expectNotFinalized?: boolean) { if (!this.isReady()) { - throw new Error("ABsmartly Context is not yet ready."); + throw new Error("ABSmartly Context is not yet ready."); } if (expectNotFinalized) { @@ -555,6 +556,10 @@ export default class Context { private _getSystemAttributes(): Record { const client = this._sdk.getClient(); const systemAttrs: Record = {}; + // A custom `client` passed to the SDK may predate these getters. + if (typeof client?.getApplication !== "function" || typeof client.getEnvironment !== "function") { + return systemAttrs; + } const applicationName = client.getApplication()?.name; if (typeof applicationName === "string" && applicationName.length > 0) { systemAttrs["application"] = applicationName; @@ -970,22 +975,14 @@ export default class Context { if (field.value === "") return ""; return JSON.parse(field.value); } catch (e) { - this._logError( - new Error( - `Failed to parse JSON custom field value '${key}' for experiment '${experimentName}': ${ - (e as Error).message - }` - ) - ); + console.error(`Failed to parse JSON custom field value '${key}' for experiment '${experimentName}'`); return null; } case "boolean": return field.value === "true"; default: - this._logError( - new Error( - `Unknown custom field type '${field.type}' for experiment '${experimentName}' and key '${key}' - you may need to upgrade to the latest SDK version` - ) + console.error( + `Unknown custom field type '${field.type}' for experiment '${experimentName}' and key '${key}' - you may need to upgrade to the latest SDK version` ); return null; } @@ -1116,7 +1113,7 @@ export default class Context { } }; - addSystemAttribute("sdk_name", client.getAgent()); + addSystemAttribute("sdk_name", typeof client?.getAgent === "function" ? client.getAgent() : undefined); addSystemAttribute("sdk_version", SDK_VERSION); } @@ -1164,18 +1161,7 @@ export default class Context { } if (this._failed) { - // _logError() isolates a throwing custom eventLogger internally, so it - // (and the internal `callback` below, which only calls resolve/reject - // and _logEvent()/_logError()) can't propagate an observer exception - // out of _flush() — that would skip clearing - // `_pending`/`_exposures`/`_goals` and, via `_finalize`'s callback never - // running, permanently strand `_finalizing` with no settlement. - this._logError( - new Error( - `Discarding ${this._exposures.length} exposures and ${this._goals.length} goals because context failed to initialize` - ) - ); - + // Events of a context that failed to initialize are dropped silently, as in 1.13. this._pending = 0; this._exposures = []; this._goals = []; @@ -1195,7 +1181,6 @@ export default class Context { uid: this._unitHash(entry[0]), })), hashed: true, - sdkVersion: SDK_VERSION, }; if (this._goals.length > 0) { @@ -1459,7 +1444,8 @@ export default class Context { private _init(data: ContextData, assignments: Record = {}) { this._data = data; - this._environmentName = this._sdk.getClient().getEnvironment() ?? null; + const client = this._sdk.getClient(); + this._environmentName = typeof client?.getEnvironment === "function" ? client.getEnvironment() ?? null : null; const index: Record = {}; const indexVariables: Record = {}; diff --git a/src/jsonexpr/evaluator.ts b/src/jsonexpr/evaluator.ts index 5c52ff0..dc8d743 100644 --- a/src/jsonexpr/evaluator.ts +++ b/src/jsonexpr/evaluator.ts @@ -3,7 +3,7 @@ import { isEqualsDeep, isObject } from "../utils"; function parseSemver(version: string) { let v = version; - if (v.startsWith("v") || v.startsWith("V")) { + if (v.charAt(0) === "v" || v.charAt(0) === "V") { v = v.substring(1); } diff --git a/src/matcher.ts b/src/matcher.ts index d54c3c5..82bff09 100644 --- a/src/matcher.ts +++ b/src/matcher.ts @@ -86,7 +86,7 @@ export class AudienceMatcher { if (!Array.isArray(rule.environments)) continue; if (rule.environments.length > 0) { - if (environmentName == null || !rule.environments.includes(environmentName)) { + if (environmentName == null || rule.environments.indexOf(environmentName) === -1) { continue; } } diff --git a/src/provider.ts b/src/provider.ts index 85c14c8..30dac20 100644 --- a/src/provider.ts +++ b/src/provider.ts @@ -1,5 +1,5 @@ import SDK from "./sdk"; -import { type ClientRequestOptions } from "./client"; +import { ClientRequestOptions } from "./client"; export class ContextDataProvider { getContextData(sdk: SDK, requestOptions?: Partial) { diff --git a/src/publisher.ts b/src/publisher.ts index 8d6f890..8e0cc64 100644 --- a/src/publisher.ts +++ b/src/publisher.ts @@ -1,12 +1,11 @@ -import Context, { type Attribute, type Exposure, type Goal, type Unit } from "./context"; +import Context, { Attribute, Exposure, Goal, Unit } from "./context"; import SDK from "./sdk"; -import { type ClientRequestOptions } from "./client"; +import { ClientRequestOptions } from "./client"; export type PublishParams = { units: Unit[]; publishedAt: number; hashed: boolean; - sdkVersion: string; attributes?: Attribute[]; goals?: Goal[]; exposures?: Exposure[]; diff --git a/src/sdk.ts b/src/sdk.ts index 33f7120..cae2a65 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -1,14 +1,9 @@ -import Client, { type ClientOptions, type ClientRequestOptions } from "./client"; -import Context, { - type ContextData, - type ContextOptions, - type ContextParams, - type Exposure, - type Goal, -} from "./context"; -import { ContextPublisher, type PublishParams } from "./publisher"; +import Client, { ClientOptions, ClientRequestOptions } from "./client"; +import Context, { ContextData, ContextOptions, ContextParams, Exposure, Goal } from "./context"; +import { ContextPublisher, PublishParams } from "./publisher"; import { ContextDataProvider } from "./provider"; import { isLongLivedApp } from "./utils"; +import { SDK_VERSION } from "./version"; export type EventLoggerData = Error | Exposure | Goal | ContextData | PublishParams; @@ -60,7 +55,7 @@ export default class SDK { "timeout", ]; const extracted: Partial = { - agent: "absmartly-javascript-sdk", + agent: `absmartly-javascript-sdk/${SDK_VERSION}`, }; for (const key of clientOptionKeys) { diff --git a/src/utils.ts b/src/utils.ts index 2c6dd11..5b7be79 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -3,8 +3,11 @@ import { md5 } from "./md5"; export const getApplicationName = (app: string | { name: string; version: number | string }): string => typeof app !== "string" ? app.name : app; -export const getApplicationVersion = (app: string | { name: string; version: number | string }): number | string => - typeof app !== "string" ? app.version : 0; +export function getApplicationVersion(app: string | { name: string; version: number }): number; +export function getApplicationVersion(app: string | { name: string; version: number | string }): number | string; +export function getApplicationVersion(app: string | { name: string; version: number | string }): number | string { + return typeof app !== "string" ? app.version : 0; +} function isBrowser() { return typeof window !== "undefined" && typeof window.document !== "undefined"; @@ -175,38 +178,28 @@ export function toWellFormedString(value: string): string { return result; } +// Encodes each UTF-16 code unit on its own, exactly as 1.13 did, so unit hashes (and so variant +// assignment) don't move in a 1.x release. A character outside the BMP is therefore encoded as two +// 3-byte surrogate sequences, not 4-byte UTF-8; the canonical encoding is planned for 2.0. export function stringToUint8Array(value: string) { - if (typeof TextEncoder !== "undefined") { - return new Uint8Array(new TextEncoder().encode(value)); - } + const n = value.length; + const array = new Array(value.length); - const utf8: number[] = []; - for (let i = 0; i < value.length; i++) { - let c = value.charCodeAt(i); - if (c >= 0xd800 && c <= 0xdbff) { - const next = i + 1 < value.length ? value.charCodeAt(i + 1) : 0; - if (next >= 0xdc00 && next <= 0xdfff) { - c = ((c - 0xd800) << 10) + (next - 0xdc00) + 0x10000; - i++; - } else { - // Unmatched high surrogate: not a valid UTF-8 code point, encode as U+FFFD. - c = 0xfffd; - } - } else if (c >= 0xdc00 && c <= 0xdfff) { - // Unmatched low surrogate: not a valid UTF-8 code point, encode as U+FFFD. - c = 0xfffd; - } + let k = 0; + for (let i = 0; i < n; ++i) { + const c = value.charCodeAt(i); if (c < 0x80) { - utf8.push(c); + array[k++] = c; } else if (c < 0x800) { - utf8.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f)); - } else if (c < 0x10000) { - utf8.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f)); + array[k++] = (c >> 6) | 192; + array[k++] = (c & 63) | 128; } else { - utf8.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f)); + array[k++] = (c >> 12) | 224; + array[k++] = ((c >> 6) & 63) | 128; + array[k++] = (c & 63) | 128; } } - return new Uint8Array(utf8); + return Uint8Array.from(array); } const Base64URLNoPaddingChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; From 96b52ad1823359934270972067b18732a8ebdb86 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 03:30:29 +0000 Subject: [PATCH 02/92] ci(release): prepare trusted npm publication and compatibility gates Pin the merged cross-SDK JavaScript lane and document every released-to-main difference. Manual publication runs are dry runs only. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/cross-sdk.yml | 55 ++++++ .github/workflows/publish.yml | 73 +++++++ release/1.14.0-compatibility.md | 87 +++++++++ release/PUBLISHING.md | 31 +++ scripts/__tests__/check-release.test.js | 23 +++ scripts/check-release.js | 72 +++++++ scripts/compatibility/consumer.ts | 164 ++++++++++++++++ scripts/compatibility/run.js | 189 ++++++++++++++++++ scripts/compatibility/runtime.js | 246 ++++++++++++++++++++++++ 9 files changed, 940 insertions(+) create mode 100644 .github/workflows/cross-sdk.yml create mode 100644 .github/workflows/publish.yml create mode 100644 release/1.14.0-compatibility.md create mode 100644 release/PUBLISHING.md create mode 100644 scripts/__tests__/check-release.test.js create mode 100644 scripts/check-release.js create mode 100644 scripts/compatibility/consumer.ts create mode 100644 scripts/compatibility/run.js create mode 100644 scripts/compatibility/runtime.js diff --git a/.github/workflows/cross-sdk.yml b/.github/workflows/cross-sdk.yml new file mode 100644 index 0000000..ad2eeac --- /dev/null +++ b/.github/workflows/cross-sdk.yml @@ -0,0 +1,55 @@ +name: Cross-SDK JavaScript + +on: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + javascript: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v6 + with: + path: javascript-sdk + - uses: actions/checkout@v6 + with: + repository: absmartly/cross-sdk-tests + ref: ada8952293a8d4ebf81f8de038f4e7a406d98870 + path: cross-sdk-tests + - uses: actions/setup-node@v6 + with: + node-version: '24' + cache: npm + cache-dependency-path: javascript-sdk/package-lock.json + - uses: actions/setup-python@v6 + with: + python-version: '3.11' + - name: Build SDK and install reference wrapper + run: | + cd javascript-sdk + npm ci --ignore-scripts + npm run build + cd ../cross-sdk-tests/javascript-wrapper + npm install --ignore-scripts + - name: Run pinned JavaScript lane + working-directory: cross-sdk-tests + env: + SDK_URLS_OVERRIDE: javascript=http://127.0.0.1:3000 + run: | + set -euo pipefail + pip install -r orchestrator/requirements.txt + node javascript-wrapper/server.js > wrapper.log 2>&1 & + wrapper=$! + trap 'kill "$wrapper" 2>/dev/null || true' EXIT + python -u orchestrator/test_runner.py --sdk javascript --report report.json + - uses: actions/upload-artifact@v6 + if: always() + with: + name: cross-sdk-javascript + path: | + cross-sdk-tests/report.json + cross-sdk-tests/wrapper.log diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..1f0193b --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,73 @@ +name: Publish to npm + +on: + push: + tags: + - 'v*' + workflow_dispatch: + inputs: + use_npm_token: + description: 'Opt in to NPM_TOKEN authentication for the manual dry run only' + type: boolean + default: false + +permissions: + contents: read + id-token: write + +jobs: + publish: + runs-on: ubuntu-latest + environment: npm + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: '22' + registry-url: 'https://registry.npmjs.org' + cache: npm + + - name: Install a trusted-publishing-compatible npm + run: npm install --global npm@11.6.2 + + - name: Install dependencies + run: npm ci --ignore-scripts + + - name: Validate version and select distribution tag + id: release + run: node scripts/check-release.js + + - name: Build and test + run: npm run build + + - name: Inspect package + run: npm pack --dry-run --ignore-scripts + + # Manual runs are always dry runs. NPM_TOKEN is an opt-in fallback for + # testing token authentication, never a replacement for tag-triggered OIDC. + - name: Dry-run publish with OIDC + if: github.event_name == 'workflow_dispatch' && !inputs.use_npm_token + run: npm publish --dry-run --ignore-scripts --provenance --access public --tag "$DIST_TAG" + env: + DIST_TAG: ${{ steps.release.outputs.dist_tag }} + + - name: Dry-run publish with token fallback + if: github.event_name == 'workflow_dispatch' && inputs.use_npm_token + run: | + if [ -z "$NODE_AUTH_TOKEN" ]; then + echo 'NPM_TOKEN must be configured for the token fallback.' >&2 + exit 1 + fi + npm publish --dry-run --ignore-scripts --provenance --access public --tag "$DIST_TAG" + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + DIST_TAG: ${{ steps.release.outputs.dist_tag }} + + - name: Publish with trusted publishing + if: github.event_name == 'push' + run: npm publish --ignore-scripts --provenance --access public --tag "$DIST_TAG" + env: + DIST_TAG: ${{ steps.release.outputs.dist_tag }} diff --git a/release/1.14.0-compatibility.md b/release/1.14.0-compatibility.md new file mode 100644 index 0000000..1de9d8e --- /dev/null +++ b/release/1.14.0-compatibility.md @@ -0,0 +1,87 @@ +# 1.14.0 compatibility evidence and classification + +Baseline: npm `@absmartly/javascript-sdk@1.13.4`, downloaded with `npm pack`. +There is no 1.13.4 git tag (tags stop at 1.11.2). Source commit +`47390aecde99b76adb610adb30fcdb13121c6459` produces byte-identical `.d.ts` +and CJS files, except the registry artifact also has an empty stale `lib/types.js`. +Unreleased main and preserved `origin/next/major` both initially point to +`311cfca6fbefafb23ea26684ec64a72d4509a8a8`; no preservation branch was recreated. +No tag or package is published by this PR. + +## Released → unreleased main → release candidate + +Classes: **a** additive; **b** agreed cross-SDK contract; **c** genuine bug fix; +**d** unrelated compatibility/behaviour change (restore the published contract). +This inventories public source/runtime differences, not just this PR's delta. + +| Change since published 1.13.4 | Class | Action for 1.14.0 | +| --- | --- | --- | +| `ABsmartly` alias in CJS/ES/browser exports | a | Keep alongside `SDK`; no old entry point removed. | +| `Client.getApplication/getEnvironment/getAgent/get`, `ApplicationObject` | a | Keep; string application still accepted. | +| `Context.getSDK/getOptions/readyError` | a | Keep. | +| Optional experiment assignment rules, variant name, holdout IDs; new holdout model types | a/b | Keep optional; no new required customer payload fields. | +| `AudienceMatcher.parseRules/evaluateRules/evaluateParsedRules`, `RuleAction` | a/b | Keep assignment/split rules with strict types, environment scoping, malformed-rule isolation, override precedence and missing-unit pinning. | +| `semver_*` operators, `Evaluator.versionCompare` | a/b | Keep; old `stringConvert`, `eq`, `in`, match behaviour remains unchanged. | +| `includeSystemAttributes` option | a/b | Keep opt-in publishing of SDK name/version; never synthetic app/environment/app_version publishing. | +| Synthetic application/environment in evaluation, user values win | b | Keep and document affected targeting under Changed; empty names absent, no synthetic app_version. | +| Assignment rules override audience/traffic/full-on/custom/holdouts | b | Keep and document affected experiments under Changed. | +| Required `Exposure.ruleOverride` source field on main | d | Make optional for old model literals; runtime always emits true/false (b). | +| Holdout suppression, control variable fallback and holdout exposures | b | Keep; document payload-linked experiments under Changed. | +| Shared variable resolution/id ordering/map-of-lists | b | Keep; released return shape unchanged. | +| GET SDK auth/metadata headers | b | Keep; preserve query parameters. | +| `getUnauthed()` silently became authenticated | d | Restore explicit unauthenticated GET; additive `get()` sends headers. | +| Versioned SDK X-Agent | b | Add from generated package version; custom agent untouched. Direct `Client` default remains `javascript-client`. | +| String application version accepted; utility return widened | a/d | Keep strings; overload `getApplicationVersion` so old numeric callers still receive `number` statically. | +| Invalid/dotted application versions sent to collector Long header | c/b | Normalize GET and PUT to trimmed 1–18 ASCII digits or zero; retain full configured getter. | +| Every publish adds `sdkVersion`, required `PublishParams.sdkVersion` | d | Restore 1.13 body/type; collector `PublishRequest` ignores this unknown field. SDK version remains in X-Agent and opt-in attributes. | +| New normal-path auth deprecation warning | d | Remove; explicit auth still accepted without new stderr output. | +| Error brand casing `ABSmartly` → `ABsmartly` | d | Restore byte-identical 1.13 not-ready/finalizing/finalized messages. | +| Custom-field console diagnostics changed to logger error events and JSON parser suffix | d | Restore released console sink/messages, null return and no new error events. | +| Failed-context flush adds discard error event | d | Restore silent discard after initial load error; preserve settlement/queue cleanup. | +| `getUnits()` changes live map to defensive copy | d | Restore live map and original `Units` return type. | +| `getAttribute()` return changes from incorrect `undefined` declaration to `unknown` | c/d | Use `any` for compatibility with both strict and non-strict existing consumers; actual last-value behaviour unchanged. | +| `ready(): Promise` narrows to boolean and README claims old errors | d | Restore declared Promise; published runtime already resolves true even on failure. Correct README, do not invent migration. | +| `finalize()` inferred `true \| Promise` narrows to `Promise` | c | Keep actual Promise-only result; published implementation never returned true. | +| Canonical UTF-8 for astral/unpaired surrogate UIDs changes hashes/assignment | d | Restore legacy UTF-16-code-unit encoding for all 1.x hashes; canonical change preserved on next/major for 2.0. | +| Type-only inline imports raise declaration parser floor to TS4.5 | d | Restore old import syntax; TS3.9 consumer compile checks it. | +| New required getters on duck-typed custom clients | d | Guard getters so existing custom clients don't crash context installation/evaluation. | +| Abort shim reason/onabort/optional abort reason and idempotence | a/c | Keep native-standard cancellation bug fixes; no required method argument. | +| Fetch global detection and clear no-fetch error | c | Keep fallback selection fix (old no-global environment was unusable). | +| Query key escaping and malformed-surrogate normalization | c | Keep encoding fixes; ordinary URL values unchanged. | +| Per-request timeout/retry budget, zero deadline semantics | c | Keep documented override bug fix; defaults unchanged. | +| Failed publisher loses events, synchronous failures and concurrent finalize races | c | Keep ordered restore/retry and promise settlement fixes. | +| Throwing event logger corrupts init/publish/finalize | c | Isolate observer exceptions; don't resend already-delivered batch. | +| Malformed/non-object variant config crashes or indexes invalid keys | c | Isolate invalid config; valid objects unchanged. | +| Audience evaluation exception fails open; indeterminate cache needless rebuild | c | Fail strict audiences closed, keep cached mismatch for indeterminate result. | +| Unit hash caches missing unit forever | c | Don't memoize missing hash; rule/holdout late-unit handling retained. | +| New @babel/runtime production dependency and helper deduplication | a | Private build helper dependency, no exposed dependency types or major bump to existing dependencies; Node6 remains supported. | +| Node24 development tooling, husky/lint-staged, generate-version, build/prepare hooks | a | Build-only; package engines remain Node>=6/npm>=3, Babel CJS Node6 and IE10 browser targets unchanged. | +| Babel relative runtime paths, delete stale generated output, browser/CJS export packaging | c | Keep portable package output. | +| README restructuring/refreshPeriod correction | c | Keep; pin install/browser examples to 1.14.0 and replace misleading Breaking migration. | + +## Measurements + +- Released source suite on release: **263 passed / 29 suites**. +- Released suite on unreleased main: **234 passed, 29 failed / 29 suites**. + Failures: GET headers, ruleOverride/sdKVersion exact payload assertions, and two + custom-field logging contract assertions (the async assertion failures also time out). +- Released suite on candidate before normalization: **238 passed, 25 failed**; + only documented new GET headers, versioned SDK agent and ruleOverride:false differ. + Custom-field logging expectations pass after restoring the released contract. +- Candidate full build at first milestone: **547 passed / 38 suites**, formatting, + ESLint, TypeScript, ES/CJS and both browser bundles pass. +- Cross-SDK snapshot `ada8952293a8d4ebf81f8de038f4e7a406d98870` (merged main): + **277 tested and passed / 28 reviewed capability skips of 305**, no failures. + Skips: 320/321 (snapshot declares unversioned JS agent), 323 (blank application), + 400–420 and 422–425 (unimplemented switchbacks). No wrapper was modified or + observations filtered. Versioned agent GET/PUT is separately tested in this repo. +- External type consumer against artifact and candidate: TS3.9/4.4/4.9 probes. + Main fails TS3.9/4.4 parsing; main on TS4.9 rejects released Exposure and + PublishParams literals and non-strict getAttribute usage. Restored candidate + compiles the released non-strict consumer under TS3.9. +- Actual npm 11.6.2 dry run proves `--tag v1` is rejected as a semver range; + use `v1-lts` for a maintained v1 when npm latest becomes v2+. No publication. + +Further exact-head independent evidence is posted per push in the PR, including +mutation measurements and verification limits. Release preparation alone does not +claim all historical malformed input is supported or all SDK lanes are implemented. diff --git a/release/PUBLISHING.md b/release/PUBLISHING.md new file mode 100644 index 0000000..d716c62 --- /dev/null +++ b/release/PUBLISHING.md @@ -0,0 +1,31 @@ +# Publishing 1.14.0 (owner action only) + +This PR does not create tags or publish. Once reviewed/merged, the owner may create +`v1.14.0` at the chosen release commit. The tag must equal `v` plus `package.json` +version; package-lock and the generated SDK agent version must agree. + +`publish.yml` uses GitHub's `npm` environment and OIDC Trusted Publishing. The npm +trusted publisher must match **absmartly/javascript-sdk**, **publish.yml**, +environment **npm** (already configured by the owner). No npm token is required +for the normal tag run. Environment protection may require owner approval. + +The workflow installs Node 22 and npm 11.6.2, installs with scripts disabled, checks +the registry latest major and exact tag, runs the full build/tests, inspects the +package, and publishes with provenance/public access. npm rejects an already +published version; it is never overwritten. A failed latest lookup fails closed. + +`workflow_dispatch` is **always a dry run**. Its optional `use_npm_token` input +uses `secrets.NPM_TOKEN` as `NODE_AUTH_TOKEN` for a fallback authentication test +only. If opted in, the owner must supply that secret; it is not needed for OIDC. +A manual dry run does not prove npm will accept OIDC on a real tag: the owner must +retain the npm publisher configuration and approve any environment protections. + +When this package's major is lower than `npm latest`, the workflow uses `v1-lts` +(or `v-lts`), leaving latest alone. **Owner deviation to approve:** the +requested `--tag v1` is impossible: npm 11.6.2 rejects it with `Tag name must not +be a valid SemVer range: v1`. `v1-lts` passes the same dry run. For 1.14.0 today, +latest is 1.13.4, so the selected tag is `latest`. + +The previous major receives bug fixes for 12 months after 2.0. All other breaking +API modernization starts from the already-preserved `next/major`; docs-site work +waits for all SDKs' next-major releases. diff --git a/scripts/__tests__/check-release.test.js b/scripts/__tests__/check-release.test.js new file mode 100644 index 0000000..f98cb7f --- /dev/null +++ b/scripts/__tests__/check-release.test.js @@ -0,0 +1,23 @@ +/* eslint-disable @typescript-eslint/no-var-requires, no-shadow */ +/* global BigInt */ +const { majorOf, releaseTag } = require("../check-release"); + +test("uses a non-semver lts tag for older major releases", () => { + expect(releaseTag("1.14.0", "2.0.0", "v1.14.0")).toBe("v1-lts"); +}); + +test("uses latest for equal or newer majors", () => { + expect(releaseTag("1.14.0", "1.13.0", "v1.14.0")).toBe("latest"); + expect(releaseTag("2.0.0", "1.14.0", "v2.0.0")).toBe("latest"); +}); + +test("rejects mismatched tags and malformed registry versions", () => { + expect(() => releaseTag("1.14.0", "2.0.0", "v1.13.0")).toThrow(); + for (const value of ["", "2", "02.0.0", "2.0.0-01", null, {}, "2.0.0\n"]) { + expect(() => releaseTag("1.14.0", value, "v1.14.0")).toThrow(); + } +}); + +test("accepts valid prerelease and build metadata", () => { + expect(majorOf("2.0.0-rc.1+build.5")).toBe(2n); +}); diff --git a/scripts/check-release.js b/scripts/check-release.js new file mode 100644 index 0000000..567cb8f --- /dev/null +++ b/scripts/check-release.js @@ -0,0 +1,72 @@ +/* eslint-disable @typescript-eslint/no-var-requires, no-shadow */ +/* global BigInt */ +const { execFileSync } = require("child_process"); +const { appendFileSync } = require("fs"); +const { name, version } = require("../package.json"); + +// npm distribution tags cannot be valid semver ranges, so use v1-lts rather +// than v1 for older majors. Reject malformed versions instead of guessing. +const VERSION = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/; + +function majorOf(value) { + if (typeof value !== "string" || !VERSION.test(value) || /[\r\n]/.test(value)) { + throw new Error("Invalid package version"); + } + return BigInt(value.split(".")[0]); +} + +function releaseTag(packageVersion, latestVersion, gitTag) { + const major = majorOf(packageVersion); + const latestMajor = majorOf(latestVersion); + if (gitTag !== `v${packageVersion}`) { + throw new Error("Git tag must match v"); + } + return major < latestMajor ? `v${major}-lts` : "latest"; +} + +function main() { + const event = process.env.GITHUB_EVENT_NAME; + if (event !== "push" && event !== "workflow_dispatch") { + throw new Error("Unsupported workflow event"); + } + const gitTag = event === "push" ? process.env.GITHUB_REF_NAME : `v${version}`; + // Check the tag before making a registry request. + majorOf(version); + if (gitTag !== `v${version}`) { + throw new Error("Git tag must match v"); + } + let latestVersion; + try { + latestVersion = JSON.parse( + execFileSync( + "npm", + ["view", `${name}@latest`, "version", "--json", "--registry=https://registry.npmjs.org/"], + { + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 30000, + } + ) + ); + } catch (_) { + throw new Error("Could not retrieve the latest version from the npm registry"); + } + const distTag = releaseTag(version, latestVersion, gitTag); + if (!process.env.GITHUB_OUTPUT) { + throw new Error("GITHUB_OUTPUT is required"); + } + appendFileSync(process.env.GITHUB_OUTPUT, `dist_tag=${distTag}\n`); + console.log(`Validated ${gitTag}; npm distribution tag: ${distTag}`); +} + +if (require.main === module) { + try { + main(); + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } +} + +module.exports = { majorOf, releaseTag }; diff --git a/scripts/compatibility/consumer.ts b/scripts/compatibility/consumer.ts new file mode 100644 index 0000000..2bbaf20 --- /dev/null +++ b/scripts/compatibility/consumer.ts @@ -0,0 +1,164 @@ +/* eslint-disable no-shadow, no-void, @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any */ +import absmartly, { + SDK, + Context, + ContextDataProvider, + ContextPublisher, + mergeConfig, + AbortController, +} from "@absmartly/javascript-sdk"; +import { ClientRequestOptions, ClientOptions } from "@absmartly/javascript-sdk/types/client"; +import { + ContextData, + ContextOptions, + ContextParams, + ExperimentData, + Experiment, + Exposure, + Attribute, + Goal, + Unit, + Units, +} from "@absmartly/javascript-sdk/types/context"; +import { EventLogger, EventName, EventLoggerData, SDKOptions } from "@absmartly/javascript-sdk/types/sdk"; +import { PublishParams } from "@absmartly/javascript-sdk/types/publisher"; + +const experiment: ExperimentData = { + id: 1, + name: "example", + unitType: "session", + iteration: 1, + fullOnVariant: 0, + trafficSplit: [1, 1], + trafficSeedHi: 1, + trafficSeedLo: 2, + audience: "", + audienceStrict: false, + split: [1, 1], + seedHi: 3, + seedLo: 4, + variants: [{ config: null }, { config: "{}" }], + variables: {}, + variant: 0, + overridden: false, + assigned: false, + exposed: false, + eligible: true, + fullOn: false, + custom: false, + audienceMismatch: false, + customFieldValues: null, +}; +const wrapped: Experiment = { data: experiment, variables: [{}, {}] }; +const exposure: Exposure = { + id: 1, + name: "example", + exposedAt: 0, + unit: "id", + variant: 1, + assigned: true, + eligible: true, + overridden: false, + fullOn: false, + custom: false, + audienceMismatch: false, +}; +const unit: Unit = { type: "session", uid: "id" }; +const attribute: Attribute = { name: "country", value: "US", setAt: 0 }; +const goal: Goal = { name: "purchase", properties: { amount: 5 }, achievedAt: 0 }; +const units: Units = { session: "id", user: 1 }; +const payload: PublishParams = { + units: [unit], + publishedAt: 0, + hashed: false, + exposures: [exposure], + attributes: [attribute], + goals: [goal], +}; +const data: ContextData = { experiments: [experiment] }; +const params: ContextParams = { units }; +const request: ClientRequestOptions = { path: "/context", method: "GET", query: { test: true } }; + +class Provider extends ContextDataProvider { + getContextData(_sdk: SDK, _options?: Partial): Promise { + return Promise.resolve(data); + } +} +class Publisher extends ContextPublisher { + publish(_request: PublishParams, _sdk: SDK, _context: Context, _options?: ClientRequestOptions): Promise { + return Promise.resolve(); + } +} +const logger: EventLogger = (_context: Context, event: EventName, info?: EventLoggerData): void => { + void event; + void info; +}; +const clientOptions: ClientOptions = { + endpoint: "https://example.test/v1", + apiKey: "key", + application: "web", + environment: "test", +}; +const options: SDKOptions = { provider: new Provider(), publisher: new Publisher(), eventLogger: logger }; +const contextOptions: ContextOptions = { + refreshPeriod: 0, + publishDelay: 0, + dataProvider: options.provider, + publisher: options.publisher, + eventLogger: logger, +}; +const sdk = new absmartly.SDK({ ...clientOptions, ...options }); +const namedSdk: SDK = sdk; +sdk.setEventLogger(logger); +sdk.setContextPublisher(new Publisher()); +sdk.setContextDataProvider(new Provider()); +sdk.getEventLogger(); +sdk.getContextPublisher(); +sdk.getContextDataProvider(); +sdk.getClient(); +sdk.getContextData(request); +const context: Context = sdk.createContext(params, contextOptions, request); +const withData = sdk.createContextWith(params, data, contextOptions); +const ready: Promise = context.ready(); +context.unit("user", 42); +context.units(units); +context.getUnit("user"); +context.getUnits(); +context.attribute("country", "US"); +context.attributes({ age: 21 }); +const value: any = context.getAttribute("country"); +context.getAttributes(); +context.peek("example"); +context.treatment("example"); +context.variableValue("color", "blue"); +context.peekVariableValue("color", "blue"); +context.variableKeys(); +context.override("example", 1); +context.overrides({ example: 1 }); +context.customAssignment("example", 1); +context.customAssignments({ example: 1 }); +context.track("purchase", { amount: 5 }); +context.publish(); +context.refresh(); +context.finalize(); +context.experiments(); +context.customFieldKeys(); +context.customFieldValue("example", "key"); +context.customFieldValueType("example", "key"); +context.isReady(); +context.isFailed(); +context.isFinalizing(); +context.isFinalized(); +context.pending(); +context.data(); +context.eventLogger(); +context.publisher(); +context.provider(); +mergeConfig(withData, {}); +const controller = new AbortController(); +controller.abort(); +void wrapped; +void payload; +void namedSdk; +void ready; +void value; diff --git a/scripts/compatibility/run.js b/scripts/compatibility/run.js new file mode 100644 index 0000000..78293e9 --- /dev/null +++ b/scripts/compatibility/run.js @@ -0,0 +1,189 @@ +#!/usr/bin/env node +/* eslint-disable @typescript-eslint/no-var-requires, no-shadow */ +/* global BigInt */ +/* Run outside the package under test so imports resolve as they do for a consumer. */ +const fs = require("fs"); +const os = require("os"); +const path = require("path"); +const child = require("child_process"); +const runtime = require("./runtime"); + +function usage() { + console.log(`Usage: node scripts/compatibility/run.js BASELINE_PACKAGE CANDIDATE_PACKAGE [--typescript-dir DIR] [--report FILE] + +Package arguments are directories containing package.json, built JS and declarations. +Example: npm pack @absmartly/javascript-sdk@1.13.4 --ignore-scripts + mkdir -p /tmp/sdk-baseline && tar -xzf absmartly-javascript-sdk-1.13.4.tgz -C /tmp/sdk-baseline + node scripts/compatibility/run.js /tmp/sdk-baseline/package . --report /tmp/sdk-compat.json + +By default, three pinned TypeScript versions are installed into a temporary directory +(requires npm registry access). To use existing compilers, install npm aliases + npm install --prefix /tmp/compat-ts --no-save --ignore-scripts \\ + typescript39@npm:typescript@3.9.10 typescript44@npm:typescript@4.4.4 typescript49@npm:typescript@4.9.5 +and pass --typescript-dir /tmp/compat-ts/node_modules. No root configuration changes. +The JSON report contains all changed declaration text and all runtime export names; +it includes failures even when the command exits nonzero. Temporary files are removed.`); +} +function exec(command, args, options) { + const result = child.spawnSync(command, args, { encoding: "utf8", ...options }); + if (result.error) throw result.error; + return result; +} +function declarations(root) { + const files = {}; + function visit(dir, prefix) { + if (!fs.existsSync(dir)) return; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const rel = prefix ? `${prefix}/${entry.name}` : entry.name; + if (entry.isDirectory()) visit(path.join(dir, entry.name), rel); + else if (entry.name.endsWith(".d.ts")) files[rel] = fs.readFileSync(path.join(dir, entry.name), "utf8"); + } + } + visit(path.join(root, "types"), ""); + return files; +} +function typeDiff(baseline, candidate) { + const a = declarations(baseline), + b = declarations(candidate), + diffs = {}; + for (const name of Array.from(new Set([...Object.keys(a), ...Object.keys(b)])).sort()) { + if (a[name] !== b[name]) + diffs[name] = { + baseline: a[name] === undefined ? null : a[name], + candidate: b[name] === undefined ? null : b[name], + }; + } + return diffs; +} +function compile(temp, compiler, packagePath, label) { + const dir = path.join(temp, label); + fs.mkdirSync(path.join(dir, "node_modules", "@absmartly"), { recursive: true }); + fs.symlinkSync(packagePath, path.join(dir, "node_modules", "@absmartly", "javascript-sdk"), "dir"); + fs.copyFileSync(path.join(__dirname, "consumer.ts"), path.join(dir, "consumer.ts")); + fs.writeFileSync( + path.join(dir, "tsconfig.json"), + JSON.stringify({ + compilerOptions: { + target: "es2017", + module: "commonjs", + moduleResolution: "node", + lib: ["es2017", "dom"], + strict: true, + noEmit: true, + types: [], + skipLibCheck: false, + esModuleInterop: true, + }, + files: ["consumer.ts"], + }) + ); + const result = exec(process.execPath, [ + compiler, + "--project", + path.join(dir, "tsconfig.json"), + "--pretty", + "false", + ]); + return { passed: result.status === 0, output: (result.stdout + result.stderr).trim() }; +} +async function main() { + const args = process.argv.slice(2); + if (args.includes("--help") || args.includes("-h")) { + usage(); + return; + } + if (args.length < 2 || args[0].startsWith("-") || args[1].startsWith("-")) { + usage(); + process.exitCode = 2; + return; + } + const baseline = path.resolve(args[0]), + candidate = path.resolve(args[1]); + let tsDir, reportFile; + for (let i = 2; i < args.length; i++) { + if (args[i] === "--typescript-dir" && args[i + 1]) tsDir = path.resolve(args[++i]); + else if (args[i] === "--report" && args[i + 1]) reportFile = path.resolve(args[++i]); + else throw new Error(`Unknown or incomplete argument: ${args[i]}`); + } + for (const pkg of [baseline, candidate]) { + if (!fs.existsSync(path.join(pkg, "package.json"))) throw new Error(`Not an installed/built package: ${pkg}`); + } + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "sdk-compat-")); + const result = { packages: {}, types: {}, runtime: null, errors: [] }; + try { + for (const [label, pkg] of [ + ["baseline", baseline], + ["candidate", candidate], + ]) { + const meta = JSON.parse(fs.readFileSync(path.join(pkg, "package.json"), "utf8")); + result.packages[label] = { path: pkg, name: meta.name, version: meta.version }; + } + result.declarationChanges = typeDiff(baseline, candidate); + if (!tsDir) { + const install = exec("npm", [ + "install", + "--prefix", + tmp, + "--no-save", + "--no-package-lock", + "--ignore-scripts", + "--no-audit", + "--no-fund", + "typescript39@npm:typescript@3.9.10", + "typescript44@npm:typescript@4.4.4", + "typescript49@npm:typescript@4.9.5", + ]); + if (install.status !== 0) + throw new Error(`TypeScript installation failed: ${install.stdout}${install.stderr}`); + tsDir = path.join(tmp, "node_modules"); + } + for (const [alias, expected] of [ + ["typescript39", "3.9.10"], + ["typescript44", "4.4.4"], + ["typescript49", "4.9.5"], + ]) { + const compilerDir = path.join(tsDir, alias); + const actual = JSON.parse(fs.readFileSync(path.join(compilerDir, "package.json"), "utf8")).version; + if (actual !== expected) throw new Error(`${alias} expected ${expected}, found ${actual}`); + result.types[expected] = {}; + for (const [label, pkg] of [ + ["baseline", baseline], + ["candidate", candidate], + ]) { + const outcome = compile(tmp, path.join(compilerDir, "bin", "tsc"), pkg, `${alias}-${label}`); + result.types[expected][label] = outcome; + console.log(`TypeScript ${expected} ${label}: ${outcome.passed ? "PASS" : "FAIL"}`); + if (!outcome.passed) { + console.error(outcome.output); + result.errors.push(`TypeScript ${expected} ${label} failed`); + } + } + } + try { + result.runtime = await runtime(baseline, candidate); + if (result.runtime.errors && result.runtime.errors.length) { + result.errors.push(...result.runtime.errors.map((error) => `Runtime: ${error}`)); + for (const error of result.runtime.errors) console.error(`Runtime: ${error}`); + } + } catch (err) { + result.errors.push(`Runtime: ${err.stack || err}`); + console.error(result.errors[result.errors.length - 1]); + } + } catch (err) { + result.errors.push(err.stack || String(err)); + console.error(result.errors[result.errors.length - 1]); + } finally { + if (reportFile) fs.writeFileSync(reportFile, `${JSON.stringify(result, null, 2)}\n`); + fs.rmSync(tmp, { recursive: true, force: true }); + } + console.log( + `Changed declaration files: ${Object.keys(result.declarationChanges || {}).length}${ + reportFile ? `; report: ${reportFile}` : " (use --report for full texts)" + }` + ); + if (result.errors.length) process.exitCode = 1; +} +main().catch((err) => { + console.error(err.stack || err); + process.exitCode = 1; +}); diff --git a/scripts/compatibility/runtime.js b/scripts/compatibility/runtime.js new file mode 100644 index 0000000..3dff05d --- /dev/null +++ b/scripts/compatibility/runtime.js @@ -0,0 +1,246 @@ +/* eslint-disable @typescript-eslint/no-var-requires, no-shadow */ +/* global BigInt */ +"use strict"; + +// Compare installed package directories, not source trees. No network is used. +const fs = require("fs"); +const path = require("path"); +const vm = require("vm"); + +const CLOCK = 1700000000000; +const options = { endpoint: "http://localhost", apiKey: "key", application: "website", environment: "test" }; +const contextOptions = { publishDelay: -1, refreshPeriod: 0 }; +const fixture = { + experiments: [ + { + id: 1, + name: "checkout", + iteration: 1, + unitType: "session_id", + seedHi: 3603515, + seedLo: 233373850, + split: [0.5, 0.5], + trafficSeedHi: 449867249, + trafficSeedLo: 455443629, + trafficSplit: [0.25, 0.75], + fullOnVariant: 0, + applications: [{ name: "website" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: '{"color":"blue"}' }, + ], + audience: null, + customFieldValues: null, + }, + ], +}; + +function snapshot(value) { + if (value instanceof Error) return { name: value.name, message: value.message }; + if (Array.isArray(value)) return value.map(snapshot); + if (value && typeof value === "object") { + const out = {}; + for (const key of Object.keys(value).sort()) { + // Newer SDKs include this optional field on exposure records. + if (key === "ruleOverride" && value[key] === false) continue; + out[key] = snapshot(value[key]); + } + return out; + } + return value; +} + +function surface(exports) { + const result = {}; + for (const key of Object.keys(exports).sort()) { + result[key] = typeof exports[key]; + } + return result; +} + +function errorOf(fn) { + try { + fn(); + return null; + } catch (error) { + return { name: error.name, message: error.message }; + } +} + +async function measure(api) { + const events = []; + const published = []; + let providerCalls = 0; + const provider = { + getContextData() { + providerCalls++; + return Promise.resolve(JSON.parse(JSON.stringify(fixture))); + }, + }; + const publisher = { + publish(request) { + published.push(snapshot(request)); + return Promise.resolve(); + }, + }; + const sdk = new api.SDK({ + ...options, + provider, + publisher, + eventLogger(_context, name, data) { + events.push({ name, data: snapshot(data) }); + }, + }); + const context = sdk.createContext({ units: { session_id: "user-123" } }, contextOptions); + const states = [{ ready: context.isReady(), pending: context.pending() }]; + const notReady = errorOf(() => context.treatment("checkout")); + await context.ready(); + states.push({ ready: context.isReady(), pending: context.pending() }); + context.attribute("plan", "pro"); + const values = { + peek: context.peek("checkout"), + treatment: context.treatment("checkout"), + repeated: context.treatment("checkout"), + missing: context.treatment("missing"), + variable: context.variableValue("color", "default"), + }; + context.track("purchase", { amount: 12 }); + states.push({ pending: context.pending() }); + await context.publish(); + states.push({ pending: context.pending() }); + await context.refresh(); + context.track("second"); + await context.finalize(); + states.push({ finalized: context.isFinalized(), pending: context.pending() }); + const errors = { + notReady, + finalized: errorOf(() => context.treatment("checkout")), + blankUnit: errorOf(() => sdk.createContextWith({ units: { session_id: " " } }, fixture, contextOptions)), + invalidUnit: errorOf(() => sdk.createContextWith({ units: { session_id: {} } }, fixture, contextOptions)), + }; + const lifecycleEvents = events.slice(); + const sweep = []; + const uids = Array.from({ length: 256 }, (_, i) => `user-${i}`).concat([ + "😀", + "café", + "漢字", + "\ud800", + "\udc00", + "a\ud800b", + " padded ", + "0", + "-1", + "9007199254740993", + 0, + -1, + 1.5, + 9007199254740992, + 12345, + ]); + for (const uid of uids) { + const ctx = sdk.createContextWith({ units: { session_id: uid } }, fixture, contextOptions); + sweep.push({ uid, peek: ctx.peek("checkout"), treatment: ctx.treatment("checkout") }); + } + // The sweep must not pollute the lifecycle trace. + return { values, states, errors, events: lifecycleEvents, published, providerCalls, sweep }; +} + +async function browserSurface(directory) { + const pkg = JSON.parse(fs.readFileSync(path.join(directory, "package.json"), "utf8")); + if (typeof pkg.browser !== "string") return null; + const file = path.resolve(directory, pkg.browser); + let request; + const sandbox = { + setTimeout, + clearTimeout, + setInterval, + clearInterval, + console, + fetch(url, opts) { + request = { url, method: opts.method, headers: opts.headers }; + return Promise.resolve({ ok: true, json: () => Promise.resolve({ experiments: [] }) }); + }, + }; + sandbox.self = sandbox; + vm.runInNewContext(fs.readFileSync(file, "utf8"), sandbox, { filename: file, timeout: 10000 }); + if (!sandbox.absmartly || typeof sandbox.absmartly.SDK !== "function") + throw new Error(`Browser bundle did not expose SDK: ${file}`); + const sdk = new sandbox.absmartly.SDK({ ...options, eventLogger() {} }); + const context = sdk.createContextWith({ units: { session_id: "browser" } }, { experiments: [] }, contextOptions); + await sdk.getClient().post({ path: "/context", body: { test: true } }); + const agent = request && request.headers && request.headers["X-Agent"]; + if (typeof agent === "string") + request.headers["X-Agent"] = agent.replace( + /^(absmartly-javascript-sdk)(?:\/[0-9]+\.[0-9]+\.[0-9]+(?:[-+][\w.-]+)?)?$/, + "$1/" + ); + return snapshot({ + exports: surface(sandbox.absmartly), + ready: context.isReady(), + missing: context.peek("missing"), + request, + }); +} + +/** Compare two installed SDK package directories and return all measured differences. */ +module.exports = async function compareRuntime(baselinePath, candidatePath) { + const baselineDir = path.resolve(baselinePath); + const candidateDir = path.resolve(candidatePath); + const baseline = require(baselineDir); + const candidate = require(candidateDir); + const baselineExports = surface(baseline); + const candidateExports = surface(candidate); + const differences = []; + function compareSubset(oldSurface, newSurface, label) { + for (const key of Object.keys(oldSurface)) { + if (newSurface[key] !== oldSurface[key]) + differences.push(`${label}.${key}: ${oldSurface[key]} -> ${newSurface[key]}`); + } + } + function compareValues(a, b, label) { + if (Object.is(a, b)) return; + if (a && b && typeof a === "object" && typeof b === "object" && Array.isArray(a) === Array.isArray(b)) { + for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) { + if (!(key in a) || !(key in b)) + differences.push( + `${label}.${key}: ${key in a ? JSON.stringify(a[key]) : ""} -> ${ + key in b ? JSON.stringify(b[key]) : "" + }` + ); + else compareValues(a[key], b[key], `${label}.${key}`); + } + } else differences.push(`${label}: ${JSON.stringify(a)} -> ${JSON.stringify(b)}`); + } + compareSubset(baselineExports, candidateExports, "Node"); + if (baseline.default) compareSubset(surface(baseline.default), surface(candidate.default || {}), "Node default"); + const oldNow = Date.now; + let before; + let after; + try { + Date.now = () => CLOCK; + before = await measure(baseline); + after = await measure(candidate); + } finally { + Date.now = oldNow; + } + compareValues(before, after, "runtime"); + const oldBrowser = await browserSurface(baselineDir); + const newBrowser = await browserSurface(candidateDir); + if (oldBrowser && !newBrowser) differences.push("Candidate browser entry is missing"); + if (oldBrowser && newBrowser) { + compareSubset(oldBrowser.exports, newBrowser.exports, "Browser"); + compareValues( + { ready: oldBrowser.ready, missing: oldBrowser.missing, request: oldBrowser.request }, + { ready: newBrowser.ready, missing: newBrowser.missing, request: newBrowser.request }, + "browser" + ); + } + return { + baselineExports, + candidateExports, + baseline: before, + candidate: after, + browser: { baseline: oldBrowser, candidate: newBrowser }, + errors: differences, + }; +}; From 4acb5f7d14c6824a2e4daa0a72213107c37a271e Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 08:48:34 +0000 Subject: [PATCH 03/92] fix(release): restore 1.13.4 client auth rules and guard dist tags request() sends SDK headers only with auth:true, post/put always authenticate and getUnauthed is a plain GET, as in 1.13.4. Prereleases never go to npm latest and an older same-major release is refused. Legacy custom clients publish no empty sdk_name. Tests kill each reviewer-found mutant. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +- release/1.14.0-compatibility.md | 92 +++++++++++---------- release/PUBLISHING.md | 2 +- scripts/__tests__/check-release.test.js | 12 +++ scripts/check-release.js | 23 +++++- src/__tests__/client.test.js | 12 +++ src/__tests__/release-compatibility.test.js | 70 +++++++++++++++- src/client.ts | 14 +++- src/context.ts | 3 +- 9 files changed, 176 insertions(+), 55 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 05f17b8..369aeeb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,7 +33,8 @@ `absmartly-javascript-sdk`. Affected: export/dashboard filters matching the old agent exactly. Explicit customer agent strings are preserved. - `GET /context` sends SDK authentication/metadata headers as well as the existing - query parameters, like PUT. Explicit `getUnauthed()` retains its old behaviour. + query parameters, like PUT. The low-level `request()`, `post()`, `put()` and + `getUnauthed()` keep their 1.13.4 header rules. `X-Application-Version` sends only 1–18 ASCII digits (trimmed), or `0` otherwise. Affected: proxies inspecting GET headers and apps configuring invalid version headers that previously caused collector HTTP 400 errors. diff --git a/release/1.14.0-compatibility.md b/release/1.14.0-compatibility.md index 1de9d8e..5437229 100644 --- a/release/1.14.0-compatibility.md +++ b/release/1.14.0-compatibility.md @@ -14,50 +14,50 @@ Classes: **a** additive; **b** agreed cross-SDK contract; **c** genuine bug fix; **d** unrelated compatibility/behaviour change (restore the published contract). This inventories public source/runtime differences, not just this PR's delta. -| Change since published 1.13.4 | Class | Action for 1.14.0 | -| --- | --- | --- | -| `ABsmartly` alias in CJS/ES/browser exports | a | Keep alongside `SDK`; no old entry point removed. | -| `Client.getApplication/getEnvironment/getAgent/get`, `ApplicationObject` | a | Keep; string application still accepted. | -| `Context.getSDK/getOptions/readyError` | a | Keep. | -| Optional experiment assignment rules, variant name, holdout IDs; new holdout model types | a/b | Keep optional; no new required customer payload fields. | -| `AudienceMatcher.parseRules/evaluateRules/evaluateParsedRules`, `RuleAction` | a/b | Keep assignment/split rules with strict types, environment scoping, malformed-rule isolation, override precedence and missing-unit pinning. | -| `semver_*` operators, `Evaluator.versionCompare` | a/b | Keep; old `stringConvert`, `eq`, `in`, match behaviour remains unchanged. | -| `includeSystemAttributes` option | a/b | Keep opt-in publishing of SDK name/version; never synthetic app/environment/app_version publishing. | -| Synthetic application/environment in evaluation, user values win | b | Keep and document affected targeting under Changed; empty names absent, no synthetic app_version. | -| Assignment rules override audience/traffic/full-on/custom/holdouts | b | Keep and document affected experiments under Changed. | -| Required `Exposure.ruleOverride` source field on main | d | Make optional for old model literals; runtime always emits true/false (b). | -| Holdout suppression, control variable fallback and holdout exposures | b | Keep; document payload-linked experiments under Changed. | -| Shared variable resolution/id ordering/map-of-lists | b | Keep; released return shape unchanged. | -| GET SDK auth/metadata headers | b | Keep; preserve query parameters. | -| `getUnauthed()` silently became authenticated | d | Restore explicit unauthenticated GET; additive `get()` sends headers. | -| Versioned SDK X-Agent | b | Add from generated package version; custom agent untouched. Direct `Client` default remains `javascript-client`. | -| String application version accepted; utility return widened | a/d | Keep strings; overload `getApplicationVersion` so old numeric callers still receive `number` statically. | -| Invalid/dotted application versions sent to collector Long header | c/b | Normalize GET and PUT to trimmed 1–18 ASCII digits or zero; retain full configured getter. | -| Every publish adds `sdkVersion`, required `PublishParams.sdkVersion` | d | Restore 1.13 body/type; collector `PublishRequest` ignores this unknown field. SDK version remains in X-Agent and opt-in attributes. | -| New normal-path auth deprecation warning | d | Remove; explicit auth still accepted without new stderr output. | -| Error brand casing `ABSmartly` → `ABsmartly` | d | Restore byte-identical 1.13 not-ready/finalizing/finalized messages. | -| Custom-field console diagnostics changed to logger error events and JSON parser suffix | d | Restore released console sink/messages, null return and no new error events. | -| Failed-context flush adds discard error event | d | Restore silent discard after initial load error; preserve settlement/queue cleanup. | -| `getUnits()` changes live map to defensive copy | d | Restore live map and original `Units` return type. | -| `getAttribute()` return changes from incorrect `undefined` declaration to `unknown` | c/d | Use `any` for compatibility with both strict and non-strict existing consumers; actual last-value behaviour unchanged. | -| `ready(): Promise` narrows to boolean and README claims old errors | d | Restore declared Promise; published runtime already resolves true even on failure. Correct README, do not invent migration. | -| `finalize()` inferred `true \| Promise` narrows to `Promise` | c | Keep actual Promise-only result; published implementation never returned true. | -| Canonical UTF-8 for astral/unpaired surrogate UIDs changes hashes/assignment | d | Restore legacy UTF-16-code-unit encoding for all 1.x hashes; canonical change preserved on next/major for 2.0. | -| Type-only inline imports raise declaration parser floor to TS4.5 | d | Restore old import syntax; TS3.9 consumer compile checks it. | -| New required getters on duck-typed custom clients | d | Guard getters so existing custom clients don't crash context installation/evaluation. | -| Abort shim reason/onabort/optional abort reason and idempotence | a/c | Keep native-standard cancellation bug fixes; no required method argument. | -| Fetch global detection and clear no-fetch error | c | Keep fallback selection fix (old no-global environment was unusable). | -| Query key escaping and malformed-surrogate normalization | c | Keep encoding fixes; ordinary URL values unchanged. | -| Per-request timeout/retry budget, zero deadline semantics | c | Keep documented override bug fix; defaults unchanged. | -| Failed publisher loses events, synchronous failures and concurrent finalize races | c | Keep ordered restore/retry and promise settlement fixes. | -| Throwing event logger corrupts init/publish/finalize | c | Isolate observer exceptions; don't resend already-delivered batch. | -| Malformed/non-object variant config crashes or indexes invalid keys | c | Isolate invalid config; valid objects unchanged. | -| Audience evaluation exception fails open; indeterminate cache needless rebuild | c | Fail strict audiences closed, keep cached mismatch for indeterminate result. | -| Unit hash caches missing unit forever | c | Don't memoize missing hash; rule/holdout late-unit handling retained. | -| New @babel/runtime production dependency and helper deduplication | a | Private build helper dependency, no exposed dependency types or major bump to existing dependencies; Node6 remains supported. | -| Node24 development tooling, husky/lint-staged, generate-version, build/prepare hooks | a | Build-only; package engines remain Node>=6/npm>=3, Babel CJS Node6 and IE10 browser targets unchanged. | -| Babel relative runtime paths, delete stale generated output, browser/CJS export packaging | c | Keep portable package output. | -| README restructuring/refreshPeriod correction | c | Keep; pin install/browser examples to 1.14.0 and replace misleading Breaking migration. | +| Change since published 1.13.4 | Class | Action for 1.14.0 | +| ------------------------------------------------------------------------------------------------------------------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ABsmartly` alias in CJS/ES/browser exports | a | Keep alongside `SDK`; no old entry point removed. | +| `Client.getApplication/getEnvironment/getAgent/get`, `ApplicationObject` | a | Keep; string application still accepted. | +| `Context.getSDK/getOptions/readyError` | a | Keep. | +| Optional experiment assignment rules, variant name, holdout IDs; new holdout model types | a/b | Keep optional; no new required customer payload fields. | +| `AudienceMatcher.parseRules/evaluateRules/evaluateParsedRules`, `RuleAction` | a/b | Keep assignment/split rules with strict types, environment scoping, malformed-rule isolation, override precedence and missing-unit pinning. | +| `semver_*` operators, `Evaluator.versionCompare` | a/b | Keep; old `stringConvert`, `eq`, `in`, match behaviour remains unchanged. | +| `includeSystemAttributes` option | a/b | Keep opt-in publishing of SDK name/version; never synthetic app/environment/app_version publishing. | +| Synthetic application/environment in evaluation, user values win | b | Keep and document affected targeting under Changed; empty names absent, no synthetic app_version. | +| Assignment rules override audience/traffic/full-on/custom/holdouts | b | Keep and document affected experiments under Changed. | +| Required `Exposure.ruleOverride` source field on main | d | Make optional for old model literals; runtime always emits true/false (b). | +| Holdout suppression, control variable fallback and holdout exposures | b | Keep; document payload-linked experiments under Changed. | +| Shared variable resolution/id ordering/map-of-lists | b | Keep; released return shape unchanged. | +| GET SDK auth/metadata headers | b | Keep; preserve query parameters. | +| Low-level `Client` auth rules: `request()` authenticated by default, `post`/`put` honoured `auth:false`, `getUnauthed` became authenticated | d | Restore 1.13.4 rules exactly: `request()` sends headers only with `auth: true`, `post`/`put` always authenticate, `getUnauthed` is a plain GET. The additive `get()` (used by `getContext`) authenticates unless `auth: false`. | +| Versioned SDK X-Agent | b | Add from generated package version; custom agent untouched. Direct `Client` default remains `javascript-client`. | +| String application version accepted; utility return widened | a/d | Keep strings; overload `getApplicationVersion` so old numeric callers still receive `number` statically. | +| Invalid/dotted application versions sent to collector Long header | c/b | Normalize GET and PUT to trimmed 1–18 ASCII digits or zero; retain full configured getter. | +| Every publish adds `sdkVersion`, required `PublishParams.sdkVersion` | d | Restore 1.13 body/type; collector `PublishRequest` ignores this unknown field. SDK version remains in X-Agent and opt-in attributes. | +| New normal-path auth deprecation warning | d | Remove; explicit auth still accepted without new stderr output. | +| Error brand casing `ABSmartly` → `ABsmartly` | d | Restore byte-identical 1.13 not-ready/finalizing/finalized messages. | +| Custom-field console diagnostics changed to logger error events and JSON parser suffix | d | Restore released console sink/messages, null return and no new error events. | +| Failed-context flush adds discard error event | d | Restore silent discard after initial load error; preserve settlement/queue cleanup. | +| `getUnits()` changes live map to defensive copy | d | Restore live map and original `Units` return type. | +| `getAttribute()` return changes from incorrect `undefined` declaration to `unknown` | c/d | Use `any` for compatibility with both strict and non-strict existing consumers; actual last-value behaviour unchanged. | +| `ready(): Promise` narrows to boolean and README claims old errors | d | Restore declared Promise; published runtime already resolves true even on failure. Correct README, do not invent migration. | +| `finalize()` inferred `true \| Promise` narrows to `Promise` | c | Keep actual Promise-only result; published implementation never returned true. | +| Canonical UTF-8 for astral/unpaired surrogate UIDs changes hashes/assignment | d | Restore legacy UTF-16-code-unit encoding for all 1.x hashes; canonical change preserved on next/major for 2.0. | +| Type-only inline imports raise declaration parser floor to TS4.5 | d | Restore old import syntax; TS3.9 consumer compile checks it. | +| New required getters on duck-typed custom clients | d | Guard getters so existing custom clients don't crash context installation/evaluation. | +| Abort shim reason/onabort/optional abort reason and idempotence | a/c | Keep native-standard cancellation bug fixes; no required method argument. | +| Fetch global detection and clear no-fetch error | c | Keep fallback selection fix (old no-global environment was unusable). | +| Query key escaping and malformed-surrogate normalization | c | Keep encoding fixes; ordinary URL values unchanged. | +| Per-request timeout/retry budget, zero deadline semantics | c | Keep documented override bug fix; defaults unchanged. | +| Failed publisher loses events, synchronous failures and concurrent finalize races | c | Keep ordered restore/retry and promise settlement fixes. | +| Throwing event logger corrupts init/publish/finalize | c | Isolate observer exceptions; don't resend already-delivered batch. | +| Malformed/non-object variant config crashes or indexes invalid keys | c | Isolate invalid config; valid objects unchanged. | +| Audience evaluation exception fails open; indeterminate cache needless rebuild | c | Fail strict audiences closed, keep cached mismatch for indeterminate result. | +| Unit hash caches missing unit forever | c | Don't memoize missing hash; rule/holdout late-unit handling retained. | +| New @babel/runtime production dependency and helper deduplication | a | Private build helper dependency, no exposed dependency types or major bump to existing dependencies; Node6 remains supported. | +| Node24 development tooling, husky/lint-staged, generate-version, build/prepare hooks | a | Build-only; package engines remain Node>=6/npm>=3, Babel CJS Node6 and IE10 browser targets unchanged. | +| Babel relative runtime paths, delete stale generated output, browser/CJS export packaging | c | Keep portable package output. | +| README restructuring/refreshPeriod correction | c | Keep; pin install/browser examples to 1.14.0 and replace misleading Breaking migration. | ## Measurements @@ -72,13 +72,15 @@ This inventories public source/runtime differences, not just this PR's delta. ESLint, TypeScript, ES/CJS and both browser bundles pass. - Cross-SDK snapshot `ada8952293a8d4ebf81f8de038f4e7a406d98870` (merged main): **277 tested and passed / 28 reviewed capability skips of 305**, no failures. - Skips: 320/321 (snapshot declares unversioned JS agent), 323 (blank application), + Skips: 320/321 (the pinned snapshot still lists `xAgentHeader` as unsupported for JS; + un-skipped, head passes both, so the policy entry is stale and needs a cross-sdk-tests change), 323 (blank application), 400–420 and 422–425 (unimplemented switchbacks). No wrapper was modified or observations filtered. Versioned agent GET/PUT is separately tested in this repo. - External type consumer against artifact and candidate: TS3.9/4.4/4.9 probes. Main fails TS3.9/4.4 parsing; main on TS4.9 rejects released Exposure and PublishParams literals and non-strict getAttribute usage. Restored candidate compiles the released non-strict consumer under TS3.9. +- Dist-tag selection: prereleases go to their own tag (`beta`, `rc`, else `next`), never `latest`; a stable release goes to `latest` only when it is newer than the current latest; an older major goes to `v-lts`; an older same-major backport is refused so the owner chooses its tag. - Actual npm 11.6.2 dry run proves `--tag v1` is rejected as a semver range; use `v1-lts` for a maintained v1 when npm latest becomes v2+. No publication. diff --git a/release/PUBLISHING.md b/release/PUBLISHING.md index d716c62..4ff3c75 100644 --- a/release/PUBLISHING.md +++ b/release/PUBLISHING.md @@ -20,7 +20,7 @@ only. If opted in, the owner must supply that secret; it is not needed for OIDC. A manual dry run does not prove npm will accept OIDC on a real tag: the owner must retain the npm publisher configuration and approve any environment protections. -When this package's major is lower than `npm latest`, the workflow uses `v1-lts` +Prereleases (for example `1.15.0-beta.0`) publish under their prerelease id (`beta`), never `latest`. A stable version that is not newer than `npm latest` in the same major (for example a 1.13.x backport after 1.14.0) fails the check, so the owner chooses its tag. When this package's major is lower than `npm latest`, the workflow uses `v1-lts` (or `v-lts`), leaving latest alone. **Owner deviation to approve:** the requested `--tag v1` is impossible: npm 11.6.2 rejects it with `Tag name must not be a valid SemVer range: v1`. `v1-lts` passes the same dry run. For 1.14.0 today, diff --git a/scripts/__tests__/check-release.test.js b/scripts/__tests__/check-release.test.js index f98cb7f..463bb2b 100644 --- a/scripts/__tests__/check-release.test.js +++ b/scripts/__tests__/check-release.test.js @@ -21,3 +21,15 @@ test("rejects mismatched tags and malformed registry versions", () => { test("accepts valid prerelease and build metadata", () => { expect(majorOf("2.0.0-rc.1+build.5")).toBe(2n); }); + +test("never puts prereleases on latest", () => { + expect(releaseTag("1.15.0-beta.0", "1.14.0", "v1.15.0-beta.0")).toBe("beta"); + expect(releaseTag("1.14.1-rc.1", "1.14.0", "v1.14.1-rc.1")).toBe("rc"); + expect(releaseTag("2.0.0-0", "1.14.0", "v2.0.0-0")).toBe("next"); +}); + +test("refuses an older same-major release instead of moving latest back", () => { + expect(() => releaseTag("1.13.5", "1.14.0", "v1.13.5")).toThrow(/not newer than latest/); + expect(() => releaseTag("1.14.0", "1.14.0", "v1.14.0")).toThrow(/not newer than latest/); + expect(releaseTag("1.14.1", "2.0.0", "v1.14.1")).toBe("v1-lts"); +}); diff --git a/scripts/check-release.js b/scripts/check-release.js index 567cb8f..212533f 100644 --- a/scripts/check-release.js +++ b/scripts/check-release.js @@ -16,13 +16,34 @@ function majorOf(value) { return BigInt(value.split(".")[0]); } +function compareCore(a, b) { + const x = a.split(/[-+]/)[0].split(".").map(BigInt); + const y = b.split(/[-+]/)[0].split(".").map(BigInt); + for (let i = 0; i < 3; i++) { + if (x[i] !== y[i]) return x[i] > y[i] ? 1 : -1; + } + return 0; +} + +// A prerelease goes to its own tag (1.15.0-beta.0 -> "beta"), never "latest". A stable release goes to +// "latest" only when it is newer than the current latest; an older major goes to v-lts, and an +// older version in the same major line (e.g. a 1.13.x backport after 1.14.0) is refused. function releaseTag(packageVersion, latestVersion, gitTag) { const major = majorOf(packageVersion); const latestMajor = majorOf(latestVersion); if (gitTag !== `v${packageVersion}`) { throw new Error("Git tag must match v"); } - return major < latestMajor ? `v${major}-lts` : "latest"; + const prerelease = packageVersion.split("+")[0].split("-").slice(1).join("-"); + if (prerelease) { + const id = prerelease.split(".")[0]; + return /^[a-z][a-z0-9]*$/i.test(id) ? id.toLowerCase() : "next"; + } + if (major < latestMajor) return `v${major}-lts`; + if (compareCore(packageVersion, latestVersion) <= 0) { + throw new Error(`${packageVersion} is not newer than latest ${latestVersion}; choose a dist tag manually`); + } + return "latest"; } function main() { diff --git a/src/__tests__/client.test.js b/src/__tests__/client.test.js index fa01020..e48da46 100644 --- a/src/__tests__/client.test.js +++ b/src/__tests__/client.test.js @@ -224,6 +224,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", query: { a: 1 }, @@ -272,6 +273,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", query: { a: 1 }, @@ -315,6 +317,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", query: { a: 1 }, @@ -365,6 +368,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", query: { a: 1 }, @@ -584,6 +588,7 @@ describe("Client", () => { client .request({ + auth: true, method: "POST", path: "/context", query: { a: 1 }, @@ -621,6 +626,7 @@ describe("Client", () => { client .request({ + auth: true, method: "POST", path: "/context", query: { a: 1 }, @@ -658,6 +664,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", query: { a: 1, b: "ã=á" }, @@ -716,6 +723,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", query: {}, @@ -751,6 +759,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", }) @@ -784,6 +793,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", }) @@ -1086,6 +1096,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", }) @@ -1223,6 +1234,7 @@ describe("Client", () => { client .request({ + auth: true, method: "GET", path: "/context", }) diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 30670c8..106ed55 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -48,7 +48,73 @@ describe("1.13.4 source and behaviour compatibility", () => { const client = new Client({ ...options, agent: "customer-agent" }); await client.get({ path: "/custom" }); expect(sdkFetch.mock.calls[0][1].headers["X-Agent"]).toBe("customer-agent"); - await client.getUnauthed({ path: "/custom", auth: true }); - expect(sdkFetch.mock.calls[1][1]).not.toHaveProperty("headers"); + }); + + it.each([ + ["request() without auth", (c) => c.request({ path: "/x", method: "GET" }), false], + ["request() with auth true", (c) => c.request({ path: "/x", method: "GET", auth: true }), true], + ["post() with auth false", (c) => c.post({ path: "/x", auth: false }), true], + ["put() with auth false", (c) => c.put({ path: "/x", auth: false }), true], + ["getUnauthed()", (c) => c.getUnauthed({ path: "/x" }), false], + ["getUnauthed() with auth true", (c) => c.getUnauthed({ path: "/x", auth: true }), true], + ["get() with auth false", (c) => c.get({ path: "/x", auth: false }), false], + ])("keeps the 1.13.4 auth header rule for %s", async (_label, call, sendsHeaders) => { + sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({}) }); + await call(new Client(options)); + const request = sdkFetch.mock.calls[sdkFetch.mock.calls.length - 1][1]; + if (sendsHeaders) expect(request.headers["X-API-Key"]).toBe("k"); + else expect(request).not.toHaveProperty("headers"); + }); + + describe("a released duck-typed custom client without the new getters", () => { + const legacyClient = () => ({ + getContext: () => Promise.resolve({ experiments: [] }), + publish: jest.fn(() => Promise.resolve()), + }); + const strictCountryExperiment = { + id: 1, + name: "exp", + iteration: 1, + unitType: "session_id", + seedHi: 3603515, + seedLo: 233373850, + split: [0, 1], + trafficSeedHi: 449867249, + trafficSeedLo: 455443629, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + audience: JSON.stringify({ filter: [{ eq: [{ var: "country" }, { value: "US" }] }] }), + audienceStrict: true, + customFieldValues: null, + }; + + it("still evaluates audiences", () => { + const sdk = new SDK({ ...options, client: legacyClient() }); + const context = sdk.createContextWith( + { units: { session_id: "e791e240fcd3df7d238cfc285f475e8152fcc0ec" } }, + { experiments: [strictCountryExperiment] } + ); + context.attribute("country", "US"); + expect(context.treatment("exp")).toBe(1); + }); + + it("publishes sdk_version but no empty sdk_name", async () => { + const client = legacyClient(); + const sdk = new SDK({ ...options, client }); + const context = sdk.createContextWith( + { units: { session_id: "u" } }, + { experiments: [] }, + { includeSystemAttributes: true, publishDelay: -1 } + ); + context.track("goal"); + await context.publish(); + const names = client.publish.mock.calls[0][0].attributes.map((a) => a.name); + expect(names).toEqual(["sdk_version"]); + }); }); }); diff --git a/src/client.ts b/src/client.ts index 10f9e86..4d06ad2 100644 --- a/src/client.ts +++ b/src/client.ts @@ -22,7 +22,7 @@ export type ClientRequestOptions = { path: string; method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS"; body?: Record; - /** @deprecated The API key is sent by default; set to false to suppress auth headers. */ + // Sends the SDK auth/metadata headers. post(), put() and get() set it; request() sends none unless true. auth?: boolean; signal?: AbortSignal | ABsmartlyAbortSignal; timeout?: number; @@ -183,7 +183,7 @@ export default class Client { keepalive: this._opts.keepalive, }; - if (options.auth !== false) { + if (options.auth) { opts.headers = { "Content-Type": "application/json", "X-API-Key": this._opts.apiKey, @@ -307,6 +307,7 @@ export default class Client { post(options: ClientRequestOptions) { return this.request({ ...options, + auth: true, method: "POST", }); } @@ -314,6 +315,7 @@ export default class Client { put(options: ClientRequestOptions) { return this.request({ ...options, + auth: true, method: "PUT", }); } @@ -329,12 +331,16 @@ export default class Client { get(options: ClientRequestOptions) { return this.request({ ...options, + auth: options.auth !== false, method: "GET", }); } - /** GET without authentication, retained for 1.x consumers. Use get() for SDK headers. */ + // Plain GET with 1.13 semantics: headers only when `auth: true` is passed. Use get() for SDK headers. getUnauthed(options: ClientRequestOptions) { - return this.get({ ...options, auth: false }); + return this.request({ + ...options, + method: "GET", + }); } } diff --git a/src/context.ts b/src/context.ts index 186c700..68026a1 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1113,7 +1113,8 @@ export default class Context { } }; - addSystemAttribute("sdk_name", typeof client?.getAgent === "function" ? client.getAgent() : undefined); + const agent = typeof client?.getAgent === "function" ? client.getAgent() : undefined; + if (typeof agent === "string" && agent.length > 0) addSystemAttribute("sdk_name", agent); addSystemAttribute("sdk_version", SDK_VERSION); } From 8614d91f4dda216f5f344eb100df44053c81c7b1 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 09:58:06 +0000 Subject: [PATCH 04/92] fix(release): restore 1.13.4 timeout and getContext semantics, keep bundle ES5 A request timeout of 0 falls back to the client timeout and a client timeout of 0 means no retries, as in 1.13.4. getContext() routes through getUnauthed() so subclass overrides still run. rfdc is transpiled for the IE 10 bundle and the build fails on non-ES5 dist output. Adds a counter test that a same-outcome refresh advances the rule key. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 +-- package-lock.json | 13 ++--- package.json | 3 +- release/1.14.0-compatibility.md | 7 ++- scripts/check-es5.js | 18 +++++++ src/__tests__/client.test.js | 57 +++++++++++--------- src/__tests__/release-compatibility.test.js | 60 +++++++++++++++++++++ src/client.ts | 15 +++--- webpack.config.js | 4 +- 9 files changed, 138 insertions(+), 47 deletions(-) create mode 100644 scripts/check-es5.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 369aeeb..a7fede7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,9 +50,11 @@ promises or lose/duplicate successfully delivered events. - Malformed variant configs are isolated rather than failing the entire context; audience evaluation exceptions fail strict audiences closed. -- Per-request timeouts now govern the retry budget consistently; zero explicitly - disables the deadline. Affected: callers overriding timeouts or using zero, whose - configured limit was previously ignored by part of the retry path. +- A per-request `timeout` now also bounds the retry budget (previously only the + client timeout did). A `timeout` of 0 keeps its 1.13.4 meaning: a request value + of 0 falls back to the client timeout, and a client timeout of 0 means no retries. +- The browser bundle is ES5 again (IE 10): `rfdc` >= 1.4 ships ES2015 syntax, so + it is now transpiled, and the build fails if `dist/` is not ES5. - Query keys are encoded and unmatched query surrogates no longer throw URIError. - Preserve published 1.13.4 error strings, custom-field console diagnostics, live `getUnits()` return, legacy unit hashing, old TypeScript parser support, diff --git a/package-lock.json b/package-lock.json index f41e88d..b002d2d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -37,6 +37,7 @@ "@types/node-fetch": "^2.6.2", "@typescript-eslint/eslint-plugin": "^5.48.2", "@typescript-eslint/parser": "^5.48.2", + "acorn": "^8.19.0", "babel-jest": "^29", "babel-loader": "^8.2.3", "eslint": "^7.32.0", @@ -3494,9 +3495,9 @@ "dev": true }, "node_modules/acorn": { - "version": "8.8.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.1.tgz", - "integrity": "sha512-7zFpHzhnqYKrkYdUjF1HI1bzd0VygEGX8lFk4k5zVMqHEoES+P+7TKI+EvLO9WVMJ8eekdO0aDEK044xTXwPPA==", + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", "dev": true, "bin": { "acorn": "bin/acorn" @@ -12711,9 +12712,9 @@ "dev": true }, "acorn": { - "version": "8.8.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.1.tgz", - "integrity": "sha512-7zFpHzhnqYKrkYdUjF1HI1bzd0VygEGX8lFk4k5zVMqHEoES+P+7TKI+EvLO9WVMJ8eekdO0aDEK044xTXwPPA==", + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", "dev": true }, "acorn-jsx": { diff --git a/package.json b/package.json index c96e472..c6062b4 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "node": ">=6" }, "scripts": { - "build-browser": "TARGET=browser webpack --progress --config webpack.config.js && TARGET=browser NODE_ENV=production webpack --progress --config webpack.config.js", + "build-browser": "TARGET=browser webpack --progress --config webpack.config.js && TARGET=browser NODE_ENV=production webpack --progress --config webpack.config.js && node scripts/check-es5.js", "build-cjs": "TARGET=cjs babel js --delete-dir-on-start --ignore 'browser.js' -d lib", "build-es": "TARGET=es babel js --delete-dir-on-start --ignore 'browser.js' -d es", "build": "npm run -s format:check && npm run -s lint && npm run -s compile && npm run -s test && npm run -s build-es && npm run -s build-cjs && npm run -s build-browser", @@ -69,6 +69,7 @@ "@types/node-fetch": "^2.6.2", "@typescript-eslint/eslint-plugin": "^5.48.2", "@typescript-eslint/parser": "^5.48.2", + "acorn": "^8.19.0", "babel-jest": "^29", "babel-loader": "^8.2.3", "eslint": "^7.32.0", diff --git a/release/1.14.0-compatibility.md b/release/1.14.0-compatibility.md index 5437229..33a0109 100644 --- a/release/1.14.0-compatibility.md +++ b/release/1.14.0-compatibility.md @@ -48,13 +48,16 @@ This inventories public source/runtime differences, not just this PR's delta. | Abort shim reason/onabort/optional abort reason and idempotence | a/c | Keep native-standard cancellation bug fixes; no required method argument. | | Fetch global detection and clear no-fetch error | c | Keep fallback selection fix (old no-global environment was unusable). | | Query key escaping and malformed-surrogate normalization | c | Keep encoding fixes; ordinary URL values unchanged. | -| Per-request timeout/retry budget, zero deadline semantics | c | Keep documented override bug fix; defaults unchanged. | +| Per-request timeout/retry budget | c | Keep: a per-request timeout now bounds retries too. | +| Main made `timeout: 0` mean "no deadline" (request) and "retry forever" (client) | d | Restore 1.13.4: request 0 falls back to the client timeout, client 0 means no retries. Measured: main hangs > 8 s where 1.13.4 fails at ~3 s. | +| `getContext()` called `get()` directly, skipping a subclass `getUnauthed()` override | d | Route through `getUnauthed()` again, keeping the GET headers. | +| `rfdc` 1.4.1 (lockfile) puts ES2015 syntax into the browser bundle | d | Transpile rfdc in webpack; `scripts/check-es5.js` fails the build if `dist/` is not ES5. | | Failed publisher loses events, synchronous failures and concurrent finalize races | c | Keep ordered restore/retry and promise settlement fixes. | | Throwing event logger corrupts init/publish/finalize | c | Isolate observer exceptions; don't resend already-delivered batch. | | Malformed/non-object variant config crashes or indexes invalid keys | c | Isolate invalid config; valid objects unchanged. | | Audience evaluation exception fails open; indeterminate cache needless rebuild | c | Fail strict audiences closed, keep cached mismatch for indeterminate result. | | Unit hash caches missing unit forever | c | Don't memoize missing hash; rule/holdout late-unit handling retained. | -| New @babel/runtime production dependency and helper deduplication | a | Private build helper dependency, no exposed dependency types or major bump to existing dependencies; Node6 remains supported. | +| New @babel/runtime production dependency and helper deduplication (owner call; kept) | a | Private build helper dependency, no exposed dependency types or major bump to existing dependencies; Node6 remains supported. | | Node24 development tooling, husky/lint-staged, generate-version, build/prepare hooks | a | Build-only; package engines remain Node>=6/npm>=3, Babel CJS Node6 and IE10 browser targets unchanged. | | Babel relative runtime paths, delete stale generated output, browser/CJS export packaging | c | Keep portable package output. | | README restructuring/refreshPeriod correction | c | Keep; pin install/browser examples to 1.14.0 and replace misleading Breaking migration. | diff --git a/scripts/check-es5.js b/scripts/check-es5.js new file mode 100644 index 0000000..4f1b371 --- /dev/null +++ b/scripts/check-es5.js @@ -0,0 +1,18 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ +// Fails the build when a browser bundle is not plain ES5 (the IE 10 target). +const fs = require("fs"); +const path = require("path"); +const acorn = require("acorn"); + +let failed = false; +for (const file of ["absmartly.js", "absmartly.min.js"]) { + const target = path.resolve(__dirname, "../dist", file); + try { + acorn.parse(fs.readFileSync(target, "utf8"), { ecmaVersion: 5 }); + console.log(`ES5 OK: dist/${file}`); + } catch (error) { + console.error(`dist/${file} is not ES5: ${error.message}`); + failed = true; + } +} +process.exitCode = failed ? 1 : 0; diff --git a/src/__tests__/client.test.js b/src/__tests__/client.test.js index e48da46..91f683d 100644 --- a/src/__tests__/client.test.js +++ b/src/__tests__/client.test.js @@ -1212,40 +1212,45 @@ describe("Client", () => { }); describe("timeout option", () => { - it("should accept an explicit timeout of 0 (nullish coalescing, not falsy)", () => { - const client = new Client({ - endpoint, - agent, - environment, - apiKey, - application, - timeout: 0, - }); - + it("should accept an explicit timeout of 0", () => { + const client = new Client({ endpoint, agent, environment, apiKey, application, timeout: 0 }); expect(client).toBeInstanceOf(Client); }); - it("should still retry a failing-then-succeeding request when timeout is 0 (no deadline)", (done) => { - fetch - .mockResolvedValueOnce(responseMock(500, "server error", "server error text")) - .mockResolvedValueOnce(responseMock(200, "OK", defaultMockResponse)); - + it("should not retry when the client timeout is 0, as in 1.13.4", (done) => { + fetch.mockRejectedValue(new Error("connection refused")); const client = new Client(Object.assign({}, clientOptions, { timeout: 0, retries: 5 })); - client - .request({ - auth: true, - method: "GET", - path: "/context", - }) - .then((response) => { - expect(fetch).toHaveBeenCalledTimes(2); - expect(response).toEqual(defaultMockResponse); + client.request({ method: "PUT", path: "/context" }).catch(() => { + expect(fetch).toHaveBeenCalledTimes(1); + done(); + }); + }); + it("should fall back to the client timeout when a request timeout is 0", (done) => { + // Like a real fetch, reject once the request's signal aborts. + fetch.mockImplementation( + (_url, opts) => + new Promise((_resolve, reject) => { + opts.signal.addEventListener("abort", () => { + const error = new Error("aborted"); + error.name = "AbortError"; + reject(error); + }); + }) + ); + const client = new Client(Object.assign({}, clientOptions, { timeout: 200, retries: 0 })); + + // The client's 200 ms deadline still aborts the request; it doesn't hang. + client.request({ method: "GET", path: "/context", timeout: 0 }).then( + () => done(new Error("expected the request to be aborted")), + (error) => { + expect(error.message).toBe("aborted"); done(); - }); + } + ); - advanceFakeTimers(); + jest.advanceTimersByTime(200); }); }); }); diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 106ed55..3b7ca55 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -2,6 +2,7 @@ import SDK from "../sdk"; import { SDK_VERSION } from "../version"; import Client from "../client"; import sdkFetch from "../fetch"; +import { AudienceMatcher } from "../matcher"; jest.mock("../fetch"); @@ -66,6 +67,65 @@ describe("1.13.4 source and behaviour compatibility", () => { else expect(request).not.toHaveProperty("headers"); }); + it("does not re-evaluate assignment rules on cached reads after a same-outcome refresh", async () => { + const experiment = (rules) => ({ + id: 7, + name: "ruled", + iteration: 1, + unitType: "session_id", + seedHi: 1, + seedLo: 2, + split: [0.5, 0.5], + trafficSeedHi: 3, + trafficSeedLo: 4, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + audience: null, + audienceStrict: false, + customFieldValues: null, + assignmentRules: JSON.stringify(rules), + }); + const rule = { type: "assign", variant: 1, conditions: { eq: [{ var: "country" }, { value: "US" }] } }; + // The refreshed rules JSON differs (an extra rule name) but still gives variant 1. + const refreshed = { experiments: [experiment({ rules: [{ ...rule, name: "renamed" }] })] }; + const provider = { getContextData: () => Promise.resolve(refreshed) }; + const sdk = new SDK({ ...options, provider }); + const context = sdk.createContextWith( + { units: { session_id: "u1" } }, + { experiments: [experiment({ rules: [rule] })] } + ); + context.attribute("country", "US"); + expect(context.treatment("ruled")).toBe(1); + + await context.refresh(); + expect(context.treatment("ruled")).toBe(1); + expect(context.pending()).toBe(1); + + const spy = jest.spyOn(AudienceMatcher.prototype, "evaluateParsedRules"); + for (let i = 0; i < 100; i++) context.treatment("ruled"); + expect(spy).toHaveBeenCalledTimes(0); + spy.mockRestore(); + }); + + it("routes getContext() through a subclass's getUnauthed() override", async () => { + sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({ experiments: [] }) }); + const seen = []; + class LoggingClient extends Client { + getUnauthed(requestOptions) { + seen.push(requestOptions.path); + return super.getUnauthed(requestOptions); + } + } + await new LoggingClient(options).getContext(); + expect(seen).toEqual(["/context"]); + expect(sdkFetch.mock.calls[0][1].headers["X-API-Key"]).toBe("k"); + }); + describe("a released duck-typed custom client without the new getters", () => { const legacyClient = () => ({ getContext: () => Promise.resolve({ experiments: [] }), diff --git a/src/client.ts b/src/client.ts index 4d06ad2..251a7cb 100644 --- a/src/client.ts +++ b/src/client.ts @@ -106,8 +106,10 @@ export default class Client { } getContext(options?: Partial) { - return this.get({ + // Routed through getUnauthed() as in 1.13.4, so a subclass overriding it is still called. + return this.getUnauthed({ ...options, + auth: options?.auth !== false, path: "/context", query: { application: this._opts.application.name, @@ -240,15 +242,11 @@ export default class Client { return tryOnce().catch((reason: Error & { _bail?: boolean }) => { console.warn(reason); - // timeout <= 0 means "no deadline": the retry budget is governed by - // `retries` alone, so the elapsed-time check below must not apply. - const hasDeadline = timeout > 0; - if (reason._bail || retries <= 0) { throw new Error(reason.message); } else if (tries >= retries) { throw new RetryError(tries, reason, url); - } else if ((hasDeadline && waited >= timeout) || reason.name === "AbortError") { + } else if (waited >= timeout || reason.name === "AbortError") { if (tryWith.timedout) { throw new TimeoutError(timeout); } @@ -257,7 +255,7 @@ export default class Client { } let delay = (1 << tries) * this._delay + 0.5 * Math.random() * this._delay; - if (hasDeadline && waited + delay > timeout) { + if (waited + delay > timeout) { delay = timeout - waited; } @@ -277,7 +275,8 @@ export default class Client { options.signal.addEventListener("abort", abort); } - const timeout = options.timeout ?? this._opts.timeout ?? 0; + // `||`, as in 1.13.4: a request timeout of 0 falls back to the client timeout rather than disabling it. + const timeout = options.timeout || this._opts.timeout || 0; const timeoutId = timeout > 0 ? setTimeout(() => { diff --git a/webpack.config.js b/webpack.config.js index 15ff2da..45ca1a5 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ const TerserPlugin = require("terser-webpack-plugin"); const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin; @@ -23,7 +24,8 @@ module.exports = function () { rules: [ { test: /\.js$/, - exclude: /node_modules/, + // rfdc >= 1.4 ships ES2015 syntax; transpile it so the bundle stays ES5 for IE 10. + exclude: /node_modules[\\/](?!rfdc[\\/])/, use: ["babel-loader"], }, ], From e109c6d0f06d1400b77ab6dd0777c2302c850614 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 12:51:51 +0000 Subject: [PATCH 05/92] fix(release): add repository for npm provenance and close review test gaps npm Trusted Publishing rejects a provenance upload whose package.json repository.url does not match the workflow repo, so add it and check it in check-release.js. Restore the 1.13.4 console diagnostic for unparsable audiences. Add tests for the per-request retry budget, the attrsSeq cache stamp, the getEnvironment guard and the package.json-derived agent version; each kills its mutant. Move the timeout change to Changed. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 +- README.md | 321 ++++++++++---------- package.json | 4 + release/1.14.0-compatibility.md | 3 +- scripts/__tests__/check-release.test.js | 9 +- scripts/check-release.js | 14 +- src/__tests__/context.test.js | 4 +- src/__tests__/release-compatibility.test.js | 102 +++++++ src/matcher.ts | 4 +- 9 files changed, 309 insertions(+), 163 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a7fede7..e5bd557 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,8 @@ - Semantic-version expression operators (`semver_eq/gt/gte/lt/lte`) and `Evaluator.versionCompare`; old expression operators keep their conversion rules. - Optional `includeSystemAttributes` publishes `sdk_name` and `sdk_version` only. -- Tag-driven npm Trusted Publishing and a manual publish dry run. +- Tag-driven npm Trusted Publishing and a manual publish dry run, plus a + `repository` field in `package.json`, which npm provenance requires. ### Changed @@ -41,6 +42,11 @@ - Shared variable keys retain experiment-id priority and fall through unassigned experiments or variants missing the key; peek queues no exposures. The existing `variableKeys()` map-of-lists return shape is unchanged. +- A per-request `timeout` now also bounds the retry budget; 1.13.4 always used the + client timeout for it. Affected: callers passing a per-request `timeout` that + differs from the client one, who now get more (or fewer) retries to match it. + `timeout: 0` keeps its 1.13.4 meaning: a request value of 0 falls back to the + client timeout, and a client timeout of 0 means no retries. ### Fixed @@ -50,9 +56,6 @@ promises or lose/duplicate successfully delivered events. - Malformed variant configs are isolated rather than failing the entire context; audience evaluation exceptions fail strict audiences closed. -- A per-request `timeout` now also bounds the retry budget (previously only the - client timeout did). A `timeout` of 0 keeps its 1.13.4 meaning: a request value - of 0 falls back to the client timeout, and a client timeout of 0 means no retries. - The browser bundle is ES5 again (IE 10): `rfdc` >= 1.4 ships ES2015 syntax, so it is now transpiled, and the build fails if `dist/` is not ES5. - Query keys are encoded and unmatched query surrogates no longer throw URIError. diff --git a/README.md b/README.md index b8ad077..bc8e9da 100644 --- a/README.md +++ b/README.md @@ -48,52 +48,54 @@ This example assumes an API Key, an Application, and an Environment have been cr ```javascript const sdk = new absmartly.SDK({ - endpoint: "https://your-company.absmartly.io/v1", - apiKey: process.env.ABSMARTLY_API_KEY, - environment: process.env.NODE_ENV, - application: process.env.APPLICATION_NAME, + endpoint: "https://your-company.absmartly.io/v1", + apiKey: process.env.ABSMARTLY_API_KEY, + environment: process.env.NODE_ENV, + application: process.env.APPLICATION_NAME, }); ``` The `application` option can also be an object with `name` and `version` to track which version of your application is generating events. The configured version can be a number or a string. The collector accepts only 1–18 ASCII digits in `X-Application-Version`; other values are sent as `0`. The getter retains the original configured value: + ```javascript const sdk = new absmartly.SDK({ - endpoint: 'https://sandbox.absmartly.io/v1', - apiKey: process.env.ABSMARTLY_API_KEY, - environment: process.env.NODE_ENV, - application: { name: 'website', version: '1.2.3' }, + endpoint: "https://sandbox.absmartly.io/v1", + apiKey: process.env.ABSMARTLY_API_KEY, + environment: process.env.NODE_ENV, + application: { name: "website", version: "1.2.3" }, }); ``` **SDK Options** -| Option | Type | Required? | Default | Description | -| :----------- | :--------- | :-------: | :-----: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| endpoint | `string` | ✅ | `null` | The URL to your API endpoint. Most commonly `"your-company.absmartly.io"` | -| apiKey | `string` | ✅ | `null` | Your API key which can be found on the Web Console. | -| environment | `string` | ✅ | `null` | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. | -| application | `string` | ✅ | `null` | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running.| -| retries | `number` | ❌ | `5` | Number of retry attempts for failed HTTP requests. | -| timeout | `number` | ❌ | `3000` | HTTP request timeout in milliseconds. | -| eventLogger | `function` | ❌ | `null` | Callback to handle SDK events (ready, exposure, goal, etc.) | +| Option | Type | Required? | Default | Description | +| :---------- | :--------- | :-------: | :-----: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| endpoint | `string` | ✅ | `null` | The URL to your API endpoint. Most commonly `"your-company.absmartly.io"` | +| apiKey | `string` | ✅ | `null` | Your API key which can be found on the Web Console. | +| environment | `string` | ✅ | `null` | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. | +| application | `string` | ✅ | `null` | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. | +| retries | `number` | ❌ | `5` | Number of retry attempts for failed HTTP requests. | +| timeout | `number` | ❌ | `3000` | HTTP request timeout in milliseconds. | +| eventLogger | `function` | ❌ | `null` | Callback to handle SDK events (ready, exposure, goal, etc.) | #### Creating a new Context with raw promises + ```javascript const request = { - units: { - session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", - }, + units: { + session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", + }, }; const context = sdk.createContext(request); context.ready().then(() => { - console.log("ABsmartly Context ready!"); - if (context.isFailed()) { - console.error("ABsmartly Context failed:", context.readyError()); - } + console.log("ABsmartly Context ready!"); + if (context.isFailed()) { + console.error("ABsmartly Context failed:", context.readyError()); + } - const treatment = context.treatment("exp_test"); + const treatment = context.treatment("exp_test"); }); ``` @@ -101,16 +103,16 @@ context.ready().then(() => { ```javascript const request = { - units: { - session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", - }, + units: { + session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", + }, }; const context = sdk.createContext(request); await context.ready(); if (context.isFailed()) { - console.error("ABsmartly Context failed:", context.readyError()); + console.error("ABsmartly Context failed:", context.readyError()); } const treatment = context.treatment("exp_test"); @@ -122,15 +124,15 @@ When doing full-stack experimentation with A/B Smartly, we recommend creating a ```html - + ``` @@ -140,13 +142,13 @@ For long-running single-page-applications (SPA), the context is usually created ```javascript const request = { - units: { - session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", - }, + units: { + session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", + }, }; const context = sdk.createContext(request, { - refreshPeriod: 5 * 60 * 1000, // 5 minutes + refreshPeriod: 5 * 60 * 1000, // 5 minutes }); ``` @@ -154,11 +156,11 @@ Alternatively, the `refresh()` method can be called manually. The `refresh()` me ```javascript setTimeout(async () => { - try { - await context.refresh(); - } catch (error) { - console.error(error); - } + try { + await context.refresh(); + } catch (error) { + console.error(error); + } }, 5 * 60 * 1000); ``` @@ -174,7 +176,7 @@ The `unit()` and `units()` methods can be called before the context is ready. context.unit("db_user_id", 1000013); context.units({ - db_user_id: 1000013, + db_user_id: 1000013, }); ``` @@ -183,32 +185,35 @@ context.units({ ### Selecting a Treatment #### Including system attributes + You can opt in to also send the SDK name and version with every publish. These are sent as context attributes and can be useful for debugging and filtering in the Web Console. To enable this, set the `includeSystemAttributes` option to `true` when creating the context: + ```javascript const context = sdk.createContext(request, { - includeSystemAttributes: true, + includeSystemAttributes: true, }); ``` When enabled, the following attributes are prepended to the publish request payload: -| Attribute | Description | -|:--- |---| -| `sdk_name` | The SDK agent name (e.g. `"absmartly-javascript-sdk"`) | -| `sdk_version` | The SDK version (e.g. `"1.14.0"`) | +| Attribute | Description | +| :------------ | ------------------------------------------------------------- | +| `sdk_name` | The SDK agent name (e.g. `"absmartly-javascript-sdk/1.14.0"`) | +| `sdk_version` | The SDK version (e.g. `"1.14.0"`) | Their `setAt` is the time of the earliest exposure or goal in the publish, so they apply to every event in it. A system attribute is not sent when you set an attribute with the same name yourself, so your value is kept. The application and environment names are not part of this option: the collector already adds them to every event, and the SDK always uses them for audiences (see [Context Attributes](#context-attributes)). #### Selecting a treatment + ```javascript if (context.treatment("exp_test_experiment") === 0) { - // user is in control group (variant 0) + // user is in control group (variant 0) } else { - // user is in treatment group + // user is in treatment group } ``` @@ -227,9 +232,9 @@ Although generally not recommended, it is sometimes necessary to peek at a treat ```javascript if (context.peek("exp_test_experiment") === 0) { - // user is in control group (variant 0) + // user is in control group (variant 0) } else { - // user is in treatment group + // user is in treatment group } ``` @@ -247,8 +252,8 @@ During development, it is useful to force a treatment for an experiment. This ca context.override("exp_test_experiment", 1); // force variant 1 context.overrides({ - exp_test_experiment: 1, - exp_another_experiment: 0, + exp_test_experiment: 1, + exp_another_experiment: 0, }); ``` @@ -262,7 +267,7 @@ Attributes are used to pass meta-data about the user and/or the request. They ca context.attribute("user_agent", navigator.userAgent); context.attributes({ - customer_age: "new_customer", + customer_age: "new_customer", }); ``` @@ -280,7 +285,7 @@ Sometimes it may be necessary to override the automatic selection of a variant. context.customAssignment("exp_test_experiment", 1); context.customAssignments({ - exp_test_experiment: 1, + exp_test_experiment: 1, }); ``` @@ -297,34 +302,38 @@ context.track("payment", { item_count: 1, total_amount: 1999.99 }); Sometimes it is necessary to ensure all events have been published to the A/B Smartly collector, before proceeding. One such case is when the user is about to navigate away right before being exposed to a treatment. You can explicitly call the `publish()` method, which returns a promise, before navigating away. + ```javascript await context.publish().then(() => { - window.location = "https://www.absmartly.com" -}) + window.location = "https://www.absmartly.com"; +}); ``` #### Finalizing + The `finalize()` method will ensure all events have been published to the A/B Smartly collector, like `publish()`, and will also "seal" the context, throwing an error if any method that could generate an event is called. + ```javascript await context.finalize().then(() => { - window.location = "https://www.absmartly.com" -}) + window.location = "https://www.absmartly.com"; +}); ``` #### Refreshing the context with fresh experiment data + For long-running single-page-applications (SPA), the context is usually created once when the application is first reached. However, any experiments being tracked in your production code, but started after the context was created, will not be triggered. To mitigate this, we can use the `refreshPeriod` option when creating the context. ```javascript const request = { - units: { - session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8', - }, + units: { + session_id: "5ebf06d8cb5d8137290c4abb64155584fbdb64d8", + }, }; const context = sdk.createContext(request, { - refreshPeriod: 5 * 60 * 1000 + refreshPeriod: 5 * 60 * 1000, }); ``` @@ -334,15 +343,15 @@ The A/B Smartly SDK can be instantiated with an event logger used for all contex ```javascript const sdk = new absmartly.SDK({ - endpoint: "https://your-company.absmartly.io/v1", - apiKey: process.env.ABSMARTLY_API_KEY, - environment: process.env.NODE_ENV, - application: process.env.APPLICATION_NAME, - eventLogger: (context, eventName, data) => { - if (eventName === "error") { - console.error(data); - } - }, + endpoint: "https://your-company.absmartly.io/v1", + apiKey: process.env.ABSMARTLY_API_KEY, + environment: process.env.NODE_ENV, + application: process.env.APPLICATION_NAME, + eventLogger: (context, eventName, data) => { + if (eventName === "error") { + console.error(data); + } + }, }); ``` @@ -350,15 +359,15 @@ const sdk = new absmartly.SDK({ The data parameter depends on the type of event. Currently, the SDK logs the following events: -| Event | When | Data | -| :----------- | :------------------------------------------------ | :-------------------------------------------- | -| `"error"` | Context receives an error | Error object thrown | -| `"ready"` | Context turns ready | Data used to initialize the context | -| `"refresh"` | `refresh()` method succeeds | Data used to refresh the context | -| `"publish"` | `publish()` method succeeds | Data sent to the A/B Smartly event collector | -| `"exposure"` | `treatment()` method succeeds on first exposure | Exposure data enqueued for publishing | -| `"goal"` | `track()` method succeeds | Goal data enqueued for publishing | -| `"finalize"` | `finalize()` method succeeds the first time | undefined | +| Event | When | Data | +| :----------- | :---------------------------------------------- | :------------------------------------------- | +| `"error"` | Context receives an error | Error object thrown | +| `"ready"` | Context turns ready | Data used to initialize the context | +| `"refresh"` | `refresh()` method succeeds | Data used to refresh the context | +| `"publish"` | `publish()` method succeeds | Data sent to the A/B Smartly event collector | +| `"exposure"` | `treatment()` method succeeds on first exposure | Exposure data enqueued for publishing | +| `"goal"` | `track()` method succeeds | Goal data enqueued for publishing | +| `"finalize"` | `finalize()` method succeeds the first time | undefined | ### HTTP Request Timeout @@ -367,11 +376,15 @@ It is possible to set a timeout per individual HTTP request, overriding the glob Here is an example of setting a timeout only for the `createContext` request. ```javascript -const context = sdk.createContext(request, { - refreshPeriod: 5 * 60 * 1000 -}, { - timeout: 1500, -}); +const context = sdk.createContext( + request, + { + refreshPeriod: 5 * 60 * 1000, + }, + { + timeout: 1500, + } +); ``` ### HTTP Request Cancellation @@ -382,11 +395,15 @@ Here is an example of a cancellation scenario. ```javascript const controller = new absmartly.AbortController(); -const context = sdk.createContext(request, { - refreshPeriod: 5 * 60 * 1000 -}, { - signal: controller.signal, -}); +const context = sdk.createContext( + request, + { + refreshPeriod: 5 * 60 * 1000, + }, + { + signal: controller.signal, + } +); // abort request if not ready after 1500ms const timeoutId = setTimeout(() => controller.abort(), 1500); @@ -404,36 +421,36 @@ clearTimeout(timeoutId); const absmartly = require("@absmartly/javascript-sdk"); const sdk = new absmartly.SDK({ - endpoint: "https://your-company.absmartly.io/v1", - apiKey: process.env.ABSMARTLY_API_KEY, - environment: "production", - application: "website", + endpoint: "https://your-company.absmartly.io/v1", + apiKey: process.env.ABSMARTLY_API_KEY, + environment: "production", + application: "website", }); app.use(async (req, res, next) => { - const context = sdk.createContext({ - units: { - session_id: req.cookies.session_id, - }, - }); - - await context.ready(); - if (context.isFailed()) { - console.error("ABsmartly context failed:", context.readyError()); - } - req.absmartly = context; - next(); + const context = sdk.createContext({ + units: { + session_id: req.cookies.session_id, + }, + }); + + await context.ready(); + if (context.isFailed()) { + console.error("ABsmartly context failed:", context.readyError()); + } + req.absmartly = context; + next(); }); app.get("/landing", (req, res) => { - const context = req.absmartly; - const treatment = context.treatment("exp_landing_page"); - - if (treatment === 0) { - res.render("landing-control"); - } else { - res.render("landing-treatment"); - } + const context = req.absmartly; + const treatment = context.treatment("exp_landing_page"); + + if (treatment === 0) { + res.render("landing-control"); + } else { + res.render("landing-treatment"); + } }); ``` @@ -443,29 +460,26 @@ Create the context on the server and pass the data to the client to avoid a seco ```javascript app.get("/", async (req, res) => { - const context = sdk.createContext({ - units: { session_id: req.cookies.session_id }, - }); + const context = sdk.createContext({ + units: { session_id: req.cookies.session_id }, + }); - await context.ready(); + await context.ready(); - const contextData = context.data(); - const treatment = context.treatment("exp_homepage"); + const contextData = context.data(); + const treatment = context.treatment("exp_homepage"); - res.render("index", { - treatment, - absmartlyData: JSON.stringify(contextData), - }); + res.render("index", { + treatment, + absmartlyData: JSON.stringify(contextData), + }); }); ``` On the client side, initialize the context with the pre-fetched data: ```javascript -const context = sdk.createContextWith( - { units: { session_id: sessionId } }, - JSON.parse(window.__ABSMARTLY_DATA__) -); +const context = sdk.createContextWith({ units: { session_id: sessionId } }, JSON.parse(window.__ABSMARTLY_DATA__)); // context is immediately ready, no round-trip needed ``` @@ -477,24 +491,24 @@ const context = sdk.createContextWith( import absmartly from "@absmartly/javascript-sdk"; const sdk = new absmartly.SDK({ - endpoint: "https://your-company.absmartly.io/v1", - apiKey: "YOUR_API_KEY", - environment: "production", - application: "website", - eventLogger: (context, eventName, data) => { - if (eventName === "exposure") { - analytics.track("Experiment Viewed", { - experiment: data.name, - variant: data.variant, - }); - } - }, + endpoint: "https://your-company.absmartly.io/v1", + apiKey: "YOUR_API_KEY", + environment: "production", + application: "website", + eventLogger: (context, eventName, data) => { + if (eventName === "exposure") { + analytics.track("Experiment Viewed", { + experiment: data.name, + variant: data.variant, + }); + } + }, }); const context = sdk.createContext({ - units: { - session_id: getUserSessionId(), - }, + units: { + session_id: getUserSessionId(), + }, }); await context.ready(); @@ -502,13 +516,13 @@ await context.ready(); const showNewFeature = context.treatment("exp_new_feature") !== 0; if (showNewFeature) { - renderNewFeature(); + renderNewFeature(); } else { - renderOldFeature(); + renderOldFeature(); } document.getElementById("checkout-btn").addEventListener("click", () => { - context.track("checkout", { total: getCartTotal() }); + context.track("checkout", { total: getCartTotal() }); }); ``` @@ -533,6 +547,7 @@ releases; this release changes only this repository's documentation. **A/B Smartly** is the leading provider of state-of-the-art, on-premises, full-stack experimentation platforms for engineering and product teams that want to confidently deploy features as fast as they can develop them. A/B Smartly's real-time analytics helps engineering and product teams ensure that new features will improve the customer experience without breaking or degrading performance and/or business metrics. ### Have a look at our growing list of clients and SDKs: + - [JavaScript SDK](https://www.github.com/absmartly/javascript-sdk) (this package) - [React SDK](https://www.github.com/absmartly/react-sdk) - [Vue2 SDK](https://www.github.com/absmartly/vue2-sdk) diff --git a/package.json b/package.json index c6062b4..e5fd050 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,10 @@ "description": "A/B Smartly Javascript SDK", "homepage": "https://github.com/absmartly/javascript-sdk#README.md", "bugs": "https://github.com/absmartly/javascript-sdk/issues", + "repository": { + "type": "git", + "url": "git+https://github.com/absmartly/javascript-sdk.git" + }, "keywords": [ "absmartly", "ab-smartly", diff --git a/release/1.14.0-compatibility.md b/release/1.14.0-compatibility.md index 33a0109..251f1c5 100644 --- a/release/1.14.0-compatibility.md +++ b/release/1.14.0-compatibility.md @@ -48,7 +48,8 @@ This inventories public source/runtime differences, not just this PR's delta. | Abort shim reason/onabort/optional abort reason and idempotence | a/c | Keep native-standard cancellation bug fixes; no required method argument. | | Fetch global detection and clear no-fetch error | c | Keep fallback selection fix (old no-global environment was unusable). | | Query key escaping and malformed-surrogate normalization | c | Keep encoding fixes; ordinary URL values unchanged. | -| Per-request timeout/retry budget | c | Keep: a per-request timeout now bounds retries too. | +| Per-request timeout bounds the retry budget (1.13.4 used the client timeout) | c | Keep; listed under Changed with who is affected, and covered by a mutant-killing test. | +| Invalid audience JSON stopped logging `console.error` | d | Restore the 1.13.4 console diagnostic; no logger `error` event. | | Main made `timeout: 0` mean "no deadline" (request) and "retry forever" (client) | d | Restore 1.13.4: request 0 falls back to the client timeout, client 0 means no retries. Measured: main hangs > 8 s where 1.13.4 fails at ~3 s. | | `getContext()` called `get()` directly, skipping a subclass `getUnauthed()` override | d | Route through `getUnauthed()` again, keeping the GET headers. | | `rfdc` 1.4.1 (lockfile) puts ES2015 syntax into the browser bundle | d | Transpile rfdc in webpack; `scripts/check-es5.js` fails the build if `dist/` is not ES5. | diff --git a/scripts/__tests__/check-release.test.js b/scripts/__tests__/check-release.test.js index 463bb2b..fe2463f 100644 --- a/scripts/__tests__/check-release.test.js +++ b/scripts/__tests__/check-release.test.js @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/no-var-requires, no-shadow */ /* global BigInt */ -const { majorOf, releaseTag } = require("../check-release"); +const { majorOf, releaseTag, checkRepository } = require("../check-release"); +const pkg = require("../../package.json"); test("uses a non-semver lts tag for older major releases", () => { expect(releaseTag("1.14.0", "2.0.0", "v1.14.0")).toBe("v1-lts"); @@ -33,3 +34,9 @@ test("refuses an older same-major release instead of moving latest back", () => expect(() => releaseTag("1.14.0", "1.14.0", "v1.14.0")).toThrow(/not newer than latest/); expect(releaseTag("1.14.1", "2.0.0", "v1.14.1")).toBe("v1-lts"); }); + +test("package.json repository matches this repo, as npm provenance requires", () => { + expect(() => checkRepository(pkg.repository, "absmartly/javascript-sdk")).not.toThrow(); + expect(() => checkRepository(undefined, "absmartly/javascript-sdk")).toThrow(/repository.url/); + expect(() => checkRepository(pkg.repository, "someone/fork")).toThrow(/repository.url/); +}); diff --git a/scripts/check-release.js b/scripts/check-release.js index 212533f..7d48139 100644 --- a/scripts/check-release.js +++ b/scripts/check-release.js @@ -2,7 +2,7 @@ /* global BigInt */ const { execFileSync } = require("child_process"); const { appendFileSync } = require("fs"); -const { name, version } = require("../package.json"); +const { name, version, repository } = require("../package.json"); // npm distribution tags cannot be valid semver ranges, so use v1-lts rather // than v1 for older majors. Reject malformed versions instead of guessing. @@ -46,12 +46,22 @@ function releaseTag(packageVersion, latestVersion, gitTag) { return "latest"; } +// npm provenance requires package.json repository.url to name the repository the workflow runs in. +function checkRepository(repo, githubRepository) { + const url = repo && typeof repo === "object" ? repo.url : repo; + const match = typeof url === "string" && /github\.com[/:]([^/]+\/[^/]+?)(?:\.git)?$/.exec(url); + if (!match || !githubRepository || match[1].toLowerCase() !== githubRepository.toLowerCase()) { + throw new Error(`package.json repository.url must point at github.com/${githubRepository}`); + } +} + function main() { const event = process.env.GITHUB_EVENT_NAME; if (event !== "push" && event !== "workflow_dispatch") { throw new Error("Unsupported workflow event"); } const gitTag = event === "push" ? process.env.GITHUB_REF_NAME : `v${version}`; + checkRepository(repository, process.env.GITHUB_REPOSITORY); // Check the tag before making a registry request. majorOf(version); if (gitTag !== `v${version}`) { @@ -90,4 +100,4 @@ if (require.main === module) { } } -module.exports = { majorOf, releaseTag }; +module.exports = { majorOf, releaseTag, checkRepository }; diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 4706d0d..da19bc7 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -8702,7 +8702,8 @@ describe("Context", () => { it("should console an error when a field type is invalid", () => { const errorSpy = jest.spyOn(console, "error"); - const context = new Context(sdk, contextOptions, contextParams, getContextResponse); + const eventLogger = jest.fn(); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, getContextResponse); expect(context.pending()).toEqual(0); expect(context.customFieldValue("exp_test_custom_fields", "invalid_type_field")).toEqual(null); @@ -8710,6 +8711,7 @@ describe("Context", () => { expect(errorSpy).toHaveBeenCalledWith( "Unknown custom field type 'invalid' for experiment 'exp_test_custom_fields' and key 'invalid_type_field' - you may need to upgrade to the latest SDK version" ); + expect(eventLogger.mock.calls.filter(([, eventName]) => eventName === "error")).toHaveLength(0); }); }); diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 3b7ca55..7cc5e13 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -1,5 +1,6 @@ import SDK from "../sdk"; import { SDK_VERSION } from "../version"; +import pkg from "../../package.json"; import Client from "../client"; import sdkFetch from "../fetch"; import { AudienceMatcher } from "../matcher"; @@ -44,6 +45,62 @@ describe("1.13.4 source and behaviour compatibility", () => { } ); + it("bounds retries by a per-request timeout that overrides the client timeout", async () => { + sdkFetch.mockRejectedValue(new Error("connection refused")); + const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); + const client = new Client({ ...options, timeout: 20, retries: 3 }); + + // With the client's 20 ms as the retry budget (1.13.4) this gives up after 2 attempts. + // The request's own 1000 ms budget now applies, so all 3 retries run. + const error = await client.request({ method: "GET", path: "/context", timeout: 1000 }).catch((e) => e); + warn.mockRestore(); + expect(error.name).toBe("RetryError"); + expect(sdkFetch).toHaveBeenCalledTimes(4); + }); + + it("logs an unparsable audience to the console as 1.13.4 did, without a logger error event", () => { + const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); + const eventLogger = jest.fn(); + const sdk = new SDK({ ...options, eventLogger }); + const context = sdk.createContextWith( + { units: { session_id: "u1" } }, + { + experiments: [ + { + id: 9, + name: "badaud", + iteration: 1, + unitType: "session_id", + seedHi: 1, + seedLo: 2, + split: [0.5, 0.5], + trafficSeedHi: 3, + trafficSeedLo: 4, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + audience: "{not json", + audienceStrict: false, + customFieldValues: null, + }, + ], + } + ); + context.treatment("badaud"); + expect(errorSpy).toHaveBeenCalledWith(expect.any(SyntaxError)); + expect(eventLogger.mock.calls.filter(([, eventName]) => eventName === "error")).toHaveLength(0); + errorSpy.mockRestore(); + }); + + it("derives the SDK agent version from package.json, not a literal", () => { + expect(SDK_VERSION).toBe(pkg.version); + expect(new SDK(options).getClient().getAgent()).toBe(`absmartly-javascript-sdk/${pkg.version}`); + }); + it("preserves explicit custom agents and the unauthenticated helper", async () => { sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({}) }); const client = new Client({ ...options, agent: "customer-agent" }); @@ -112,6 +169,40 @@ describe("1.13.4 source and behaviour compatibility", () => { spy.mockRestore(); }); + it("evaluates an audience once after an unrelated setAttribute, not on every cached read", () => { + const sdk = new SDK(options); + const experiment = { + id: 8, + name: "aud", + iteration: 1, + unitType: "session_id", + seedHi: 1, + seedLo: 2, + split: [0.5, 0.5], + trafficSeedHi: 3, + trafficSeedLo: 4, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + audience: JSON.stringify({ filter: [{ eq: [{ var: "country" }, { value: "US" }] }] }), + audienceStrict: false, + customFieldValues: null, + }; + const context = sdk.createContextWith({ units: { session_id: "u1" } }, { experiments: [experiment] }); + context.attribute("country", "US"); + const first = context.treatment("aud"); + context.attribute("plan", "pro"); + + const spy = jest.spyOn(AudienceMatcher.prototype, "evaluate"); + for (let i = 0; i < 100; i++) expect(context.treatment("aud")).toBe(first); + expect(spy).toHaveBeenCalledTimes(1); + spy.mockRestore(); + }); + it("routes getContext() through a subclass's getUnauthed() override", async () => { sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({ experiments: [] }) }); const seen = []; @@ -153,6 +244,17 @@ describe("1.13.4 source and behaviour compatibility", () => { customFieldValues: null, }; + it("still evaluates audiences when only getApplication exists", () => { + const client = { ...legacyClient(), getApplication: () => ({ name: "web", version: 0 }) }; + const sdk = new SDK({ ...options, client }); + const context = sdk.createContextWith( + { units: { session_id: "e791e240fcd3df7d238cfc285f475e8152fcc0ec" } }, + { experiments: [strictCountryExperiment] } + ); + context.attribute("country", "US"); + expect(context.treatment("exp")).toBe(1); + }); + it("still evaluates audiences", () => { const sdk = new SDK({ ...options, client: legacyClient() }); const context = sdk.createContextWith( diff --git a/src/matcher.ts b/src/matcher.ts index 82bff09..2433454 100644 --- a/src/matcher.ts +++ b/src/matcher.ts @@ -35,7 +35,9 @@ export class AudienceMatcher { let audience; try { audience = JSON.parse(audienceString); - } catch (_error) { + } catch (error) { + // 1.13.4 logged unparsable audiences to the console; keep that diagnostic. + console.error(error); return null; } From c9654892b9d49e9607b5ca7fcf7798e6aa5c4241 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 15:53:42 +0000 Subject: [PATCH 06/92] fix(release): restore null-timeout retries and the no-rule read path A client timeout of null or undefined again falls back to the default retry budget, as in 1.13.4, instead of disabling retries. The attribute map is built only for experiments with assignment rules, so ordinary reads after setAttribute no longer rebuild it. Audience-exception handling moves to Changed with who is affected. Tests kill each mutant, including a hardcoded generated version. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +- src/__tests__/release-compatibility.test.js | 74 +++++++++++++++++++++ src/client.ts | 3 +- src/context.ts | 8 +-- 4 files changed, 85 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e5bd557..8c8a777 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,10 @@ differs from the client one, who now get more (or fewer) retries to match it. `timeout: 0` keeps its 1.13.4 meaning: a request value of 0 falls back to the client timeout, and a client timeout of 0 means no retries. +- An audience whose evaluation throws now counts as a mismatch (fail closed) and + emits one logger `error` event; 1.13.4 treated it as a match. Affected: strict + audiences move such units to control (variant 0); non-strict exposures publish + `audienceMismatch: true` instead of `false`. ### Fixed @@ -55,7 +59,7 @@ - Custom publisher failures and throwing event loggers no longer strand lifecycle promises or lose/duplicate successfully delivered events. - Malformed variant configs are isolated rather than failing the entire context; - audience evaluation exceptions fail strict audiences closed. + audience evaluation exceptions are logged instead of thrown. - The browser bundle is ES5 again (IE 10): `rfdc` >= 1.4 ships ES2015 syntax, so it is now transpiled, and the build fails if `dist/` is not ES5. - Query keys are encoded and unmatched query surrogates no longer throw URIError. diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 7cc5e13..52f550d 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -1,6 +1,10 @@ import SDK from "../sdk"; import { SDK_VERSION } from "../version"; import pkg from "../../package.json"; +import fs from "fs"; +import os from "os"; +import path from "path"; +import { execFileSync } from "child_process"; import Client from "../client"; import sdkFetch from "../fetch"; import { AudienceMatcher } from "../matcher"; @@ -10,6 +14,10 @@ jest.mock("../fetch"); const options = { endpoint: "https://collector/v1", apiKey: "k", application: "web", environment: "prod" }; describe("1.13.4 source and behaviour compatibility", () => { + beforeEach(() => { + sdkFetch.mockReset(); + }); + it("keeps the live units map and released error strings", async () => { const sdk = new SDK(options); const context = sdk.createContextWith({ units: { user: "one" } }, { experiments: [] }); @@ -96,6 +104,72 @@ describe("1.13.4 source and behaviour compatibility", () => { errorSpy.mockRestore(); }); + it("does not build the attribute map on the no-rule, no-audience path after setAttribute", () => { + const sdk = new SDK(options); + const plain = { + id: 10, + name: "plain", + iteration: 1, + unitType: "session_id", + seedHi: 1, + seedLo: 2, + split: [0.5, 0.5], + trafficSeedHi: 3, + trafficSeedLo: 4, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + audience: null, + audienceStrict: false, + customFieldValues: null, + }; + const context = sdk.createContextWith({ units: { session_id: "u1" } }, { experiments: [plain] }); + const first = context.treatment("plain"); + + const spy = jest.spyOn(context, "_getAttributesMap"); + for (let i = 0; i < 50; i++) { + context.attribute(`a${i}`, i); + for (let j = 0; j < 5; j++) expect(context.treatment("plain")).toBe(first); + } + expect(spy).toHaveBeenCalledTimes(0); + spy.mockRestore(); + }); + + it.each([undefined, null])("retries like 1.13.4 when the client timeout is %p", async (timeout) => { + sdkFetch.mockResolvedValue({ + ok: false, + status: 503, + statusText: "Unavailable", + text: () => Promise.resolve(""), + }); + const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); + const client = new Client({ ...options, timeout, retries: 2 }); + const error = await client.request({ method: "GET", path: "/context" }).catch((e) => e); + warn.mockRestore(); + expect(error.name).toBe("RetryError"); + expect(sdkFetch).toHaveBeenCalledTimes(3); + }); + + it("generates the SDK version from package.json, so a hardcoded version cannot pass", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "sdk-version-")); + fs.mkdirSync(path.join(dir, "scripts")); + fs.mkdirSync(path.join(dir, "src")); + fs.copyFileSync( + path.join(__dirname, "../../scripts/generate-version.js"), + path.join(dir, "scripts/generate-version.js") + ); + fs.writeFileSync(path.join(dir, "package.json"), JSON.stringify({ version: "9.8.7-fixture.1" })); + execFileSync(process.execPath, [path.join(dir, "scripts/generate-version.js")]); + expect(fs.readFileSync(path.join(dir, "src/version.ts"), "utf8")).toBe( + 'export const SDK_VERSION = "9.8.7-fixture.1";\n' + ); + fs.rmSync(dir, { recursive: true, force: true }); + }); + it("derives the SDK agent version from package.json, not a literal", () => { expect(SDK_VERSION).toBe(pkg.version); expect(new SDK(options).getClient().getAgent()).toBe(`absmartly-javascript-sdk/${pkg.version}`); diff --git a/src/client.ts b/src/client.ts index 251a7cb..2a49b02 100644 --- a/src/client.ts +++ b/src/client.ts @@ -292,7 +292,8 @@ export default class Client { } }; - return tryWith(this._opts.retries ?? DEFAULT_RETRIES, timeout) + // The retry budget falls back to the default when the client timeout is null/undefined, as in 1.13.4. + return tryWith(this._opts.retries ?? DEFAULT_RETRIES, options.timeout || (this._opts.timeout ?? DEFAULT_TIMEOUT_MS)) .then((value: string) => { finalCleanUp(); return value; diff --git a/src/context.ts b/src/context.ts index 68026a1..99fc045 100644 --- a/src/context.ts +++ b/src/context.ts @@ -621,9 +621,10 @@ export default class Context { } if (this._attrsSeq > (assignment.attrsSeq ?? 0) || ruleKeyChanged) { - const attrs = this._getAttributesMap(); - if (experiment.assignmentRules && experiment.assignmentRules.length > 0) { + // Built only when there are rules: the no-rule path must not rebuild the attribute map + // after every setAttribute (1.13.4 never built it there). + const attrs = this._getAttributesMap(); // An exposed split resolved without its unit keeps resolving as if the unit were still // missing, so a unit set afterwards cannot switch the variant the user already saw. const isUnitPinnedMissing = assignment.exposed && assignment.isRuleMissingUnit === true; @@ -767,7 +768,6 @@ export default class Context { } else { if (experiment != null) { const unitType = experiment.data.unitType; - const attrs = this._getAttributesMap(); // Set even when suppressed, or `audienceMatches` rebuilds (losing `exposed`) on every call. assignment.ruleKey = experiment.data.assignmentRules @@ -776,7 +776,7 @@ export default class Context { const rule = experiment.data.assignmentRules && experiment.data.assignmentRules.length > 0 - ? this._resolveRule(experiment, attrs, false) + ? this._resolveRule(experiment, this._getAttributesMap(), false) : null; const ruleVariant = rule?.variant ?? null; From eb82c3cac76325060ee2187c1ddb6a61ce89c774 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 17:53:53 +0000 Subject: [PATCH 07/92] test(release): close the remaining review test gaps Check the default agent against a mocked SDK_VERSION, count attribute-map builds across audience experiments, and spy on the map before the first read. Each test kills the mutant the independent review found surviving. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/release-compatibility.test.js | 50 ++++++++++++++++++++- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 52f550d..ad0fee4 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -128,9 +128,8 @@ describe("1.13.4 source and behaviour compatibility", () => { customFieldValues: null, }; const context = sdk.createContextWith({ units: { session_id: "u1" } }, { experiments: [plain] }); - const first = context.treatment("plain"); - const spy = jest.spyOn(context, "_getAttributesMap"); + const first = context.treatment("plain"); for (let i = 0; i < 50; i++) { context.attribute(`a${i}`, i); for (let j = 0; j < 5; j++) expect(context.treatment("plain")).toBe(first); @@ -170,6 +169,15 @@ describe("1.13.4 source and behaviour compatibility", () => { fs.rmSync(dir, { recursive: true, force: true }); }); + it("builds the default agent from the generated SDK_VERSION, not a literal", () => { + jest.isolateModules(() => { + jest.doMock("../version", () => ({ SDK_VERSION: "9.8.7-fixture.1" })); + const IsolatedSDK = require("../sdk").default; // eslint-disable-line @typescript-eslint/no-var-requires + expect(new IsolatedSDK(options).getClient().getAgent()).toBe("absmartly-javascript-sdk/9.8.7-fixture.1"); + }); + jest.dontMock("../version"); + }); + it("derives the SDK agent version from package.json, not a literal", () => { expect(SDK_VERSION).toBe(pkg.version); expect(new SDK(options).getClient().getAgent()).toBe(`absmartly-javascript-sdk/${pkg.version}`); @@ -277,6 +285,44 @@ describe("1.13.4 source and behaviour compatibility", () => { spy.mockRestore(); }); + it("builds the attribute map once per setAttribute across audience experiments", () => { + const audienceExperiment = (id, experimentName) => ({ + id, + name: experimentName, + iteration: 1, + unitType: "session_id", + seedHi: 1, + seedLo: 2, + split: [0.5, 0.5], + trafficSeedHi: 3, + trafficSeedLo: 4, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + audience: JSON.stringify({ filter: [{ eq: [{ var: "country" }, { value: "US" }] }] }), + audienceStrict: false, + customFieldValues: null, + }); + const sdk = new SDK(options); + const context = sdk.createContextWith( + { units: { session_id: "u1" } }, + { experiments: [audienceExperiment(11, "aud1"), audienceExperiment(12, "aud2")] } + ); + context.treatment("aud1"); + context.treatment("aud2"); + context.attribute("country", "US"); + + const spy = jest.spyOn(context, "_getSystemAttributes"); + context.treatment("aud1"); + context.treatment("aud2"); + expect(spy).toHaveBeenCalledTimes(1); + spy.mockRestore(); + }); + it("routes getContext() through a subclass's getUnauthed() override", async () => { sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({ experiments: [] }) }); const seen = []; From 791d2111e177592f5409f469d6946438b250ad4f Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 18:55:36 +0000 Subject: [PATCH 08/92] fix(release): pass explicitly undefined SDK client options through, as 1.13.4 did Main dropped options set to undefined before they reached the Client, so agent: undefined silently used the default and timeout/keepalive changed meaning. Pass every present key through again and test it. Co-Authored-By: Claude Opus 5.5 --- release/1.14.0-compatibility.md | 1 + src/__tests__/sdk.test.js | 23 +++++++++++++++++++++++ src/sdk.ts | 4 +++- 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/release/1.14.0-compatibility.md b/release/1.14.0-compatibility.md index 251f1c5..7ce34ce 100644 --- a/release/1.14.0-compatibility.md +++ b/release/1.14.0-compatibility.md @@ -30,6 +30,7 @@ This inventories public source/runtime differences, not just this PR's delta. | Shared variable resolution/id ordering/map-of-lists | b | Keep; released return shape unchanged. | | GET SDK auth/metadata headers | b | Keep; preserve query parameters. | | Low-level `Client` auth rules: `request()` authenticated by default, `post`/`put` honoured `auth:false`, `getUnauthed` became authenticated | d | Restore 1.13.4 rules exactly: `request()` sends headers only with `auth: true`, `post`/`put` always authenticate, `getUnauthed` is a plain GET. The additive `get()` (used by `getContext`) authenticates unless `auth: false`. | +| `SDK` dropped client options passed as explicit `undefined` (`agent`, `timeout`, `keepalive`) | d | Restore 1.13.4 pass-through of every present key; `agent: undefined` again reaches the Client and is rejected. | | Versioned SDK X-Agent | b | Add from generated package version; custom agent untouched. Direct `Client` default remains `javascript-client`. | | String application version accepted; utility return widened | a/d | Keep strings; overload `getApplicationVersion` so old numeric callers still receive `number` statically. | | Invalid/dotted application versions sent to collector Long header | c/b | Normalize GET and PUT to trimmed 1–18 ASCII digits or zero; retain full configured getter. | diff --git a/src/__tests__/sdk.test.js b/src/__tests__/sdk.test.js index 035c6c4..3852840 100644 --- a/src/__tests__/sdk.test.js +++ b/src/__tests__/sdk.test.js @@ -101,6 +101,29 @@ describe("SDK", () => { done(); }); + it("should pass explicitly undefined client options through, as 1.13.4 did", (done) => { + const options = { + application: "application", + apiKey: "apikey", + endpoint: "localhost:8080", + environment: "test", + agent: undefined, + timeout: undefined, + keepalive: undefined, + }; + + new SDK(options); // eslint-disable-line no-new + + const passed = Client.mock.calls[Client.mock.calls.length - 1][0]; + expect(Object.prototype.hasOwnProperty.call(passed, "agent")).toBe(true); + expect(passed.agent).toBeUndefined(); + expect(Object.prototype.hasOwnProperty.call(passed, "timeout")).toBe(true); + expect(Object.prototype.hasOwnProperty.call(passed, "keepalive")).toBe(true); + expect(Object.prototype.hasOwnProperty.call(passed, "retries")).toBe(false); + + done(); + }); + it("should set default values for unspecified client options", (done) => { const options = { application: "application", diff --git a/src/sdk.ts b/src/sdk.ts index cae2a65..834934b 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -58,8 +58,10 @@ export default class SDK { agent: `absmartly-javascript-sdk/${SDK_VERSION}`, }; + // Every key present on the options is passed through, even when its value is undefined, as 1.13.4 + // did (so `agent: undefined` still overrides the default and the Client rejects it). for (const key of clientOptionKeys) { - if (options?.[key] !== undefined) { + if (options != null && Object.prototype.hasOwnProperty.call(options, key)) { extracted[key] = options[key] as never; } } From 720bd073b0d85811d7c61448002886bc53ec821a Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 19:45:35 +0000 Subject: [PATCH 09/92] fix(release): read SDK client options with 1.13.4's key set Use own enumerable keys (what Object.entries read in 1.13.4) so inherited and non-enumerable options are ignored as before, with a test that fails for both broader checks. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/sdk.test.js | 20 ++++++++++++++++++++ src/sdk.ts | 6 +++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/__tests__/sdk.test.js b/src/__tests__/sdk.test.js index 3852840..7be27cd 100644 --- a/src/__tests__/sdk.test.js +++ b/src/__tests__/sdk.test.js @@ -101,6 +101,26 @@ describe("SDK", () => { done(); }); + it("should ignore inherited and non-enumerable option keys, as 1.13.4 did", (done) => { + const base = { + application: "application", + apiKey: "apikey", + endpoint: "localhost:8080", + environment: "test", + }; + const options = Object.assign(Object.create({ timeout: 777, agent: undefined }), base); + Object.defineProperty(options, "retries", { value: 9, enumerable: false }); + + new SDK(options); // eslint-disable-line no-new + + const passed = Client.mock.calls[Client.mock.calls.length - 1][0]; + expect(Object.prototype.hasOwnProperty.call(passed, "timeout")).toBe(false); + expect(Object.prototype.hasOwnProperty.call(passed, "retries")).toBe(false); + expect(passed.agent).toBe(`absmartly-javascript-sdk/${SDK_VERSION}`); + + done(); + }); + it("should pass explicitly undefined client options through, as 1.13.4 did", (done) => { const options = { application: "application", diff --git a/src/sdk.ts b/src/sdk.ts index 834934b..b5bf794 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -58,10 +58,10 @@ export default class SDK { agent: `absmartly-javascript-sdk/${SDK_VERSION}`, }; - // Every key present on the options is passed through, even when its value is undefined, as 1.13.4 - // did (so `agent: undefined` still overrides the default and the Client rejects it). + // Every own enumerable key is passed through, even when its value is undefined: the same key set + // 1.13.4 read with Object.entries (so `agent: undefined` still overrides the default and is rejected). for (const key of clientOptionKeys) { - if (options != null && Object.prototype.hasOwnProperty.call(options, key)) { + if (options != null && Object.prototype.propertyIsEnumerable.call(options, key)) { extracted[key] = options[key] as never; } } From c81e5d6ddf34c5c42a79cd3d010147bdecbbacdf Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 18 Nov 2026 22:28:08 +0000 Subject: [PATCH 10/92] fix(release): address release review findings Serialize npm publishing, select only alpha/beta/rc/next prerelease channels, and restore browser startup without native Map/Set. Also handle live-unit and partial-client edge cases from review. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/publish.yml | 3 + package-lock.json | 176 +++++++++++++++++--- package.json | 1 + release/PUBLISHING.md | 14 +- scripts/__tests__/check-release.test.js | 87 +++++++++- scripts/check-es5.js | 20 ++- scripts/check-release.js | 11 +- scripts/compatibility/run.js | 1 + src/__tests__/release-compatibility.test.js | 46 +++++ src/browser.ts | 3 + src/client.ts | 8 +- src/context.ts | 20 ++- src/matcher.ts | 1 - 13 files changed, 339 insertions(+), 52 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 1f0193b..1cd7fc6 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -19,6 +19,9 @@ jobs: publish: runs-on: ubuntu-latest environment: npm + concurrency: + group: npm-publish-absmartly-javascript-sdk + cancel-in-progress: false steps: - name: Checkout code uses: actions/checkout@v6 diff --git a/package-lock.json b/package-lock.json index b002d2d..00c9cfa 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,6 +44,7 @@ "eslint-config-prettier": "^7.1.0", "husky": "^9.1.7", "jest": "^29.3.1", + "js-yaml": "^4.3.2", "lint-staged": "^16.4.0", "prettier": "^2.4.1", "terser-webpack-plugin": "^5.3.1", @@ -1928,6 +1929,15 @@ "node": "^10.12.0 || >=12.0.0" } }, + "node_modules/@eslint/eslintrc/node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, "node_modules/@eslint/eslintrc/node_modules/globals": { "version": "13.19.0", "resolved": "https://registry.npmjs.org/globals/-/globals-13.19.0.tgz", @@ -1952,6 +1962,19 @@ "node": ">= 4" } }, + "node_modules/@eslint/eslintrc/node_modules/js-yaml": { + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", + "dev": true, + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, "node_modules/@eslint/eslintrc/node_modules/type-fest": { "version": "0.20.2", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", @@ -2000,6 +2023,28 @@ "node": ">=8" } }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", + "dev": true, + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, "node_modules/@istanbuljs/schema": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", @@ -3599,13 +3644,10 @@ } }, "node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "dependencies": { - "sprintf-js": "~1.0.2" - } + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true }, "node_modules/array-union": { "version": "2.1.0", @@ -4735,6 +4777,15 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/eslint/node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, "node_modules/eslint/node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -4838,6 +4889,19 @@ "node": ">= 4" } }, + "node_modules/eslint/node_modules/js-yaml": { + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", + "dev": true, + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, "node_modules/eslint/node_modules/lru-cache": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", @@ -7457,13 +7521,22 @@ "dev": true }, "node_modules/js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" + "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" @@ -11476,6 +11549,15 @@ "strip-json-comments": "^3.1.1" }, "dependencies": { + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "requires": { + "sprintf-js": "~1.0.2" + } + }, "globals": { "version": "13.19.0", "resolved": "https://registry.npmjs.org/globals/-/globals-13.19.0.tgz", @@ -11491,6 +11573,16 @@ "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", "dev": true }, + "js-yaml": { + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, "type-fest": { "version": "0.20.2", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", @@ -11527,6 +11619,27 @@ "get-package-type": "^0.1.0", "js-yaml": "^3.13.1", "resolve-from": "^5.0.0" + }, + "dependencies": { + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "js-yaml": { + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + } } }, "@istanbuljs/schema": { @@ -12784,13 +12897,10 @@ } }, "argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "requires": { - "sprintf-js": "~1.0.2" - } + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true }, "array-union": { "version": "2.1.0", @@ -13555,6 +13665,15 @@ "color-convert": "^2.0.1" } }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "requires": { + "sprintf-js": "~1.0.2" + } + }, "chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -13624,6 +13743,16 @@ "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", "dev": true }, + "js-yaml": { + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, "lru-cache": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", @@ -15591,13 +15720,12 @@ "dev": true }, "js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", "dev": true, "requires": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" + "argparse": "^2.0.1" } }, "jsesc": { diff --git a/package.json b/package.json index e5fd050..2174ac5 100644 --- a/package.json +++ b/package.json @@ -80,6 +80,7 @@ "eslint-config-prettier": "^7.1.0", "husky": "^9.1.7", "jest": "^29.3.1", + "js-yaml": "^4.3.2", "lint-staged": "^16.4.0", "prettier": "^2.4.1", "terser-webpack-plugin": "^5.3.1", diff --git a/release/PUBLISHING.md b/release/PUBLISHING.md index 4ff3c75..1daf34c 100644 --- a/release/PUBLISHING.md +++ b/release/PUBLISHING.md @@ -13,6 +13,10 @@ The workflow installs Node 22 and npm 11.6.2, installs with scripts disabled, ch the registry latest major and exact tag, runs the full build/tests, inspects the package, and publishes with provenance/public access. npm rejects an already published version; it is never overwritten. A failed latest lookup fails closed. +All publish jobs, including manual dry runs, share the fixed package-wide concurrency +group `npm-publish-absmartly-javascript-sdk`, with `cancel-in-progress: false`. +Registry/tag validation and publishing run inside that same locked job, so concurrent +release tags cannot both validate against a stale `latest` and then move it backwards. `workflow_dispatch` is **always a dry run**. Its optional `use_npm_token` input uses `secrets.NPM_TOKEN` as `NODE_AUTH_TOKEN` for a fallback authentication test @@ -20,7 +24,15 @@ only. If opted in, the owner must supply that secret; it is not needed for OIDC. A manual dry run does not prove npm will accept OIDC on a real tag: the owner must retain the npm publisher configuration and approve any environment protections. -Prereleases (for example `1.15.0-beta.0`) publish under their prerelease id (`beta`), never `latest`. A stable version that is not newer than `npm latest` in the same major (for example a 1.13.x backport after 1.14.0) fails the check, so the owner chooses its tag. When this package's major is lower than `npm latest`, the workflow uses `v1-lts` +Prereleases use a bounded set of distribution channels: `alpha`, `beta`, `rc`, and +`next`. The first prerelease identifier is matched case-insensitively and normalized +to lowercase (for example `1.15.0-BETA.0` uses `beta`). Every other identifier maps +to `next`, including `latest`, `LATEST`, `v1`, and numeric identifiers. A prerelease +never publishes to `latest` or an arbitrary npm tag. + +A stable version that is not newer than `npm latest` in the same major (for example +a 1.13.x backport after 1.14.0) fails the check, so the owner chooses its tag. When +this package's major is lower than `npm latest`, the workflow uses `v1-lts` (or `v-lts`), leaving latest alone. **Owner deviation to approve:** the requested `--tag v1` is impossible: npm 11.6.2 rejects it with `Tag name must not be a valid SemVer range: v1`. `v1-lts` passes the same dry run. For 1.14.0 today, diff --git a/scripts/__tests__/check-release.test.js b/scripts/__tests__/check-release.test.js index fe2463f..05e173f 100644 --- a/scripts/__tests__/check-release.test.js +++ b/scripts/__tests__/check-release.test.js @@ -1,5 +1,8 @@ -/* eslint-disable @typescript-eslint/no-var-requires, no-shadow */ +/* eslint-disable @typescript-eslint/no-var-requires, no-shadow, no-template-curly-in-string */ /* global BigInt */ +const { readFileSync } = require("fs"); +const path = require("path"); +const yaml = require("js-yaml"); const { majorOf, releaseTag, checkRepository } = require("../check-release"); const pkg = require("../../package.json"); @@ -23,11 +26,37 @@ test("accepts valid prerelease and build metadata", () => { expect(majorOf("2.0.0-rc.1+build.5")).toBe(2n); }); -test("never puts prereleases on latest", () => { - expect(releaseTag("1.15.0-beta.0", "1.14.0", "v1.15.0-beta.0")).toBe("beta"); - expect(releaseTag("1.14.1-rc.1", "1.14.0", "v1.14.1-rc.1")).toBe("rc"); - expect(releaseTag("2.0.0-0", "1.14.0", "v2.0.0-0")).toBe("next"); -}); +test.each(["alpha", "ALPHA", "beta", "Beta", "rc", "RC", "next", "NeXt"])( + "normalizes the supported prerelease channel %s", + (id) => { + const version = `2.0.0-${id}.1+build.5`; + expect(releaseTag(version, "1.14.0", `v${version}`)).toBe(id.toLowerCase()); + } +); + +test.each(["latest", "LATEST", "v1", "V1", "0", "123", "preview", "beta1", "alpha-beta"])( + "maps unsupported prerelease channel %s to next, never latest or an invalid npm tag", + (id) => { + const version = `2.0.0-${id}.0`; + for (const latest of ["1.14.0", "2.0.0", "3.0.0"]) { + expect(releaseTag(version, latest, `v${version}`)).toBe("next"); + } + } +); + +test.each(["1.15.0", "latest", "v1", "v1.14.0", "v1.15.0\n", "v1.15.0-beta.0"])( + "rejects invalid or mismatched git tag %j", + (tag) => { + expect(() => releaseTag("1.15.0", "1.14.0", tag)).toThrow(/Git tag must match/); + } +); + +test.each(["1.15", "01.15.0", "1.15.0-01", "1.15.0-beta_1", "1.15.0\n"])( + "rejects malformed package version %j", + (version) => { + expect(() => releaseTag(version, "1.14.0", `v${version}`)).toThrow(/Invalid package version/); + } +); test("refuses an older same-major release instead of moving latest back", () => { expect(() => releaseTag("1.13.5", "1.14.0", "v1.13.5")).toThrow(/not newer than latest/); @@ -40,3 +69,49 @@ test("package.json repository matches this repo, as npm provenance requires", () expect(() => checkRepository(undefined, "absmartly/javascript-sdk")).toThrow(/repository.url/); expect(() => checkRepository(pkg.repository, "someone/fork")).toThrow(/repository.url/); }); + +describe("publish workflow", () => { + const workflow = yaml.load(readFileSync(path.join(__dirname, "../../.github/workflows/publish.yml"), "utf8")); + const job = workflow.jobs.publish; + const publishSteps = job.steps.filter((step) => /npm publish\b/.test(step.run || "")); + + test("serializes all releases with one fixed package-wide lock without cancelling a running publish", () => { + expect(Object.keys(workflow.jobs)).toEqual(["publish"]); + expect(job.concurrency).toEqual({ + group: "npm-publish-absmartly-javascript-sdk", + "cancel-in-progress": false, + }); + expect(job.environment).toBe("npm"); + }); + + test("validates the registry and tag inside the locked job before every publish", () => { + const validationIndex = job.steps.findIndex((step) => step.run === "node scripts/check-release.js"); + expect(validationIndex).toBeGreaterThanOrEqual(0); + expect(job.steps[validationIndex].id).toBe("release"); + expect(job.steps[validationIndex].if).toBeUndefined(); + expect(publishSteps).toHaveLength(3); + for (const step of publishSteps) { + expect(job.steps.indexOf(step)).toBeGreaterThan(validationIndex); + expect(step.env.DIST_TAG).toBe("${{ steps.release.outputs.dist_tag }}"); + expect(step.run).toContain('--tag "$DIST_TAG"'); + expect(step.run).toContain("--provenance --access public"); + } + }); + + test("keeps manual runs dry and token-free trusted publishing restricted to pushes", () => { + expect(workflow.on.push.tags).toEqual(["v*"]); + expect(workflow.on.workflow_dispatch.inputs.use_npm_token.default).toBe(false); + expect(workflow.permissions["id-token"]).toBe("write"); + const liveSteps = publishSteps.filter((step) => !step.run.includes("--dry-run")); + expect(liveSteps).toHaveLength(1); + expect(liveSteps[0].if).toBe("github.event_name == 'push'"); + expect(liveSteps[0].env.NODE_AUTH_TOKEN).toBeUndefined(); + const drySteps = publishSteps.filter((step) => step.run.includes("--dry-run")); + expect(drySteps.map((step) => step.if)).toEqual([ + "github.event_name == 'workflow_dispatch' && !inputs.use_npm_token", + "github.event_name == 'workflow_dispatch' && inputs.use_npm_token", + ]); + expect(drySteps[0].env.NODE_AUTH_TOKEN).toBeUndefined(); + expect(drySteps[1].env.NODE_AUTH_TOKEN).toBe("${{ secrets.NPM_TOKEN }}"); + }); +}); diff --git a/scripts/check-es5.js b/scripts/check-es5.js index 4f1b371..57910fd 100644 --- a/scripts/check-es5.js +++ b/scripts/check-es5.js @@ -1,15 +1,31 @@ /* eslint-disable @typescript-eslint/no-var-requires */ -// Fails the build when a browser bundle is not plain ES5 (the IE 10 target). const fs = require("fs"); const path = require("path"); const acorn = require("acorn"); +const vm = require("vm"); let failed = false; for (const file of ["absmartly.js", "absmartly.min.js"]) { const target = path.resolve(__dirname, "../dist", file); try { acorn.parse(fs.readFileSync(target, "utf8"), { ecmaVersion: 5 }); - console.log(`ES5 OK: dist/${file}`); + const sandbox = { + console, + setTimeout, + clearTimeout, + setInterval, + clearInterval, + Promise, + Map: undefined, + Set: undefined, + WeakMap: undefined, + WeakSet: undefined, + }; + sandbox.self = sandbox; + vm.runInNewContext(fs.readFileSync(target, "utf8"), sandbox, { timeout: 10000 }); + if (typeof sandbox.absmartly?.SDK !== "function") + throw new Error("SDK did not load without native collections"); + console.log(`ES5 and legacy startup OK: dist/${file}`); } catch (error) { console.error(`dist/${file} is not ES5: ${error.message}`); failed = true; diff --git a/scripts/check-release.js b/scripts/check-release.js index 7d48139..c9726a0 100644 --- a/scripts/check-release.js +++ b/scripts/check-release.js @@ -25,9 +25,9 @@ function compareCore(a, b) { return 0; } -// A prerelease goes to its own tag (1.15.0-beta.0 -> "beta"), never "latest". A stable release goes to -// "latest" only when it is newer than the current latest; an older major goes to v-lts, and an -// older version in the same major line (e.g. a 1.13.x backport after 1.14.0) is refused. +// Prereleases use alpha, beta, rc or next (case-insensitive), with all other ids mapped to next. +// A stable release goes to "latest" only when it is newer than the current latest; an older major +// goes to v-lts, and an older version in the same major line is refused. function releaseTag(packageVersion, latestVersion, gitTag) { const major = majorOf(packageVersion); const latestMajor = majorOf(latestVersion); @@ -36,8 +36,8 @@ function releaseTag(packageVersion, latestVersion, gitTag) { } const prerelease = packageVersion.split("+")[0].split("-").slice(1).join("-"); if (prerelease) { - const id = prerelease.split(".")[0]; - return /^[a-z][a-z0-9]*$/i.test(id) ? id.toLowerCase() : "next"; + const id = prerelease.split(".")[0].toLowerCase(); + return ["alpha", "beta", "rc", "next"].includes(id) ? id : "next"; } if (major < latestMajor) return `v${major}-lts`; if (compareCore(packageVersion, latestVersion) <= 0) { @@ -62,7 +62,6 @@ function main() { } const gitTag = event === "push" ? process.env.GITHUB_REF_NAME : `v${version}`; checkRepository(repository, process.env.GITHUB_REPOSITORY); - // Check the tag before making a registry request. majorOf(version); if (gitTag !== `v${version}`) { throw new Error("Git tag must match v"); diff --git a/scripts/compatibility/run.js b/scripts/compatibility/run.js index 78293e9..8c71ead 100644 --- a/scripts/compatibility/run.js +++ b/scripts/compatibility/run.js @@ -14,6 +14,7 @@ function usage() { Package arguments are directories containing package.json, built JS and declarations. Example: npm pack @absmartly/javascript-sdk@1.13.4 --ignore-scripts mkdir -p /tmp/sdk-baseline && tar -xzf absmartly-javascript-sdk-1.13.4.tgz -C /tmp/sdk-baseline + npm install --prefix /tmp/sdk-baseline/package --omit=dev --ignore-scripts node scripts/compatibility/run.js /tmp/sdk-baseline/package . --report /tmp/sdk-compat.json By default, three pinned TypeScript versions are installed into a temporary directory diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index ad0fee4..c9dfb4e 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -337,6 +337,38 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(sdkFetch.mock.calls[0][1].headers["X-API-Key"]).toBe("k"); }); + it("invalidates a cached missing-unit assignment when the live units map gains the unit", () => { + const sdk = new SDK(options); + const holdout = { id: 99, name: "h", iteration: 1, unitType: "user_id", seedHi: 1, seedLo: 2, split: [1, 0] }; + const exp = { + id: 13, + name: "covered", + iteration: 1, + unitType: "user_id", + seedHi: 1, + seedLo: 2, + split: [0.5, 0.5], + trafficSeedHi: 3, + trafficSeedLo: 4, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + audience: null, + audienceStrict: false, + customFieldValues: null, + holdoutIds: [99], + }; + const context = sdk.createContextWith({ units: {} }, { experiments: [exp], holdouts: [holdout] }); + expect(context.peek("covered")).toBe(0); + context.getUnits().user_id = "u1"; + context.treatment("covered"); + expect(context.pending()).toBeGreaterThan(0); + }); + describe("a released duck-typed custom client without the new getters", () => { const legacyClient = () => ({ getContext: () => Promise.resolve({ experiments: [] }), @@ -375,6 +407,20 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(context.treatment("exp")).toBe(1); }); + it.each(["application", "environment"])("uses %s when only its getter exists", (attributeName) => { + const client = legacyClient(); + if (attributeName === "application") client.getApplication = () => ({ name: "web", version: 0 }); + else client.getEnvironment = () => "prod"; + const sdk = new SDK({ ...options, client }); + const value = attributeName === "application" ? "web" : "prod"; + const exp = { + ...strictCountryExperiment, + audience: JSON.stringify({ filter: [{ eq: [{ var: attributeName }, { value }] }] }), + }; + const context = sdk.createContextWith({ units: { session_id: "u1" } }, { experiments: [exp] }); + expect(context.treatment("exp")).toBe(1); + }); + it("still evaluates audiences", () => { const sdk = new SDK({ ...options, client: legacyClient() }); const context = sdk.createContextWith( diff --git a/src/browser.ts b/src/browser.ts index 450a290..3bf5bf9 100644 --- a/src/browser.ts +++ b/src/browser.ts @@ -1,3 +1,6 @@ +// rfdc uses Map and Set during module initialization; include their IE10 polyfills before config imports it. +import "core-js/es/map"; +import "core-js/es/set"; import Context from "./context"; import SDK from "./sdk"; import { mergeConfig } from "./config"; diff --git a/src/client.ts b/src/client.ts index 2a49b02..2983ffd 100644 --- a/src/client.ts +++ b/src/client.ts @@ -22,7 +22,6 @@ export type ClientRequestOptions = { path: string; method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS"; body?: Record; - // Sends the SDK auth/metadata headers. post(), put() and get() set it; request() sends none unless true. auth?: boolean; signal?: AbortSignal | ABsmartlyAbortSignal; timeout?: number; @@ -48,11 +47,8 @@ export type ClientOptions = { // The collector reads X-Application-Version as a 64-bit integer and rejects anything else with a 400, // so only a whole number of 1 to 18 digits is sent as-is; anything else (e.g. "1.2.3") is sent as 0. function applicationVersionHeader(version: number | string): number | string { - if (typeof version === "number") { - return /^[0-9]{1,18}$/.test(String(version)) ? version : 0; - } - const trimmed = typeof version === "string" ? version.trim() : ""; - return /^[0-9]{1,18}$/.test(trimmed) ? trimmed : 0; + const candidate = typeof version === "number" ? version : typeof version === "string" ? version.trim() : ""; + return /^[0-9]{1,18}$/.test(String(candidate)) ? candidate : 0; } type NormalizedClientOptions = Omit, "application"> & { diff --git a/src/context.ts b/src/context.ts index 99fc045..ee12219 100644 --- a/src/context.ts +++ b/src/context.ts @@ -556,15 +556,12 @@ export default class Context { private _getSystemAttributes(): Record { const client = this._sdk.getClient(); const systemAttrs: Record = {}; - // A custom `client` passed to the SDK may predate these getters. - if (typeof client?.getApplication !== "function" || typeof client.getEnvironment !== "function") { - return systemAttrs; - } - const applicationName = client.getApplication()?.name; + // A custom `client` passed to the SDK may predate either getter. + const applicationName = typeof client?.getApplication === "function" ? client.getApplication()?.name : undefined; if (typeof applicationName === "string" && applicationName.length > 0) { systemAttrs["application"] = applicationName; } - const environmentName = client.getEnvironment(); + const environmentName = typeof client?.getEnvironment === "function" ? client.getEnvironment() : undefined; if (typeof environmentName === "string" && environmentName.length > 0) { systemAttrs["environment"] = environmentName; } @@ -683,6 +680,17 @@ export default class Context { const hasOverride = experimentName in this._overrides; const experiment = experimentName in this._index ? this._index[experimentName] : null; + const cached = this._assignments[experimentName]; + if ( + cached && + !cached.exposed && + cached.unitType != null && + cached.unitType in this._units && + (cached.isRuleMissingUnit || cached.holdoutAssignments?.some((assignment) => assignment === null)) + ) { + this._invalidateAssignmentsPinnedWithMissingUnit(cached.unitType); + } + if (experimentName in this._assignments) { const assignment = this._assignments[experimentName]; if (hasOverride) { diff --git a/src/matcher.ts b/src/matcher.ts index 2433454..be8575e 100644 --- a/src/matcher.ts +++ b/src/matcher.ts @@ -36,7 +36,6 @@ export class AudienceMatcher { try { audience = JSON.parse(audienceString); } catch (error) { - // 1.13.4 logged unparsable audiences to the console; keep that diagnostic. console.error(error); return null; } From f697ea9d26ba7328cfc8e9195e4efb0314337926 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 19 Nov 2026 12:16:06 +0000 Subject: [PATCH 11/92] fix(release): gate the live-units check and test it Only run the live-units missing-pin check while some assignment was resolved without its unit, so ordinary cached reads pay nothing. Add tests that kill each mutant of the check and a read-counting test for the gate, assert a user-set app_version is published, and give the legacy-startup failure its own build message. Co-Authored-By: Claude Opus 5.5 --- scripts/check-es5.js | 8 +- src/__tests__/release-compatibility.test.js | 110 ++++++++++++++++++++ src/context.ts | 8 +- 3 files changed, 124 insertions(+), 2 deletions(-) diff --git a/scripts/check-es5.js b/scripts/check-es5.js index 57910fd..f57b8e0 100644 --- a/scripts/check-es5.js +++ b/scripts/check-es5.js @@ -9,6 +9,12 @@ for (const file of ["absmartly.js", "absmartly.min.js"]) { const target = path.resolve(__dirname, "../dist", file); try { acorn.parse(fs.readFileSync(target, "utf8"), { ecmaVersion: 5 }); + } catch (error) { + console.error(`dist/${file} is not ES5: ${error.message}`); + failed = true; + continue; + } + try { const sandbox = { console, setTimeout, @@ -27,7 +33,7 @@ for (const file of ["absmartly.js", "absmartly.min.js"]) { throw new Error("SDK did not load without native collections"); console.log(`ES5 and legacy startup OK: dist/${file}`); } catch (error) { - console.error(`dist/${file} is not ES5: ${error.message}`); + console.error(`dist/${file} does not start without native Map/Set: ${error.message}`); failed = true; } } diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index c9dfb4e..19844da 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -337,6 +337,116 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(sdkFetch.mock.calls[0][1].headers["X-API-Key"]).toBe("k"); }); + describe("live units map additions", () => { + const liveExp = (extra) => ({ + id: 13, + name: "covered", + iteration: 1, + unitType: "user_id", + seedHi: 1, + seedLo: 2, + split: [0.5, 0.5], + trafficSeedHi: 3, + trafficSeedLo: 4, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + audience: null, + audienceStrict: false, + customFieldValues: null, + ...extra, + }); + const splitRules = JSON.stringify({ + rules: [{ name: "s", type: "split", percentages: "0/100", conditions: null }], + }); + + it("re-resolves a peeked missing-unit split rule once the live map gains the unit", () => { + const context = new SDK(options).createContextWith( + { units: {} }, + { experiments: [liveExp({ assignmentRules: splitRules })] } + ); + expect(context.peek("covered")).toBe(0); + context.getUnits().user_id = "u1"; + expect(context.peek("covered")).toBe(1); + }); + + it("matches unit() for a holdout-covered experiment peeked before the unit existed", () => { + const holdout = { + id: 99, + name: "h", + iteration: 1, + unitType: "user_id", + seedHi: 1, + seedLo: 2, + split: [0, 1], + }; + const data = { experiments: [liveExp({ holdoutIds: [99] })], holdouts: [holdout] }; + const viaUnit = new SDK(options).createContextWith({ units: {} }, data); + viaUnit.peek("covered"); + viaUnit.unit("user_id", "u1"); + viaUnit.treatment("covered"); + const viaMap = new SDK(options).createContextWith({ units: {} }, data); + viaMap.peek("covered"); + viaMap.getUnits().user_id = "u1"; + viaMap.treatment("covered"); + const shape = (c) => c._exposures.map((x) => [x.name, x.variant, x.assigned]); + expect(shape(viaMap)).toEqual(shape(viaUnit)); + }); + + it("keeps the cached assignment while the unit is still missing", () => { + const context = new SDK(options).createContextWith( + { units: {} }, + { experiments: [liveExp({ assignmentRules: splitRules })] } + ); + context.peek("covered"); + const first = context._assignments.covered; + context.peek("covered"); + expect(context._assignments.covered).toBe(first); + }); + + it("does no live-units work on cached reads when nothing was resolved without its unit", () => { + const context = new SDK(options).createContextWith( + { units: { user_id: "u1" } }, + { experiments: [liveExp({})] } + ); + context.peek("covered"); + const cached = context._assignments.covered; + let reads = 0; + let value = cached.isRuleMissingUnit; + Object.defineProperty(cached, "isRuleMissingUnit", { + get: () => { + reads++; + return value; + }, + set: (v) => { + value = v; + }, + }); + for (let i = 0; i < 50; i++) context.peek("covered"); + expect(context._missingUnitPins).toBe(0); + expect(reads).toBe(0); + }); + }); + + it("publishes an app_version the user set, like any other attribute", async () => { + const publisher = { publish: jest.fn(() => Promise.resolve()) }; + const sdk = new SDK({ ...options, publisher }); + const context = sdk.createContextWith( + { units: { session_id: "u1" } }, + { experiments: [] }, + { publishDelay: -1 } + ); + context.attribute("app_version", "2.3.4"); + context.track("goal"); + await context.publish(); + const attributes = publisher.publish.mock.calls[0][0].attributes; + expect(attributes).toEqual([expect.objectContaining({ name: "app_version", value: "2.3.4" })]); + }); + it("invalidates a cached missing-unit assignment when the live units map gains the unit", () => { const sdk = new SDK(options); const holdout = { id: 99, name: "h", iteration: 1, unitType: "user_id", seedHi: 1, seedLo: 2, split: [1, 0] }; diff --git a/src/context.ts b/src/context.ts index ee12219..b7b07f6 100644 --- a/src/context.ts +++ b/src/context.ts @@ -190,6 +190,8 @@ export default class Context { private _overrides: Record; private _pending: number; private _attrsSeq: number; + // Assignments resolved while their unit was missing; while zero, _assign() skips the live-units check. + private _missingUnitPins: number; private _attrsMapCache: Record | null; private _attrsMapCacheSeq: number; private _hashes?: Record; @@ -219,6 +221,7 @@ export default class Context { this._audienceMatcher = new AudienceMatcher(); this._environmentName = null; this._attrsSeq = 0; + this._missingUnitPins = 0; this._attrsMapCache = null; this._attrsMapCacheSeq = -1; @@ -633,6 +636,7 @@ export default class Context { assignment.ruleVariant = ruleVariant; assignment.isRuleMissingUnit = rule?.isMissingUnit ?? false; + if (assignment.isRuleMissingUnit) this._missingUnitPins++; } if (!assignment.ruleOverride && experiment.audience && experiment.audience.length > 0) { @@ -680,7 +684,7 @@ export default class Context { const hasOverride = experimentName in this._overrides; const experiment = experimentName in this._index ? this._index[experimentName] : null; - const cached = this._assignments[experimentName]; + const cached = this._missingUnitPins > 0 ? this._assignments[experimentName] : undefined; if ( cached && !cached.exposed && @@ -757,6 +761,7 @@ export default class Context { assignment.holdouts = holdouts; assignment.holdoutAssignments = holdoutAssignments; + if (holdoutAssignments.some((holdoutAssignment) => holdoutAssignment === null)) this._missingUnitPins++; assignment.suppressed = holdoutAssignments.some( (holdoutAssignment) => @@ -790,6 +795,7 @@ export default class Context { assignment.ruleVariant = ruleVariant; assignment.isRuleMissingUnit = rule?.isMissingUnit ?? false; + if (assignment.isRuleMissingUnit) this._missingUnitPins++; // A matching assignment rule wins over holdout suppression, the same way override() // does: it's an explicit, author-specified assignment (flagged `ruleOverride`, From f8cd40e78d9860aeca662e8c24dcb13e3e9ee82b Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 19 Nov 2026 12:49:14 +0000 Subject: [PATCH 12/92] test(release): cover the revalidation missing-unit pin An assignment that revalidates from an assign rule onto a split rule resolved without its unit must still re-resolve when the unit is added through the live units map, as unit() does. Kills the surviving mutant that drops the revalidation pin count. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/release-compatibility.test.js | 37 +++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 19844da..85e8c6f 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -397,6 +397,43 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(shape(viaMap)).toEqual(shape(viaUnit)); }); + it("re-resolves via the live map after revalidation turns an assignment into a missing-unit pin", () => { + const rules = JSON.stringify({ + rules: [ + { + name: "us", + type: "assign", + variant: 0, + conditions: { eq: [{ var: "country" }, { value: "US" }] }, + }, + { + name: "gb", + type: "split", + percentages: "0/100", + conditions: { eq: [{ var: "country" }, { value: "GB" }] }, + }, + ], + }); + const sequence = (setUnit) => { + const context = new SDK(options).createContextWith( + { units: {} }, + { experiments: [liveExp({ assignmentRules: rules })] } + ); + context.attribute("country", "US"); + expect(context.peek("covered")).toBe(0); + context.attribute("country", "GB"); + expect(context.peek("covered")).toBe(0); + setUnit(context); + return context.peek("covered"); + }; + expect(sequence((context) => context.unit("user_id", "u1"))).toBe(1); + expect( + sequence((context) => { + context.getUnits().user_id = "u1"; + }) + ).toBe(1); + }); + it("keeps the cached assignment while the unit is still missing", () => { const context = new SDK(options).createContextWith( { units: {} }, From 813134fd70707ec6182e198bd0bb9cebfca93530 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 19 Nov 2026 14:01:48 +0000 Subject: [PATCH 13/92] perf(release): index loops on attribute paths; pin publish actions Replace for...of over the attribute history with index loops so the compiled code skips the iterator helper on audience re-evaluation and publish, matching 1.13.4. Pin the publish workflow's actions to commit SHAs since the job can mint an OIDC token, and add a test that an assign rule wins over excluded traffic on every read API. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/publish.yml | 4 +-- scripts/__tests__/check-release.test.js | 6 ++++ src/__tests__/release-compatibility.test.js | 31 +++++++++++++++++++++ src/context.ts | 14 ++++++---- 4 files changed, 47 insertions(+), 8 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 1cd7fc6..b14b664 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -24,10 +24,10 @@ jobs: cancel-in-progress: false steps: - name: Checkout code - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - name: Setup Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: '22' registry-url: 'https://registry.npmjs.org' diff --git a/scripts/__tests__/check-release.test.js b/scripts/__tests__/check-release.test.js index 05e173f..64e4183 100644 --- a/scripts/__tests__/check-release.test.js +++ b/scripts/__tests__/check-release.test.js @@ -75,6 +75,12 @@ describe("publish workflow", () => { const job = workflow.jobs.publish; const publishSteps = job.steps.filter((step) => /npm publish\b/.test(step.run || "")); + test("pins every action to a commit SHA, since the job can mint an OIDC token", () => { + for (const step of job.steps.filter((step) => step.uses)) { + expect(step.uses).toMatch(/^[\w.-]+\/[\w.-]+@[0-9a-f]{40}$/); + } + }); + test("serializes all releases with one fixed package-wide lock without cancelling a running publish", () => { expect(Object.keys(workflow.jobs)).toEqual(["publish"]); expect(job.concurrency).toEqual({ diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 85e8c6f..ddae6c7 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -469,6 +469,37 @@ describe("1.13.4 source and behaviour compatibility", () => { }); }); + it("lets an unconditional assign rule win over excluded traffic on every read API", () => { + const experiment = { + id: 14, + name: "excluded", + iteration: 1, + unitType: "session_id", + seedHi: 1, + seedLo: 2, + split: [0.5, 0.5], + trafficSeedHi: 3, + trafficSeedLo: 4, + trafficSplit: [1, 0], + fullOnVariant: 0, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: '{"color":"blue"}' }, + ], + audience: null, + audienceStrict: false, + customFieldValues: null, + assignmentRules: JSON.stringify({ rules: [{ name: "all", type: "assign", variant: 1, conditions: null }] }), + }; + const make = () => + new SDK(options).createContextWith({ units: { session_id: "u1" } }, { experiments: [experiment] }); + expect(make().peek("excluded")).toBe(1); + expect(make().treatment("excluded")).toBe(1); + expect(make().variableValue("color", "none")).toBe("blue"); + expect(make().peekVariableValue("color", "none")).toBe("blue"); + }); + it("publishes an app_version the user set, like any other attribute", async () => { const publisher = { publish: jest.fn(() => Promise.resolve()) }; const sdk = new SDK({ ...options, publisher }); diff --git a/src/context.ts b/src/context.ts index b7b07f6..895908c 100644 --- a/src/context.ts +++ b/src/context.ts @@ -409,8 +409,9 @@ export default class Context { getAttributes() { const attributes: Record = {}; - for (const attr of this._attrs) { - attributes[attr.name] = attr.value; + // Index loops: the compiled for...of adds an iterator helper per call on these hot paths. + for (let i = 0; i < this._attrs.length; i++) { + attributes[this._attrs[i].name] = this._attrs[i].value; } return attributes; } @@ -578,8 +579,8 @@ export default class Context { return this._attrsMapCache; } const attrs: Record = this._getSystemAttributes(); - for (const attr of this._attrs) { - attrs[attr.name] = attr.value; + for (let i = 0; i < this._attrs.length; i++) { + attrs[this._attrs[i].name] = this._attrs[i].value; } this._attrsMapCache = attrs; this._attrsMapCacheSeq = this._attrsSeq; @@ -1120,7 +1121,7 @@ export default class Context { const client = this._sdk.getClient(); // A plain object, not a Set: the browser bundle still supports IE 10, which has no Set. const userNames: Record = {}; - for (const x of this._attrs) userNames[x.name] = true; + for (let i = 0; i < this._attrs.length; i++) userNames[this._attrs[i].name] = true; const addSystemAttribute = (attrName: string, value: unknown) => { if (!Object.prototype.hasOwnProperty.call(userNames, attrName)) { allAttributes.push({ name: attrName, value, setAt: systemSetAt }); @@ -1132,7 +1133,8 @@ export default class Context { addSystemAttribute("sdk_version", SDK_VERSION); } - for (const x of this._attrs) { + for (let i = 0; i < this._attrs.length; i++) { + const x = this._attrs[i]; allAttributes.push({ name: x.name, value: x.value, setAt: x.setAt }); } From a5d368096e2ae7c3d61caf6d363c9b736b227ab3 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 19 Nov 2026 15:25:31 +0000 Subject: [PATCH 14/92] test(release): pin getAttributes() latest-value ordering Kills the surviving mutant that reverses the getAttributes() index loop so the oldest value of a repeated attribute would win. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/release-compatibility.test.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index ddae6c7..e571719 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -469,6 +469,14 @@ describe("1.13.4 source and behaviour compatibility", () => { }); }); + it("returns the latest value for a repeated attribute from getAttributes()", () => { + const context = new SDK(options).createContextWith({ units: { session_id: "u1" } }, { experiments: [] }); + context.attribute("age", 10); + context.attribute("country", "US"); + context.attribute("age", 30); + expect(context.getAttributes()).toEqual({ age: 30, country: "US" }); + }); + it("lets an unconditional assign rule win over excluded traffic on every read API", () => { const experiment = { id: 14, From 8b62ce786cf3db2e204eda5189a37b4b6f387436 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 19 Nov 2026 16:41:12 +0000 Subject: [PATCH 15/92] fix(release): treat null parents in audience paths as missing; keep finalize type A nested var path under an attribute set to null threw in extractVar, which the fail-closed audience handling turned into a mismatch and an error event, moving strict audiences to control. Return null there as 1.13.4 and Java do. Declare finalize() as true | Promise as in 1.13.4, note the @babel/runtime dependency in the CHANGELOG, and pin the cross-SDK workflow actions to commit SHAs. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/cross-sdk.yml | 10 +++---- CHANGELOG.md | 3 ++ scripts/compatibility/consumer.ts | 5 +++- src/__tests__/release-compatibility.test.js | 32 +++++++++++++++++++++ src/context.ts | 3 +- src/jsonexpr/evaluator.ts | 1 + 6 files changed, 47 insertions(+), 7 deletions(-) diff --git a/.github/workflows/cross-sdk.yml b/.github/workflows/cross-sdk.yml index ad2eeac..f0d9968 100644 --- a/.github/workflows/cross-sdk.yml +++ b/.github/workflows/cross-sdk.yml @@ -12,20 +12,20 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 15 steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: path: javascript-sdk - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: repository: absmartly/cross-sdk-tests ref: ada8952293a8d4ebf81f8de038f4e7a406d98870 path: cross-sdk-tests - - uses: actions/setup-node@v6 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 with: node-version: '24' cache: npm cache-dependency-path: javascript-sdk/package-lock.json - - uses: actions/setup-python@v6 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: '3.11' - name: Build SDK and install reference wrapper @@ -46,7 +46,7 @@ jobs: wrapper=$! trap 'kill "$wrapper" 2>/dev/null || true' EXIT python -u orchestrator/test_runner.py --sdk javascript --report report.json - - uses: actions/upload-artifact@v6 + - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 if: always() with: name: cross-sdk-javascript diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c8a777..0c7e043 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,9 @@ emits one logger `error` event; 1.13.4 treated it as a match. Affected: strict audiences move such units to control (variant 0); non-strict exposures publish `audienceMismatch: true` instead of `false`. +- New runtime dependency `@babel/runtime` (shared Babel helpers, which shrink the + browser bundle). It declares Node `>=6.9.0`; the package still declares `>=6`, so + Node 6.0–6.8 installs may warn. No helper types are exposed in the public API. ### Fixed diff --git a/scripts/compatibility/consumer.ts b/scripts/compatibility/consumer.ts index 2bbaf20..1370aef 100644 --- a/scripts/compatibility/consumer.ts +++ b/scripts/compatibility/consumer.ts @@ -140,7 +140,10 @@ context.customAssignments({ example: 1 }); context.track("purchase", { amount: 5 }); context.publish(); context.refresh(); -context.finalize(); +const finalized: true | Promise = context.finalize(); +if (finalized === true) { + void finalized; +} context.experiments(); context.customFieldKeys(); context.customFieldValue("example", "key"); diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index e571719..7dc3d33 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -469,6 +469,38 @@ describe("1.13.4 source and behaviour compatibility", () => { }); }); + it("treats a nested audience path under a null attribute as missing, not a mismatch, as 1.13.4 did", () => { + const eventLogger = jest.fn(); + const experiment = { + id: 15, + name: "nested", + iteration: 1, + unitType: "session_id", + seedHi: 3603515, + seedLo: 233373850, + split: [0, 1], + trafficSeedHi: 449867249, + trafficSeedLo: 455443629, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + audience: JSON.stringify({ filter: [{ not: [{ eq: [{ var: "user/plan" }, { value: "free" }] }] }] }), + audienceStrict: true, + customFieldValues: null, + }; + const context = new SDK({ ...options, eventLogger }).createContextWith( + { units: { session_id: "e791e240fcd3df7d238cfc285f475e8152fcc0ec" } }, + { experiments: [experiment] } + ); + context.attribute("user", null); + expect(context.treatment("nested")).toBe(1); + expect(eventLogger.mock.calls.filter(([, eventName]) => eventName === "error")).toHaveLength(0); + }); + it("returns the latest value for a repeated attribute from getAttributes()", () => { const context = new SDK(options).createContextWith({ units: { session_id: "u1" } }, { experiments: [] }); context.attribute("age", 10); diff --git a/src/context.ts b/src/context.ts index 895908c..05d1e00 100644 --- a/src/context.ts +++ b/src/context.ts @@ -440,7 +440,8 @@ export default class Context { return this._track(goalName, properties); } - finalize(requestOptions?: ClientRequestOptions) { + // Declared as in 1.13.4 so existing `=== true` checks still compile; it only ever returns a promise. + finalize(requestOptions?: ClientRequestOptions): true | Promise { return this._finalize(requestOptions); } diff --git a/src/jsonexpr/evaluator.ts b/src/jsonexpr/evaluator.ts index dc8d743..bc5118c 100644 --- a/src/jsonexpr/evaluator.ts +++ b/src/jsonexpr/evaluator.ts @@ -125,6 +125,7 @@ export class Evaluator { let target = this.vars ?? {}; for (let index = 0; index < frags.length; ++index) { const frag = frags[index]; + if (target == null) return null; const value = target[frag]; if (value !== undefined) { From 7bdfe3cbf16432c37608b4914edb8844f6d2a155 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 19 Nov 2026 18:26:12 +0000 Subject: [PATCH 16/92] fix(release): preserve null-parent audience results from 1.13.4 Track null-parent traversal in the expression evaluator and preserve the released indeterminate audience result without changing safe rule evaluation. Test strict and non-strict equality audiences and mismatch flags. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/release-compatibility.test.js | 35 +++++++++++++++++++++ src/jsonexpr/evaluator.ts | 6 +++- src/jsonexpr/jsonexpr.ts | 10 ++++-- src/matcher.ts | 2 +- 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 7dc3d33..f13ce02 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -501,6 +501,41 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(eventLogger.mock.calls.filter(([, eventName]) => eventName === "error")).toHaveLength(0); }); + it.each([true, false])("preserves null-parent equality audience behavior with strict=%p", (strict) => { + const eventLogger = jest.fn(); + const experiment = { + id: 15, + name: "nested", + iteration: 1, + unitType: "session_id", + seedHi: 3603515, + seedLo: 233373850, + split: [0, 1], + trafficSeedHi: 449867249, + trafficSeedLo: 455443629, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + audienceStrict: strict, + customFieldValues: null, + }; + const context = new SDK({ ...options, eventLogger }).createContextWith( + { units: { session_id: "e791e240fcd3df7d238cfc285f475e8152fcc0ec" } }, + { experiments: [experiment] } + ); + context.attribute("user", null); + expect(context.treatment("nested")).toBe(1); + expect(eventLogger.mock.calls.find(([, eventName]) => eventName === "exposure")[2].audienceMismatch).toBe( + false + ); + expect(eventLogger.mock.calls.filter(([, eventName]) => eventName === "error")).toHaveLength(0); + }); + it("returns the latest value for a repeated attribute from getAttributes()", () => { const context = new SDK(options).createContextWith({ units: { session_id: "u1" } }, { experiments: [] }); context.attribute("age", 10); diff --git a/src/jsonexpr/evaluator.ts b/src/jsonexpr/evaluator.ts index bc5118c..c853ff0 100644 --- a/src/jsonexpr/evaluator.ts +++ b/src/jsonexpr/evaluator.ts @@ -53,6 +53,7 @@ function compareIdentifiers(a: string, b: string) { } export class Evaluator { + nullParentEncountered = false; private readonly operators: any; private readonly vars: any; @@ -125,7 +126,10 @@ export class Evaluator { let target = this.vars ?? {}; for (let index = 0; index < frags.length; ++index) { const frag = frags[index]; - if (target == null) return null; + if (target == null) { + this.nullParentEncountered = true; + return null; + } const value = target[frag]; if (value !== undefined) { diff --git a/src/jsonexpr/jsonexpr.ts b/src/jsonexpr/jsonexpr.ts index 84414c7..77782a4 100644 --- a/src/jsonexpr/jsonexpr.ts +++ b/src/jsonexpr/jsonexpr.ts @@ -40,9 +40,15 @@ const operators = { }; export class JsonExpr { - evaluateBooleanExpr(expr: TData[] | Record, vars: Record) { + evaluateBooleanExpr( + expr: TData[] | Record, + vars: Record, + preserveNullParentAudience = false + ) { const evaluator = new Evaluator(operators, vars); - return evaluator.booleanConvert(evaluator.evaluate(expr)); + const result = evaluator.booleanConvert(evaluator.evaluate(expr)); + // Released audiences ignored an expression whose path crossed a null parent. + return preserveNullParentAudience && evaluator.nullParentEncountered ? null : result; } evaluateExpr(expr: TData[] | Record, vars: Record) { diff --git a/src/matcher.ts b/src/matcher.ts index be8575e..e03ccec 100644 --- a/src/matcher.ts +++ b/src/matcher.ts @@ -42,7 +42,7 @@ export class AudienceMatcher { if (audience && audience.filter) { if (Array.isArray(audience.filter) || isObject(audience.filter)) { - return this._jsonExpr.evaluateBooleanExpr(audience.filter, vars); + return this._jsonExpr.evaluateBooleanExpr(audience.filter, vars, true); } } From eb9264aecc1958a24ff69eed69958262cc66dfbd Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 20 Nov 2026 00:59:20 +0000 Subject: [PATCH 17/92] fix(release): keep rule-condition semantics and restore 1.13.4 audience error handling Revert the evaluator to main so a rule condition whose path crosses a null attribute throws and the rule is skipped, as the JS reference does. Restore the 1.13.4 audience matcher catch so such audiences are logged and ignored, not counted as mismatches. Removes the internal plumbing from the public types and fixes the CHANGELOG wording. Each behaviour is pinned by a test that kills its mutant. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 +++--- src/__tests__/release-compatibility.test.js | 39 +++++++++++++++++++++ src/jsonexpr/evaluator.ts | 7 +--- src/jsonexpr/jsonexpr.ts | 10 ++---- src/matcher.ts | 9 ++++- 5 files changed, 54 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c7e043..b2f16ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,10 +47,10 @@ differs from the client one, who now get more (or fewer) retries to match it. `timeout: 0` keeps its 1.13.4 meaning: a request value of 0 falls back to the client timeout, and a client timeout of 0 means no retries. -- An audience whose evaluation throws now counts as a mismatch (fail closed) and - emits one logger `error` event; 1.13.4 treated it as a match. Affected: strict - audiences move such units to control (variant 0); non-strict exposures publish - `audienceMismatch: true` instead of `false`. +- If the audience matcher itself fails unexpectedly, the audience now counts as a + mismatch (fail closed) and emits one logger `error` event. Errors inside an + audience expression (for example a path through a `null` attribute) are still + logged to the console and the audience ignored, as in 1.13.4. - New runtime dependency `@babel/runtime` (shared Babel helpers, which shrink the browser bundle). It declares Node `>=6.9.0`; the package still declares `>=6`, so Node 6.0–6.8 installs may warn. No helper types are exposed in the public API. @@ -66,6 +66,3 @@ - The browser bundle is ES5 again (IE 10): `rfdc` >= 1.4 ships ES2015 syntax, so it is now transpiled, and the build fails if `dist/` is not ES5. - Query keys are encoded and unmatched query surrogates no longer throw URIError. -- Preserve published 1.13.4 error strings, custom-field console diagnostics, - live `getUnits()` return, legacy unit hashing, old TypeScript parser support, - and existing model literals rather than shipping main-era compatibility breaks. diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index f13ce02..82591d1 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -536,6 +536,45 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(eventLogger.mock.calls.filter(([, eventName]) => eventName === "error")).toHaveLength(0); }); + it("skips a rule whose condition path crosses a null attribute, as main (the JS reference) does", () => { + const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); + const experiment = { + id: 16, + name: "rulenull", + iteration: 1, + unitType: "session_id", + seedHi: 1, + seedLo: 2, + split: [0.34, 0.33, 0.33], + trafficSeedHi: 3, + trafficSeedLo: 4, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + { name: "C", config: null }, + ], + audience: null, + audienceStrict: false, + customFieldValues: null, + assignmentRules: JSON.stringify({ + rules: [ + { name: "nullplan", type: "assign", variant: 2, conditions: { null: { var: "user/plan" } } }, + { name: "fallback", type: "assign", variant: 1, conditions: null }, + ], + }), + }; + const context = new SDK(options).createContextWith( + { units: { session_id: "u1" } }, + { experiments: [experiment] } + ); + context.attribute("user", null); + expect(context.treatment("rulenull")).toBe(1); + warn.mockRestore(); + }); + it("returns the latest value for a repeated attribute from getAttributes()", () => { const context = new SDK(options).createContextWith({ units: { session_id: "u1" } }, { experiments: [] }); context.attribute("age", 10); diff --git a/src/jsonexpr/evaluator.ts b/src/jsonexpr/evaluator.ts index c853ff0..5c52ff0 100644 --- a/src/jsonexpr/evaluator.ts +++ b/src/jsonexpr/evaluator.ts @@ -3,7 +3,7 @@ import { isEqualsDeep, isObject } from "../utils"; function parseSemver(version: string) { let v = version; - if (v.charAt(0) === "v" || v.charAt(0) === "V") { + if (v.startsWith("v") || v.startsWith("V")) { v = v.substring(1); } @@ -53,7 +53,6 @@ function compareIdentifiers(a: string, b: string) { } export class Evaluator { - nullParentEncountered = false; private readonly operators: any; private readonly vars: any; @@ -126,10 +125,6 @@ export class Evaluator { let target = this.vars ?? {}; for (let index = 0; index < frags.length; ++index) { const frag = frags[index]; - if (target == null) { - this.nullParentEncountered = true; - return null; - } const value = target[frag]; if (value !== undefined) { diff --git a/src/jsonexpr/jsonexpr.ts b/src/jsonexpr/jsonexpr.ts index 77782a4..84414c7 100644 --- a/src/jsonexpr/jsonexpr.ts +++ b/src/jsonexpr/jsonexpr.ts @@ -40,15 +40,9 @@ const operators = { }; export class JsonExpr { - evaluateBooleanExpr( - expr: TData[] | Record, - vars: Record, - preserveNullParentAudience = false - ) { + evaluateBooleanExpr(expr: TData[] | Record, vars: Record) { const evaluator = new Evaluator(operators, vars); - const result = evaluator.booleanConvert(evaluator.evaluate(expr)); - // Released audiences ignored an expression whose path crossed a null parent. - return preserveNullParentAudience && evaluator.nullParentEncountered ? null : result; + return evaluator.booleanConvert(evaluator.evaluate(expr)); } evaluateExpr(expr: TData[] | Record, vars: Record) { diff --git a/src/matcher.ts b/src/matcher.ts index e03ccec..683e8eb 100644 --- a/src/matcher.ts +++ b/src/matcher.ts @@ -42,7 +42,14 @@ export class AudienceMatcher { if (audience && audience.filter) { if (Array.isArray(audience.filter) || isObject(audience.filter)) { - return this._jsonExpr.evaluateBooleanExpr(audience.filter, vars, true); + // As in 1.13.4, an audience whose evaluation throws (e.g. a path through a null + // attribute) is ignored rather than counted as a mismatch. + try { + return this._jsonExpr.evaluateBooleanExpr(audience.filter, vars); + } catch (error) { + console.error(error); + return null; + } } } From 6acdbe7d5295a089437101537449ff5ff4149bc5 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 20 Nov 2026 07:29:27 +0000 Subject: [PATCH 18/92] fix(release): keep IE semver parsing and fail closed on real audience errors Restore charAt for the semver v-prefix (IE 10/11 has no startsWith). Narrow the 1.13.4 audience catch to a dedicated internal NullParentError so a path through a null attribute stays indeterminate while any other evaluation error still fails strict audiences closed. An indeterminate result revalidates as a match, as in 1.13.4. Tests pin each behaviour and kill its mutant; NullParentError is stripped from the public types. Co-Authored-By: Claude Opus 5.5 --- release/1.14.0-compatibility.md | 98 ++++++++-------- src/__tests__/release-compatibility.test.js | 123 ++++++++++++++++++++ src/context.ts | 9 +- src/jsonexpr/evaluator.ts | 8 +- src/matcher.ts | 6 +- tsconfig.json | 1 + 6 files changed, 187 insertions(+), 58 deletions(-) diff --git a/release/1.14.0-compatibility.md b/release/1.14.0-compatibility.md index 7ce34ce..0898cfd 100644 --- a/release/1.14.0-compatibility.md +++ b/release/1.14.0-compatibility.md @@ -14,55 +14,55 @@ Classes: **a** additive; **b** agreed cross-SDK contract; **c** genuine bug fix; **d** unrelated compatibility/behaviour change (restore the published contract). This inventories public source/runtime differences, not just this PR's delta. -| Change since published 1.13.4 | Class | Action for 1.14.0 | -| ------------------------------------------------------------------------------------------------------------------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `ABsmartly` alias in CJS/ES/browser exports | a | Keep alongside `SDK`; no old entry point removed. | -| `Client.getApplication/getEnvironment/getAgent/get`, `ApplicationObject` | a | Keep; string application still accepted. | -| `Context.getSDK/getOptions/readyError` | a | Keep. | -| Optional experiment assignment rules, variant name, holdout IDs; new holdout model types | a/b | Keep optional; no new required customer payload fields. | -| `AudienceMatcher.parseRules/evaluateRules/evaluateParsedRules`, `RuleAction` | a/b | Keep assignment/split rules with strict types, environment scoping, malformed-rule isolation, override precedence and missing-unit pinning. | -| `semver_*` operators, `Evaluator.versionCompare` | a/b | Keep; old `stringConvert`, `eq`, `in`, match behaviour remains unchanged. | -| `includeSystemAttributes` option | a/b | Keep opt-in publishing of SDK name/version; never synthetic app/environment/app_version publishing. | -| Synthetic application/environment in evaluation, user values win | b | Keep and document affected targeting under Changed; empty names absent, no synthetic app_version. | -| Assignment rules override audience/traffic/full-on/custom/holdouts | b | Keep and document affected experiments under Changed. | -| Required `Exposure.ruleOverride` source field on main | d | Make optional for old model literals; runtime always emits true/false (b). | -| Holdout suppression, control variable fallback and holdout exposures | b | Keep; document payload-linked experiments under Changed. | -| Shared variable resolution/id ordering/map-of-lists | b | Keep; released return shape unchanged. | -| GET SDK auth/metadata headers | b | Keep; preserve query parameters. | -| Low-level `Client` auth rules: `request()` authenticated by default, `post`/`put` honoured `auth:false`, `getUnauthed` became authenticated | d | Restore 1.13.4 rules exactly: `request()` sends headers only with `auth: true`, `post`/`put` always authenticate, `getUnauthed` is a plain GET. The additive `get()` (used by `getContext`) authenticates unless `auth: false`. | -| `SDK` dropped client options passed as explicit `undefined` (`agent`, `timeout`, `keepalive`) | d | Restore 1.13.4 pass-through of every present key; `agent: undefined` again reaches the Client and is rejected. | -| Versioned SDK X-Agent | b | Add from generated package version; custom agent untouched. Direct `Client` default remains `javascript-client`. | -| String application version accepted; utility return widened | a/d | Keep strings; overload `getApplicationVersion` so old numeric callers still receive `number` statically. | -| Invalid/dotted application versions sent to collector Long header | c/b | Normalize GET and PUT to trimmed 1–18 ASCII digits or zero; retain full configured getter. | -| Every publish adds `sdkVersion`, required `PublishParams.sdkVersion` | d | Restore 1.13 body/type; collector `PublishRequest` ignores this unknown field. SDK version remains in X-Agent and opt-in attributes. | -| New normal-path auth deprecation warning | d | Remove; explicit auth still accepted without new stderr output. | -| Error brand casing `ABSmartly` → `ABsmartly` | d | Restore byte-identical 1.13 not-ready/finalizing/finalized messages. | -| Custom-field console diagnostics changed to logger error events and JSON parser suffix | d | Restore released console sink/messages, null return and no new error events. | -| Failed-context flush adds discard error event | d | Restore silent discard after initial load error; preserve settlement/queue cleanup. | -| `getUnits()` changes live map to defensive copy | d | Restore live map and original `Units` return type. | -| `getAttribute()` return changes from incorrect `undefined` declaration to `unknown` | c/d | Use `any` for compatibility with both strict and non-strict existing consumers; actual last-value behaviour unchanged. | -| `ready(): Promise` narrows to boolean and README claims old errors | d | Restore declared Promise; published runtime already resolves true even on failure. Correct README, do not invent migration. | -| `finalize()` inferred `true \| Promise` narrows to `Promise` | c | Keep actual Promise-only result; published implementation never returned true. | -| Canonical UTF-8 for astral/unpaired surrogate UIDs changes hashes/assignment | d | Restore legacy UTF-16-code-unit encoding for all 1.x hashes; canonical change preserved on next/major for 2.0. | -| Type-only inline imports raise declaration parser floor to TS4.5 | d | Restore old import syntax; TS3.9 consumer compile checks it. | -| New required getters on duck-typed custom clients | d | Guard getters so existing custom clients don't crash context installation/evaluation. | -| Abort shim reason/onabort/optional abort reason and idempotence | a/c | Keep native-standard cancellation bug fixes; no required method argument. | -| Fetch global detection and clear no-fetch error | c | Keep fallback selection fix (old no-global environment was unusable). | -| Query key escaping and malformed-surrogate normalization | c | Keep encoding fixes; ordinary URL values unchanged. | -| Per-request timeout bounds the retry budget (1.13.4 used the client timeout) | c | Keep; listed under Changed with who is affected, and covered by a mutant-killing test. | -| Invalid audience JSON stopped logging `console.error` | d | Restore the 1.13.4 console diagnostic; no logger `error` event. | -| Main made `timeout: 0` mean "no deadline" (request) and "retry forever" (client) | d | Restore 1.13.4: request 0 falls back to the client timeout, client 0 means no retries. Measured: main hangs > 8 s where 1.13.4 fails at ~3 s. | -| `getContext()` called `get()` directly, skipping a subclass `getUnauthed()` override | d | Route through `getUnauthed()` again, keeping the GET headers. | -| `rfdc` 1.4.1 (lockfile) puts ES2015 syntax into the browser bundle | d | Transpile rfdc in webpack; `scripts/check-es5.js` fails the build if `dist/` is not ES5. | -| Failed publisher loses events, synchronous failures and concurrent finalize races | c | Keep ordered restore/retry and promise settlement fixes. | -| Throwing event logger corrupts init/publish/finalize | c | Isolate observer exceptions; don't resend already-delivered batch. | -| Malformed/non-object variant config crashes or indexes invalid keys | c | Isolate invalid config; valid objects unchanged. | -| Audience evaluation exception fails open; indeterminate cache needless rebuild | c | Fail strict audiences closed, keep cached mismatch for indeterminate result. | -| Unit hash caches missing unit forever | c | Don't memoize missing hash; rule/holdout late-unit handling retained. | -| New @babel/runtime production dependency and helper deduplication (owner call; kept) | a | Private build helper dependency, no exposed dependency types or major bump to existing dependencies; Node6 remains supported. | -| Node24 development tooling, husky/lint-staged, generate-version, build/prepare hooks | a | Build-only; package engines remain Node>=6/npm>=3, Babel CJS Node6 and IE10 browser targets unchanged. | -| Babel relative runtime paths, delete stale generated output, browser/CJS export packaging | c | Keep portable package output. | -| README restructuring/refreshPeriod correction | c | Keep; pin install/browser examples to 1.14.0 and replace misleading Breaking migration. | +| Change since published 1.13.4 | Class | Action for 1.14.0 | +| ------------------------------------------------------------------------------------------------------------------------------------------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ABsmartly` alias in CJS/ES/browser exports | a | Keep alongside `SDK`; no old entry point removed. | +| `Client.getApplication/getEnvironment/getAgent/get`, `ApplicationObject` | a | Keep; string application still accepted. | +| `Context.getSDK/getOptions/readyError` | a | Keep. | +| Optional experiment assignment rules, variant name, holdout IDs; new holdout model types | a/b | Keep optional; no new required customer payload fields. | +| `AudienceMatcher.parseRules/evaluateRules/evaluateParsedRules`, `RuleAction` | a/b | Keep assignment/split rules with strict types, environment scoping, malformed-rule isolation, override precedence and missing-unit pinning. | +| `semver_*` operators, `Evaluator.versionCompare` | a/b | Keep; old `stringConvert`, `eq`, `in`, match behaviour remains unchanged. | +| `includeSystemAttributes` option | a/b | Keep opt-in publishing of SDK name/version; never synthetic app/environment/app_version publishing. | +| Synthetic application/environment in evaluation, user values win | b | Keep and document affected targeting under Changed; empty names absent, no synthetic app_version. | +| Assignment rules override audience/traffic/full-on/custom/holdouts | b | Keep and document affected experiments under Changed. | +| Required `Exposure.ruleOverride` source field on main | d | Make optional for old model literals; runtime always emits true/false (b). | +| Holdout suppression, control variable fallback and holdout exposures | b | Keep; document payload-linked experiments under Changed. | +| Shared variable resolution/id ordering/map-of-lists | b | Keep; released return shape unchanged. | +| GET SDK auth/metadata headers | b | Keep; preserve query parameters. | +| Low-level `Client` auth rules: `request()` authenticated by default, `post`/`put` honoured `auth:false`, `getUnauthed` became authenticated | d | Restore 1.13.4 rules exactly: `request()` sends headers only with `auth: true`, `post`/`put` always authenticate, `getUnauthed` is a plain GET. The additive `get()` (used by `getContext`) authenticates unless `auth: false`. | +| `SDK` dropped client options passed as explicit `undefined` (`agent`, `timeout`, `keepalive`) | d | Restore 1.13.4 pass-through of every present key; `agent: undefined` again reaches the Client and is rejected. | +| Versioned SDK X-Agent | b | Add from generated package version; custom agent untouched. Direct `Client` default remains `javascript-client`. | +| String application version accepted; utility return widened | a/d | Keep strings; overload `getApplicationVersion` so old numeric callers still receive `number` statically. | +| Invalid/dotted application versions sent to collector Long header | c/b | Normalize GET and PUT to trimmed 1–18 ASCII digits or zero; retain full configured getter. | +| Every publish adds `sdkVersion`, required `PublishParams.sdkVersion` | d | Restore 1.13 body/type; collector `PublishRequest` ignores this unknown field. SDK version remains in X-Agent and opt-in attributes. | +| New normal-path auth deprecation warning | d | Remove; explicit auth still accepted without new stderr output. | +| Error brand casing `ABSmartly` → `ABsmartly` | d | Restore byte-identical 1.13 not-ready/finalizing/finalized messages. | +| Custom-field console diagnostics changed to logger error events and JSON parser suffix | d | Restore released console sink/messages, null return and no new error events. | +| Failed-context flush adds discard error event | d | Restore silent discard after initial load error; preserve settlement/queue cleanup. | +| `getUnits()` changes live map to defensive copy | d | Restore live map and original `Units` return type. | +| `getAttribute()` return changes from incorrect `undefined` declaration to `unknown` | c/d | Use `any` for compatibility with both strict and non-strict existing consumers; actual last-value behaviour unchanged. | +| `ready(): Promise` narrows to boolean and README claims old errors | d | Restore declared Promise; published runtime already resolves true even on failure. Correct README, do not invent migration. | +| `finalize()` inferred `true \| Promise` narrows to `Promise` | c | Keep actual Promise-only result; published implementation never returned true. | +| Canonical UTF-8 for astral/unpaired surrogate UIDs changes hashes/assignment | d | Restore legacy UTF-16-code-unit encoding for all 1.x hashes; canonical change preserved on next/major for 2.0. | +| Type-only inline imports raise declaration parser floor to TS4.5 | d | Restore old import syntax; TS3.9 consumer compile checks it. | +| New required getters on duck-typed custom clients | d | Guard getters so existing custom clients don't crash context installation/evaluation. | +| Abort shim reason/onabort/optional abort reason and idempotence | a/c | Keep native-standard cancellation bug fixes; no required method argument. | +| Fetch global detection and clear no-fetch error | c | Keep fallback selection fix (old no-global environment was unusable). | +| Query key escaping and malformed-surrogate normalization | c | Keep encoding fixes; ordinary URL values unchanged. | +| Per-request timeout bounds the retry budget (1.13.4 used the client timeout) | c | Keep; listed under Changed with who is affected, and covered by a mutant-killing test. | +| Invalid audience JSON stopped logging `console.error` | d | Restore the 1.13.4 console diagnostic; no logger `error` event. | +| Main made `timeout: 0` mean "no deadline" (request) and "retry forever" (client) | d | Restore 1.13.4: request 0 falls back to the client timeout, client 0 means no retries. Measured: main hangs > 8 s where 1.13.4 fails at ~3 s. | +| `getContext()` called `get()` directly, skipping a subclass `getUnauthed()` override | d | Route through `getUnauthed()` again, keeping the GET headers. | +| `rfdc` 1.4.1 (lockfile) puts ES2015 syntax into the browser bundle | d | Transpile rfdc in webpack; `scripts/check-es5.js` fails the build if `dist/` is not ES5. | +| Failed publisher loses events, synchronous failures and concurrent finalize races | c | Keep ordered restore/retry and promise settlement fixes. | +| Throwing event logger corrupts init/publish/finalize | c | Isolate observer exceptions; don't resend already-delivered batch. | +| Malformed/non-object variant config crashes or indexes invalid keys | c | Isolate invalid config; valid objects unchanged. | +| Audience evaluation exception fails open | c | An unexpected matcher error fails strict audiences closed with one `error` event. A path through a `null` attribute stays indeterminate (ignored), and an indeterminate result revalidates as a match, both exactly as in 1.13.4. | +| Unit hash caches missing unit forever | c | Don't memoize missing hash; rule/holdout late-unit handling retained. | +| New @babel/runtime production dependency and helper deduplication (owner call; kept) | a | Private build helper dependency, no exposed dependency types or major bump to existing dependencies; Node6 remains supported. | +| Node24 development tooling, husky/lint-staged, generate-version, build/prepare hooks | a | Build-only; package engines remain Node>=6/npm>=3, Babel CJS Node6 and IE10 browser targets unchanged. | +| Babel relative runtime paths, delete stale generated output, browser/CJS export packaging | c | Keep portable package output. | +| README restructuring/refreshPeriod correction | c | Keep; pin install/browser examples to 1.14.0 and replace misleading Breaking migration. | ## Measurements diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 82591d1..ac28c50 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -575,6 +575,129 @@ describe("1.13.4 source and behaviour compatibility", () => { warn.mockRestore(); }); + describe("audience and rule evaluation errors", () => { + const strictExp = (audience) => ({ + id: 17, + name: "aud", + iteration: 1, + unitType: "session_id", + seedHi: 3603515, + seedLo: 233373850, + split: [0, 1], + trafficSeedHi: 449867249, + trafficSeedLo: 455443629, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + audience: JSON.stringify({ filter: audience }), + audienceStrict: true, + customFieldValues: null, + }); + const uid = "e791e240fcd3df7d238cfc285f475e8152fcc0ec"; + + it("evaluates semver audiences without String.prototype.startsWith (IE 10/11)", () => { + const original = String.prototype.startsWith; + // eslint-disable-next-line no-extend-native + delete String.prototype.startsWith; + try { + const context = new SDK(options).createContextWith( + { units: { session_id: uid } }, + { experiments: [strictExp([{ semver_gte: [{ var: "app_version" }, { value: "v2.0.0" }] }])] } + ); + context.attribute("app_version", "v1.0.0"); + expect(context.treatment("aud")).toBe(0); + + const matching = new SDK(options).createContextWith( + { units: { session_id: uid } }, + { experiments: [strictExp([{ semver_gte: [{ var: "app_version" }, { value: "v2.0.0" }] }])] } + ); + matching.attribute("app_version", "v3.0.0"); + expect(matching.treatment("aud")).toBe(1); + } finally { + // eslint-disable-next-line no-extend-native + String.prototype.startsWith = original; + } + }); + + it("fails a strict audience closed when an attribute getter throws, and logs one error event", () => { + const eventLogger = jest.fn(); + const context = new SDK({ ...options, eventLogger }).createContextWith( + { units: { session_id: uid } }, + { experiments: [strictExp([{ eq: [{ var: "user/plan" }, { value: "pro" }] }])] } + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("getter boom"); + }, + }); + context.attribute("user", user); + expect(context.treatment("aud")).toBe(0); + expect(context._exposures[0].audienceMismatch).toBe(true); + expect(eventLogger.mock.calls.filter(([, eventName]) => eventName === "error")).toHaveLength(1); + }); + + it("logs a null-parent audience path to the console, without an error event", () => { + const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); + const eventLogger = jest.fn(); + const context = new SDK({ ...options, eventLogger }).createContextWith( + { units: { session_id: uid } }, + { experiments: [strictExp([{ eq: [{ var: "user/plan" }, { value: "pro" }] }])] } + ); + context.attribute("user", null); + expect(context.treatment("aud")).toBe(1); + expect(errorSpy).toHaveBeenCalledWith(expect.any(TypeError)); + expect(eventLogger.mock.calls.filter(([, eventName]) => eventName === "error")).toHaveLength(0); + errorSpy.mockRestore(); + }); + + it("rebuilds a cached mismatch when a later null-parent read is indeterminate, as 1.13.4 did", () => { + const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); + const context = new SDK(options).createContextWith( + { units: { session_id: uid } }, + { experiments: [strictExp([{ eq: [{ var: "user/plan" }, { value: "pro" }] }])] } + ); + context.attribute("user", { plan: "free" }); + expect(context.peek("aud")).toBe(0); + context.attribute("user", null); + expect(context.peek("aud")).toBe(1); + errorSpy.mockRestore(); + }); + + it("logs a failing rule condition with console.warn, not console.error", () => { + const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); + const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); + const exp = { + ...strictExp(null), + audience: null, + audienceStrict: false, + assignmentRules: JSON.stringify({ + rules: [ + { + name: "r", + type: "assign", + variant: 1, + conditions: { eq: [{ var: "user/plan" }, { value: "pro" }] }, + }, + ], + }), + }; + const context = new SDK(options).createContextWith({ units: { session_id: uid } }, { experiments: [exp] }); + context.attribute("user", null); + context.treatment("aud"); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining("Failed to evaluate assignment rule conditions for rule r") + ); + expect(errorSpy).not.toHaveBeenCalled(); + warn.mockRestore(); + errorSpy.mockRestore(); + }); + }); + it("returns the latest value for a repeated attribute from getAttributes()", () => { const context = new SDK(options).createContextWith({ units: { session_id: "u1" } }, { experiments: [] }); context.attribute("age", 10); diff --git a/src/context.ts b/src/context.ts index 05d1e00..5216674 100644 --- a/src/context.ts +++ b/src/context.ts @@ -643,12 +643,9 @@ export default class Context { if (!assignment.ruleOverride && experiment.audience && experiment.audience.length > 0) { const result = this._evaluateAudience(experiment.audience); - // An indeterminate (null) audience result leaves the cached - // `audienceMismatch` flag as-is rather than forcing it to `false`, - // so a cached mismatch=true assignment isn't wrongly treated as - // stale — this only affects the cache-validity check below, not - // the flag's value. - const newAudienceMismatch = result !== null ? !result : assignment.audienceMismatch; + // As in 1.13.4, an indeterminate (null) result counts as a match, so a cached mismatch is + // rebuilt and the unit gets what a fresh context with the same attributes would. + const newAudienceMismatch = typeof result === "boolean" ? !result : false; if (newAudienceMismatch !== assignment.audienceMismatch) { return false; diff --git a/src/jsonexpr/evaluator.ts b/src/jsonexpr/evaluator.ts index 5c52ff0..1c24d71 100644 --- a/src/jsonexpr/evaluator.ts +++ b/src/jsonexpr/evaluator.ts @@ -1,9 +1,12 @@ /* eslint-disable */ import { isEqualsDeep, isObject } from "../utils"; +/** @internal Thrown when a `var` path reads below an attribute whose value is null or undefined. */ +export class NullParentError extends TypeError {} + function parseSemver(version: string) { let v = version; - if (v.startsWith("v") || v.startsWith("V")) { + if (v.charAt(0) === "v" || v.charAt(0) === "V") { v = v.substring(1); } @@ -125,6 +128,9 @@ export class Evaluator { let target = this.vars ?? {}; for (let index = 0; index < frags.length; ++index) { const frag = frags[index]; + if (target == null) { + throw new NullParentError(`Cannot read '${frag}' of ${target} in var path '${path}'`); + } const value = target[frag]; if (value !== undefined) { diff --git a/src/matcher.ts b/src/matcher.ts index 683e8eb..64dfe4f 100644 --- a/src/matcher.ts +++ b/src/matcher.ts @@ -1,5 +1,6 @@ import { isObject } from "./utils"; import { JsonExpr } from "./jsonexpr/jsonexpr"; +import { NullParentError } from "./jsonexpr/evaluator"; export type RuleAction = { variant: number } | { split: number[] }; @@ -42,11 +43,12 @@ export class AudienceMatcher { if (audience && audience.filter) { if (Array.isArray(audience.filter) || isObject(audience.filter)) { - // As in 1.13.4, an audience whose evaluation throws (e.g. a path through a null - // attribute) is ignored rather than counted as a mismatch. + // As in 1.13.4, an audience whose path reads below a null attribute is ignored rather than + // counted as a mismatch. Any other evaluation error propagates, so strict audiences fail closed. try { return this._jsonExpr.evaluateBooleanExpr(audience.filter, vars); } catch (error) { + if (!(error instanceof NullParentError)) throw error; console.error(error); return null; } diff --git a/tsconfig.json b/tsconfig.json index acd4126..349d754 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -13,6 +13,7 @@ "isolatedModules": true, "moduleResolution": "node", "removeComments": true, + "stripInternal": true, "noImplicitAny": true, "strictNullChecks": true, "strictFunctionTypes": true, From cfe6cedea2abbeb784c7b8184206aa425ace1fd6 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 20 Nov 2026 08:05:03 +0000 Subject: [PATCH 19/92] fix(release): mark null-parent errors instead of subclassing TypeError Babel's built-in subclass helper cannot set the prototype on IE 10 (no Reflect, setPrototypeOf or __proto__), so instanceof NullParentError was false there and null-parent audiences failed closed. Throw a plain TypeError with a nullParent marker instead. check-es5.js now runs both bundles in an IE 10-like realm and fails unless a null-parent audience stays indeterminate with no error event; it fails on the previous code. Co-Authored-By: Claude Opus 5.5 --- scripts/check-es5.js | 47 +++++++++++++++++++++++++++++++++++++++ src/jsonexpr/evaluator.ts | 10 +++++---- src/matcher.ts | 3 +-- 3 files changed, 54 insertions(+), 6 deletions(-) diff --git a/scripts/check-es5.js b/scripts/check-es5.js index f57b8e0..6d41460 100644 --- a/scripts/check-es5.js +++ b/scripts/check-es5.js @@ -35,6 +35,53 @@ for (const file of ["absmartly.js", "absmartly.min.js"]) { } catch (error) { console.error(`dist/${file} does not start without native Map/Set: ${error.message}`); failed = true; + continue; + } + try { + checkIe10NullParentAudience(target); + console.log(`IE 10 null-parent audience OK: dist/${file}`); + } catch (error) { + console.error(`dist/${file} breaks a null-parent audience on IE 10: ${error.message}`); + failed = true; + } +} + +// IE 10 has no Reflect, Object.setPrototypeOf or __proto__. A null-parent audience path must stay +// indeterminate there (as in 1.13.4), not fail closed. Runs the bundle in a fresh realm with those removed. +function checkIe10NullParentAudience(target) { + const prelude = ` + delete this.Reflect; + delete Object.setPrototypeOf; + delete Object.prototype.__proto__; + `; + const sandbox = { + setTimeout, + clearTimeout, + setInterval, + clearInterval, + Promise, + console: { ...console, error() {} }, + }; + sandbox.self = sandbox; + const context = vm.createContext(sandbox); + vm.runInContext(prelude, context); + vm.runInContext(fs.readFileSync(target, "utf8"), context, { timeout: 10000 }); + const probe = `(function () { + var errors = 0; + var sdk = new absmartly.SDK({ endpoint: "http://x/v1", apiKey: "k", application: "web", environment: "prod", + eventLogger: function (c, name) { if (name === "error") errors++; } }); + var exp = { id: 1, name: "aud", iteration: 1, unitType: "session_id", seedHi: 3603515, seedLo: 233373850, + split: [0, 1], trafficSeedHi: 449867249, trafficSeedLo: 455443629, trafficSplit: [0, 1], fullOnVariant: 0, + applications: [{ name: "web" }], variants: [{ name: "A", config: null }, { name: "B", config: null }], + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + audienceStrict: true, customFieldValues: null }; + var ctx = sdk.createContextWith({ units: { session_id: "e791e240fcd3df7d238cfc285f475e8152fcc0ec" } }, { experiments: [exp] }); + ctx.attribute("user", null); + return { variant: ctx.treatment("aud"), errors: errors }; + })()`; + const result = vm.runInContext(probe, context); + if (result.variant !== 1 || result.errors !== 0) { + throw new Error(`expected variant 1 and 0 error events, got ${JSON.stringify(result)}`); } } process.exitCode = failed ? 1 : 0; diff --git a/src/jsonexpr/evaluator.ts b/src/jsonexpr/evaluator.ts index 1c24d71..e459a52 100644 --- a/src/jsonexpr/evaluator.ts +++ b/src/jsonexpr/evaluator.ts @@ -1,9 +1,6 @@ /* eslint-disable */ import { isEqualsDeep, isObject } from "../utils"; -/** @internal Thrown when a `var` path reads below an attribute whose value is null or undefined. */ -export class NullParentError extends TypeError {} - function parseSemver(version: string) { let v = version; if (v.charAt(0) === "v" || v.charAt(0) === "V") { @@ -129,7 +126,12 @@ export class Evaluator { for (let index = 0; index < frags.length; ++index) { const frag = frags[index]; if (target == null) { - throw new NullParentError(`Cannot read '${frag}' of ${target} in var path '${path}'`); + // A plain TypeError with a marker, not a subclass: subclassing built-ins breaks instanceof on IE 10. + const error: TypeError & { nullParent?: boolean } = new TypeError( + `Cannot read '${frag}' of ${target} in var path '${path}'` + ); + error.nullParent = true; + throw error; } const value = target[frag]; diff --git a/src/matcher.ts b/src/matcher.ts index 64dfe4f..1497a10 100644 --- a/src/matcher.ts +++ b/src/matcher.ts @@ -1,6 +1,5 @@ import { isObject } from "./utils"; import { JsonExpr } from "./jsonexpr/jsonexpr"; -import { NullParentError } from "./jsonexpr/evaluator"; export type RuleAction = { variant: number } | { split: number[] }; @@ -48,7 +47,7 @@ export class AudienceMatcher { try { return this._jsonExpr.evaluateBooleanExpr(audience.filter, vars); } catch (error) { - if (!(error instanceof NullParentError)) throw error; + if (!(error && (error as { nullParent?: boolean }).nullParent === true)) throw error; console.error(error); return null; } From ea19253232a7c468c73806bd99d2e54c6c8757b5 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 20 Nov 2026 08:39:50 +0000 Subject: [PATCH 20/92] test(release): fail closed on TypeError and truthy-marker audience errors A getter that throws a TypeError, or an error with a non-true nullParent marker, must still fail a strict audience closed with one error event. Kills the mutants that catch every TypeError or accept any truthy marker. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/release-compatibility.test.js | 44 +++++++++++++-------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index ac28c50..8b8db0e 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -623,23 +623,33 @@ describe("1.13.4 source and behaviour compatibility", () => { } }); - it("fails a strict audience closed when an attribute getter throws, and logs one error event", () => { - const eventLogger = jest.fn(); - const context = new SDK({ ...options, eventLogger }).createContextWith( - { units: { session_id: uid } }, - { experiments: [strictExp([{ eq: [{ var: "user/plan" }, { value: "pro" }] }])] } - ); - const user = {}; - Object.defineProperty(user, "plan", { - get() { - throw new Error("getter boom"); - }, - }); - context.attribute("user", user); - expect(context.treatment("aud")).toBe(0); - expect(context._exposures[0].audienceMismatch).toBe(true); - expect(eventLogger.mock.calls.filter(([, eventName]) => eventName === "error")).toHaveLength(1); - }); + it.each([ + ["an Error", () => new Error("getter boom")], + ["a TypeError", () => new TypeError("getter boom")], + [ + "an error object marked nullParent: 1", + () => Object.assign(new TypeError("getter boom"), { nullParent: 1 }), + ], + ])( + "fails a strict audience closed when an attribute getter throws %s, and logs one error event", + (_label, makeError) => { + const eventLogger = jest.fn(); + const context = new SDK({ ...options, eventLogger }).createContextWith( + { units: { session_id: uid } }, + { experiments: [strictExp([{ eq: [{ var: "user/plan" }, { value: "pro" }] }])] } + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw makeError(); + }, + }); + context.attribute("user", user); + expect(context.treatment("aud")).toBe(0); + expect(context._exposures[0].audienceMismatch).toBe(true); + expect(eventLogger.mock.calls.filter(([, eventName]) => eventName === "error")).toHaveLength(1); + } + ); it("logs a null-parent audience path to the console, without an error event", () => { const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); From aa38149cb8668fb60594afaa65fb6ff6238b7292 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 20 Nov 2026 09:15:14 +0000 Subject: [PATCH 21/92] docs(release): state which audience errors fail closed Only a path through a null attribute is still ignored as in 1.13.4; any other audience evaluation error now fails strict audiences closed with one error event. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b2f16ef..9295265 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,10 +47,11 @@ differs from the client one, who now get more (or fewer) retries to match it. `timeout: 0` keeps its 1.13.4 meaning: a request value of 0 falls back to the client timeout, and a client timeout of 0 means no retries. -- If the audience matcher itself fails unexpectedly, the audience now counts as a - mismatch (fail closed) and emits one logger `error` event. Errors inside an - audience expression (for example a path through a `null` attribute) are still - logged to the console and the audience ignored, as in 1.13.4. +- An audience whose evaluation throws now counts as a mismatch (fail closed) and + emits one logger `error` event; in 1.13.4 it was ignored, so strict audiences + could let users through. Affected: strict audiences with, for example, a throwing + attribute getter now serve control. Only a path through a `null` attribute is + still logged to the console and the audience ignored, as in 1.13.4. - New runtime dependency `@babel/runtime` (shared Babel helpers, which shrink the browser bundle). It declares Node `>=6.9.0`; the package still declares `>=6`, so Node 6.0–6.8 installs may warn. No helper types are exposed in the public API. From 87ead56045790c9fcdb962ec1eee4430d2dc13ed Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 20 Nov 2026 12:27:45 +0000 Subject: [PATCH 22/92] test(release): pin null-parent audience revalidation; fix CHANGELOG line A null-parent audience must keep its cached assignment across unrelated setAttribute calls (one exposure). Kills the mutant that rebuilds on every indeterminate result. Drop the CHANGELOG claim that 1.13.4 threw on audience errors; it logged them. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +-- src/__tests__/release-compatibility.test.js | 24 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9295265..18b41cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,8 +62,7 @@ can be retried. Concurrent flush/finalize waits for in-flight delivery. - Custom publisher failures and throwing event loggers no longer strand lifecycle promises or lose/duplicate successfully delivered events. -- Malformed variant configs are isolated rather than failing the entire context; - audience evaluation exceptions are logged instead of thrown. +- Malformed variant configs are isolated rather than failing the entire context. - The browser bundle is ES5 again (IE 10): `rfdc` >= 1.4 ships ES2015 syntax, so it is now transpiled, and the build fails if `dist/` is not ES5. - Query keys are encoded and unmatched query surrogates no longer throw URIError. diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 8b8db0e..a422117 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -678,6 +678,30 @@ describe("1.13.4 source and behaviour compatibility", () => { errorSpy.mockRestore(); }); + it.each([true, false])( + "keeps one exposure for a null-parent audience across unrelated setAttribute calls (strict=%p)", + (strict) => { + const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); + const exp = { + ...strictExp([{ eq: [{ var: "user/plan" }, { value: "pro" }] }]), + audienceStrict: strict, + }; + const context = new SDK(options).createContextWith( + { units: { session_id: uid } }, + { experiments: [exp] }, + { publishDelay: -1 } + ); + context.attribute("user", null); + expect(context.treatment("aud")).toBe(1); + context.attribute("other", 1); + expect(context.treatment("aud")).toBe(1); + context.attribute("other", 2); + expect(context.treatment("aud")).toBe(1); + expect(context.pending()).toBe(1); + errorSpy.mockRestore(); + } + ); + it("logs a failing rule condition with console.warn, not console.error", () => { const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); From 5196126a908decdf478e939318106fbf0221f136 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 20 Nov 2026 14:11:59 +0000 Subject: [PATCH 23/92] fix(release): preserve numeric ClientOptions readers with additive input options Keep the published ClientOptions.application.version type numeric and accept string versions through ClientInputOptions. Pin old typed reads in the external consumer and correct the finalize compatibility inventory. Co-Authored-By: Claude Opus 5.5 --- release/1.14.0-compatibility.md | 4 ++-- scripts/compatibility/consumer.ts | 5 +++++ src/client.ts | 8 ++++++-- src/sdk.ts | 12 ++++++------ 4 files changed, 19 insertions(+), 10 deletions(-) diff --git a/release/1.14.0-compatibility.md b/release/1.14.0-compatibility.md index 0898cfd..923c00c 100644 --- a/release/1.14.0-compatibility.md +++ b/release/1.14.0-compatibility.md @@ -32,7 +32,7 @@ This inventories public source/runtime differences, not just this PR's delta. | Low-level `Client` auth rules: `request()` authenticated by default, `post`/`put` honoured `auth:false`, `getUnauthed` became authenticated | d | Restore 1.13.4 rules exactly: `request()` sends headers only with `auth: true`, `post`/`put` always authenticate, `getUnauthed` is a plain GET. The additive `get()` (used by `getContext`) authenticates unless `auth: false`. | | `SDK` dropped client options passed as explicit `undefined` (`agent`, `timeout`, `keepalive`) | d | Restore 1.13.4 pass-through of every present key; `agent: undefined` again reaches the Client and is rejected. | | Versioned SDK X-Agent | b | Add from generated package version; custom agent untouched. Direct `Client` default remains `javascript-client`. | -| String application version accepted; utility return widened | a/d | Keep strings; overload `getApplicationVersion` so old numeric callers still receive `number` statically. | +| String application version accepted; utility return widened | a/d | Keep strings through additive `ClientInputOptions`; preserve the exported numeric `ClientOptions.application.version` and the numeric utility overload for old readers. | | Invalid/dotted application versions sent to collector Long header | c/b | Normalize GET and PUT to trimmed 1–18 ASCII digits or zero; retain full configured getter. | | Every publish adds `sdkVersion`, required `PublishParams.sdkVersion` | d | Restore 1.13 body/type; collector `PublishRequest` ignores this unknown field. SDK version remains in X-Agent and opt-in attributes. | | New normal-path auth deprecation warning | d | Remove; explicit auth still accepted without new stderr output. | @@ -42,7 +42,7 @@ This inventories public source/runtime differences, not just this PR's delta. | `getUnits()` changes live map to defensive copy | d | Restore live map and original `Units` return type. | | `getAttribute()` return changes from incorrect `undefined` declaration to `unknown` | c/d | Use `any` for compatibility with both strict and non-strict existing consumers; actual last-value behaviour unchanged. | | `ready(): Promise` narrows to boolean and README claims old errors | d | Restore declared Promise; published runtime already resolves true even on failure. Correct README, do not invent migration. | -| `finalize()` inferred `true \| Promise` narrows to `Promise` | c | Keep actual Promise-only result; published implementation never returned true. | +| `finalize()` inferred `true \| Promise` narrowed on main | d | Restore the released `true \| Promise` declaration, so old `=== true` guards compile; runtime was and remains Promise-only. | | Canonical UTF-8 for astral/unpaired surrogate UIDs changes hashes/assignment | d | Restore legacy UTF-16-code-unit encoding for all 1.x hashes; canonical change preserved on next/major for 2.0. | | Type-only inline imports raise declaration parser floor to TS4.5 | d | Restore old import syntax; TS3.9 consumer compile checks it. | | New required getters on duck-typed custom clients | d | Guard getters so existing custom clients don't crash context installation/evaluation. | diff --git a/scripts/compatibility/consumer.ts b/scripts/compatibility/consumer.ts index 1370aef..b6d50fb 100644 --- a/scripts/compatibility/consumer.ts +++ b/scripts/compatibility/consumer.ts @@ -165,3 +165,8 @@ void payload; void namedSdk; void ready; void value; + +function readReleasedApplicationVersion(options: ClientOptions): number { + return typeof options.application === "string" ? 0 : options.application.version; +} +void readReleasedApplicationVersion; diff --git a/src/client.ts b/src/client.ts index 2983ffd..f0e1d85 100644 --- a/src/client.ts +++ b/src/client.ts @@ -36,7 +36,7 @@ const RETRY_DELAY_MS = 50; export type ClientOptions = { agent?: string; apiKey: string; - application: string | ApplicationObject; + application: string | { name: string; version: number }; endpoint: string; environment: string; retries?: number; @@ -51,6 +51,10 @@ function applicationVersionHeader(version: number | string): number | string { return /^[0-9]{1,18}$/.test(String(candidate)) ? candidate : 0; } +export type ClientInputOptions = Omit & { + application: string | ApplicationObject; +}; + type NormalizedClientOptions = Omit, "application"> & { application: ApplicationObject; }; @@ -59,7 +63,7 @@ export default class Client { private readonly _opts: NormalizedClientOptions; private readonly _delay: number; - constructor(opts: ClientOptions) { + constructor(opts: ClientInputOptions) { const merged: Record = Object.assign( { agent: "javascript-client", diff --git a/src/sdk.ts b/src/sdk.ts index b5bf794..de56cf7 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -1,4 +1,4 @@ -import Client, { ClientOptions, ClientRequestOptions } from "./client"; +import Client, { ClientInputOptions, ClientRequestOptions } from "./client"; import Context, { ContextData, ContextOptions, ContextParams, Exposure, Goal } from "./context"; import { ContextPublisher, PublishParams } from "./publisher"; import { ContextDataProvider } from "./provider"; @@ -33,7 +33,7 @@ export default class SDK { private _provider: ContextDataProvider; private readonly _client: Client; - constructor(options: ClientOptions & SDKOptions) { + constructor(options: ClientInputOptions & SDKOptions) { const clientOptions = SDK._extractClientOptions(options); options = Object.assign({}, options); @@ -43,8 +43,8 @@ export default class SDK { this._provider = options.provider || new ContextDataProvider(); } - private static _extractClientOptions(options: ClientOptions & SDKOptions): ClientOptions { - const clientOptionKeys: (keyof ClientOptions)[] = [ + private static _extractClientOptions(options: ClientInputOptions & SDKOptions): ClientInputOptions { + const clientOptionKeys: (keyof ClientInputOptions)[] = [ "application", "agent", "apiKey", @@ -54,7 +54,7 @@ export default class SDK { "retries", "timeout", ]; - const extracted: Partial = { + const extracted: Partial = { agent: `absmartly-javascript-sdk/${SDK_VERSION}`, }; @@ -66,7 +66,7 @@ export default class SDK { } } - return extracted as ClientOptions; + return extracted as ClientInputOptions; } getContextData(requestOptions: ClientRequestOptions) { From 6770fcc63284c40caf67ae13490e2b47ec22c858 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 20 Nov 2026 14:42:45 +0000 Subject: [PATCH 24/92] fix(release): keep released constructor parameter types via overloads Declare the released ClientOptions signature last on the SDK and Client constructors, so ConstructorParameters keeps its 1.13.4 numeric application.version, with a ClientInputOptions overload first for string versions. The external consumer now reads constructor parameters too and fails on the previous types. CHANGELOG lists the string version under Added. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ scripts/compatibility/consumer.ts | 13 ++++++++++++- src/client.ts | 3 +++ src/sdk.ts | 6 +++++- 4 files changed, 23 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18b41cf..1992a47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ - Semantic-version expression operators (`semver_eq/gt/gte/lt/lte`) and `Evaluator.versionCompare`; old expression operators keep their conversion rules. - Optional `includeSystemAttributes` publishes `sdk_name` and `sdk_version` only. +- The `SDK` and `Client` constructors also accept a string application version + (`application: { name, version: "1.2.3" }`) through the new `ClientInputOptions` + overload. `ClientOptions` and the constructors' released signatures are unchanged. - Tag-driven npm Trusted Publishing and a manual publish dry run, plus a `repository` field in `package.json`, which npm provenance requires. diff --git a/scripts/compatibility/consumer.ts b/scripts/compatibility/consumer.ts index b6d50fb..41617d8 100644 --- a/scripts/compatibility/consumer.ts +++ b/scripts/compatibility/consumer.ts @@ -7,7 +7,7 @@ import absmartly, { mergeConfig, AbortController, } from "@absmartly/javascript-sdk"; -import { ClientRequestOptions, ClientOptions } from "@absmartly/javascript-sdk/types/client"; +import Client, { ClientRequestOptions, ClientOptions } from "@absmartly/javascript-sdk/types/client"; import { ContextData, ContextOptions, @@ -170,3 +170,14 @@ function readReleasedApplicationVersion(options: ClientOptions): number { return typeof options.application === "string" ? 0 : options.application.version; } void readReleasedApplicationVersion; + +type ReleasedSdkOptions = ConstructorParameters[0]; +type ReleasedClientOptions = ConstructorParameters[0]; +function readSdkCtorVersion(options: ReleasedSdkOptions): number { + return typeof options.application === "string" ? 0 : options.application.version; +} +function readClientCtorVersion(options: ReleasedClientOptions): number { + return typeof options.application === "string" ? 0 : options.application.version; +} +void readSdkCtorVersion; +void readClientCtorVersion; diff --git a/src/client.ts b/src/client.ts index f0e1d85..df6eedf 100644 --- a/src/client.ts +++ b/src/client.ts @@ -63,6 +63,9 @@ export default class Client { private readonly _opts: NormalizedClientOptions; private readonly _delay: number; + // The released signature is declared last, so ConstructorParameters keeps its 1.13.4 type. + constructor(opts: ClientInputOptions); + constructor(opts: ClientOptions); constructor(opts: ClientInputOptions) { const merged: Record = Object.assign( { diff --git a/src/sdk.ts b/src/sdk.ts index de56cf7..5a69455 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -1,4 +1,4 @@ -import Client, { ClientInputOptions, ClientRequestOptions } from "./client"; +import Client, { ClientInputOptions, ClientOptions, ClientRequestOptions } from "./client"; import Context, { ContextData, ContextOptions, ContextParams, Exposure, Goal } from "./context"; import { ContextPublisher, PublishParams } from "./publisher"; import { ContextDataProvider } from "./provider"; @@ -33,6 +33,10 @@ export default class SDK { private _provider: ContextDataProvider; private readonly _client: Client; + // The released signature is declared last, so ConstructorParameters keeps its 1.13.4 type; + // the first overload additionally accepts a string application version. + constructor(options: ClientInputOptions & SDKOptions); + constructor(options: ClientOptions & SDKOptions); constructor(options: ClientInputOptions & SDKOptions) { const clientOptions = SDK._extractClientOptions(options); options = Object.assign({}, options); From 4bbfb92e31090907c1841a25d4d2cd31fe6394cd Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 20 Nov 2026 15:55:13 +0000 Subject: [PATCH 25/92] test(release): gate constructor readers and zero-request-timeout retry budget Compile released ConstructorParameters readers with the gated tsc and assert request timeout zero still retries under the client budget. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/constructor-types.ts | 11 +++++++++++ src/__tests__/release-compatibility.test.js | 13 +++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 src/__tests__/constructor-types.ts diff --git a/src/__tests__/constructor-types.ts b/src/__tests__/constructor-types.ts new file mode 100644 index 0000000..da7ff9b --- /dev/null +++ b/src/__tests__/constructor-types.ts @@ -0,0 +1,11 @@ +import SDK from "../sdk"; +import Client from "../client"; + +// Included in tsc: ConstructorParameters uses the final overload, which must remain the released type. +export function sdkApplicationVersion(options: ConstructorParameters[0]): number { + return typeof options.application === "string" ? 0 : options.application.version; +} + +export function clientApplicationVersion(options: ConstructorParameters[0]): number { + return typeof options.application === "string" ? 0 : options.application.version; +} diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index a422117..7a4de85 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -14,6 +14,19 @@ jest.mock("../fetch"); const options = { endpoint: "https://collector/v1", apiKey: "k", application: "web", environment: "prod" }; describe("1.13.4 source and behaviour compatibility", () => { + it("uses the client retry budget for request timeout zero", async () => { + sdkFetch.mockRejectedValue(new Error("connection refused")); + const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); + try { + const client = new Client({ ...options, timeout: 3000, retries: 1 }); + const error = await client.request({ path: "/context", method: "GET", timeout: 0 }).catch((e) => e); + expect(sdkFetch).toHaveBeenCalledTimes(2); + expect(error.name).toBe("RetryError"); + } finally { + warn.mockRestore(); + } + }); + beforeEach(() => { sdkFetch.mockReset(); }); From 68e54f6c944a3e768b0a190c9a5886131540ec68 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 20 Nov 2026 16:56:56 +0000 Subject: [PATCH 26/92] fix(release): retain native expression errors and utility return types Mark and rethrow the original null-indexing TypeError without replacing its message or enumerable shape; keep the numeric getApplicationVersion overload last for old ReturnType readers. Add gated regression checks. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/constructor-types.ts | 5 +++++ src/__tests__/release-compatibility.test.js | 20 ++++++++++++++++++++ src/jsonexpr/evaluator.ts | 12 +++++------- src/utils.ts | 2 +- 4 files changed, 31 insertions(+), 8 deletions(-) diff --git a/src/__tests__/constructor-types.ts b/src/__tests__/constructor-types.ts index da7ff9b..0b6604a 100644 --- a/src/__tests__/constructor-types.ts +++ b/src/__tests__/constructor-types.ts @@ -9,3 +9,8 @@ export function sdkApplicationVersion(options: ConstructorParameters export function clientApplicationVersion(options: ConstructorParameters[0]): number { return typeof options.application === "string" ? 0 : options.application.version; } + +import { getApplicationVersion } from "../utils"; +export function releasedUtilityReturnType(value: ReturnType): number { + return value + 1; +} diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 7a4de85..09806cf 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -1,3 +1,4 @@ +import { JsonExpr } from "../jsonexpr/jsonexpr"; import SDK from "../sdk"; import { SDK_VERSION } from "../version"; import pkg from "../../package.json"; @@ -14,6 +15,25 @@ jest.mock("../fetch"); const options = { endpoint: "https://collector/v1", apiKey: "k", application: "web", environment: "prod" }; describe("1.13.4 source and behaviour compatibility", () => { + it("preserves the runtime's native null-indexing error text and shape", () => { + let native; + try { + const nullValue = null; + nullValue["plan"]; + } catch (error) { + native = error; + } + let actual; + try { + new JsonExpr().evaluateExpr({ var: "user/plan" }, { user: null }); + } catch (error) { + actual = error; + } + expect(actual).toBeInstanceOf(TypeError); + expect(actual.message).toBe(native.message); + expect(Object.keys(actual)).toEqual(Object.keys(native)); + }); + it("uses the client retry budget for request timeout zero", async () => { sdkFetch.mockRejectedValue(new Error("connection refused")); const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); diff --git a/src/jsonexpr/evaluator.ts b/src/jsonexpr/evaluator.ts index e459a52..3cdbaa6 100644 --- a/src/jsonexpr/evaluator.ts +++ b/src/jsonexpr/evaluator.ts @@ -125,16 +125,14 @@ export class Evaluator { let target = this.vars ?? {}; for (let index = 0; index < frags.length; ++index) { const frag = frags[index]; - if (target == null) { - // A plain TypeError with a marker, not a subclass: subclassing built-ins breaks instanceof on IE 10. - const error: TypeError & { nullParent?: boolean } = new TypeError( - `Cannot read '${frag}' of ${target} in var path '${path}'` - ); - error.nullParent = true; + let value; + try { + value = target[frag]; + } catch (error) { + if (target == null) Object.defineProperty(error, "nullParent", { value: true }); throw error; } - const value = target[frag]; if (value !== undefined) { target = value; continue; diff --git a/src/utils.ts b/src/utils.ts index 5b7be79..90a14fb 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -3,8 +3,8 @@ import { md5 } from "./md5"; export const getApplicationName = (app: string | { name: string; version: number | string }): string => typeof app !== "string" ? app.name : app; -export function getApplicationVersion(app: string | { name: string; version: number }): number; export function getApplicationVersion(app: string | { name: string; version: number | string }): number | string; +export function getApplicationVersion(app: string | { name: string; version: number }): number; export function getApplicationVersion(app: string | { name: string; version: number | string }): number | string { return typeof app !== "string" ? app.version : 0; } From c3361817d209eb017691ffdfc5967a813b42fcf0 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 20 Nov 2026 17:55:51 +0000 Subject: [PATCH 27/92] fix(release): preserve direct getApplicationVersion types and pin unknown fields Declare the released numeric getApplicationVersion overload first (so direct calls type as number) and again last (so ReturnType stays number), with the wide overload between for string versions. A gated compile pins direct calls and ReturnType. A new test ignores unknown context-data fields at every payload level across creation and refresh, killing a rejecting-decoder mutant. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/constructor-types.ts | 6 +++ src/__tests__/release-compatibility.test.js | 52 +++++++++++++++++++++ src/utils.ts | 1 + 3 files changed, 59 insertions(+) diff --git a/src/__tests__/constructor-types.ts b/src/__tests__/constructor-types.ts index 0b6604a..31845c4 100644 --- a/src/__tests__/constructor-types.ts +++ b/src/__tests__/constructor-types.ts @@ -14,3 +14,9 @@ import { getApplicationVersion } from "../utils"; export function releasedUtilityReturnType(value: ReturnType): number { return value + 1; } + +export const releasedDirectUtilityTypes: [number, number, number | string] = [ + getApplicationVersion("web"), + getApplicationVersion({ name: "web", version: 3 }), + getApplicationVersion({ name: "web", version: "1.2.3" }), +]; diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 09806cf..2b554cb 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -15,6 +15,58 @@ jest.mock("../fetch"); const options = { endpoint: "https://collector/v1", apiKey: "k", application: "web", environment: "prod" }; describe("1.13.4 source and behaviour compatibility", () => { + it("ignores unknown context-data fields at every payload level, including after refresh", async () => { + const eventLogger = jest.fn(); + const experiment = (id, experimentName) => ({ + id, + name: experimentName, + iteration: 1, + unitType: "session_id", + seedHi: 3603515 + id, + seedLo: 233373850 + id, + split: [0.5, 0.5], + trafficSeedHi: 449867249, + trafficSeedLo: 455443629, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "web", futureApplication: [1] }], + audience: null, + audienceStrict: false, + variants: [ + { name: "A", config: null, futureVariant: { nested: true } }, + { name: "B", config: null, futureVariant: 2 }, + ], + customFieldValues: [{ name: "f", type: "string", value: "x", futureField: [1, { y: 2 }] }], + futureExperiment: "scalar", + futureObject: { a: [1] }, + futureArray: [{ b: 2 }], + }); + const data = { + experiments: [experiment(21, "unknownA"), experiment(22, "unknownB")], + futureRoot: { nested: [1] }, + futureList: [1, "x"], + }; + const provider = { getContextData: () => Promise.resolve(data) }; + const uids = ["u1", "u2", "u3", "u4"]; + const assigned = () => + uids.map((uid) => { + const context = new SDK({ ...options, provider, eventLogger }).createContextWith( + { units: { session_id: uid } }, + data + ); + return [context.treatment("unknownA"), context.treatment("unknownB")]; + }); + const before = assigned(); + const context = new SDK({ ...options, provider, eventLogger }).createContextWith( + { units: { session_id: "u1" } }, + data + ); + await context.refresh(); + expect(assigned()).toEqual(before); + expect([context.treatment("unknownA"), context.treatment("unknownB")]).toEqual(before[0]); + expect(eventLogger.mock.calls.filter(([, eventName]) => eventName === "error")).toHaveLength(0); + }); + it("preserves the runtime's native null-indexing error text and shape", () => { let native; try { diff --git a/src/utils.ts b/src/utils.ts index 90a14fb..dcc364f 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -3,6 +3,7 @@ import { md5 } from "./md5"; export const getApplicationName = (app: string | { name: string; version: number | string }): string => typeof app !== "string" ? app.name : app; +export function getApplicationVersion(app: string | { name: string; version: number }): number; export function getApplicationVersion(app: string | { name: string; version: number | string }): number | string; export function getApplicationVersion(app: string | { name: string; version: number }): number; export function getApplicationVersion(app: string | { name: string; version: number | string }): number | string { From 834aebef9be85446a18e8ca73f0deff655903ed7 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 20 Nov 2026 19:10:43 +0000 Subject: [PATCH 28/92] fix(release): restore forEach on the audience path, test getContext auth:false, keep tests out of the package Use forEach in _getAttributesMap as 1.13.4 did; it is measurably faster than the compiled for...of or an index loop on audience re-evaluation. Add a test that getContext({ auth: false }) sends no SDK headers. Type-check the type-only tests through tsconfig.typecheck.json (noEmit) so they gate the build without shipping in lib/, es/ or types/. Document the abort shim and fetch detection fixes, and the small residual audience-path cost at very long attribute histories. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +++++++++ package.json | 2 +- src/__tests__/release-compatibility.test.js | 6 ++++++ src/context.ts | 7 ++++--- tsconfig.json | 2 +- tsconfig.typecheck.json | 8 ++++++++ 6 files changed, 29 insertions(+), 5 deletions(-) create mode 100644 tsconfig.typecheck.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 1992a47..671de35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,10 @@ - New runtime dependency `@babel/runtime` (shared Babel helpers, which shrink the browser bundle). It declares Node `>=6.9.0`; the package still declares `>=6`, so Node 6.0–6.8 installs may warn. No helper types are exposed in the public API. +- Re-evaluating an audience after `setAttribute` now also checks the assignment-rule + and holdout state, so it costs slightly more with very long attribute histories + (measured about 10% at 3,000 attributes; unchanged at 1,000 and below). Ordinary + cached reads are unaffected. ### Fixed @@ -69,3 +73,8 @@ - The browser bundle is ES5 again (IE 10): `rfdc` >= 1.4 ships ES2015 syntax, so it is now transpiled, and the build fails if `dist/` is not ES5. - Query keys are encoded and unmatched query surrogates no longer throw URIError. +- The bundled `AbortController` shim matches the native one: a second `abort()` is + a no-op (listeners fire once) and `signal.reason` is set. +- `fetch` is detected through `globalThis` as well as `window`/`self`/`global`, and + a missing implementation now throws "No fetch implementation found" instead of an + undefined-call TypeError. diff --git a/package.json b/package.json index 2174ac5..94293ad 100644 --- a/package.json +++ b/package.json @@ -40,7 +40,7 @@ "pretest": "npm run -s generate-version", "test": "jest --coverage", "prepack": "npm run -s build", - "compile": "tsc", + "compile": "tsc && tsc -p tsconfig.typecheck.json", "generate-version": "node scripts/generate-version.js", "prepare": "husky && npm run -s compile && npm run -s build-es && npm run -s build-cjs && npm run -s build-browser" }, diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 2b554cb..8575676 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -408,6 +408,12 @@ describe("1.13.4 source and behaviour compatibility", () => { spy.mockRestore(); }); + it("sends no SDK headers from getContext() when auth is false, as 1.13.4 did", async () => { + sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({ experiments: [] }) }); + await new Client(options).getContext({ auth: false }); + expect(sdkFetch.mock.calls[0][1]).not.toHaveProperty("headers"); + }); + it("routes getContext() through a subclass's getUnauthed() override", async () => { sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({ experiments: [] }) }); const seen = []; diff --git a/src/context.ts b/src/context.ts index 5216674..0cff149 100644 --- a/src/context.ts +++ b/src/context.ts @@ -580,9 +580,10 @@ export default class Context { return this._attrsMapCache; } const attrs: Record = this._getSystemAttributes(); - for (let i = 0; i < this._attrs.length; i++) { - attrs[this._attrs[i].name] = this._attrs[i].value; - } + // forEach, as in 1.13.4: measurably faster here than the compiled for...of or an index loop. + this._attrs.forEach((attr) => { + attrs[attr.name] = attr.value; + }); this._attrsMapCache = attrs; this._attrsMapCacheSeq = this._attrsSeq; return attrs; diff --git a/tsconfig.json b/tsconfig.json index 349d754..8f89305 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -28,6 +28,6 @@ "resolveJsonModule": true, "baseUrl": "." }, - "exclude": ["node_modules"], + "exclude": ["node_modules", "src/__tests__"], "include": ["./src/**/*.ts"] } diff --git a/tsconfig.typecheck.json b/tsconfig.typecheck.json new file mode 100644 index 0000000..18f9b00 --- /dev/null +++ b/tsconfig.typecheck.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": true + }, + "exclude": ["node_modules"], + "include": ["./src/**/*.ts"] +} From 2396511199ee93438f6f93dad2bde90219f4d392 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 20 Nov 2026 19:46:59 +0000 Subject: [PATCH 29/92] perf(release): restore 1.13.4 loop shapes on attribute paths Use forEach in getAttributes() and for the system-attribute name set, and map() to build the publish attribute list, as 1.13.4 did; on long attribute histories these are measurably faster than index or push loops. A counter test fails if any of these paths goes back to an iterator loop. Restate the audience-path CHANGELOG cost from fresh measurements. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 ++++--- src/__tests__/release-compatibility.test.js | 21 +++++++++++++++++++++ src/context.ts | 21 ++++++++++----------- 3 files changed, 35 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 671de35..209e88a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,9 +59,10 @@ browser bundle). It declares Node `>=6.9.0`; the package still declares `>=6`, so Node 6.0–6.8 installs may warn. No helper types are exposed in the public API. - Re-evaluating an audience after `setAttribute` now also checks the assignment-rule - and holdout state, so it costs slightly more with very long attribute histories - (measured about 10% at 3,000 attributes; unchanged at 1,000 and below). Ordinary - cached reads are unaffected. + and holdout state. Measured on Node 22 (synthetic, one audience experiment): about + 4% faster than 1.13.4 with 300 attributes, about 6% slower with 1,000 and about + 16% slower with 3,000. Ordinary cached reads, `getAttributes()` and publishing are + at or below 1.13.4 cost. ### Fixed diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 8575676..a0b8819 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -408,6 +408,27 @@ describe("1.13.4 source and behaviour compatibility", () => { spy.mockRestore(); }); + it("builds the attribute map, getAttributes() and the publish list with one pass over the history", async () => { + const publisher = { publish: jest.fn(() => Promise.resolve()) }; + const context = new SDK({ ...options, publisher }).createContextWith( + { units: { session_id: "u1" } }, + { experiments: [] }, + { publishDelay: -1 } + ); + for (let i = 0; i < 5; i++) context.attribute(`a${i}`, i); + // Count iterator use: a for...of over the history calls Symbol.iterator, forEach/map do not. + const iterator = jest.spyOn(context._attrs, Symbol.iterator); + const forEach = jest.spyOn(context._attrs, "forEach"); + const map = jest.spyOn(context._attrs, "map"); + context._getAttributesMap(); + context.getAttributes(); + context.track("g"); + await context.publish(); + expect(iterator).not.toHaveBeenCalled(); + expect(forEach).toHaveBeenCalledTimes(2); + expect(map).toHaveBeenCalledTimes(1); + }); + it("sends no SDK headers from getContext() when auth is false, as 1.13.4 did", async () => { sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({ experiments: [] }) }); await new Client(options).getContext({ auth: false }); diff --git a/src/context.ts b/src/context.ts index 0cff149..483b6f2 100644 --- a/src/context.ts +++ b/src/context.ts @@ -409,10 +409,10 @@ export default class Context { getAttributes() { const attributes: Record = {}; - // Index loops: the compiled for...of adds an iterator helper per call on these hot paths. - for (let i = 0; i < this._attrs.length; i++) { - attributes[this._attrs[i].name] = this._attrs[i].value; - } + // forEach, as in 1.13.4: measurably faster on long attribute histories than for...of or an index loop. + this._attrs.forEach((attr) => { + attributes[attr.name] = attr.value; + }); return attributes; } @@ -1120,7 +1120,9 @@ export default class Context { const client = this._sdk.getClient(); // A plain object, not a Set: the browser bundle still supports IE 10, which has no Set. const userNames: Record = {}; - for (let i = 0; i < this._attrs.length; i++) userNames[this._attrs[i].name] = true; + this._attrs.forEach((attr) => { + userNames[attr.name] = true; + }); const addSystemAttribute = (attrName: string, value: unknown) => { if (!Object.prototype.hasOwnProperty.call(userNames, attrName)) { allAttributes.push({ name: attrName, value, setAt: systemSetAt }); @@ -1132,12 +1134,9 @@ export default class Context { addSystemAttribute("sdk_version", SDK_VERSION); } - for (let i = 0; i < this._attrs.length; i++) { - const x = this._attrs[i]; - allAttributes.push({ name: x.name, value: x.value, setAt: x.setAt }); - } - - return allAttributes; + // Built with map(), as 1.13.4 did; pushing one element at a time is measurably slower here. + const userAttributes = this._attrs.map((x) => ({ name: x.name, value: x.value, setAt: x.setAt })); + return allAttributes.length === 0 ? userAttributes : allAttributes.concat(userAttributes); } // A caught exception or a rejected promise's reason can be any value. Only From d17d3094aac9402d36d66560c716824489096877 Mon Sep 17 00:00:00 2001 From: lux worker Date: Sat, 21 Nov 2026 01:29:40 +0000 Subject: [PATCH 30/92] test(release): pin the includeSystemAttributes publish loop; scope the CHANGELOG cost note Kills the surviving mutant that turns the system-attribute name loop back into for...of. The CHANGELOG publish-cost sentence now says default publishing and states the opt-in includeSystemAttributes cost. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++++-- src/__tests__/release-compatibility.test.js | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 209e88a..c65f346 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,8 +61,10 @@ - Re-evaluating an audience after `setAttribute` now also checks the assignment-rule and holdout state. Measured on Node 22 (synthetic, one audience experiment): about 4% faster than 1.13.4 with 300 attributes, about 6% slower with 1,000 and about - 16% slower with 3,000. Ordinary cached reads, `getAttributes()` and publishing are - at or below 1.13.4 cost. + 16% slower with 3,000. Ordinary cached reads, `getAttributes()` and default + publishing are at or below 1.13.4 cost. With the new opt-in + `includeSystemAttributes`, publishing also builds a set of attribute names (about + 1.9x the default publish at 3,000 attributes); the option did not exist in 1.13.4. ### Fixed diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index a0b8819..78b32bf 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -429,6 +429,22 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(map).toHaveBeenCalledTimes(1); }); + it("publishes with includeSystemAttributes without an iterator loop over the history", async () => { + const publisher = { publish: jest.fn(() => Promise.resolve()) }; + const context = new SDK({ ...options, publisher }).createContextWith( + { units: { session_id: "u1" } }, + { experiments: [] }, + { publishDelay: -1, includeSystemAttributes: true } + ); + for (let i = 0; i < 5; i++) context.attribute(`a${i}`, i); + const iterator = jest.spyOn(context._attrs, Symbol.iterator); + context.track("g"); + await context.publish(); + expect(iterator).not.toHaveBeenCalled(); + const names = publisher.publish.mock.calls[0][0].attributes.map((a) => a.name); + expect(names.slice(0, 2)).toEqual(["sdk_name", "sdk_version"]); + }); + it("sends no SDK headers from getContext() when auth is false, as 1.13.4 did", async () => { sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({ experiments: [] }) }); await new Client(options).getContext({ auth: false }); From abcf7c270576ae34778179efe68a415bb2d81ceb Mon Sep 17 00:00:00 2001 From: lux worker Date: Sat, 21 Nov 2026 03:33:23 +0000 Subject: [PATCH 31/92] fix(release): classify null-parent audience reads by identity; tighten release tests The audience matcher trusted a nullParent property on any thrown error, so a getter that threw a TypeError with that property could admit a unit to a strict audience. The evaluator now records the exact error it caught while reading below a null value, and only that error yields the 1.13.4 indeterminate result; everything else fails closed. The manual publish test now asks the pinned npm 11.6.2 whether each command is an effective dry run, so a later --no-dry-run is caught. The live-unit holdout test asserts the holdout exposure itself. Manual runs collapse to one token-free dry-run preflight, documented as not exercising authentication. Applies the review's comment cleanups. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/publish.yml | 25 ++---------- CHANGELOG.md | 5 ++- release/PUBLISHING.md | 10 ++--- scripts/__tests__/check-release.test.js | 45 +++++++++++++++------ scripts/check-release.js | 3 -- scripts/compatibility/runtime.js | 1 - src/__tests__/client.test.js | 1 - src/__tests__/release-compatibility.test.js | 9 ++++- src/context.ts | 4 +- src/jsonexpr/evaluator.ts | 4 +- src/jsonexpr/jsonexpr.ts | 16 ++++++++ src/matcher.ts | 11 +---- 12 files changed, 74 insertions(+), 60 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b14b664..de5463b 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -5,11 +5,6 @@ on: tags: - 'v*' workflow_dispatch: - inputs: - use_npm_token: - description: 'Opt in to NPM_TOKEN authentication for the manual dry run only' - type: boolean - default: false permissions: contents: read @@ -49,26 +44,14 @@ jobs: - name: Inspect package run: npm pack --dry-run --ignore-scripts - # Manual runs are always dry runs. NPM_TOKEN is an opt-in fallback for - # testing token authentication, never a replacement for tag-triggered OIDC. - - name: Dry-run publish with OIDC - if: github.event_name == 'workflow_dispatch' && !inputs.use_npm_token + # A manual run is a package preflight only: npm's dry run skips the authenticated publish request, + # so it cannot prove OIDC or any token works. Only a pushed v* tag publishes. + - name: Dry-run publish (package preflight) + if: github.event_name == 'workflow_dispatch' run: npm publish --dry-run --ignore-scripts --provenance --access public --tag "$DIST_TAG" env: DIST_TAG: ${{ steps.release.outputs.dist_tag }} - - name: Dry-run publish with token fallback - if: github.event_name == 'workflow_dispatch' && inputs.use_npm_token - run: | - if [ -z "$NODE_AUTH_TOKEN" ]; then - echo 'NPM_TOKEN must be configured for the token fallback.' >&2 - exit 1 - fi - npm publish --dry-run --ignore-scripts --provenance --access public --tag "$DIST_TAG" - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - DIST_TAG: ${{ steps.release.outputs.dist_tag }} - - name: Publish with trusted publishing if: github.event_name == 'push' run: npm publish --ignore-scripts --provenance --access public --tag "$DIST_TAG" diff --git a/CHANGELOG.md b/CHANGELOG.md index c65f346..6246ac9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,8 +13,9 @@ - The `SDK` and `Client` constructors also accept a string application version (`application: { name, version: "1.2.3" }`) through the new `ClientInputOptions` overload. `ClientOptions` and the constructors' released signatures are unchanged. -- Tag-driven npm Trusted Publishing and a manual publish dry run, plus a - `repository` field in `package.json`, which npm provenance requires. +- Tag-driven npm Trusted Publishing, a manual dry-run package preflight (it does + not exercise authentication), and a `repository` field in `package.json`, which + npm provenance requires. ### Changed diff --git a/release/PUBLISHING.md b/release/PUBLISHING.md index 1daf34c..f159e77 100644 --- a/release/PUBLISHING.md +++ b/release/PUBLISHING.md @@ -18,11 +18,11 @@ group `npm-publish-absmartly-javascript-sdk`, with `cancel-in-progress: false`. Registry/tag validation and publishing run inside that same locked job, so concurrent release tags cannot both validate against a stale `latest` and then move it backwards. -`workflow_dispatch` is **always a dry run**. Its optional `use_npm_token` input -uses `secrets.NPM_TOKEN` as `NODE_AUTH_TOKEN` for a fallback authentication test -only. If opted in, the owner must supply that secret; it is not needed for OIDC. -A manual dry run does not prove npm will accept OIDC on a real tag: the owner must -retain the npm publisher configuration and approve any environment protections. +`workflow_dispatch` is **always a dry run** and is a package preflight only: it checks +the version, tag selection, build and package contents. npm's dry run skips the +authenticated publish request, so it does not prove OIDC (or any token) works; the +owner must keep the npm trusted-publisher configuration and approve any environment +protections. No `NPM_TOKEN` secret is used or needed. Prereleases use a bounded set of distribution channels: `alpha`, `beta`, `rc`, and `next`. The first prerelease identifier is matched case-insensitively and normalized diff --git a/scripts/__tests__/check-release.test.js b/scripts/__tests__/check-release.test.js index 64e4183..86efc64 100644 --- a/scripts/__tests__/check-release.test.js +++ b/scripts/__tests__/check-release.test.js @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/no-var-requires, no-shadow, no-template-curly-in-string */ /* global BigInt */ const { readFileSync } = require("fs"); +const { execFileSync } = require("child_process"); const path = require("path"); const yaml = require("js-yaml"); const { majorOf, releaseTag, checkRepository } = require("../check-release"); @@ -95,7 +96,7 @@ describe("publish workflow", () => { expect(validationIndex).toBeGreaterThanOrEqual(0); expect(job.steps[validationIndex].id).toBe("release"); expect(job.steps[validationIndex].if).toBeUndefined(); - expect(publishSteps).toHaveLength(3); + expect(publishSteps).toHaveLength(2); for (const step of publishSteps) { expect(job.steps.indexOf(step)).toBeGreaterThan(validationIndex); expect(step.env.DIST_TAG).toBe("${{ steps.release.outputs.dist_tag }}"); @@ -104,20 +105,38 @@ describe("publish workflow", () => { } }); - test("keeps manual runs dry and token-free trusted publishing restricted to pushes", () => { + // Asks the workflow's pinned npm how it parses each publish command's flags, so a later negating + // flag (for example --no-dry-run after --dry-run) is caught, not just the presence of --dry-run. + test("npm 11.6.2 parses every manual publish command as an effective dry run", () => { + const npmVersion = /npm@(\d+\.\d+\.\d+)/.exec(job.steps.map((step) => step.run || "").join("\n"))[1]; + const effectiveDryRun = (run) => { + const line = run.split("\n").find((l) => /^\s*npm publish\b/.test(l)); + const args = line + .trim() + .split(/\s+/) + .slice(2) + .map((arg) => arg.replace(/^"\$DIST_TAG"$/, "latest")); + return execFileSync("npx", ["-y", `npm@${npmVersion}`, "config", "get", "dry-run", ...args], { + encoding: "utf8", + }).trim(); + }; + const manual = publishSteps.filter((step) => step.if && step.if.includes("workflow_dispatch")); + expect(manual.length).toBeGreaterThan(0); + for (const step of manual) expect(effectiveDryRun(step.run)).toBe("true"); + const live = publishSteps.filter((step) => step.if === "github.event_name == 'push'"); + expect(live.map((step) => effectiveDryRun(step.run))).toEqual(["false"]); + }, 120000); + + test("keeps manual runs to one dry-run preflight and publishes only on a pushed tag, with no token", () => { expect(workflow.on.push.tags).toEqual(["v*"]); - expect(workflow.on.workflow_dispatch.inputs.use_npm_token.default).toBe(false); + expect(workflow.on.workflow_dispatch).toBeNull(); expect(workflow.permissions["id-token"]).toBe("write"); - const liveSteps = publishSteps.filter((step) => !step.run.includes("--dry-run")); - expect(liveSteps).toHaveLength(1); - expect(liveSteps[0].if).toBe("github.event_name == 'push'"); - expect(liveSteps[0].env.NODE_AUTH_TOKEN).toBeUndefined(); - const drySteps = publishSteps.filter((step) => step.run.includes("--dry-run")); - expect(drySteps.map((step) => step.if)).toEqual([ - "github.event_name == 'workflow_dispatch' && !inputs.use_npm_token", - "github.event_name == 'workflow_dispatch' && inputs.use_npm_token", + expect(publishSteps).toHaveLength(2); + expect(publishSteps.map((step) => step.if)).toEqual([ + "github.event_name == 'workflow_dispatch'", + "github.event_name == 'push'", ]); - expect(drySteps[0].env.NODE_AUTH_TOKEN).toBeUndefined(); - expect(drySteps[1].env.NODE_AUTH_TOKEN).toBe("${{ secrets.NPM_TOKEN }}"); + for (const step of publishSteps) expect(step.env.NODE_AUTH_TOKEN).toBeUndefined(); + expect(JSON.stringify(workflow)).not.toContain("NPM_TOKEN"); }); }); diff --git a/scripts/check-release.js b/scripts/check-release.js index c9726a0..9bde1c3 100644 --- a/scripts/check-release.js +++ b/scripts/check-release.js @@ -25,9 +25,6 @@ function compareCore(a, b) { return 0; } -// Prereleases use alpha, beta, rc or next (case-insensitive), with all other ids mapped to next. -// A stable release goes to "latest" only when it is newer than the current latest; an older major -// goes to v-lts, and an older version in the same major line is refused. function releaseTag(packageVersion, latestVersion, gitTag) { const major = majorOf(packageVersion); const latestMajor = majorOf(latestVersion); diff --git a/scripts/compatibility/runtime.js b/scripts/compatibility/runtime.js index 3dff05d..615ad30 100644 --- a/scripts/compatibility/runtime.js +++ b/scripts/compatibility/runtime.js @@ -41,7 +41,6 @@ function snapshot(value) { if (value && typeof value === "object") { const out = {}; for (const key of Object.keys(value).sort()) { - // Newer SDKs include this optional field on exposure records. if (key === "ruleOverride" && value[key] === false) continue; out[key] = snapshot(value[key]); } diff --git a/src/__tests__/client.test.js b/src/__tests__/client.test.js index 91f683d..e958a6c 100644 --- a/src/__tests__/client.test.js +++ b/src/__tests__/client.test.js @@ -1241,7 +1241,6 @@ describe("Client", () => { ); const client = new Client(Object.assign({}, clientOptions, { timeout: 200, retries: 0 })); - // The client's 200 ms deadline still aborts the request; it doesn't hang. client.request({ method: "GET", path: "/context", timeout: 0 }).then( () => done(new Error("expected the request to be aborted")), (error) => { diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 78b32bf..5c15834 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -315,7 +315,6 @@ describe("1.13.4 source and behaviour compatibility", () => { assignmentRules: JSON.stringify(rules), }); const rule = { type: "assign", variant: 1, conditions: { eq: [{ var: "country" }, { value: "US" }] } }; - // The refreshed rules JSON differs (an extra rule name) but still gives variant 1. const refreshed = { experiments: [experiment({ rules: [{ ...rule, name: "renamed" }] })] }; const provider = { getContextData: () => Promise.resolve(refreshed) }; const sdk = new SDK({ ...options, provider }); @@ -758,6 +757,10 @@ describe("1.13.4 source and behaviour compatibility", () => { "an error object marked nullParent: 1", () => Object.assign(new TypeError("getter boom"), { nullParent: 1 }), ], + [ + "a TypeError marked nullParent: true", + () => Object.assign(new TypeError("getter boom"), { nullParent: true }), + ], ])( "fails a strict audience closed when an attribute getter throws %s, and logs one error event", (_label, makeError) => { @@ -943,7 +946,9 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(context.peek("covered")).toBe(0); context.getUnits().user_id = "u1"; context.treatment("covered"); - expect(context.pending()).toBeGreaterThan(0); + // The holdout must now resolve with the unit and queue its own exposure (it holds the unit out, so + // the covered experiment is suppressed and queues none). + expect(context._exposures.map((x) => x.name)).toEqual(["h"]); }); describe("a released duck-typed custom client without the new getters", () => { diff --git a/src/context.ts b/src/context.ts index 483b6f2..c5226dc 100644 --- a/src/context.ts +++ b/src/context.ts @@ -190,7 +190,8 @@ export default class Context { private _overrides: Record; private _pending: number; private _attrsSeq: number; - // Assignments resolved while their unit was missing; while zero, _assign() skips the live-units check. + // Never decremented: a stale positive only costs the cheap per-read check, while a missed increment + // would skip a needed re-resolution. While zero, _assign() skips the live-units check entirely. private _missingUnitPins: number; private _attrsMapCache: Record | null; private _attrsMapCacheSeq: number; @@ -1176,7 +1177,6 @@ export default class Context { } if (this._failed) { - // Events of a context that failed to initialize are dropped silently, as in 1.13. this._pending = 0; this._exposures = []; this._goals = []; diff --git a/src/jsonexpr/evaluator.ts b/src/jsonexpr/evaluator.ts index 3cdbaa6..24d3563 100644 --- a/src/jsonexpr/evaluator.ts +++ b/src/jsonexpr/evaluator.ts @@ -55,6 +55,8 @@ function compareIdentifiers(a: string, b: string) { export class Evaluator { private readonly operators: any; private readonly vars: any; + /** @internal Set only when this evaluation read below a null/undefined value; never taken from a thrown error. */ + nullParentError: unknown = undefined; constructor(operators: any, vars: any) { this.operators = operators; @@ -129,7 +131,7 @@ export class Evaluator { try { value = target[frag]; } catch (error) { - if (target == null) Object.defineProperty(error, "nullParent", { value: true }); + if (target == null) this.nullParentError = error; throw error; } diff --git a/src/jsonexpr/jsonexpr.ts b/src/jsonexpr/jsonexpr.ts index 84414c7..d1afa92 100644 --- a/src/jsonexpr/jsonexpr.ts +++ b/src/jsonexpr/jsonexpr.ts @@ -45,6 +45,22 @@ export class JsonExpr { return evaluator.booleanConvert(evaluator.evaluate(expr)); } + /** + * @internal Like evaluateBooleanExpr, but returns null (and logs) when this evaluation read below a + * null/undefined attribute, as 1.13.4 audiences did. Any other error, including one thrown by an attribute + * getter, propagates. The match is by identity with the error the evaluator caught, not by a property on it. + */ + evaluateAudienceExpr(expr: TData[] | Record, vars: Record) { + const evaluator = new Evaluator(operators, vars); + try { + return evaluator.booleanConvert(evaluator.evaluate(expr)); + } catch (error) { + if (evaluator.nullParentError === undefined || error !== evaluator.nullParentError) throw error; + console.error(error); + return null; + } + } + evaluateExpr(expr: TData[] | Record, vars: Record) { const evaluator = new Evaluator(operators, vars); return evaluator.evaluate(expr); diff --git a/src/matcher.ts b/src/matcher.ts index 1497a10..2ba5ed0 100644 --- a/src/matcher.ts +++ b/src/matcher.ts @@ -42,15 +42,8 @@ export class AudienceMatcher { if (audience && audience.filter) { if (Array.isArray(audience.filter) || isObject(audience.filter)) { - // As in 1.13.4, an audience whose path reads below a null attribute is ignored rather than - // counted as a mismatch. Any other evaluation error propagates, so strict audiences fail closed. - try { - return this._jsonExpr.evaluateBooleanExpr(audience.filter, vars); - } catch (error) { - if (!(error && (error as { nullParent?: boolean }).nullParent === true)) throw error; - console.error(error); - return null; - } + // A null-parent read is ignored as in 1.13.4; any other error propagates so strict audiences fail closed. + return this._jsonExpr.evaluateAudienceExpr(audience.filter, vars); } } From 0910afcb0893fc906979aad5c062ac51d239005b Mon Sep 17 00:00:00 2001 From: lux worker Date: Sat, 21 Nov 2026 04:21:25 +0000 Subject: [PATCH 32/92] test(release): make the npm dry-run probe hermetic; cover an undefined throw npm exports npm_config_dry_run to scripts during npm pack/publish --dry-run, which the probe's child npm inherited, so the build failed under a local dry-run preflight. Strip npm_config_* from the probe environment, and skip it cleanly when the pinned npm cannot be fetched (offline builds). Add an undefined-throwing getter to the fail-closed table, killing the mutant that drops the undefined guard. Co-Authored-By: Claude Opus 5.5 --- scripts/__tests__/check-release.test.js | 57 ++++++++++++++------- src/__tests__/release-compatibility.test.js | 1 + 2 files changed, 39 insertions(+), 19 deletions(-) diff --git a/scripts/__tests__/check-release.test.js b/scripts/__tests__/check-release.test.js index 86efc64..29661de 100644 --- a/scripts/__tests__/check-release.test.js +++ b/scripts/__tests__/check-release.test.js @@ -107,25 +107,44 @@ describe("publish workflow", () => { // Asks the workflow's pinned npm how it parses each publish command's flags, so a later negating // flag (for example --no-dry-run after --dry-run) is caught, not just the presence of --dry-run. - test("npm 11.6.2 parses every manual publish command as an effective dry run", () => { - const npmVersion = /npm@(\d+\.\d+\.\d+)/.exec(job.steps.map((step) => step.run || "").join("\n"))[1]; - const effectiveDryRun = (run) => { - const line = run.split("\n").find((l) => /^\s*npm publish\b/.test(l)); - const args = line - .trim() - .split(/\s+/) - .slice(2) - .map((arg) => arg.replace(/^"\$DIST_TAG"$/, "latest")); - return execFileSync("npx", ["-y", `npm@${npmVersion}`, "config", "get", "dry-run", ...args], { - encoding: "utf8", - }).trim(); - }; - const manual = publishSteps.filter((step) => step.if && step.if.includes("workflow_dispatch")); - expect(manual.length).toBeGreaterThan(0); - for (const step of manual) expect(effectiveDryRun(step.run)).toBe("true"); - const live = publishSteps.filter((step) => step.if === "github.event_name == 'push'"); - expect(live.map((step) => effectiveDryRun(step.run))).toEqual(["false"]); - }, 120000); + const pinnedNpm = /npm@(\d+\.\d+\.\d+)/.exec(job.steps.map((step) => step.run || "").join("\n"))[1]; + // Needs the pinned npm from the registry or cache. Offline builds skip it; CI is online and runs it. + let pinnedNpmAvailable = true; + try { + execFileSync("npx", ["-y", `npm@${pinnedNpm}`, "--version"], { encoding: "utf8", stdio: "pipe" }); + } catch (_) { + pinnedNpmAvailable = false; + } + (pinnedNpmAvailable ? test : test.skip)( + "npm 11.6.2 parses every manual publish command as an effective dry run", + () => { + const npmVersion = pinnedNpm; + const effectiveDryRun = (run) => { + const line = run.split("\n").find((l) => /^\s*npm publish\b/.test(l)); + const args = line + .trim() + .split(/\s+/) + .slice(2) + .map((arg) => arg.replace(/^"\$DIST_TAG"$/, "latest")); + // npm exports npm_config_* to scripts (e.g. npm_config_dry_run=true under `npm pack --dry-run`); + // drop them so only the flags in the workflow command decide the answer. + const env = {}; + for (const [key, value] of Object.entries(process.env)) { + if (!/^npm_config_/i.test(key)) env[key] = value; + } + return execFileSync("npx", ["-y", `npm@${npmVersion}`, "config", "get", "dry-run", ...args], { + encoding: "utf8", + env, + }).trim(); + }; + const manual = publishSteps.filter((step) => step.if && step.if.includes("workflow_dispatch")); + expect(manual.length).toBeGreaterThan(0); + for (const step of manual) expect(effectiveDryRun(step.run)).toBe("true"); + const live = publishSteps.filter((step) => step.if === "github.event_name == 'push'"); + expect(live.map((step) => effectiveDryRun(step.run))).toEqual(["false"]); + }, + 120000 + ); test("keeps manual runs to one dry-run preflight and publishes only on a pushed tag, with no token", () => { expect(workflow.on.push.tags).toEqual(["v*"]); diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 5c15834..e39443d 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -761,6 +761,7 @@ describe("1.13.4 source and behaviour compatibility", () => { "a TypeError marked nullParent: true", () => Object.assign(new TypeError("getter boom"), { nullParent: true }), ], + ["undefined", () => undefined], ])( "fails a strict audience closed when an attribute getter throws %s, and logs one error event", (_label, makeError) => { From 5eaec56546052d9d917c2048fbe81048ce1866c4 Mon Sep 17 00:00:00 2001 From: lux worker Date: Sat, 21 Nov 2026 04:58:52 +0000 Subject: [PATCH 33/92] test(release): never silently skip the dry-run probe in CI; bound its npm calls The pinned-npm probe now skips only outside CI, so a registry failure in CI fails the publish-flag gate instead of turning it into a green skip. Both npm invocations get a 30 s timeout so an unreachable registry cannot hang the build. Co-Authored-By: Claude Opus 5.5 --- scripts/__tests__/check-release.test.js | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/scripts/__tests__/check-release.test.js b/scripts/__tests__/check-release.test.js index 29661de..5e184c0 100644 --- a/scripts/__tests__/check-release.test.js +++ b/scripts/__tests__/check-release.test.js @@ -108,14 +108,19 @@ describe("publish workflow", () => { // Asks the workflow's pinned npm how it parses each publish command's flags, so a later negating // flag (for example --no-dry-run after --dry-run) is caught, not just the presence of --dry-run. const pinnedNpm = /npm@(\d+\.\d+\.\d+)/.exec(job.steps.map((step) => step.run || "").join("\n"))[1]; - // Needs the pinned npm from the registry or cache. Offline builds skip it; CI is online and runs it. + // Needs the pinned npm from the registry or cache. Local offline builds skip it; in CI it always runs, + // so a registry failure there fails the gate instead of silently skipping it. let pinnedNpmAvailable = true; try { - execFileSync("npx", ["-y", `npm@${pinnedNpm}`, "--version"], { encoding: "utf8", stdio: "pipe" }); + execFileSync("npx", ["-y", `npm@${pinnedNpm}`, "--version"], { + encoding: "utf8", + stdio: "pipe", + timeout: 30000, + }); } catch (_) { pinnedNpmAvailable = false; } - (pinnedNpmAvailable ? test : test.skip)( + (pinnedNpmAvailable || process.env.CI ? test : test.skip)( "npm 11.6.2 parses every manual publish command as an effective dry run", () => { const npmVersion = pinnedNpm; @@ -135,6 +140,7 @@ describe("publish workflow", () => { return execFileSync("npx", ["-y", `npm@${npmVersion}`, "config", "get", "dry-run", ...args], { encoding: "utf8", env, + timeout: 30000, }).trim(); }; const manual = publishSteps.filter((step) => step.if && step.if.includes("workflow_dispatch")); From a0b312ca60b065d1c53fbb0a58a065874b64991d Mon Sep 17 00:00:00 2001 From: lux worker Date: Sat, 21 Nov 2026 06:37:41 +0000 Subject: [PATCH 34/92] perf(release): precompute the rule key and skip holdout checks on cached reads Build each experiment's rule key once when context data is installed instead of re-concatenating the full assignment-rules JSON on every cached read; a work-counter test fails if a read touches the rules JSON again. Return early from the holdout-set check when neither side has holdouts, which narrows the cached-read gap to 1.13.4. Restate the CHANGELOG performance notes from fresh measurements and name who the throwing-ready-logger fix affects. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 21 +++++++---- src/__tests__/release-compatibility.test.js | 41 +++++++++++++++++++++ src/context.ts | 14 +++++-- 3 files changed, 64 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6246ac9..2b10ab0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,20 +59,25 @@ - New runtime dependency `@babel/runtime` (shared Babel helpers, which shrink the browser bundle). It declares Node `>=6.9.0`; the package still declares `>=6`, so Node 6.0–6.8 installs may warn. No helper types are exposed in the public API. -- Re-evaluating an audience after `setAttribute` now also checks the assignment-rule - and holdout state. Measured on Node 22 (synthetic, one audience experiment): about - 4% faster than 1.13.4 with 300 attributes, about 6% slower with 1,000 and about - 16% slower with 3,000. Ordinary cached reads, `getAttributes()` and default - publishing are at or below 1.13.4 cost. With the new opt-in - `includeSystemAttributes`, publishing also builds a set of attribute names (about - 1.9x the default publish at 3,000 attributes); the option did not exist in 1.13.4. +- Each read now also checks the assignment-rule, holdout and missing-unit state. + Measured on Node 22 (synthetic warmed loops, one experiment, median of 5): a cached + `peek` costs about 2 ns more than 1.13.4 (16.5 vs 14.6 ns) and a cached `treatment` + about 7 ns more (47.8 vs 40.8 ns). Re-evaluating an audience after `setAttribute` + matches 1.13.4 with 300 attributes and is about 6% slower with 1,000 and 10% slower + with 3,000. `getAttributes()` and default publishing are at or below 1.13.4 cost. + With the new opt-in `includeSystemAttributes`, publishing also builds a set of + attribute names (about 1.9x the default publish at 3,000 attributes); the option + did not exist in 1.13.4. ### Fixed - Failed publishes retain queued events in order; failed finalize stays open and can be retried. Concurrent flush/finalize waits for in-flight delivery. - Custom publisher failures and throwing event loggers no longer strand lifecycle - promises or lose/duplicate successfully delivered events. + promises or lose/duplicate successfully delivered events. Affected: an event logger + that throws on `ready` used to mark the context failed in 1.13.4, so every user got + control and nothing was exposed; such a context now becomes ready and serves real + variants and exposures. - Malformed variant configs are isolated rather than failing the entire context. - The browser bundle is ES5 again (IE 10): `rfdc` >= 1.4 ships ES2015 syntax, so it is now transpiled, and the build fails if `dist/` is not ES5. diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index e39443d..e69fba0 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -444,6 +444,47 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(names.slice(0, 2)).toEqual(["sdk_name", "sdk_version"]); }); + it("does not read the assignment-rules JSON on cached reads", () => { + const rules = JSON.stringify({ rules: [{ name: "all", type: "assign", variant: 1, conditions: null }] }); + const experiment = { + id: 31, + name: "ruled", + iteration: 1, + unitType: "session_id", + seedHi: 1, + seedLo: 2, + split: [0.5, 0.5], + trafficSeedHi: 3, + trafficSeedLo: 4, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + audience: null, + audienceStrict: false, + customFieldValues: null, + assignmentRules: rules, + }; + const context = new SDK(options).createContextWith( + { units: { session_id: "u1" } }, + { experiments: [experiment] } + ); + expect(context.treatment("ruled")).toBe(1); + let reads = 0; + const data = context._index.ruled.data; + Object.defineProperty(data, "assignmentRules", { + get: () => { + reads++; + return rules; + }, + }); + for (let i = 0; i < 100; i++) expect(context.peek("ruled")).toBe(1); + expect(reads).toBe(0); + }); + it("sends no SDK headers from getContext() when auth is false, as 1.13.4 did", async () => { sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({ experiments: [] }) }); await new Client(options).getContext({ auth: false }); diff --git a/src/context.ts b/src/context.ts index c5226dc..04644ed 100644 --- a/src/context.ts +++ b/src/context.ts @@ -100,6 +100,11 @@ export type Experiment = { // Parsed `data.assignmentRules`, filled on first use; `undefined` until then. The entry is rebuilt // whenever context data is installed, so the cache never outlives the rules it was parsed from. rules?: unknown[] | null; + /** + * @internal Identity of the rules and configured environment, built once when context data is installed + * so a cached read compares one string instead of re-concatenating the full rules JSON. + */ + ruleKey?: string; }; export type Unit = { @@ -612,7 +617,7 @@ export default class Context { const audienceMatches = (entry: Experiment, assignment: Assignment) => { const experiment = entry.data; - const ruleKey = experiment.assignmentRules ? `${experiment.assignmentRules}:${this._environmentName}` : ""; + const ruleKey = entry.ruleKey ?? ""; const ruleKeyChanged = ruleKey !== (assignment.ruleKey ?? ""); if (ruleKeyChanged) { @@ -662,6 +667,8 @@ export default class Context { // (id, iteration) only: seed/split edits must not force a duplicate exposure. const holdoutSetMatches = (experiment: Experiment, assignment: Assignment) => { + // Fast path for the usual no-holdout case, so a cached read allocates nothing here. + if (experiment.holdouts == null && assignment.holdouts == null) return true; const freshHoldouts = experiment.holdouts ?? []; const pinnedHoldouts = assignment.holdouts ?? []; @@ -784,9 +791,7 @@ export default class Context { const unitType = experiment.data.unitType; // Set even when suppressed, or `audienceMatches` rebuilds (losing `exposed`) on every call. - assignment.ruleKey = experiment.data.assignmentRules - ? `${experiment.data.assignmentRules}:${this._environmentName}` - : ""; + assignment.ruleKey = experiment.ruleKey ?? ""; const rule = experiment.data.assignmentRules && experiment.data.assignmentRules.length > 0 @@ -1516,6 +1521,7 @@ export default class Context { data: experiment, variables, holdouts, + ruleKey: experiment.assignmentRules ? `${experiment.assignmentRules}:${this._environmentName}` : "", }; index[experiment.name] = entry; From fa1c655f5a2a03e94dc7b03609fe87f37fe4ad3d Mon Sep 17 00:00:00 2001 From: lux worker Date: Sat, 21 Nov 2026 07:24:53 +0000 Subject: [PATCH 35/92] fix(release): reject a second publish command; fold opt-in attribute detection into one pass Round-4 review: the manual-release test only checked the first npm publish in a step, so a second live command could pass. Require exactly one npm publish per publish step (structural, works offline) in addition to the effective dry-run probe. Detect user-set sdk_name/sdk_version during the single history map instead of building a separate name set (opt-in publish about 8x cheaper at 3,000 attributes), with tests for the one-pass shape and the user-override rule. The CHANGELOG now says the manual preflight does not prove authentication and restates publish costs from fresh measurements. Drops two restating comments. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 +++--- scripts/__tests__/check-release.test.js | 12 +++++- src/__tests__/release-compatibility.test.js | 26 +++++++++++-- src/context.ts | 41 ++++++++++----------- src/matcher.ts | 1 - 5 files changed, 60 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b10ab0..8d3bb6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,8 +14,8 @@ (`application: { name, version: "1.2.3" }`) through the new `ClientInputOptions` overload. `ClientOptions` and the constructors' released signatures are unchanged. - Tag-driven npm Trusted Publishing, a manual dry-run package preflight (it does - not exercise authentication), and a `repository` field in `package.json`, which - npm provenance requires. + not prove authentication works: npm may try to obtain an OIDC token but skips the + upload), and a `repository` field in `package.json`, which npm provenance requires. ### Changed @@ -64,10 +64,10 @@ `peek` costs about 2 ns more than 1.13.4 (16.5 vs 14.6 ns) and a cached `treatment` about 7 ns more (47.8 vs 40.8 ns). Re-evaluating an audience after `setAttribute` matches 1.13.4 with 300 attributes and is about 6% slower with 1,000 and 10% slower - with 3,000. `getAttributes()` and default publishing are at or below 1.13.4 cost. - With the new opt-in `includeSystemAttributes`, publishing also builds a set of - attribute names (about 1.9x the default publish at 3,000 attributes); the option - did not exist in 1.13.4. + with 3,000. `getAttributes()` is faster than 1.13.4. A default `track()` + + `publish()` matches 1.13.4 up to a few hundred attributes (7.3 vs 7.1 µs at 300) + and costs about 30% more at 3,000 (about 52 vs 40 µs; unreleased main was about + 77 µs). The new opt-in `includeSystemAttributes` adds about 10% on top. ### Fixed diff --git a/scripts/__tests__/check-release.test.js b/scripts/__tests__/check-release.test.js index 5e184c0..a3fd94d 100644 --- a/scripts/__tests__/check-release.test.js +++ b/scripts/__tests__/check-release.test.js @@ -125,7 +125,7 @@ describe("publish workflow", () => { () => { const npmVersion = pinnedNpm; const effectiveDryRun = (run) => { - const line = run.split("\n").find((l) => /^\s*npm publish\b/.test(l)); + const line = run.split("\n").filter((l) => /\bnpm\s+publish\b/.test(l))[0]; const args = line .trim() .split(/\s+/) @@ -152,6 +152,16 @@ describe("publish workflow", () => { 120000 ); + // Every publish step must contain exactly one `npm publish` (on its own line), so the effective dry-run + // check above covers all of them: a second command in a manual step could otherwise publish for real. + test("each publish step runs exactly one npm publish command", () => { + for (const step of job.steps.filter((s) => /\bnpm\s+publish\b/.test(s.run || ""))) { + const commands = step.run.split("\n").filter((l) => /\bnpm\s+publish\b/.test(l)); + expect({ step: step.name, commands: commands.length }).toEqual({ step: step.name, commands: 1 }); + expect(commands[0]).toMatch(/^\s*npm publish\b/); + } + }); + test("keeps manual runs to one dry-run preflight and publishes only on a pushed tag, with no token", () => { expect(workflow.on.push.tags).toEqual(["v*"]); expect(workflow.on.workflow_dispatch).toBeNull(); diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index e69fba0..8bbdc59 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -428,7 +428,7 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(map).toHaveBeenCalledTimes(1); }); - it("publishes with includeSystemAttributes without an iterator loop over the history", async () => { + it("publishes with includeSystemAttributes in one pass over the history", async () => { const publisher = { publish: jest.fn(() => Promise.resolve()) }; const context = new SDK({ ...options, publisher }).createContextWith( { units: { session_id: "u1" } }, @@ -437,13 +437,35 @@ describe("1.13.4 source and behaviour compatibility", () => { ); for (let i = 0; i < 5; i++) context.attribute(`a${i}`, i); const iterator = jest.spyOn(context._attrs, Symbol.iterator); + const forEach = jest.spyOn(context._attrs, "forEach"); + const map = jest.spyOn(context._attrs, "map"); context.track("g"); await context.publish(); expect(iterator).not.toHaveBeenCalled(); + expect(forEach).not.toHaveBeenCalled(); + expect(map).toHaveBeenCalledTimes(1); const names = publisher.publish.mock.calls[0][0].attributes.map((a) => a.name); expect(names.slice(0, 2)).toEqual(["sdk_name", "sdk_version"]); }); + it.each([ + ["sdk_name", ["sdk_version", "sdk_name"]], + ["sdk_version", ["sdk_name", "sdk_version"]], + ])("keeps a user-set %s instead of the system one", async (userName, expectedNames) => { + const publisher = { publish: jest.fn(() => Promise.resolve()) }; + const context = new SDK({ ...options, publisher }).createContextWith( + { units: { session_id: "u1" } }, + { experiments: [] }, + { publishDelay: -1, includeSystemAttributes: true } + ); + context.attribute(userName, "mine"); + context.track("g"); + await context.publish(); + const attributes = publisher.publish.mock.calls[0][0].attributes; + expect(attributes.map((a) => a.name)).toEqual(expectedNames); + expect(attributes.find((a) => a.name === userName).value).toBe("mine"); + }); + it("does not read the assignment-rules JSON on cached reads", () => { const rules = JSON.stringify({ rules: [{ name: "all", type: "assign", variant: 1, conditions: null }] }); const experiment = { @@ -988,8 +1010,6 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(context.peek("covered")).toBe(0); context.getUnits().user_id = "u1"; context.treatment("covered"); - // The holdout must now resolve with the unit and queue its own exposure (it holds the unit out, so - // the covered experiment is suppressed and queues none). expect(context._exposures.map((x) => x.name)).toEqual(["h"]); }); diff --git a/src/context.ts b/src/context.ts index 04644ed..a84ba3b 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1120,29 +1120,28 @@ export default class Context { // among duplicates, so system attributes are stamped with the earliest event in the batch and left // out when the user set the same name. private _buildAttributes(systemSetAt: number): Attribute[] { - const allAttributes: Attribute[] = []; - - if (this._opts.includeSystemAttributes === true) { - const client = this._sdk.getClient(); - // A plain object, not a Set: the browser bundle still supports IE 10, which has no Set. - const userNames: Record = {}; - this._attrs.forEach((attr) => { - userNames[attr.name] = true; - }); - const addSystemAttribute = (attrName: string, value: unknown) => { - if (!Object.prototype.hasOwnProperty.call(userNames, attrName)) { - allAttributes.push({ name: attrName, value, setAt: systemSetAt }); - } - }; - - const agent = typeof client?.getAgent === "function" ? client.getAgent() : undefined; - if (typeof agent === "string" && agent.length > 0) addSystemAttribute("sdk_name", agent); - addSystemAttribute("sdk_version", SDK_VERSION); + // Built with map(), as 1.13.4 did; pushing one element at a time is measurably slower here. + if (this._opts.includeSystemAttributes !== true) { + return this._attrs.map((x) => ({ name: x.name, value: x.value, setAt: x.setAt })); } - // Built with map(), as 1.13.4 did; pushing one element at a time is measurably slower here. - const userAttributes = this._attrs.map((x) => ({ name: x.name, value: x.value, setAt: x.setAt })); - return allAttributes.length === 0 ? userAttributes : allAttributes.concat(userAttributes); + // Opt-in path: detect user-set sdk_name/sdk_version in the same pass instead of a separate name set. + let userSetSdkName = false; + let userSetSdkVersion = false; + const userAttributes = this._attrs.map((x) => { + if (x.name === "sdk_name") userSetSdkName = true; + else if (x.name === "sdk_version") userSetSdkVersion = true; + return { name: x.name, value: x.value, setAt: x.setAt }; + }); + + const client = this._sdk.getClient(); + const systemAttributes: Attribute[] = []; + const agent = typeof client?.getAgent === "function" ? client.getAgent() : undefined; + if (!userSetSdkName && typeof agent === "string" && agent.length > 0) { + systemAttributes.push({ name: "sdk_name", value: agent, setAt: systemSetAt }); + } + if (!userSetSdkVersion) systemAttributes.push({ name: "sdk_version", value: SDK_VERSION, setAt: systemSetAt }); + return systemAttributes.length === 0 ? userAttributes : systemAttributes.concat(userAttributes); } // A caught exception or a rejected promise's reason can be any value. Only diff --git a/src/matcher.ts b/src/matcher.ts index 2ba5ed0..8ce0517 100644 --- a/src/matcher.ts +++ b/src/matcher.ts @@ -42,7 +42,6 @@ export class AudienceMatcher { if (audience && audience.filter) { if (Array.isArray(audience.filter) || isObject(audience.filter)) { - // A null-parent read is ignored as in 1.13.4; any other error propagates so strict audiences fail closed. return this._jsonExpr.evaluateAudienceExpr(audience.filter, vars); } } From 48e573245380fe1dfb40519b5f0f8ab51c621fe5 Mon Sep 17 00:00:00 2001 From: lux worker Date: Sat, 21 Nov 2026 08:35:06 +0000 Subject: [PATCH 36/92] test(release): pin configured environment in rule identity and no-holdout work Refresh the same rule JSON after a custom client environment change and assert re-resolution; count holdout reads to catch removal of the no-holdout fast return. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/release-compatibility.test.js | 65 +++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 8bbdc59..62e278c 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -15,6 +15,71 @@ jest.mock("../fetch"); const options = { endpoint: "https://collector/v1", apiKey: "k", application: "web", environment: "prod" }; describe("1.13.4 source and behaviour compatibility", () => { + const cacheProbeExperiment = (extra = {}) => ({ + id: 40, + name: "cacheProbe", + iteration: 1, + unitType: "session_id", + seedHi: 1, + seedLo: 2, + split: [0.5, 0.5], + trafficSeedHi: 3, + trafficSeedLo: 4, + trafficSplit: [0, 1], + fullOnVariant: 0, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + audience: null, + audienceStrict: false, + customFieldValues: null, + ...extra, + }); + + it("refreshes rule identity when a custom client's configured environment changes", async () => { + let environment = "prod"; + const client = new Client(options); + client.getEnvironment = () => environment; + const experiment = cacheProbeExperiment({ + assignmentRules: JSON.stringify({ + rules: [ + { type: "assign", variant: 0, environments: ["prod"], conditions: null }, + { type: "assign", variant: 1, environments: ["staging"], conditions: null }, + ], + }), + }); + const data = { experiments: [experiment] }; + const provider = { getContextData: () => Promise.resolve(data) }; + const context = new SDK({ ...options, client, provider }).createContextWith( + { units: { session_id: "u1" } }, + data + ); + expect(context.peek("cacheProbe")).toBe(0); + environment = "staging"; + await context.refresh(); + expect(context.peek("cacheProbe")).toBe(1); + }); + + it("takes the no-holdout fast return without reading fallback holdout sets", () => { + const context = new SDK(options).createContextWith( + { units: { session_id: "u1" } }, + { experiments: [cacheProbeExperiment()] } + ); + context.treatment("cacheProbe"); + const entry = context._index.cacheProbe; + let reads = 0; + Object.defineProperty(entry, "holdouts", { + get: () => { + reads++; + return null; + }, + }); + for (let i = 0; i < 100; i++) context.peek("cacheProbe"); + expect(reads).toBe(100); + }); + it("ignores unknown context-data fields at every payload level, including after refresh", async () => { const eventLogger = jest.fn(); const experiment = (id, experimentName) => ({ From fbce0cc0f19f616da6fc3af60f26dd81b74b9c9b Mon Sep 17 00:00:00 2001 From: lux worker Date: Sat, 21 Nov 2026 09:02:57 +0000 Subject: [PATCH 37/92] fix(release): preserve custom expression hooks on audience evaluation Dispatch audience evaluation through the released boolean-expression hook, including replacements and subclass overrides. Drop the optional no-holdout micro-optimization and its ineffective counter. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/release-compatibility.test.js | 33 ++++++++++----------- src/context.ts | 2 -- src/jsonexpr/jsonexpr.ts | 15 +++++++--- src/matcher.ts | 4 ++- 4 files changed, 29 insertions(+), 25 deletions(-) diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 62e278c..56f63f9 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -15,6 +15,21 @@ jest.mock("../fetch"); const options = { endpoint: "https://collector/v1", apiKey: "k", application: "web", environment: "prod" }; describe("1.13.4 source and behaviour compatibility", () => { + it("preserves replacement and subclass boolean-expression hooks", () => { + const matcher = new AudienceMatcher(); + const replacement = { evaluateBooleanExpr: jest.fn(() => true), evaluateExpr: () => true }; + matcher._jsonExpr = replacement; + expect(matcher.evaluate('{"filter":{"value":true}}', {})).toBe(true); + expect(replacement.evaluateBooleanExpr).toHaveBeenCalledTimes(1); + class CustomExpr extends JsonExpr { + evaluateBooleanExpr() { + return false; + } + } + matcher._jsonExpr = new CustomExpr(); + expect(matcher.evaluate('{"filter":{"value":true}}', {})).toBe(false); + }); + const cacheProbeExperiment = (extra = {}) => ({ id: 40, name: "cacheProbe", @@ -62,24 +77,6 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(context.peek("cacheProbe")).toBe(1); }); - it("takes the no-holdout fast return without reading fallback holdout sets", () => { - const context = new SDK(options).createContextWith( - { units: { session_id: "u1" } }, - { experiments: [cacheProbeExperiment()] } - ); - context.treatment("cacheProbe"); - const entry = context._index.cacheProbe; - let reads = 0; - Object.defineProperty(entry, "holdouts", { - get: () => { - reads++; - return null; - }, - }); - for (let i = 0; i < 100; i++) context.peek("cacheProbe"); - expect(reads).toBe(100); - }); - it("ignores unknown context-data fields at every payload level, including after refresh", async () => { const eventLogger = jest.fn(); const experiment = (id, experimentName) => ({ diff --git a/src/context.ts b/src/context.ts index a84ba3b..61d7fbc 100644 --- a/src/context.ts +++ b/src/context.ts @@ -667,8 +667,6 @@ export default class Context { // (id, iteration) only: seed/split edits must not force a duplicate exposure. const holdoutSetMatches = (experiment: Experiment, assignment: Assignment) => { - // Fast path for the usual no-holdout case, so a cached read allocates nothing here. - if (experiment.holdouts == null && assignment.holdouts == null) return true; const freshHoldouts = experiment.holdouts ?? []; const pinnedHoldouts = assignment.holdouts ?? []; diff --git a/src/jsonexpr/jsonexpr.ts b/src/jsonexpr/jsonexpr.ts index d1afa92..10d6464 100644 --- a/src/jsonexpr/jsonexpr.ts +++ b/src/jsonexpr/jsonexpr.ts @@ -40,9 +40,16 @@ const operators = { }; export class JsonExpr { + private _nullParentError: unknown; + evaluateBooleanExpr(expr: TData[] | Record, vars: Record) { const evaluator = new Evaluator(operators, vars); - return evaluator.booleanConvert(evaluator.evaluate(expr)); + try { + return evaluator.booleanConvert(evaluator.evaluate(expr)); + } catch (error) { + this._nullParentError = evaluator.nullParentError; + throw error; + } } /** @@ -51,11 +58,11 @@ export class JsonExpr { * getter, propagates. The match is by identity with the error the evaluator caught, not by a property on it. */ evaluateAudienceExpr(expr: TData[] | Record, vars: Record) { - const evaluator = new Evaluator(operators, vars); + this._nullParentError = undefined; try { - return evaluator.booleanConvert(evaluator.evaluate(expr)); + return this.evaluateBooleanExpr(expr, vars); } catch (error) { - if (evaluator.nullParentError === undefined || error !== evaluator.nullParentError) throw error; + if (this._nullParentError === undefined || error !== this._nullParentError) throw error; console.error(error); return null; } diff --git a/src/matcher.ts b/src/matcher.ts index 8ce0517..f9c1de8 100644 --- a/src/matcher.ts +++ b/src/matcher.ts @@ -42,7 +42,9 @@ export class AudienceMatcher { if (audience && audience.filter) { if (Array.isArray(audience.filter) || isObject(audience.filter)) { - return this._jsonExpr.evaluateAudienceExpr(audience.filter, vars); + return typeof this._jsonExpr.evaluateAudienceExpr === "function" + ? this._jsonExpr.evaluateAudienceExpr(audience.filter, vars) + : this._jsonExpr.evaluateBooleanExpr(audience.filter, vars); } } From 1b5be09dbeb67cef3123620592e8fe31cca346d4 Mon Sep 17 00:00:00 2001 From: lux worker Date: Sat, 21 Nov 2026 09:41:43 +0000 Subject: [PATCH 38/92] fix(release): keep JsonExpr structural and recover only stale requested assignments Strip implementation bookkeeping from the public JsonExpr type and pin released structural implementations. Fold live-map recovery into the existing assignment lookup, rebuild only the requested stale record, and remove the global pin counter. Cover unknown assignment-rule fields through fetch, with-data and refresh. Co-Authored-By: Claude Opus 5.5 --- scripts/compatibility/consumer.ts | 12 ++++++++ src/__tests__/release-compatibility.test.js | 31 +++++++++++++++++++-- src/context.ts | 29 +++++++------------ src/jsonexpr/jsonexpr.ts | 1 + 4 files changed, 52 insertions(+), 21 deletions(-) diff --git a/scripts/compatibility/consumer.ts b/scripts/compatibility/consumer.ts index 41617d8..351be79 100644 --- a/scripts/compatibility/consumer.ts +++ b/scripts/compatibility/consumer.ts @@ -181,3 +181,15 @@ function readClientCtorVersion(options: ReleasedClientOptions): number { } void readSdkCtorVersion; void readClientCtorVersion; + +import { JsonExpr } from "@absmartly/javascript-sdk/types/jsonexpr/jsonexpr"; +class ReleasedExpressionImplementation implements JsonExpr { + evaluateBooleanExpr(expr: T[] | Record, vars: Record): any { + return true; + } + evaluateExpr(expr: T[] | Record, vars: Record): any { + return null; + } +} +const releasedExpression: JsonExpr = new ReleasedExpressionImplementation(); +void releasedExpression; diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 56f63f9..d0affc5 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -77,6 +77,34 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(context.peek("cacheProbe")).toBe(1); }); + it.each(["fetch", "with-data", "refresh"])("ignores future assignment-rule fields via %s", async (creation) => { + const ruled = cacheProbeExperiment({ + assignmentRules: JSON.stringify({ + rules: [ + { + type: "assign", + variant: 1, + conditions: null, + futureScalar: "x", + futureObject: { x: [1] }, + futureArray: [{ y: true }], + }, + ], + }), + trafficSplit: [1, 0], + }); + const ordinary = { ...cacheProbeExperiment(), id: 41, name: "ordinary", split: [0, 1] }; + const data = { experiments: [ruled, ordinary] }; + const provider = { getContextData: () => Promise.resolve(data) }; + const sdk = new SDK({ ...options, provider }); + const params = { units: { session_id: "u1" } }; + const context = creation === "fetch" ? sdk.createContext(params) : sdk.createContextWith(params, data); + await context.ready(); + if (creation === "refresh") await context.refresh(); + expect(context.treatment("cacheProbe")).toBe(1); + expect(context.treatment("ordinary")).toBe(1); + }); + it("ignores unknown context-data fields at every payload level, including after refresh", async () => { const eventLogger = jest.fn(); const experiment = (id, experimentName) => ({ @@ -702,7 +730,7 @@ describe("1.13.4 source and behaviour compatibility", () => { { units: { user_id: "u1" } }, { experiments: [liveExp({})] } ); - context.peek("covered"); + context.treatment("covered"); const cached = context._assignments.covered; let reads = 0; let value = cached.isRuleMissingUnit; @@ -716,7 +744,6 @@ describe("1.13.4 source and behaviour compatibility", () => { }, }); for (let i = 0; i < 50; i++) context.peek("covered"); - expect(context._missingUnitPins).toBe(0); expect(reads).toBe(0); }); }); diff --git a/src/context.ts b/src/context.ts index 61d7fbc..3d9e2e0 100644 --- a/src/context.ts +++ b/src/context.ts @@ -195,9 +195,6 @@ export default class Context { private _overrides: Record; private _pending: number; private _attrsSeq: number; - // Never decremented: a stale positive only costs the cheap per-read check, while a missed increment - // would skip a needed re-resolution. While zero, _assign() skips the live-units check entirely. - private _missingUnitPins: number; private _attrsMapCache: Record | null; private _attrsMapCacheSeq: number; private _hashes?: Record; @@ -227,7 +224,6 @@ export default class Context { this._audienceMatcher = new AudienceMatcher(); this._environmentName = null; this._attrsSeq = 0; - this._missingUnitPins = 0; this._attrsMapCache = null; this._attrsMapCacheSeq = -1; @@ -604,7 +600,7 @@ export default class Context { } } - private _assign(experimentName: string) { + private _assign(experimentName: string): Assignment { const experimentMatches = (experiment: ExperimentData, assignment: Assignment) => { return ( experiment.id === assignment.id && @@ -645,7 +641,6 @@ export default class Context { assignment.ruleVariant = ruleVariant; assignment.isRuleMissingUnit = rule?.isMissingUnit ?? false; - if (assignment.isRuleMissingUnit) this._missingUnitPins++; } if (!assignment.ruleOverride && experiment.audience && experiment.audience.length > 0) { @@ -690,19 +685,17 @@ export default class Context { const hasOverride = experimentName in this._overrides; const experiment = experimentName in this._index ? this._index[experimentName] : null; - const cached = this._missingUnitPins > 0 ? this._assignments[experimentName] : undefined; - if ( - cached && - !cached.exposed && - cached.unitType != null && - cached.unitType in this._units && - (cached.isRuleMissingUnit || cached.holdoutAssignments?.some((assignment) => assignment === null)) - ) { - this._invalidateAssignmentsPinnedWithMissingUnit(cached.unitType); - } - if (experimentName in this._assignments) { const assignment = this._assignments[experimentName]; + if ( + !assignment.exposed && + assignment.unitType != null && + (assignment.isRuleMissingUnit || assignment.holdoutAssignments?.some((item) => item === null)) && + assignment.unitType in this._units + ) { + delete this._assignments[experimentName]; + return this._assign(experimentName); + } if (hasOverride) { if ( assignment.overridden && @@ -767,7 +760,6 @@ export default class Context { assignment.holdouts = holdouts; assignment.holdoutAssignments = holdoutAssignments; - if (holdoutAssignments.some((holdoutAssignment) => holdoutAssignment === null)) this._missingUnitPins++; assignment.suppressed = holdoutAssignments.some( (holdoutAssignment) => @@ -799,7 +791,6 @@ export default class Context { assignment.ruleVariant = ruleVariant; assignment.isRuleMissingUnit = rule?.isMissingUnit ?? false; - if (assignment.isRuleMissingUnit) this._missingUnitPins++; // A matching assignment rule wins over holdout suppression, the same way override() // does: it's an explicit, author-specified assignment (flagged `ruleOverride`, diff --git a/src/jsonexpr/jsonexpr.ts b/src/jsonexpr/jsonexpr.ts index 10d6464..29e6028 100644 --- a/src/jsonexpr/jsonexpr.ts +++ b/src/jsonexpr/jsonexpr.ts @@ -40,6 +40,7 @@ const operators = { }; export class JsonExpr { + /** @internal */ private _nullParentError: unknown; evaluateBooleanExpr(expr: TData[] | Record, vars: Record) { From 6194e32be59561d57fdc1e43a6778b7624af99b8 Mon Sep 17 00:00:00 2001 From: lux worker Date: Sat, 21 Nov 2026 11:00:29 +0000 Subject: [PATCH 39/92] fix(release): build the rule key only from a non-empty string assignmentRules A malformed payload such as `assignmentRules: { toString: null }` threw while building the key in `_init`, failing the whole context. Non-string values now mean "no rules", and the has-rules checks reuse the precomputed key. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/release-compatibility.test.js | 26 +++++++++++++++++++++ src/context.ts | 13 ++++++----- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index d0affc5..46f49be 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -105,6 +105,32 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(context.treatment("ordinary")).toBe(1); }); + it.each(["fetch", "with-data", "refresh"])( + "treats non-string assignment rules as no rules via %s", + async (creation) => { + const malformed = [{ toString: null }, ["x"], 1, true, { rules: [] }]; + const experiments = malformed.map((assignmentRules, i) => ({ + ...cacheProbeExperiment({ assignmentRules }), + id: 50 + i, + name: `malformed${i}`, + split: [0, 1], + })); + const ordinary = { ...cacheProbeExperiment(), id: 41, name: "ordinary", split: [0, 1] }; + const data = { experiments: [...experiments, ordinary] }; + const provider = { getContextData: () => Promise.resolve(data) }; + const sdk = new SDK({ ...options, provider }); + const params = { units: { session_id: "u1" } }; + const context = creation === "fetch" ? sdk.createContext(params) : sdk.createContextWith(params, data); + await context.ready(); + if (creation === "refresh") await context.refresh(); + expect(context.isFailed()).toBe(false); + experiments.forEach((experiment) => expect(context.treatment(experiment.name)).toBe(1)); + context.attribute("age", 1); + experiments.forEach((experiment) => expect(context.treatment(experiment.name)).toBe(1)); + expect(context.treatment("ordinary")).toBe(1); + } + ); + it("ignores unknown context-data fields at every payload level, including after refresh", async () => { const eventLogger = jest.fn(); const experiment = (id, experimentName) => ({ diff --git a/src/context.ts b/src/context.ts index 3d9e2e0..161bead 100644 --- a/src/context.ts +++ b/src/context.ts @@ -626,7 +626,7 @@ export default class Context { } if (this._attrsSeq > (assignment.attrsSeq ?? 0) || ruleKeyChanged) { - if (experiment.assignmentRules && experiment.assignmentRules.length > 0) { + if (entry.ruleKey) { // Built only when there are rules: the no-rule path must not rebuild the attribute map // after every setAttribute (1.13.4 never built it there). const attrs = this._getAttributesMap(); @@ -783,10 +783,7 @@ export default class Context { // Set even when suppressed, or `audienceMatches` rebuilds (losing `exposed`) on every call. assignment.ruleKey = experiment.ruleKey ?? ""; - const rule = - experiment.data.assignmentRules && experiment.data.assignmentRules.length > 0 - ? this._resolveRule(experiment, this._getAttributesMap(), false) - : null; + const rule = experiment.ruleKey ? this._resolveRule(experiment, this._getAttributesMap(), false) : null; const ruleVariant = rule?.variant ?? null; assignment.ruleVariant = ruleVariant; @@ -1509,7 +1506,11 @@ export default class Context { data: experiment, variables, holdouts, - ruleKey: experiment.assignmentRules ? `${experiment.assignmentRules}:${this._environmentName}` : "", + // Only a non-empty string carries rules; anything else (a malformed payload) has none. + ruleKey: + typeof experiment.assignmentRules === "string" && experiment.assignmentRules + ? `${experiment.assignmentRules}:${this._environmentName}` + : "", }; index[experiment.name] = entry; From d521b3195887c084e5e49cd3c46d4f4088eda397 Mon Sep 17 00:00:00 2001 From: lux worker Date: Sat, 21 Nov 2026 11:17:22 +0000 Subject: [PATCH 40/92] test(release): cover an empty assignmentRules string as no rules Co-Authored-By: Claude Opus 5.5 --- src/__tests__/release-compatibility.test.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 46f49be..f2427ed 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -108,7 +108,8 @@ describe("1.13.4 source and behaviour compatibility", () => { it.each(["fetch", "with-data", "refresh"])( "treats non-string assignment rules as no rules via %s", async (creation) => { - const malformed = [{ toString: null }, ["x"], 1, true, { rules: [] }]; + const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); + const malformed = ["", { toString: null }, ["x"], 1, true, { rules: [] }]; const experiments = malformed.map((assignmentRules, i) => ({ ...cacheProbeExperiment({ assignmentRules }), id: 50 + i, @@ -128,6 +129,9 @@ describe("1.13.4 source and behaviour compatibility", () => { context.attribute("age", 1); experiments.forEach((experiment) => expect(context.treatment(experiment.name)).toBe(1)); expect(context.treatment("ordinary")).toBe(1); + // Nothing tried to parse a rule set that is not a non-empty string. + expect(errorSpy).not.toHaveBeenCalled(); + errorSpy.mockRestore(); } ); From 95f906fcd54567a93f08c2caa924722ef0ea9b18 Mon Sep 17 00:00:00 2001 From: lux worker Date: Sat, 21 Nov 2026 11:27:34 +0000 Subject: [PATCH 41/92] test(release): pin the parseRules error log; restore console spies in finally Co-Authored-By: Claude Opus 5.5 --- src/__tests__/matcher.test.js | 11 +++++ src/__tests__/release-compatibility.test.js | 49 +++++++++++---------- 2 files changed, 37 insertions(+), 23 deletions(-) diff --git a/src/__tests__/matcher.test.js b/src/__tests__/matcher.test.js index 1dc9ac9..a517597 100644 --- a/src/__tests__/matcher.test.js +++ b/src/__tests__/matcher.test.js @@ -32,6 +32,17 @@ describe("AudienceMatcher", () => { expect(matcher.evaluateRules('{"filter":[]}', "production", {})).toBe(null); }); + it("should return null and log the parse error once for invalid rules JSON", () => { + const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); + try { + expect(matcher.evaluateRules("{not json", "production", {})).toBe(null); + expect(errorSpy).toHaveBeenCalledTimes(1); + expect(errorSpy.mock.calls[0][0]).toBeInstanceOf(SyntaxError); + } finally { + errorSpy.mockRestore(); + } + }); + it("should return null when rules is empty array", () => { expect(matcher.evaluateRules('{"rules":[]}', "production", {})).toBe(null); }); diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index f2427ed..94bc7ed 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -109,29 +109,32 @@ describe("1.13.4 source and behaviour compatibility", () => { "treats non-string assignment rules as no rules via %s", async (creation) => { const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); - const malformed = ["", { toString: null }, ["x"], 1, true, { rules: [] }]; - const experiments = malformed.map((assignmentRules, i) => ({ - ...cacheProbeExperiment({ assignmentRules }), - id: 50 + i, - name: `malformed${i}`, - split: [0, 1], - })); - const ordinary = { ...cacheProbeExperiment(), id: 41, name: "ordinary", split: [0, 1] }; - const data = { experiments: [...experiments, ordinary] }; - const provider = { getContextData: () => Promise.resolve(data) }; - const sdk = new SDK({ ...options, provider }); - const params = { units: { session_id: "u1" } }; - const context = creation === "fetch" ? sdk.createContext(params) : sdk.createContextWith(params, data); - await context.ready(); - if (creation === "refresh") await context.refresh(); - expect(context.isFailed()).toBe(false); - experiments.forEach((experiment) => expect(context.treatment(experiment.name)).toBe(1)); - context.attribute("age", 1); - experiments.forEach((experiment) => expect(context.treatment(experiment.name)).toBe(1)); - expect(context.treatment("ordinary")).toBe(1); - // Nothing tried to parse a rule set that is not a non-empty string. - expect(errorSpy).not.toHaveBeenCalled(); - errorSpy.mockRestore(); + try { + const malformed = ["", { toString: null }, ["x"], 1, true, { rules: [] }]; + const experiments = malformed.map((assignmentRules, i) => ({ + ...cacheProbeExperiment({ assignmentRules }), + id: 50 + i, + name: `malformed${i}`, + split: [0, 1], + })); + const ordinary = { ...cacheProbeExperiment(), id: 41, name: "ordinary", split: [0, 1] }; + const data = { experiments: [...experiments, ordinary] }; + const provider = { getContextData: () => Promise.resolve(data) }; + const sdk = new SDK({ ...options, provider }); + const params = { units: { session_id: "u1" } }; + const context = creation === "fetch" ? sdk.createContext(params) : sdk.createContextWith(params, data); + await context.ready(); + if (creation === "refresh") await context.refresh(); + expect(context.isFailed()).toBe(false); + experiments.forEach((experiment) => expect(context.treatment(experiment.name)).toBe(1)); + context.attribute("age", 1); + experiments.forEach((experiment) => expect(context.treatment(experiment.name)).toBe(1)); + expect(context.treatment("ordinary")).toBe(1); + // Nothing tried to parse a rule set that is not a non-empty string. + expect(errorSpy).not.toHaveBeenCalled(); + } finally { + errorSpy.mockRestore(); + } } ); From 845ce9b3769ecbae44432cee8544624e5f7ac9f1 Mon Sep 17 00:00:00 2001 From: lux worker Date: Mon, 23 Nov 2026 17:04:03 +0000 Subject: [PATCH 42/92] fix(context): select shared variable winner independently of arm Stop at the first assigned, overridden or rule-overridden experiment even if its selected variant lacks the key. Return the caller default rather than selecting and exposing another experiment by arm. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 ++-- src/__tests__/context.test.js | 98 ++++++++++++++++++++++++++++++----- src/context.ts | 6 ++- 3 files changed, 98 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d3bb6d..679f5a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,9 +43,14 @@ `X-Application-Version` sends only 1–18 ASCII digits (trimmed), or `0` otherwise. Affected: proxies inspecting GET headers and apps configuring invalid version headers that previously caused collector HTTP 400 errors. -- Shared variable keys retain experiment-id priority and fall through unassigned - experiments or variants missing the key; peek queues no exposures. The existing - `variableKeys()` map-of-lists return shape is unchanged. +- Shared variable keys retain experiment-id priority: candidates define the key in + any variant, and the first assigned, explicitly overridden or rule-overridden + experiment wins. Its selected variant returns the value (including `null`, `false`, + `0` or `""`), or the caller default if the key is missing. This intentionally fixes + variant-dependent fallthrough: selecting/exposing a different experiment because + the winning arm lacks the key biases the experiment. Unassigned candidates still + fall through; holdout control fallback is unchanged; peek queues no exposures. + The existing `variableKeys()` map-of-lists return shape is unchanged. - A per-request `timeout` now also bounds the retry budget; 1.13.4 always used the client timeout for it. Affected: callers passing a per-request `timeout` that differs from the client one, who now get more (or fewer) retries to match it. diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index da19bc7..f0a9eb0 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6140,13 +6140,9 @@ describe("Context", () => { expect(exposureCalls.map((c) => c[2].name)).toContain("exp_holdout_var_winner_after_throw_2"); }); - // java's override write path never sets `suppressed` at all (see Assignment.suppressed's - // doc comment), so an override can never become java's suppressedFallback. The JS port - // pins `suppressed` eagerly on the override path too, so the fallback capture must - // explicitly exclude overridden assignments to reproduce the same outcome — otherwise an - // override to a variant that happens to omit the requested key could win the fallback - // slot ahead of a genuinely suppressed sibling that actually defines it. - it("excludes an overridden assignment from the suppressedFallback even when it is also held out", () => { + // An override wins even when its selected variant omits the key; holdout fallback + // must not replace it with another experiment's control value. + it("returns the winning override default even when it is also held out", () => { const overriddenExperiment = { id: 1, name: "exp_holdout_var_overridden", @@ -6161,8 +6157,7 @@ describe("Context", () => { fullOnVariant: 0, applications: [{ name: "website" }], variants: [ - // Override target (variant 0) omits the key, so this candidate can't win - // outright, and must not be allowed to claim the fallback slot either. + // The override wins outright, even though variant 0 omits the key. { name: "A", config: null }, { name: "B", config: JSON.stringify({ "button.color": "OVERRIDE_SIBLING" }) }, ], @@ -6204,13 +6199,14 @@ describe("Context", () => { const context = new Context(sdk, contextOptions, contextParams, response); context.override("exp_holdout_var_overridden", 0); - expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("GENUINE_SUPPRESSED_CTRL"); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("APP_FALLBACK"); + expect(context.pending()).toEqual(2); }); // _peekVariable carries the identical override-exclusion guard as _variableValue (same // fix, same commit), but never triggers exposures, so it needs its own regression test // rather than relying on variableValue()'s coverage of the guard. - it("peekVariableValue(): excludes an overridden assignment from the suppressedFallback even when it is also held out", () => { + it("peekVariableValue(): returns the winning override default even when it is also held out", () => { const overriddenExperiment = { id: 1, name: "exp_holdout_var_peek_overridden", @@ -6266,12 +6262,90 @@ describe("Context", () => { const context = new Context(sdk, contextOptions, contextParams, response); context.override("exp_holdout_var_peek_overridden", 0); - expect(context.peekVariableValue("button.color", "APP_FALLBACK")).toEqual("GENUINE_SUPPRESSED_CTRL"); + expect(context.peekVariableValue("button.color", "APP_FALLBACK")).toEqual("APP_FALLBACK"); expect(context.pending()).toEqual(0); }); }); }); + describe("shared variable winner", () => { + const shared = (id, split, config, over = {}) => ({ + ...getContextResponse.experiments[0], + id, + name: `shared_${id}`, + split, + trafficSplit: [0, 1], + variants: [ + { name: "A", config: JSON.stringify(config) }, + { name: "B", config: JSON.stringify({ shared: `value_${id}` }) }, + ], + ...over, + }); + + it.each([0, 1])("keeps the first assigned experiment in arm %i, independent of key presence", (arm) => { + const eventLogger = jest.fn(); + // Reverse payload order to test experiment-id precedence, not insertion order. + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, { + experiments: [shared(2, [1, 0], { shared: "SECOND" }), shared(1, arm ? [0, 1] : [1, 0], {})], + }); + const expected = arm ? "value_1" : "SENTINEL"; + expect(context.peekVariableValue("shared", "SENTINEL")).toBe(expected); + expect(context.pending()).toBe(0); + expect(eventLogger.mock.calls.filter((c) => c[1] === "exposure")).toEqual([]); + expect(context.variableValue("shared", "SENTINEL")).toBe(expected); + expect(context.variableValue("shared", "SENTINEL")).toBe(expected); + expect(context.pending()).toBe(1); + expect(eventLogger.mock.calls.filter((c) => c[1] === "exposure").map((c) => c[2])).toEqual([ + expect.objectContaining({ name: "shared_1", variant: arm, assigned: true }), + ]); + }); + + it.each([null, false, 0, ""])( + "returns the present value %p rather than default or another experiment", + (value) => { + const context = new Context(sdk, contextOptions, contextParams, { + experiments: [shared(1, [1, 0], { shared: value }), shared(2, [1, 0], { shared: "SECOND" })], + }); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe(value); + expect(context.pending()).toBe(0); + expect(context.variableValue("shared", "SENTINEL")).toBe(value); + expect(context.pending()).toBe(1); + } + ); + + it.each(["override", "rule"])("stops at a missing key when the first experiment wins by %s", (mode) => { + const assignmentRules = JSON.stringify({ + rules: [{ name: "control", type: "assign", conditions: { value: true }, environments: [], variant: 0 }], + }); + const context = new Context(sdk, contextOptions, contextParams, { + experiments: [ + shared(1, [0, 1], {}, { trafficSplit: [1, 0], ...(mode === "rule" ? { assignmentRules } : {}) }), + shared(2, [1, 0], { shared: "SECOND" }), + ], + }); + if (mode === "override") context.override("shared_1", 0); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(context.pending()).toBe(0); + expect(context.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(context.pending()).toBe(1); + }); + + it("retains ordinary unassigned fallthrough and no-winner defaults", () => { + const first = shared(1, [1, 0], {}, { audienceStrict: true, audience: '{"filter":[{"value":false}]}' }); + const second = shared(2, [1, 0], { shared: "SECOND" }); + const context = new Context(sdk, contextOptions, contextParams, { experiments: [first, second] }); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SECOND"); + expect(context.pending()).toBe(0); + expect(context.variableValue("shared", "SENTINEL")).toBe("SECOND"); + // Existing exposure behavior for visited unassigned candidates is preserved. + expect(context.pending()).toBe(2); + const noWinner = new Context(sdk, contextOptions, contextParams, { experiments: [first] }); + expect(noWinner.peekVariableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(noWinner.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(noWinner.variableValue("unknown", "SENTINEL")).toBe("SENTINEL"); + }); + }); + describe("variableValue()", () => { it("should not return variable values when unassigned", (done) => { const context = new Context(sdk, contextOptions, contextParams, audienceStrictContextResponse); diff --git a/src/context.ts b/src/context.ts index 161bead..0d90079 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1038,8 +1038,10 @@ export default class Context { this._triggerExposures(experimentName, assignment); } - if (key in assignment.variables && (assignment.assigned || assignment.overridden || assignment.ruleOverride)) { - return assignment.variables[key] as string; + // Select the experiment independently of its arm: a missing key uses the caller's + // default, never a later experiment (which would bias exposure by variant). + if (assignment.assigned || assignment.overridden || assignment.ruleOverride) { + return key in assignment.variables ? (assignment.variables[key] as string) : defaultValue; } if ( From 232801a2ae0f01f3a458e2979293e8bb4c2fb900 Mon Sep 17 00:00:00 2001 From: lux worker Date: Mon, 23 Nov 2026 19:12:44 +0000 Subject: [PATCH 43/92] test(release): pin initial assignment rule cache Kill the survived mutation that removes the cached rule identity write. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/release-compatibility.test.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 94bc7ed..f148df5 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -53,6 +53,26 @@ describe("1.13.4 source and behaviour compatibility", () => { ...extra, }); + it("caches the rule identity on the initial assignment", () => { + const experiment = cacheProbeExperiment({ + assignmentRules: JSON.stringify({ + rules: [{ type: "assign", variant: 1, conditions: { value: true } }], + }), + }); + const context = new SDK(options).createContextWith( + { units: { session_id: "u1" } }, + { experiments: [experiment] } + ); + const spy = jest.spyOn(AudienceMatcher.prototype, "evaluateParsedRules"); + try { + for (let i = 0; i < 100; i++) expect(context.treatment("cacheProbe")).toBe(1); + expect(spy).toHaveBeenCalledTimes(1); + expect(context.pending()).toBe(1); + } finally { + spy.mockRestore(); + } + }); + it("refreshes rule identity when a custom client's configured environment changes", async () => { let environment = "prod"; const client = new Client(options); From 55678b6e8f3ea451a1a2a0ea8ebb1a9ec66d0193 Mon Sep 17 00:00:00 2001 From: lux worker Date: Mon, 23 Nov 2026 21:06:31 +0000 Subject: [PATCH 44/92] fix(context): stop shared variable lookup at an out-of-range winning arm An overridden/assigned first candidate whose arm has no variables still wins and returns the caller default, instead of falling through to a later experiment. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 11 +++++++++++ src/context.ts | 36 +++++++++++++++++------------------ 2 files changed, 29 insertions(+), 18 deletions(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index f0a9eb0..ef7d379 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6330,6 +6330,17 @@ describe("Context", () => { expect(context.pending()).toBe(1); }); + it("stops at an out-of-range override instead of falling through", () => { + const context = new Context(sdk, contextOptions, contextParams, { + experiments: [shared(1, [1, 0], {}), shared(2, [1, 0], { shared: "SECOND" })], + }); + context.override("shared_1", 7); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); + // Existing behavior: an out-of-range override has no variables to expose. + expect(context.pending()).toBe(0); + }); + it("retains ordinary unassigned fallthrough and no-winner defaults", () => { const first = shared(1, [1, 0], {}, { audienceStrict: true, audience: '{"filter":[{"value":false}]}' }); const second = shared(2, [1, 0], { shared: "SECOND" }); diff --git a/src/context.ts b/src/context.ts index 0d90079..3b4e822 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1031,27 +1031,27 @@ export default class Context { for (const experiment of this._indexVariables[key] ?? []) { const experimentName = experiment.data.name; const assignment = this._assign(experimentName); - if (assignment.variables !== undefined) { - if (shouldQueueExposure && !assignment.exposed) { - assignment.exposed = true; + const variables = assignment.variables; + if (variables !== undefined && shouldQueueExposure && !assignment.exposed) { + assignment.exposed = true; - this._triggerExposures(experimentName, assignment); - } + this._triggerExposures(experimentName, assignment); + } - // Select the experiment independently of its arm: a missing key uses the caller's - // default, never a later experiment (which would bias exposure by variant). - if (assignment.assigned || assignment.overridden || assignment.ruleOverride) { - return key in assignment.variables ? (assignment.variables[key] as string) : defaultValue; - } + // Select the experiment independently of its arm: a missing key (or out-of-range arm) + // uses the caller's default, never a later experiment (which would bias exposure by variant). + if (assignment.assigned || assignment.overridden || assignment.ruleOverride) { + return variables !== undefined && key in variables ? (variables[key] as string) : defaultValue; + } - if ( - assignment.suppressed && - !assignment.overridden && - !assignment.ruleOverride && - suppressedFallback === undefined - ) { - suppressedFallback = assignment.variables; - } + if ( + variables !== undefined && + assignment.suppressed && + !assignment.overridden && + !assignment.ruleOverride && + suppressedFallback === undefined + ) { + suppressedFallback = variables; } } From 96aa2c95b12af5d6d778a962dc9766981ceab30e Mon Sep 17 00:00:00 2001 From: lux worker Date: Mon, 23 Nov 2026 21:55:21 +0000 Subject: [PATCH 45/92] fix(context): restore caller default for prototype-named variable keys variableValue/peekVariableValue("toString") returned the default in 1.13.4 but threw on the rewritten lookup. Use an own-property check. Also pin out-of-range custom and fullOn winners and say who is affected in the CHANGELOG. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +++++- src/__tests__/context.test.js | 23 +++++++++++++++++++++++ src/context.ts | 5 ++++- 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 679f5a5..5bc537d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,7 +50,11 @@ variant-dependent fallthrough: selecting/exposing a different experiment because the winning arm lacks the key biases the experiment. Unassigned candidates still fall through; holdout control fallback is unchanged; peek queues no exposures. - The existing `variableKeys()` map-of-lists return shape is unchanged. + An out-of-range overridden or custom arm also returns the caller default. + Affected: units whose first winning experiment's arm lacks the key; 1.13.4 + served (and exposed) a later experiment's value, 1.14.0 returns the default and + exposes only the winner. The existing `variableKeys()` map-of-lists return shape + is unchanged. - A per-request `timeout` now also bounds the retry budget; 1.13.4 always used the client timeout for it. Affected: callers passing a per-request `timeout` that differs from the client one, who now get more (or fewer) retries to match it. diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index ef7d379..5de8694 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6341,6 +6341,29 @@ describe("Context", () => { expect(context.pending()).toBe(0); }); + it.each(["custom", "fullOn"])("stops at an out-of-range %s assignment instead of falling through", (mode) => { + const first = shared(1, [1, 0], {}, mode === "fullOn" ? { fullOnVariant: 7 } : {}); + const context = new Context(sdk, contextOptions, contextParams, { + experiments: [first, shared(2, [1, 0], { shared: "SECOND" })], + }); + if (mode === "custom") context.customAssignment("shared_1", 7); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(context.pending()).toBe(0); + }); + + it.each(["toString", "valueOf", "hasOwnProperty", "__proto__", "constructor"])( + "returns the caller default for the unindexed prototype-named key %s", + (key) => { + const context = new Context(sdk, contextOptions, contextParams, { + experiments: [shared(1, [0, 1], {})], + }); + expect(context.peekVariableValue(key, "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue(key, "SENTINEL")).toBe("SENTINEL"); + expect(context.pending()).toBe(0); + } + ); + it("retains ordinary unassigned fallthrough and no-winner defaults", () => { const first = shared(1, [1, 0], {}, { audienceStrict: true, audience: '{"filter":[{"value":false}]}' }); const second = shared(2, [1, 0], { shared: "SECOND" }); diff --git a/src/context.ts b/src/context.ts index 3b4e822..e67bd47 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1028,7 +1028,10 @@ export default class Context { private _resolveVariableValue(key: string, defaultValue: string, shouldQueueExposure: boolean): string { let suppressedFallback: Record | undefined; - for (const experiment of this._indexVariables[key] ?? []) { + // Own-property lookup: a key such as "toString" must not resolve an Object.prototype member. + const candidates = Object.prototype.hasOwnProperty.call(this._indexVariables, key) ? this._indexVariables[key] : []; + + for (const experiment of candidates) { const experimentName = experiment.data.name; const assignment = this._assign(experimentName); const variables = assignment.variables; From 1dd5f59f00cf2fa3e7937d37d587ae7b85845754 Mon Sep 17 00:00:00 2001 From: lux worker Date: Mon, 23 Nov 2026 23:18:39 +0000 Subject: [PATCH 46/92] fix(context): expose only the winning experiment for shared variable keys Match java-sdk Context.getVariableAssignment: pick the first candidate (by experiment id) the unit is in, whatever its arm, falling back to the first held-out candidate; expose only that one. Checked-but-losing candidates no longer get exposures (that recorded users in experiments they never saw); their applicable holdouts still fire, as in Java. An out-of-range winner is exposed like Java. Variable reads no longer expose a strict-mismatched experiment the unit is not in. Use an Array.isArray own-list check instead of hasOwnProperty on the hot path. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 30 ++++--- README.md | 9 ++ src/__tests__/context.test.js | 161 +++++++++++++++++++--------------- src/context.ts | 53 +++++------ 4 files changed, 146 insertions(+), 107 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5bc537d..a0b2d65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,18 +43,7 @@ `X-Application-Version` sends only 1–18 ASCII digits (trimmed), or `0` otherwise. Affected: proxies inspecting GET headers and apps configuring invalid version headers that previously caused collector HTTP 400 errors. -- Shared variable keys retain experiment-id priority: candidates define the key in - any variant, and the first assigned, explicitly overridden or rule-overridden - experiment wins. Its selected variant returns the value (including `null`, `false`, - `0` or `""`), or the caller default if the key is missing. This intentionally fixes - variant-dependent fallthrough: selecting/exposing a different experiment because - the winning arm lacks the key biases the experiment. Unassigned candidates still - fall through; holdout control fallback is unchanged; peek queues no exposures. - An out-of-range overridden or custom arm also returns the caller default. - Affected: units whose first winning experiment's arm lacks the key; 1.13.4 - served (and exposed) a later experiment's value, 1.14.0 returns the default and - exposes only the winner. The existing `variableKeys()` map-of-lists return shape - is unchanged. +- `variableKeys()` keeps its map-of-lists return shape. - A per-request `timeout` now also bounds the retry budget; 1.13.4 always used the client timeout for it. Affected: callers passing a per-request `timeout` that differs from the client one, who now get more (or fewer) retries to match it. @@ -80,6 +69,23 @@ ### Fixed +- Shared variable keys now pick and expose one experiment, as the Java SDK does. + Previously `variableValue()` exposed every experiment it checked that had the + key, including ones the unit was not in (for example a strict audience + mismatch), which recorded users in experiments they never saw. The wrong + experiment could also win: when the first experiment's selected variant lacked + the key, a later experiment's value was served and exposed, so which experiment + a unit was counted in depended on its arm, biasing the result. Rule now applied: + candidates are the experiments defining the key in any variant, by experiment id + ascending; the winner is the first one the unit is in (assigned, overridden or + rule-assigned), whatever its arm. Its selected variant's value is returned + (`null`, `false`, `0` and `""` included), or the caller default if that variant + lacks the key. With no winner, a held-out candidate supplies its control value, + otherwise the caller default. Only the winner is exposed; each checked + candidate's applicable holdouts still fire, as in Java. `peekVariableValue()` + exposes nothing. Keys named like `Object.prototype` members (`toString`, ...) + return the default again, as in 1.13.4. Affected: anyone with two or more + running experiments sharing a variable key. - Failed publishes retain queued events in order; failed finalize stays open and can be retried. Concurrent flush/finalize waits for in-flight delivery. - Custom publisher failures and throwing event loggers no longer strand lifecycle diff --git a/README.md b/README.md index bc8e9da..5d05d09 100644 --- a/README.md +++ b/README.md @@ -226,6 +226,15 @@ const defaultButtonColor = "red"; const buttonColor = context.variableValue("button.color", defaultButtonColor); ``` +#### Shared variable keys + +When several experiments define the same variable key, the SDK checks them in +ascending experiment id and uses the first one the user is in (assigned, +overridden or assigned by a rule). Its variant's value is returned, or your +default if that variant does not define the key; later experiments are never used +instead. Only that experiment gets an exposure. `peekVariableValue()` never queues +one. + ### Peek at Treatment Variants Although generally not recommended, it is sometimes necessary to peek at a treatment without triggering an exposure. The A/B Smartly SDK provides a `peek()` method for that. diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 5de8694..a6f565c 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6330,28 +6330,6 @@ describe("Context", () => { expect(context.pending()).toBe(1); }); - it("stops at an out-of-range override instead of falling through", () => { - const context = new Context(sdk, contextOptions, contextParams, { - experiments: [shared(1, [1, 0], {}), shared(2, [1, 0], { shared: "SECOND" })], - }); - context.override("shared_1", 7); - expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SENTINEL"); - expect(context.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); - // Existing behavior: an out-of-range override has no variables to expose. - expect(context.pending()).toBe(0); - }); - - it.each(["custom", "fullOn"])("stops at an out-of-range %s assignment instead of falling through", (mode) => { - const first = shared(1, [1, 0], {}, mode === "fullOn" ? { fullOnVariant: 7 } : {}); - const context = new Context(sdk, contextOptions, contextParams, { - experiments: [first, shared(2, [1, 0], { shared: "SECOND" })], - }); - if (mode === "custom") context.customAssignment("shared_1", 7); - expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SENTINEL"); - expect(context.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); - expect(context.pending()).toBe(0); - }); - it.each(["toString", "valueOf", "hasOwnProperty", "__proto__", "constructor"])( "returns the caller default for the unindexed prototype-named key %s", (key) => { @@ -6364,19 +6342,94 @@ describe("Context", () => { } ); - it("retains ordinary unassigned fallthrough and no-winner defaults", () => { - const first = shared(1, [1, 0], {}, { audienceStrict: true, audience: '{"filter":[{"value":false}]}' }); - const second = shared(2, [1, 0], { shared: "SECOND" }); - const context = new Context(sdk, contextOptions, contextParams, { experiments: [first, second] }); - expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SECOND"); + const exposures = (eventLogger) => eventLogger.mock.calls.filter((c) => c[1] === "exposure").map((c) => c[2]); + const notInFirst = { + audienceMismatch: { audienceStrict: true, audience: '{"filter":[{"value":false}]}' }, + missingUnit: { unitType: "device_id" }, + }; + + it.each(Object.keys(notInFirst))( + "exposes only the later winner when the lower-id candidate is not entered (%s)", + (reason) => { + const eventLogger = jest.fn(); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, { + experiments: [shared(1, [1, 0], {}, notInFirst[reason]), shared(2, [1, 0], { shared: "SECOND" })], + }); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SECOND"); + expect(context.pending()).toBe(0); + expect(context.variableValue("shared", "SENTINEL")).toBe("SECOND"); + expect(context.variableValue("shared", "SENTINEL")).toBe("SECOND"); + expect(context.pending()).toBe(1); + expect(exposures(eventLogger)).toEqual([expect.objectContaining({ name: "shared_2", variant: 0 })]); + } + ); + + it("exposes only the winner whose variant lacks the key, not the later candidate", () => { + const eventLogger = jest.fn(); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, { + experiments: [shared(1, [1, 0], {}), shared(2, [1, 0], { shared: "SECOND" })], + }); + expect(context.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(exposures(eventLogger)).toEqual([expect.objectContaining({ name: "shared_1", variant: 0 })]); + }); + + it("returns the default and exposes nothing when no candidate is entered", () => { + const eventLogger = jest.fn(); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, { + experiments: [ + shared(1, [1, 0], {}, notInFirst.audienceMismatch), + shared(2, [1, 0], { shared: "SECOND" }, notInFirst.missingUnit), + ], + }); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue("unknown", "SENTINEL")).toBe("SENTINEL"); + expect(context.pending()).toBe(0); + expect(exposures(eventLogger)).toEqual([]); + }); + + it.each(["override", "rule"])("a lower-id %s winner beats a later assigned candidate", (mode) => { + const eventLogger = jest.fn(); + const assignmentRules = JSON.stringify({ + rules: [{ name: "treat", type: "assign", conditions: { value: true }, environments: [], variant: 1 }], + }); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, { + experiments: [ + shared( + 1, + [1, 0], + {}, + { ...notInFirst.audienceMismatch, ...(mode === "rule" ? { assignmentRules } : {}) } + ), + shared(2, [1, 0], { shared: "SECOND" }), + ], + }); + if (mode === "override") context.override("shared_1", 1); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe("value_1"); + expect(context.pending()).toBe(0); + expect(context.variableValue("shared", "SENTINEL")).toBe("value_1"); + expect(exposures(eventLogger)).toEqual([ + expect.objectContaining({ + name: "shared_1", + variant: 1, + overridden: mode === "override", + ruleOverride: mode === "rule", + }), + ]); + }); + + it.each(["override", "custom", "fullOn"])("exposes an out-of-range %s winner like Java", (mode) => { + const eventLogger = jest.fn(); + const first = shared(1, [1, 0], {}, mode === "fullOn" ? { fullOnVariant: 7 } : {}); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, { + experiments: [first, shared(2, [1, 0], { shared: "SECOND" })], + }); + if (mode === "override") context.override("shared_1", 7); + if (mode === "custom") context.customAssignment("shared_1", 7); + expect(context.peekVariableValue("shared", "SENTINEL")).toBe("SENTINEL"); expect(context.pending()).toBe(0); - expect(context.variableValue("shared", "SENTINEL")).toBe("SECOND"); - // Existing exposure behavior for visited unassigned candidates is preserved. - expect(context.pending()).toBe(2); - const noWinner = new Context(sdk, contextOptions, contextParams, { experiments: [first] }); - expect(noWinner.peekVariableValue("shared", "SENTINEL")).toBe("SENTINEL"); - expect(noWinner.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); - expect(noWinner.variableValue("unknown", "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue("shared", "SENTINEL")).toBe("SENTINEL"); + expect(exposures(eventLogger)).toEqual([expect.objectContaining({ name: "shared_1", variant: 7 })]); }); }); @@ -6753,46 +6806,14 @@ describe("Context", () => { }); }); - it("should queue exposure with audienceMatch false and control variant on audience mismatch in strict mode", (done) => { + // The unit is not in a strict-mismatched experiment, so a variable read must not expose it; + // treatment() still records the audience mismatch (see the treatment() tests). + it("should not queue an exposure on audience mismatch in strict mode", () => { const context = new Context(sdk, contextOptions, contextParams, audienceStrictContextResponse); expect(context.variableValue("banner.size", "small")).toEqual("small"); - expect(context.pending()).toEqual(1); - - publisher.publish.mockReturnValue(Promise.resolve()); - - context.publish().then(() => { - expect(publisher.publish).toHaveBeenCalledWith( - { - publishedAt: 1611141535729, - units: publishUnits, - hashed: true, - - exposures: [ - { - id: 1, - assigned: false, - eligible: true, - exposedAt: 1611141535729, - name: "exp_test_ab", - overridden: false, - unit: "session_id", - variant: 0, - fullOn: false, - custom: false, - audienceMismatch: true, - ruleOverride: false, - }, - ], - }, - sdk, - context, - undefined - ); - - done(); - }); + expect(context.pending()).toEqual(0); }); it("should throw after finalized() call", (done) => { diff --git a/src/context.ts b/src/context.ts index e67bd47..0d3f8de 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1023,46 +1023,49 @@ export default class Context { return this._customFieldValueType(experimentName, key); } - // A held-out unit reads the control value, not the caller's default, when nothing else wins. - // The first suppressed candidate is captured even if it lacks the key, so a later one can't win. + // Mirrors java-sdk Context.getVariableAssignment. Candidates define the key in any variant, in + // experiment-id order. The first one the unit is actually in (assigned, overridden or + // rule-assigned) wins regardless of its arm; otherwise the first held-out candidate supplies + // its control value. Only the winner gets an exposure, so a unit is never recorded in an + // experiment it only got checked against. Like Java, each visited candidate's applicable + // holdouts still fire on the non-peek path. private _resolveVariableValue(key: string, defaultValue: string, shouldQueueExposure: boolean): string { - let suppressedFallback: Record | undefined; + const indexed = this._indexVariables[key]; + // Own lists only: a key such as "toString" must not resolve an Object.prototype member. + const candidates = Array.isArray(indexed) ? indexed : []; - // Own-property lookup: a key such as "toString" must not resolve an Object.prototype member. - const candidates = Object.prototype.hasOwnProperty.call(this._indexVariables, key) ? this._indexVariables[key] : []; + let winner: [string, Assignment] | undefined; + let suppressedFallback: [string, Assignment] | undefined; for (const experiment of candidates) { const experimentName = experiment.data.name; const assignment = this._assign(experimentName); - const variables = assignment.variables; - if (variables !== undefined && shouldQueueExposure && !assignment.exposed) { - assignment.exposed = true; + if (shouldQueueExposure) this._triggerApplicableHoldoutExposures(assignment); - this._triggerExposures(experimentName, assignment); - } - - // Select the experiment independently of its arm: a missing key (or out-of-range arm) - // uses the caller's default, never a later experiment (which would bias exposure by variant). if (assignment.assigned || assignment.overridden || assignment.ruleOverride) { - return variables !== undefined && key in variables ? (variables[key] as string) : defaultValue; + winner = [experimentName, assignment]; + break; } - if ( - variables !== undefined && - assignment.suppressed && - !assignment.overridden && - !assignment.ruleOverride && - suppressedFallback === undefined - ) { - suppressedFallback = variables; + if (assignment.suppressed && suppressedFallback === undefined) { + suppressedFallback = [experimentName, assignment]; } } - if (suppressedFallback !== undefined && key in suppressedFallback) { - return suppressedFallback[key] as string; + const selected = winner ?? suppressedFallback; + if (selected === undefined) return defaultValue; + + const [experimentName, assignment] = selected; + if (shouldQueueExposure && !assignment.exposed) { + assignment.exposed = true; + + this._triggerExposures(experimentName, assignment); } - return defaultValue; + // A missing key (or out-of-range arm) returns the caller's default, never a later + // experiment's value: falling through by arm would bias the winning experiment. + const variables = assignment.variables; + return variables !== undefined && key in variables ? (variables[key] as string) : defaultValue; } private _variableValue(key: string, defaultValue: string): string { From 2ceac728e54b9bd5604ea4afce5f78d0dda60fc6 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 00:22:05 +0000 Subject: [PATCH 47/92] perf(context): resolve shared variable winner without per-read tuples Address the independent review of 1dd5f59: plain locals on the hot path, pin Java holdout-before-winner exposure order, add a Changed entry for variable reads no longer exposing experiments the unit is not in, and mention holdout exposures in the README. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 ++++++++-- README.md | 6 ++++-- src/__tests__/context.test.js | 18 ++++++++++++++++++ src/context.ts | 24 +++++++++++++----------- 4 files changed, 43 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a0b2d65..4c351ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,7 +43,12 @@ `X-Application-Version` sends only 1–18 ASCII digits (trimmed), or `0` otherwise. Affected: proxies inspecting GET headers and apps configuring invalid version headers that previously caused collector HTTP 400 errors. -- `variableKeys()` keeps its map-of-lists return shape. +- `variableValue()` no longer queues an exposure for an experiment the unit is not + in (strict audience mismatch, or no unit for its unit type), even when that is + the only experiment defining the key; 1.13.4 published one with + `assigned: false`. Affected: anyone counting those exposures from variable + reads of strict-audience or unit-gated experiments. Call `treatment()` to record + them. See the shared variable keys entry under Fixed. - A per-request `timeout` now also bounds the retry budget; 1.13.4 always used the client timeout for it. Affected: callers passing a per-request `timeout` that differs from the client one, who now get more (or fewer) retries to match it. @@ -85,7 +90,8 @@ candidate's applicable holdouts still fire, as in Java. `peekVariableValue()` exposes nothing. Keys named like `Object.prototype` members (`toString`, ...) return the default again, as in 1.13.4. Affected: anyone with two or more - running experiments sharing a variable key. + running experiments sharing a variable key. `variableKeys()` keeps its + map-of-lists return shape. - Failed publishes retain queued events in order; failed finalize stays open and can be retried. Concurrent flush/finalize waits for in-flight delivery. - Custom publisher failures and throwing event loggers no longer strand lifecycle diff --git a/README.md b/README.md index 5d05d09..dc588c2 100644 --- a/README.md +++ b/README.md @@ -232,8 +232,10 @@ When several experiments define the same variable key, the SDK checks them in ascending experiment id and uses the first one the user is in (assigned, overridden or assigned by a rule). Its variant's value is returned, or your default if that variant does not define the key; later experiments are never used -instead. Only that experiment gets an exposure. `peekVariableValue()` never queues -one. +instead. Only that experiment gets an exposure (plus any holdouts covering the +experiments checked). An experiment the user is not in, such as a strict audience +mismatch, gets none; call `treatment()` to record it. `peekVariableValue()` never +queues one. ### Peek at Treatment Variants diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index a6f565c..885e2db 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6418,6 +6418,24 @@ describe("Context", () => { ]); }); + it("fires the winner's applicable holdouts before its own exposure, like Java", () => { + const eventLogger = jest.fn(); + const holdout = { + ...shared(11, [0, 1], {}), + name: "holdout_11", + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + }; + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, { + experiments: [shared(1, [1, 0], { shared: "FIRST" }, { holdoutIds: [11] })], + holdouts: [holdout], + }); + expect(context.variableValue("shared", "SENTINEL")).toBe("FIRST"); + expect(exposures(eventLogger).map((e) => e.name)).toEqual(["holdout_11", "shared_1"]); + }); + it.each(["override", "custom", "fullOn"])("exposes an out-of-range %s winner like Java", (mode) => { const eventLogger = jest.fn(); const first = shared(1, [1, 0], {}, mode === "fullOn" ? { fullOnVariant: 7 } : {}); diff --git a/src/context.ts b/src/context.ts index 0d3f8de..06d31b1 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1034,8 +1034,9 @@ export default class Context { // Own lists only: a key such as "toString" must not resolve an Object.prototype member. const candidates = Array.isArray(indexed) ? indexed : []; - let winner: [string, Assignment] | undefined; - let suppressedFallback: [string, Assignment] | undefined; + // Plain locals rather than tuples: this is a hot path and must not allocate per read. + let selectedName = ""; + let selected: Assignment | undefined; for (const experiment of candidates) { const experimentName = experiment.data.name; @@ -1043,28 +1044,29 @@ export default class Context { if (shouldQueueExposure) this._triggerApplicableHoldoutExposures(assignment); if (assignment.assigned || assignment.overridden || assignment.ruleOverride) { - winner = [experimentName, assignment]; + selectedName = experimentName; + selected = assignment; break; } - if (assignment.suppressed && suppressedFallback === undefined) { - suppressedFallback = [experimentName, assignment]; + // A winner breaks out above, so `selected` here can only be an earlier suppressed one. + if (assignment.suppressed && selected === undefined) { + selectedName = experimentName; + selected = assignment; } } - const selected = winner ?? suppressedFallback; if (selected === undefined) return defaultValue; - const [experimentName, assignment] = selected; - if (shouldQueueExposure && !assignment.exposed) { - assignment.exposed = true; + if (shouldQueueExposure && !selected.exposed) { + selected.exposed = true; - this._triggerExposures(experimentName, assignment); + this._triggerExposures(selectedName, selected); } // A missing key (or out-of-range arm) returns the caller's default, never a later // experiment's value: falling through by arm would bias the winning experiment. - const variables = assignment.variables; + const variables = selected.variables; return variables !== undefined && key in variables ? (variables[key] as string) : defaultValue; } From 92ba8cdb77ef2d1440c5c41e353cc8dd8655d10a Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 01:18:47 +0000 Subject: [PATCH 48/92] docs: note the held-out fallback and out-of-range winner exposure P3-only follow-up on top of the gated 2ceac72. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +++- README.md | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c351ae..c05bfd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,7 +48,9 @@ the only experiment defining the key; 1.13.4 published one with `assigned: false`. Affected: anyone counting those exposures from variable reads of strict-audience or unit-gated experiments. Call `treatment()` to record - them. See the shared variable keys entry under Fixed. + them. Conversely, a winning experiment whose overridden, custom or full-on variant + is out of range is now exposed with that variant (1.13.4 recorded nothing), as + in the Java SDK. See the shared variable keys entry under Fixed. - A per-request `timeout` now also bounds the retry budget; 1.13.4 always used the client timeout for it. Affected: callers passing a per-request `timeout` that differs from the client one, who now get more (or fewer) retries to match it. diff --git a/README.md b/README.md index dc588c2..8ee20f2 100644 --- a/README.md +++ b/README.md @@ -232,7 +232,8 @@ When several experiments define the same variable key, the SDK checks them in ascending experiment id and uses the first one the user is in (assigned, overridden or assigned by a rule). Its variant's value is returned, or your default if that variant does not define the key; later experiments are never used -instead. Only that experiment gets an exposure (plus any holdouts covering the +instead. If the user is in none of them but one is held out by a holdout, that +experiment's control value is returned. Only that experiment gets an exposure (plus any holdouts covering the experiments checked). An experiment the user is not in, such as a strict audience mismatch, gets none; call `treatment()` to record it. `peekVariableValue()` never queues one. From 0bb7c552c6b12ede2c8819e7693a844062b3d586 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 06:35:08 +0000 Subject: [PATCH 49/92] fix(context): accept variables named like Object.prototype members A variant config defining "toString", "constructor" or "__proto__" crashed context initialization in 1.13.4 and main. Index variables and parse configs into null-prototype maps, build variableKeys() with own properties, and pin an out-of-range winner returning the default even when control defines the key. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 ++-- src/__tests__/context.test.js | 52 ++++++++++++++++++++++++++++++++++- src/context.ts | 24 +++++++++------- 3 files changed, 68 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c05bfd1..036f5e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -90,8 +90,9 @@ lacks the key. With no winner, a held-out candidate supplies its control value, otherwise the caller default. Only the winner is exposed; each checked candidate's applicable holdouts still fire, as in Java. `peekVariableValue()` - exposes nothing. Keys named like `Object.prototype` members (`toString`, ...) - return the default again, as in 1.13.4. Affected: anyone with two or more + exposes nothing. Keys no experiment defines return the default + again, as in 1.13.4, including names like `toString`; a variant config that defines + such a key (`toString`, `constructor`, `__proto__`) no longer fails the context. Affected: anyone with two or more running experiments sharing a variable key. `variableKeys()` keeps its map-of-lists return shape. - Failed publishes retain queued events in order; failed finalize stays open and diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 885e2db..85508a4 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6330,6 +6330,55 @@ describe("Context", () => { expect(context.pending()).toBe(1); }); + describe("variables named like Object.prototype members", () => { + const protoKeyed = (config) => ({ + ...shared(1, [0, 1], {}), + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify(config) }, + ], + }); + const keys = ["toString", "constructor", "hasOwnProperty", "__proto__", "valueOf"]; + // From JSON, as the payload arrives: a `__proto__:` literal key would set the prototype instead. + const config = JSON.parse( + '{"toString":"ts","constructor":0,"hasOwnProperty":false,"__proto__":"p","valueOf":null}' + ); + + it("creates a ready context and resolves each defined key", () => { + const context = new Context(sdk, contextOptions, contextParams, { experiments: [protoKeyed(config)] }); + expect(context.isReady()).toBe(true); + expect(context.isFailed()).toBe(false); + for (const key of keys) { + expect(context.peekVariableValue(key, "SENTINEL")).toBe(config[key]); + expect(context.variableValue(key, "SENTINEL")).toBe(config[key]); + } + expect(context.pending()).toBe(1); + }); + + it("returns the default when the winner's variant does not define the key", () => { + // Variant A has a parsed config without these keys, so inherited members must not match. + const winner = { ...protoKeyed(config), split: [1, 0] }; + winner.variants = [{ name: "A", config: '{"other":1}' }, winner.variants[1]]; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [winner] }); + for (const key of keys) { + expect(context.peekVariableValue(key, "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue(key, "SENTINEL")).toBe("SENTINEL"); + } + expect(context.pending()).toBe(1); + }); + + it("lists each key as an own entry of variableKeys()", () => { + const context = new Context(sdk, contextOptions, contextParams, { + experiments: [protoKeyed(config), { ...protoKeyed({ toString: "x" }), id: 2, name: "shared_2" }], + }); + const variableKeys = context.variableKeys(); + expect(Object.getPrototypeOf(variableKeys)).toBe(Object.prototype); + expect(Object.keys(variableKeys).sort()).toEqual([...keys].sort()); + expect(variableKeys.toString).toEqual(["shared_1", "shared_2"]); + expect(Object.getOwnPropertyDescriptor(variableKeys, "__proto__").value).toEqual(["shared_1"]); + }); + }); + it.each(["toString", "valueOf", "hasOwnProperty", "__proto__", "constructor"])( "returns the caller default for the unindexed prototype-named key %s", (key) => { @@ -6438,7 +6487,8 @@ describe("Context", () => { it.each(["override", "custom", "fullOn"])("exposes an out-of-range %s winner like Java", (mode) => { const eventLogger = jest.fn(); - const first = shared(1, [1, 0], {}, mode === "fullOn" ? { fullOnVariant: 7 } : {}); + // Control defines the key, so serving variant 0 instead of the default would be caught. + const first = shared(1, [1, 0], { shared: "CONTROL" }, mode === "fullOn" ? { fullOnVariant: 7 } : {}); const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, { experiments: [first, shared(2, [1, 0], { shared: "SECOND" })], }); diff --git a/src/context.ts b/src/context.ts index 06d31b1..fb18484 100644 --- a/src/context.ts +++ b/src/context.ts @@ -470,11 +470,14 @@ export default class Context { const variableExperiments: Record = {}; + // defineProperty keeps a key such as "__proto__" an own entry of the returned plain object. for (const [key, values] of Object.entries(this._indexVariables)) { - for (const value of values) { - if (variableExperiments[key]) variableExperiments[key].push(value.data.name); - else variableExperiments[key] = [value.data.name]; - } + Object.defineProperty(variableExperiments, key, { + value: values.map((value) => value.data.name), + enumerable: true, + writable: true, + configurable: true, + }); } return variableExperiments; @@ -1030,9 +1033,8 @@ export default class Context { // experiment it only got checked against. Like Java, each visited candidate's applicable // holdouts still fire on the non-peek path. private _resolveVariableValue(key: string, defaultValue: string, shouldQueueExposure: boolean): string { - const indexed = this._indexVariables[key]; - // Own lists only: a key such as "toString" must not resolve an Object.prototype member. - const candidates = Array.isArray(indexed) ? indexed : []; + // The index has no prototype, so a key such as "toString" only finds a real entry. + const candidates = this._indexVariables[key] ?? []; // Plain locals rather than tuples: this is a hot path and must not allocate per read. let selectedName = ""; @@ -1463,7 +1465,9 @@ export default class Context { this._environmentName = typeof client?.getEnvironment === "function" ? client.getEnvironment() ?? null : null; const index: Record = {}; - const indexVariables: Record = {}; + // Null-prototype maps: variable keys come from customer configs and may be named like + // Object.prototype members ("toString", "__proto__"). + const indexVariables: Record = Object.create(null); const holdoutsById: Record = {}; @@ -1528,13 +1532,13 @@ export default class Context { for (let i = 0; i < experiment.variants.length; i++) { const variant = experiment.variants[i]; const config = variant.config; - let parsed = {}; + let parsed: Record = Object.create(null); if (config != null && config.length > 0) { try { const value = JSON.parse(config); if (isObject(value)) { - parsed = value; + parsed = Object.assign(Object.create(null), value); } } catch (error) { this._logError( From e3814b980b513fcd207c8a7343c2da10162a4084 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 07:17:51 +0000 Subject: [PATCH 50/92] test(context): cover empty and non-object configs with prototype-named variables Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 85508a4..75ee8c3 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6355,17 +6355,20 @@ describe("Context", () => { expect(context.pending()).toBe(1); }); - it("returns the default when the winner's variant does not define the key", () => { - // Variant A has a parsed config without these keys, so inherited members must not match. - const winner = { ...protoKeyed(config), split: [1, 0] }; - winner.variants = [{ name: "A", config: '{"other":1}' }, winner.variants[1]]; - const context = new Context(sdk, contextOptions, contextParams, { experiments: [winner] }); - for (const key of keys) { - expect(context.peekVariableValue(key, "SENTINEL")).toBe("SENTINEL"); - expect(context.variableValue(key, "SENTINEL")).toBe("SENTINEL"); + it.each([null, "", "[]", "0", "false", '"string"', "null", '{"other":1}'])( + "returns the default when the winner config %p does not define the key", + (selectedConfig) => { + // No selected config shape may leak inherited Object.prototype members. + const winner = { ...protoKeyed(config), split: [1, 0] }; + winner.variants = [{ name: "A", config: selectedConfig }, winner.variants[1]]; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [winner] }); + for (const key of keys) { + expect(context.peekVariableValue(key, "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue(key, "SENTINEL")).toBe("SENTINEL"); + } + expect(context.pending()).toBe(1); } - expect(context.pending()).toBe(1); - }); + ); it("lists each key as an own entry of variableKeys()", () => { const context = new Context(sdk, contextOptions, contextParams, { From 8fe259eebc2841c74935dbbfc38ea83ec6a1b35d Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 07:24:18 +0000 Subject: [PATCH 51/92] perf(context): retain ordinary object layouts with safe own-key lookup Define index entries as own properties, including __proto__, and require an own variant config key on reads. Avoid dictionary-mode maps for all ordinary reads. Co-Authored-By: Claude Opus 5.5 --- src/context.ts | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/src/context.ts b/src/context.ts index fb18484..bd5e4df 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1033,8 +1033,8 @@ export default class Context { // experiment it only got checked against. Like Java, each visited candidate's applicable // holdouts still fire on the non-peek path. private _resolveVariableValue(key: string, defaultValue: string, shouldQueueExposure: boolean): string { - // The index has no prototype, so a key such as "toString" only finds a real entry. - const candidates = this._indexVariables[key] ?? []; + const indexed = this._indexVariables[key]; + const candidates = Array.isArray(indexed) ? indexed : []; // Plain locals rather than tuples: this is a hot path and must not allocate per read. let selectedName = ""; @@ -1069,7 +1069,9 @@ export default class Context { // A missing key (or out-of-range arm) returns the caller's default, never a later // experiment's value: falling through by arm would bias the winning experiment. const variables = selected.variables; - return variables !== undefined && key in variables ? (variables[key] as string) : defaultValue; + return variables !== undefined && Object.prototype.hasOwnProperty.call(variables, key) + ? (variables[key] as string) + : defaultValue; } private _variableValue(key: string, defaultValue: string): string { @@ -1465,9 +1467,7 @@ export default class Context { this._environmentName = typeof client?.getEnvironment === "function" ? client.getEnvironment() ?? null : null; const index: Record = {}; - // Null-prototype maps: variable keys come from customer configs and may be named like - // Object.prototype members ("toString", "__proto__"). - const indexVariables: Record = Object.create(null); + const indexVariables: Record = {}; const holdoutsById: Record = {}; @@ -1532,13 +1532,13 @@ export default class Context { for (let i = 0; i < experiment.variants.length; i++) { const variant = experiment.variants[i]; const config = variant.config; - let parsed: Record = Object.create(null); + let parsed: Record = {}; if (config != null && config.length > 0) { try { const value = JSON.parse(config); if (isObject(value)) { - parsed = Object.assign(Object.create(null), value); + parsed = value; } } catch (error) { this._logError( @@ -1551,13 +1551,20 @@ export default class Context { for (const key of Object.keys(parsed)) { const value = entry; - if (indexVariables[key]) { + if (Array.isArray(indexVariables[key])) { insertUniqueSorted( indexVariables[key], value, (a, b) => (a as Experiment).data.id < (b as Experiment).data.id ); - } else indexVariables[key] = [value]; + } else { + Object.defineProperty(indexVariables, key, { + value: [value], + enumerable: true, + writable: true, + configurable: true, + }); + } } variables[i] = parsed; From 4ab001a478de428c58df2c55ce2dc7c883b5885b Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 09:13:22 +0000 Subject: [PATCH 52/92] perf(context): restrict own-key checks to prototype-named variables Ordinary keys retain the fast membership path; prototype-named keys must be own config properties. Co-Authored-By: Claude Opus 5.5 --- src/context.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/context.ts b/src/context.ts index bd5e4df..69bdf46 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1069,7 +1069,9 @@ export default class Context { // A missing key (or out-of-range arm) returns the caller's default, never a later // experiment's value: falling through by arm would bias the winning experiment. const variables = selected.variables; - return variables !== undefined && Object.prototype.hasOwnProperty.call(variables, key) + return variables !== undefined && + key in variables && + (!(key in Object.prototype) || Object.prototype.hasOwnProperty.call(variables, key)) ? (variables[key] as string) : defaultValue; } From 5ca7cd6b09d09e9183eccb575b05285a65c814b9 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 10:01:57 +0000 Subject: [PATCH 53/92] perf(context): classify prototype-key configs at indexing time Keep ordinary variable reads on the fast membership path; only experiments defining prototype-named keys require null-prototype variant maps. Co-Authored-By: Claude Opus 5.5 --- src/context.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/context.ts b/src/context.ts index 69bdf46..46c957f 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1069,11 +1069,7 @@ export default class Context { // A missing key (or out-of-range arm) returns the caller's default, never a later // experiment's value: falling through by arm would bias the winning experiment. const variables = selected.variables; - return variables !== undefined && - key in variables && - (!(key in Object.prototype) || Object.prototype.hasOwnProperty.call(variables, key)) - ? (variables[key] as string) - : defaultValue; + return variables !== undefined && key in variables ? (variables[key] as string) : defaultValue; } private _variableValue(key: string, defaultValue: string): string { @@ -1531,6 +1527,7 @@ export default class Context { index[experiment.name] = entry; + let hasPrototypeVariable = false; for (let i = 0; i < experiment.variants.length; i++) { const variant = experiment.variants[i]; const config = variant.config; @@ -1552,6 +1549,7 @@ export default class Context { } for (const key of Object.keys(parsed)) { + if (key in Object.prototype) hasPrototypeVariable = true; const value = entry; if (Array.isArray(indexVariables[key])) { insertUniqueSorted( @@ -1571,6 +1569,14 @@ export default class Context { variables[i] = parsed; } + + // Only experiments defining a prototype-named key need dictionary configs. Classify at + // indexing time so ordinary variable reads retain their existing fast membership check. + if (hasPrototypeVariable) { + for (let i = 0; i < variables.length; i++) { + variables[i] = Object.assign(Object.create(null), variables[i]); + } + } }); this._index = index; From d526b0894dfbca9e8bb9b5097fb8659b0341d78c Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 10:17:20 +0000 Subject: [PATCH 54/92] fix(context): queue every exposure of a variable read before user callbacks run A holdout exposure callback that called finalize() sealed the context with the winner still pending. Queue the read's exposures first and run eventLogger callbacks afterwards; make the throwing-logger test reach and expose a real winner; return the default early for an unindexed key. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++- src/__tests__/context.test.js | 68 +++++++++++++++++++++++------------ src/context.ts | 31 ++++++++++++++-- 3 files changed, 77 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 036f5e4..c6b6755 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,7 +89,9 @@ (`null`, `false`, `0` and `""` included), or the caller default if that variant lacks the key. With no winner, a held-out candidate supplies its control value, otherwise the caller default. Only the winner is exposed; each checked - candidate's applicable holdouts still fire, as in Java. `peekVariableValue()` + candidate's applicable holdouts still fire, as in Java. All exposures of one read + are queued before any `eventLogger` callback runs, so a callback that calls + `finalize()` still sends the winner. `peekVariableValue()` exposes nothing. Keys no experiment defines return the default again, as in 1.13.4, including names like `toString`; a variant config that defines such a key (`toString`, `constructor`, `__proto__`) no longer fails the context. Affected: anyone with two or more diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 75ee8c3..2040605 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6025,24 +6025,23 @@ describe("Context", () => { expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("APP_FALLBACK"); }); - // A throwing eventLogger for one candidate's exposure is isolated by _logEvent (it never - // propagates), so it must not stop the loop from visiting (and firing exposures for) the - // remaining candidates sharing the key. - it("a throwing eventLogger for one candidate does not stop later candidates in the loop from being visited and exposed", () => { - const firstExperiment = holdoutVarExperiment({ - id: 1, - name: "exp_holdout_var_throw_first", - holdoutIds: [11], - }); - - const secondExperiment = holdoutVarExperiment({ - id: 2, - name: "exp_holdout_var_throw_second", - holdoutIds: [12], - }); - - const secondHoldout = alwaysHoldsOut({ id: 12, name: "holdout_var_second" }); + const winnerAfterHoldout = (over) => ({ + ...holdoutVarExperiment({}), + id: 2, + name: "exp_holdout_var_later_winner", + split: [0, 1], + fullOnVariant: 1, + holdoutIds: null, + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ "button.color": "WINNER_AFTER_HOLDOUT" }) }, + ], + ...over, + }); + // A throwing eventLogger for the first candidate's holdout exposure is isolated by _logEvent, + // so the loop still reaches the later winner and exposes it. + it("a throwing eventLogger for one candidate does not stop the loop from reaching and exposing the winner", () => { const eventLogger = jest.fn((ctx, eventName, data) => { if (eventName === "exposure" && data.name === "holdout_var") { throw new Error("boom"); @@ -6050,17 +6049,42 @@ describe("Context", () => { }); const response = buildHoldoutResponse( - [firstExperiment, secondExperiment], - [alwaysHoldsOut({}), secondHoldout] + [holdoutVarExperiment({}), winnerAfterHoldout({})], + [alwaysHoldsOut({})] ); const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); - expect(() => context.variableValue("button.color", "APP_FALLBACK")).not.toThrow(); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); const exposureCalls = eventLogger.mock.calls.filter((c) => c[1] === "exposure"); - expect(exposureCalls.map((c) => c[2].name).sort()).toEqual( - ["holdout_var", "holdout_var_second"].sort() + expect(exposureCalls.map((c) => c[2].name)).toEqual(["holdout_var", "exp_holdout_var_later_winner"]); + expect(context.pending()).toEqual(2); + }); + + // A logger that finalizes from a holdout's exposure callback must still send the winner: + // every exposure of the read is queued before any user callback runs. + it("sends the winner when an exposure callback finalizes the context mid-read", async () => { + publisher.publish.mockReturnValue(Promise.resolve()); + let finalizing; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName === "exposure" && data.name === "holdout_var" && finalizing === undefined) { + finalizing = ctx.finalize(); + } + }); + + const response = buildHoldoutResponse( + [holdoutVarExperiment({}), winnerAfterHoldout({})], + [alwaysHoldsOut({})] ); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + await finalizing; + + expect(context.isFinalized()).toBe(true); + expect(context.pending()).toEqual(0); + const published = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0]; + expect(published.exposures.map((e) => e.name)).toEqual(["holdout_var", "exp_holdout_var_later_winner"]); }); // peekVariableValue() shares the exact same suppressedFallback capture as variableValue() diff --git a/src/context.ts b/src/context.ts index 46c957f..4750385 100644 --- a/src/context.ts +++ b/src/context.ts @@ -194,6 +194,8 @@ export default class Context { private _holdoutAssignments: Record; private _overrides: Record; private _pending: number; + // Set while a variable read queues its exposures, so user callbacks run only after all are queued. + private _deferredExposureLogs?: Exposure[]; private _attrsSeq: number; private _attrsMapCache: Record | null; private _attrsMapCacheSeq: number; @@ -937,6 +939,11 @@ export default class Context { this._exposures.push(exposureEvent); this._pending++; + if (this._deferredExposureLogs !== undefined) { + this._deferredExposureLogs.push(exposureEvent); + return; + } + try { this._logEvent("exposure", exposureEvent); } finally { @@ -1033,8 +1040,8 @@ export default class Context { // experiment it only got checked against. Like Java, each visited candidate's applicable // holdouts still fire on the non-peek path. private _resolveVariableValue(key: string, defaultValue: string, shouldQueueExposure: boolean): string { - const indexed = this._indexVariables[key]; - const candidates = Array.isArray(indexed) ? indexed : []; + const candidates = this._indexVariables[key]; + if (!Array.isArray(candidates)) return defaultValue; // Plain locals rather than tuples: this is a hot path and must not allocate per read. let selectedName = ""; @@ -1072,8 +1079,26 @@ export default class Context { return variables !== undefined && key in variables ? (variables[key] as string) : defaultValue; } + // A user eventLogger may call finalize() or publish(). Every exposure this read produces (the + // candidates' holdouts and the winner) is queued before any logger runs, so such a call sees + // and sends all of them instead of sealing the context with the winner still pending. private _variableValue(key: string, defaultValue: string): string { - return this._resolveVariableValue(key, defaultValue, true); + if (this._deferredExposureLogs !== undefined) return this._resolveVariableValue(key, defaultValue, true); + + const deferred: Exposure[] = []; + this._deferredExposureLogs = deferred; + try { + return this._resolveVariableValue(key, defaultValue, true); + } finally { + this._deferredExposureLogs = undefined; + if (deferred.length > 0) { + try { + for (const exposure of deferred) this._logEvent("exposure", exposure); + } finally { + this._setTimeout(); + } + } + } } private _peekVariable(key: string, defaultValue: string): string { From 2a903337409b1d1a513ad364966d95e09f3a1481 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 11:54:04 +0000 Subject: [PATCH 55/92] fix(context): defer variable-read callbacks without per-read cost; reclassify after refresh Create the deferred callback list only when a read queues an exposure or error, and defer error callbacks too, so finalize() from either still sends the winner without slowing warmed reads (85 vs 95 ns on main). After a refresh, a reused assignment of a newly prototype-keyed experiment gets a null-prototype copy of its variables. Pin toString-only classification, ordinary configs keeping Object.prototype, the publish timer, nested re-entrant reads and error-callback finalize. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +- src/__tests__/context.test.js | 161 ++++++++++++++++++++++++++++++++-- src/context.ts | 52 ++++++++--- 3 files changed, 196 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6b6755..cee3de1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -90,8 +90,8 @@ lacks the key. With no winner, a held-out candidate supplies its control value, otherwise the caller default. Only the winner is exposed; each checked candidate's applicable holdouts still fire, as in Java. All exposures of one read - are queued before any `eventLogger` callback runs, so a callback that calls - `finalize()` still sends the winner. `peekVariableValue()` + are queued before its `exposure` and `error` callbacks run, so a callback that + calls `finalize()` still sends the winner. `peekVariableValue()` exposes nothing. Keys no experiment defines return the default again, as in 1.13.4, including names like `toString`; a variant config that defines such a key (`toString`, `constructor`, `__proto__`) no longer fails the context. Affected: anyone with two or more diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 2040605..a4d6650 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6087,9 +6087,118 @@ describe("Context", () => { expect(published.exposures.map((e) => e.name)).toEqual(["holdout_var", "exp_holdout_var_later_winner"]); }); - // peekVariableValue() shares the exact same suppressedFallback capture as variableValue() - // (both fixed together in the same commit), but never triggers exposures, so it needs its - // own ordering regression test rather than relying on variableValue()'s coverage. + it("reports nested variable reads from a callback after the outer read's exposures, in queue order", () => { + const names = []; + let nested = false; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + names.push(data.name); + if (!nested) { + nested = true; + ctx.variableValue("button.color", "APP_FALLBACK"); + } + }); + const response = buildHoldoutResponse( + [holdoutVarExperiment({}), winnerAfterHoldout({})], + [alwaysHoldsOut({})] + ); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + expect(names).toEqual(["holdout_var", "exp_holdout_var_later_winner"]); + expect(context.pending()).toEqual(2); + }); + + // An attribute getter is user code that can re-enter variableValue() mid-read; the nested read + // must not release the outer read's deferral before the outer winner is queued. + it("keeps deferring when an attribute getter re-enters variableValue() mid-read", async () => { + publisher.publish.mockReturnValue(Promise.resolve()); + let reentered = false; + let finalizing; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName === "exposure" && finalizing === undefined) finalizing = ctx.finalize(); + }); + const strictFirst = { + ...holdoutVarExperiment({}), + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + }; + const other = { + ...winnerAfterHoldout({}), + id: 3, + name: "exp_other_key", + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ "other.key": "OTHER" }) }, + ], + }; + const response = buildHoldoutResponse([strictFirst, winnerAfterHoldout({}), other], []); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + if (!reentered) { + reentered = true; + context.variableValue("other.key", "D"); + } + return "free"; + }, + }); + context.attribute("user", user); + + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + await finalizing; + expect(context.pending()).toEqual(0); + const published = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0]; + expect(published.exposures.map((e) => e.name)).toEqual([ + "exp_other_key", + "exp_holdout_var_later_winner", + ]); + }); + + it("schedules the publish timer after a variable read's deferred exposures", () => { + const response = buildHoldoutResponse([winnerAfterHoldout({})], []); + const context = new Context(sdk, { ...contextOptions, publishDelay: 100 }, contextParams, response); + const schedule = jest.spyOn(context, "_setTimeout"); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + expect(context.pending()).toEqual(1); + expect(schedule).toHaveBeenCalled(); + expect(context._publishTimeout).toBeDefined(); + clearTimeout(context._publishTimeout); + }); + + it("defers an error callback raised mid-read so finalizing from it still sends the winner", async () => { + publisher.publish.mockReturnValue(Promise.resolve()); + let finalizing; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName === "error" && finalizing === undefined) finalizing = ctx.finalize(); + }); + const strictFirst = { + ...holdoutVarExperiment({}), + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + }; + const response = buildHoldoutResponse([strictFirst, winnerAfterHoldout({})], []); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("getter boom"); + }, + }); + context.attribute("user", user); + + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + await finalizing; + expect(context.isFinalized()).toBe(true); + expect(context.pending()).toEqual(0); + const published = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0]; + expect(published.exposures.map((e) => e.name)).toEqual(["exp_holdout_var_later_winner"]); + }); + + // peekVariableValue() picks the same first held-out fallback as variableValue() but never + // triggers exposures, so it needs its own ordering regression test. it("peekVariableValue(): an earlier suppressed candidate without the key blocks a later suppressed candidate that has it", () => { const firstSuppressed = holdoutVarExperiment({ id: 1, @@ -6227,9 +6336,8 @@ describe("Context", () => { expect(context.pending()).toEqual(2); }); - // _peekVariable carries the identical override-exclusion guard as _variableValue (same - // fix, same commit), but never triggers exposures, so it needs its own regression test - // rather than relying on variableValue()'s coverage of the guard. + // peekVariableValue() stops at the same override winner as variableValue() but never + // triggers exposures, so it needs its own regression test. it("peekVariableValue(): returns the winning override default even when it is also held out", () => { const overriddenExperiment = { id: 1, @@ -6394,6 +6502,47 @@ describe("Context", () => { } ); + it("treats a config defining only toString as prototype-keyed", () => { + const winner = { ...protoKeyed({ toString: "T" }), split: [1, 0] }; + winner.variants = [ + { name: "A", config: '{"other":1}' }, + { name: "B", config: '{"toString":"T"}' }, + ]; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [winner] }); + expect(context.peekVariableValue("toString", "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue("toString", "SENTINEL")).toBe("SENTINEL"); + }); + + it("keeps Object.prototype on ordinary configs", () => { + const context = new Context(sdk, contextOptions, contextParams, { + experiments: [shared(1, [0, 1], {}), { ...protoKeyed(config), id: 2, name: "shared_2" }], + }); + expect(Object.getPrototypeOf(context._index.shared_1.variables[1])).toBe(Object.prototype); + expect(Object.getPrototypeOf(context._index.shared_2.variables[1])).toBe(null); + }); + + it("does not resolve inherited members after a refresh makes an experiment prototype-keyed", async () => { + const before = { + ...shared(1, [1, 0], {}), + variants: [ + { name: "A", config: '{"other":1}' }, + { name: "B", config: null }, + ], + }; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [before] }); + expect(context.treatment("shared_1")).toBe(0); + const after = { + ...before, + variants: [before.variants[0], { name: "B", config: '{"toString":"T","valueOf":"V"}' }], + }; + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [after] })); + await context.refresh(); + for (const key of ["toString", "valueOf"]) { + expect(context.peekVariableValue(key, "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue(key, "SENTINEL")).toBe("SENTINEL"); + } + }); + it("lists each key as an own entry of variableKeys()", () => { const context = new Context(sdk, contextOptions, contextParams, { experiments: [protoKeyed(config), { ...protoKeyed({ toString: "x" }), id: 2, name: "shared_2" }], diff --git a/src/context.ts b/src/context.ts index 4750385..f9237fb 100644 --- a/src/context.ts +++ b/src/context.ts @@ -194,8 +194,10 @@ export default class Context { private _holdoutAssignments: Record; private _overrides: Record; private _pending: number; - // Set while a variable read queues its exposures, so user callbacks run only after all are queued. - private _deferredExposureLogs?: Exposure[]; + // While a variable read runs, user eventLogger callbacks it would trigger are held here (the + // list is created on first use) and replayed once every exposure of the read is queued. + private _deferringLogs = false; + private _deferredLogs?: [EventName, Record | Error][]; private _attrsSeq: number; private _attrsMapCache: Record | null; private _attrsMapCacheSeq: number; @@ -939,8 +941,8 @@ export default class Context { this._exposures.push(exposureEvent); this._pending++; - if (this._deferredExposureLogs !== undefined) { - this._deferredExposureLogs.push(exposureEvent); + if (this._deferringLogs) { + (this._deferredLogs ??= []).push(["exposure", exposureEvent]); return; } @@ -1079,21 +1081,25 @@ export default class Context { return variables !== undefined && key in variables ? (variables[key] as string) : defaultValue; } - // A user eventLogger may call finalize() or publish(). Every exposure this read produces (the - // candidates' holdouts and the winner) is queued before any logger runs, so such a call sees - // and sends all of them instead of sealing the context with the winner still pending. + // A user eventLogger may call finalize() or publish(). Exposure and error callbacks this read + // triggers run only after every exposure of the read (candidates' holdouts and the winner) is + // queued, so such a call sends all of them instead of sealing the context with one pending. private _variableValue(key: string, defaultValue: string): string { - if (this._deferredExposureLogs !== undefined) return this._resolveVariableValue(key, defaultValue, true); + if (this._deferringLogs) return this._resolveVariableValue(key, defaultValue, true); - const deferred: Exposure[] = []; - this._deferredExposureLogs = deferred; + this._deferringLogs = true; try { return this._resolveVariableValue(key, defaultValue, true); } finally { - this._deferredExposureLogs = undefined; - if (deferred.length > 0) { + this._deferringLogs = false; + const deferred = this._deferredLogs; + if (deferred !== undefined) { + this._deferredLogs = undefined; try { - for (const exposure of deferred) this._logEvent("exposure", exposure); + for (const [eventName, data] of deferred) { + if (eventName === "error") this._logError(data as Error); + else this._logEvent(eventName, data as Record); + } } finally { this._setTimeout(); } @@ -1416,6 +1422,10 @@ export default class Context { } private _logError(error: Error) { + if (this._deferringLogs) { + (this._deferredLogs ??= []).push(["error", error]); + return; + } if (this._eventLogger) { try { this._eventLogger(this, "error", error); @@ -1604,6 +1614,22 @@ export default class Context { } }); + // A reused assignment still points at the previous parse of its configs; if a refresh made + // the experiment prototype-keyed, its cached variables must not resolve inherited members. + for (const experimentName of Object.keys(assignments)) { + const assignment = assignments[experimentName]; + const variables = assignment.variables; + const experiment = index[experimentName]; + if ( + variables !== undefined && + Object.getPrototypeOf(variables) !== null && + experiment !== undefined && + Object.getPrototypeOf(experiment.variables[0] ?? {}) === null + ) { + assignment.variables = Object.assign(Object.create(null), variables); + } + } + this._index = index; this._indexVariables = indexVariables; this._assignments = assignments; From a82ee6f21838e21d759bae7586657cf2f05dd885 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 13:32:24 +0000 Subject: [PATCH 56/92] perf(context): outline the deferred-callback replay; fix refresh and treatment edge cases Move the replay of a read's held callbacks into its own method with an indexed loop, so a warmed read stays small (about 80 vs 75 ns on main, documented), and arm the publish timer only when an exposure was replayed. treatment() also queues its holdout exposures before callbacks run, so finalize() from the first callback sends them. The refresh reclassification looks experiments up as own properties. Pin the lazy list, replay order, error-only reads, retained values and ordinary snapshots across refresh, and prototype-named experiments. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++- src/__tests__/context.test.js | 124 ++++++++++++++++++++++++++++++++++ src/context.ts | 50 ++++++++++---- 3 files changed, 169 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cee3de1..0188e23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,7 +72,11 @@ with 3,000. `getAttributes()` is faster than 1.13.4. A default `track()` + `publish()` matches 1.13.4 up to a few hundred attributes (7.3 vs 7.1 µs at 300) and costs about 30% more at 3,000 (about 52 vs 40 µs; unreleased main was about - 77 µs). The new opt-in `includeSystemAttributes` adds about 10% on top. + 77 µs). The new opt-in `includeSystemAttributes` adds about 10% on top. A + cached `variableValue()` costs about 5 ns more than unreleased main (about 80 vs + 75 ns, four experiments sharing a key): about 4 ns hold its `eventLogger` + callbacks until all its exposures are queued (see Fixed), the rest is the + shared-key winner rule. `peekVariableValue()` is unchanged. ### Fixed @@ -91,7 +95,8 @@ otherwise the caller default. Only the winner is exposed; each checked candidate's applicable holdouts still fire, as in Java. All exposures of one read are queued before its `exposure` and `error` callbacks run, so a callback that - calls `finalize()` still sends the winner. `peekVariableValue()` + calls `finalize()` still sends the winner. `treatment()` likewise queues an + experiment's and its holdouts' exposures before their callbacks run. `peekVariableValue()` exposes nothing. Keys no experiment defines return the default again, as in 1.13.4, including names like `toString`; a variant config that defines such a key (`toString`, `constructor`, `__proto__`) no longer fails the context. Affected: anyone with two or more diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index a4d6650..76a4bdb 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6156,6 +6156,93 @@ describe("Context", () => { ]); }); + it("creates no deferred list and arms no timer on a warmed read", () => { + const response = buildHoldoutResponse([winnerAfterHoldout({})], []); + const context = new Context(sdk, { ...contextOptions, publishDelay: 100 }, contextParams, response); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + clearTimeout(context._publishTimeout); + context._publishTimeout = undefined; + const schedule = jest.spyOn(context, "_setTimeout"); + const flush = jest.spyOn(context, "_flushDeferredLogs"); + for (let i = 0; i < 5; i++) context.variableValue("button.color", "APP_FALLBACK"); + expect(flush).not.toHaveBeenCalled(); + expect(schedule).not.toHaveBeenCalled(); + }); + + it("replays a read's exposure and error callbacks in the order they were raised", () => { + const events = []; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName === "exposure") events.push(`exposure:${data.name}`); + if (eventName === "error") events.push("error"); + }); + const strictSecond = { + ...holdoutVarExperiment({}), + id: 2, + name: "exp_strict_second", + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + }; + const response = buildHoldoutResponse( + [holdoutVarExperiment({}), strictSecond, winnerAfterHoldout({ id: 3 })], + [alwaysHoldsOut({})] + ); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("getter boom"); + }, + }); + context.attribute("user", user); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + expect(events).toEqual(["exposure:holdout_var", "error", "exposure:exp_holdout_var_later_winner"]); + }); + + it("arms no publish timer when a read raises only an error", () => { + const strictOnly = { + ...holdoutVarExperiment({}), + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + }; + const context = new Context( + sdk, + { ...contextOptions, publishDelay: 100, eventLogger: jest.fn() }, + contextParams, + buildHoldoutResponse([strictOnly], []) + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("getter boom"); + }, + }); + context.attribute("user", user); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("APP_FALLBACK"); + expect(context.pending()).toEqual(0); + expect(context._publishTimeout).toBeUndefined(); + }); + + it("sends a treatment's holdout exposure when its exposure callback finalizes", async () => { + publisher.publish.mockReturnValue(Promise.resolve()); + let finalizing; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName === "exposure" && finalizing === undefined) finalizing = ctx.finalize(); + }); + const covered = { ...winnerAfterHoldout({}), holdoutIds: [11] }; + const neverHolds = alwaysHoldsOut({ split: [0, 1] }); + const response = buildHoldoutResponse([covered], [neverHolds]); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + expect(context.treatment("exp_holdout_var_later_winner")).toBe(1); + await finalizing; + expect(context.pending()).toEqual(0); + const published = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0]; + expect(published.exposures.map((e) => e.name).sort()).toEqual( + ["exp_holdout_var_later_winner", "holdout_var"].sort() + ); + }); + it("schedules the publish timer after a variable read's deferred exposures", () => { const response = buildHoldoutResponse([winnerAfterHoldout({})], []); const context = new Context(sdk, { ...contextOptions, publishDelay: 100 }, contextParams, response); @@ -6513,6 +6600,43 @@ describe("Context", () => { expect(context.variableValue("toString", "SENTINEL")).toBe("SENTINEL"); }); + it("keeps a retained unit's value and ordinary snapshot across a refresh", async () => { + const before = { + ...shared(1, [0, 1], {}), + variants: [ + { name: "A", config: '{"k":"a1"}' }, + { name: "B", config: '{"k":"OLD"}' }, + ], + }; + const plain = { ...shared(2, [0, 1], { other: 1 }), name: "plain" }; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [before, plain] }); + expect(context.variableValue("k", "SENTINEL")).toBe("OLD"); + expect(context.treatment("plain")).toBe(1); + const after = { + ...before, + variants: [ + { name: "A", config: '{"k":"a1","valueOf":"V"}' }, + { name: "B", config: '{"k":"NEW"}' }, + ], + }; + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [after, plain] })); + await context.refresh(); + expect(context.peekVariableValue("k", "SENTINEL")).toBe("OLD"); + expect(context.variableValue("k", "SENTINEL")).toBe("OLD"); + expect(context.variableValue("valueOf", "SENTINEL")).toBe("SENTINEL"); + expect(Object.getPrototypeOf(context._assignments.plain.variables)).toBe(Object.prototype); + }); + + it("refreshes after an overridden experiment named like an Object.prototype member stops", async () => { + const named = { ...shared(1, [0, 1], {}), name: "toString" }; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [named] }); + context.override("toString", 1); + expect(context.treatment("toString")).toBe(1); + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [] })); + await expect(context.refresh()).resolves.toBeUndefined(); + expect(context.experiments()).toEqual([]); + }); + it("keeps Object.prototype on ordinary configs", () => { const context = new Context(sdk, contextOptions, contextParams, { experiments: [shared(1, [0, 1], {}), { ...protoKeyed(config), id: 2, name: "shared_2" }], diff --git a/src/context.ts b/src/context.ts index f9237fb..ae58a11 100644 --- a/src/context.ts +++ b/src/context.ts @@ -888,7 +888,19 @@ export default class Context { if (!assignment.exposed) { assignment.exposed = true; - this._triggerExposures(experimentName, assignment); + // Queue the experiment's and its holdouts' exposures before any callback runs, so an + // eventLogger that finalizes on the first one still sends the holdout's. + if (this._deferringLogs) { + this._triggerExposures(experimentName, assignment); + } else { + this._deferringLogs = true; + try { + this._triggerExposures(experimentName, assignment); + } finally { + this._deferringLogs = false; + if (this._deferredLogs !== undefined) this._flushDeferredLogs(); + } + } } return assignment; @@ -1084,6 +1096,7 @@ export default class Context { // A user eventLogger may call finalize() or publish(). Exposure and error callbacks this read // triggers run only after every exposure of the read (candidates' holdouts and the winner) is // queued, so such a call sends all of them instead of sealing the context with one pending. + // The replay lives in its own method so a warmed read, which defers nothing, stays small. private _variableValue(key: string, defaultValue: string): string { if (this._deferringLogs) return this._resolveVariableValue(key, defaultValue, true); @@ -1092,18 +1105,28 @@ export default class Context { return this._resolveVariableValue(key, defaultValue, true); } finally { this._deferringLogs = false; - const deferred = this._deferredLogs; - if (deferred !== undefined) { - this._deferredLogs = undefined; - try { - for (const [eventName, data] of deferred) { - if (eventName === "error") this._logError(data as Error); - else this._logEvent(eventName, data as Record); - } - } finally { - this._setTimeout(); + if (this._deferredLogs !== undefined) this._flushDeferredLogs(); + } + } + + private _flushDeferredLogs() { + const deferred = this._deferredLogs as [EventName, Record | Error][]; + this._deferredLogs = undefined; + + let exposed = false; + try { + for (let i = 0; i < deferred.length; i++) { + const entry = deferred[i]; + if (entry[0] === "error") { + this._logError(entry[1] as Error); + } else { + exposed = true; + this._logEvent(entry[0], entry[1] as Record); } } + } finally { + // Only exposures need publishing; an error alone must not arm the timer. + if (exposed) this._setTimeout(); } } @@ -1619,7 +1642,10 @@ export default class Context { for (const experimentName of Object.keys(assignments)) { const assignment = assignments[experimentName]; const variables = assignment.variables; - const experiment = index[experimentName]; + // Own lookup: an experiment named like an Object.prototype member must not resolve one. + const experiment = Object.prototype.hasOwnProperty.call(index, experimentName) + ? index[experimentName] + : undefined; if ( variables !== undefined && Object.getPrototypeOf(variables) !== null && From 1419d6afe756a36b7adc94a3e68fc5d622388d65 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 13:51:34 +0000 Subject: [PATCH 57/92] refactor(context): skip the winner's second holdout walk; tidy shared-key docs The resolver loop already fires every visited candidate's holdouts, including the winner's, so its exposure no longer walks the snapshot again. Drop a comment that restated the loop and reflow the README note (held-out fallback records only its holdout's exposure). Co-Authored-By: Claude Opus 5.5 --- README.md | 13 +++++++------ src/__tests__/context.test.js | 1 - src/context.ts | 8 ++++---- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 8ee20f2..903eb5b 100644 --- a/README.md +++ b/README.md @@ -231,12 +231,13 @@ const buttonColor = context.variableValue("button.color", defaultButtonColor); When several experiments define the same variable key, the SDK checks them in ascending experiment id and uses the first one the user is in (assigned, overridden or assigned by a rule). Its variant's value is returned, or your -default if that variant does not define the key; later experiments are never used -instead. If the user is in none of them but one is held out by a holdout, that -experiment's control value is returned. Only that experiment gets an exposure (plus any holdouts covering the -experiments checked). An experiment the user is not in, such as a strict audience -mismatch, gets none; call `treatment()` to record it. `peekVariableValue()` never -queues one. +default if that variant does not define the key; later experiments are never +used instead. If the user is in none of them but one is held out by a holdout, +that experiment's control value is returned. Only the winning experiment gets an +exposure (plus any holdouts covering the experiments checked); a held-out +experiment that supplies its control value records only its holdout's exposure. +An experiment the user is not in, such as a strict audience mismatch, gets none; +call `treatment()` to record it. `peekVariableValue()` never queues an exposure. ### Peek at Treatment Variants diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 76a4bdb..53b5289 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6377,7 +6377,6 @@ describe("Context", () => { fullOnVariant: 0, applications: [{ name: "website" }], variants: [ - // The override wins outright, even though variant 0 omits the key. { name: "A", config: null }, { name: "B", config: JSON.stringify({ "button.color": "OVERRIDE_SIBLING" }) }, ], diff --git a/src/context.ts b/src/context.ts index ae58a11..f0b7460 100644 --- a/src/context.ts +++ b/src/context.ts @@ -906,12 +906,12 @@ export default class Context { return assignment; } - private _triggerExposures(experimentName: string, assignment: Assignment): void { + private _triggerExposures(experimentName: string, assignment: Assignment, withHoldouts = true): void { if (!assignment.suppressed || assignment.overridden || assignment.ruleOverride) { this._queueExposure(experimentName, assignment); } - this._triggerApplicableHoldoutExposures(assignment); + if (withHoldouts) this._triggerApplicableHoldoutExposures(assignment); } // Uses the pinned snapshot, not a live re-resolution, so a refresh between the suppression @@ -1072,7 +1072,6 @@ export default class Context { break; } - // A winner breaks out above, so `selected` here can only be an earlier suppressed one. if (assignment.suppressed && selected === undefined) { selectedName = experimentName; selected = assignment; @@ -1084,7 +1083,8 @@ export default class Context { if (shouldQueueExposure && !selected.exposed) { selected.exposed = true; - this._triggerExposures(selectedName, selected); + // The loop above already fired this candidate's holdouts. + this._triggerExposures(selectedName, selected, false); } // A missing key (or out-of-range arm) returns the caller's default, never a later From 76b1269732fb11441ca05eb2a51c8623eea078b3 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 16:10:58 +0000 Subject: [PATCH 58/92] fix(context): replay deferred callbacks in queue order under one deferral owner Keep deferral on while replaying so callbacks raised by a nested read or treatment() follow the ones already queued, and let _endDeferral own the flag for both variableValue() and treatment(). Pin treatment() re-entered from an attribute getter mid-read, nested treatment() from an exposure callback, nested-read queue order and the lazy list via a setter spy. State the cached variableValue()/peekVariableValue() cost against 1.13.4 and unreleased main. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +-- src/__tests__/context.test.js | 113 +++++++++++++++++++++++++++++++++- src/context.ts | 42 ++++++++----- 3 files changed, 143 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0188e23..efbe6dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -73,10 +73,11 @@ `publish()` matches 1.13.4 up to a few hundred attributes (7.3 vs 7.1 µs at 300) and costs about 30% more at 3,000 (about 52 vs 40 µs; unreleased main was about 77 µs). The new opt-in `includeSystemAttributes` adds about 10% on top. A - cached `variableValue()` costs about 5 ns more than unreleased main (about 80 vs - 75 ns, four experiments sharing a key): about 4 ns hold its `eventLogger` - callbacks until all its exposures are queued (see Fixed), the rest is the - shared-key winner rule. `peekVariableValue()` is unchanged. + cached `variableValue()` (four experiments sharing a key) costs about 71 ns, down + from about 155 ns in 1.13.4, but about 4–6 ns more than unreleased main: about + 4 ns hold its `eventLogger` callbacks until all its exposures are queued (see + Fixed), the rest is the shared-key winner rule. `peekVariableValue()` costs about + 2–6 ns more than unreleased main. ### Fixed diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 53b5289..08fd5b9 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6163,9 +6163,18 @@ describe("Context", () => { clearTimeout(context._publishTimeout); context._publishTimeout = undefined; const schedule = jest.spyOn(context, "_setTimeout"); - const flush = jest.spyOn(context, "_flushDeferredLogs"); + const lists = []; + let deferredLogs; + Object.defineProperty(context, "_deferredLogs", { + configurable: true, + get: () => deferredLogs, + set: (value) => { + if (value !== undefined) lists.push(value); + deferredLogs = value; + }, + }); for (let i = 0; i < 5; i++) context.variableValue("button.color", "APP_FALLBACK"); - expect(flush).not.toHaveBeenCalled(); + expect(lists).toEqual([]); expect(schedule).not.toHaveBeenCalled(); }); @@ -6243,6 +6252,106 @@ describe("Context", () => { ); }); + it("reports a nested treatment() exposure raised from an exposure callback", () => { + const names = []; + let nested = false; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + names.push(data.name); + if (!nested) { + nested = true; + ctx.treatment("exp_holdout_var_later_winner"); + } + }); + const covered = { ...winnerAfterHoldout({ id: 3, name: "exp_covered" }), holdoutIds: [11] }; + const neverHolds = alwaysHoldsOut({ split: [0, 1] }); + const response = buildHoldoutResponse([covered, winnerAfterHoldout({})], [neverHolds]); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + context.treatment("exp_covered"); + expect(names).toEqual(["exp_covered", "holdout_var", "exp_holdout_var_later_winner"]); + expect(context._deferredLogs).toBeUndefined(); + expect(context.pending()).toEqual(3); + }); + + it("keeps a read's deferral when an attribute getter calls treatment() mid-read", async () => { + publisher.publish.mockReturnValue(Promise.resolve()); + let finalizing; + let reentered = false; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName === "exposure" && finalizing === undefined) finalizing = ctx.finalize(); + }); + const strictFirst = { + ...holdoutVarExperiment({}), + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + }; + const plain = { + ...winnerAfterHoldout({}), + id: 3, + name: "exp_plain", + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + }; + const response = buildHoldoutResponse( + [strictFirst, winnerAfterHoldout({}), plain], + [alwaysHoldsOut({ split: [0, 1] })] + ); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + if (!reentered) { + reentered = true; + context.treatment("exp_plain"); + } + return "free"; + }, + }); + context.attribute("user", user); + + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + await finalizing; + expect(context.pending()).toEqual(0); + const published = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0]; + expect(published.exposures.map((e) => e.name)).toEqual([ + "exp_plain", + "holdout_var", + "exp_holdout_var_later_winner", + ]); + }); + + it("logs callbacks in queue order when a replayed callback reads another key", () => { + const names = []; + let nested = false; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + names.push(data.name); + if (!nested) { + nested = true; + ctx.variableValue("other.key", "D"); + } + }); + const other = { + ...winnerAfterHoldout({}), + id: 3, + name: "exp_other_key", + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ "other.key": "OTHER" }) }, + ], + }; + const response = buildHoldoutResponse( + [holdoutVarExperiment({}), winnerAfterHoldout({}), other], + [alwaysHoldsOut({})] + ); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + expect(names).toEqual(context._exposures.map((e) => e.name)); + expect(names).toEqual(["holdout_var", "exp_holdout_var_later_winner", "exp_other_key"]); + }); + it("schedules the publish timer after a variable read's deferred exposures", () => { const response = buildHoldoutResponse([winnerAfterHoldout({})], []); const context = new Context(sdk, { ...contextOptions, publishDelay: 100 }, contextParams, response); diff --git a/src/context.ts b/src/context.ts index f0b7460..aac9879 100644 --- a/src/context.ts +++ b/src/context.ts @@ -897,8 +897,7 @@ export default class Context { try { this._triggerExposures(experimentName, assignment); } finally { - this._deferringLogs = false; - if (this._deferredLogs !== undefined) this._flushDeferredLogs(); + this._endDeferral(); } } } @@ -1104,27 +1103,36 @@ export default class Context { try { return this._resolveVariableValue(key, defaultValue, true); } finally { - this._deferringLogs = false; - if (this._deferredLogs !== undefined) this._flushDeferredLogs(); + this._endDeferral(); } } - private _flushDeferredLogs() { - const deferred = this._deferredLogs as [EventName, Record | Error][]; - this._deferredLogs = undefined; - + // Ends a deferral scope, replaying held callbacks in queue order. Deferral stays on while + // replaying, so a nested read or treatment() made from a callback appends its own callbacks + // behind the ones already queued. + private _endDeferral() { + if (this._deferredLogs === undefined) { + this._deferringLogs = false; + return; + } let exposed = false; try { - for (let i = 0; i < deferred.length; i++) { - const entry = deferred[i]; - if (entry[0] === "error") { - this._logError(entry[1] as Error); - } else { - exposed = true; - this._logEvent(entry[0], entry[1] as Record); + let deferred: [EventName, Record | Error][] | undefined = this._deferredLogs; + while (deferred !== undefined) { + this._deferredLogs = undefined; + for (let i = 0; i < deferred.length; i++) { + const entry = deferred[i]; + if (entry[0] === "error") { + this._emitError(entry[1] as Error); + } else { + exposed = true; + this._logEvent(entry[0], entry[1] as Record); + } } + deferred = this._deferredLogs; } } finally { + this._deferringLogs = false; // Only exposures need publishing; an error alone must not arm the timer. if (exposed) this._setTimeout(); } @@ -1449,6 +1457,10 @@ export default class Context { (this._deferredLogs ??= []).push(["error", error]); return; } + this._emitError(error); + } + + private _emitError(error: Error) { if (this._eventLogger) { try { this._eventLogger(this, "error", error); From 5360576bfc09f6a31eeb9dbdd9a6609026e76564 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 16:14:26 +0000 Subject: [PATCH 59/92] test(context): pin single holdout walk, nested treatment() deferral and unindexed reads Add tests for the once-per-candidate holdout walk, an unindexed key that assigns nothing, and the CHANGELOG note that treatment() audience errors are still reported first. Rename a nested-read test whose title overstated callback ordering. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++- src/__tests__/context.test.js | 23 ++++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index efbe6dd..659549e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -97,7 +97,8 @@ candidate's applicable holdouts still fire, as in Java. All exposures of one read are queued before its `exposure` and `error` callbacks run, so a callback that calls `finalize()` still sends the winner. `treatment()` likewise queues an - experiment's and its holdouts' exposures before their callbacks run. `peekVariableValue()` + experiment's and its holdouts' exposures before their `exposure` callbacks run + (an audience `error` raised by `treatment()` itself is still reported first). `peekVariableValue()` exposes nothing. Keys no experiment defines return the default again, as in 1.13.4, including names like `toString`; a variant config that defines such a key (`toString`, `constructor`, `__proto__`) no longer fails the context. Affected: anyone with two or more diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 08fd5b9..e6797c3 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6087,7 +6087,7 @@ describe("Context", () => { expect(published.exposures.map((e) => e.name)).toEqual(["holdout_var", "exp_holdout_var_later_winner"]); }); - it("reports nested variable reads from a callback after the outer read's exposures, in queue order", () => { + it("reports a nested read's callbacks after the outer read's exposures", () => { const names = []; let nested = false; const eventLogger = jest.fn((ctx, eventName, data) => { @@ -6352,6 +6352,27 @@ describe("Context", () => { expect(names).toEqual(["holdout_var", "exp_holdout_var_later_winner", "exp_other_key"]); }); + it("walks each visited candidate's holdouts once per read", () => { + const response = buildHoldoutResponse( + [holdoutVarExperiment({}), { ...winnerAfterHoldout({}), holdoutIds: [12] }], + [alwaysHoldsOut({}), alwaysHoldsOut({ id: 12, name: "holdout_never", split: [0, 1] })] + ); + const context = new Context(sdk, contextOptions, contextParams, response); + const walk = jest.spyOn(context, "_triggerApplicableHoldoutExposures"); + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + expect(walk).toHaveBeenCalledTimes(2); + }); + + it("returns the default for an unindexed key without assigning any experiment", () => { + const response = buildHoldoutResponse([winnerAfterHoldout({})], []); + const context = new Context(sdk, contextOptions, contextParams, response); + const assign = jest.spyOn(context, "_assign"); + expect(context.variableValue("not.indexed", "APP_FALLBACK")).toEqual("APP_FALLBACK"); + expect(context.peekVariableValue("not.indexed", "APP_FALLBACK")).toEqual("APP_FALLBACK"); + expect(assign).not.toHaveBeenCalled(); + expect(context._deferredLogs).toBeUndefined(); + }); + it("schedules the publish timer after a variable read's deferred exposures", () => { const response = buildHoldoutResponse([winnerAfterHoldout({})], []); const context = new Context(sdk, { ...contextOptions, publishDelay: 100 }, contextParams, response); From 8cbb1047f12b9af07a5eabce1e81b154363b3c12 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 17:37:28 +0000 Subject: [PATCH 60/92] fix(context): bound observer feedback while retaining ordered replay Do not invoke an error observer recursively for errors it raises. Report an identical exposure callback only once per drain while retaining every exposure event in the publish queue. Outline cold replay to keep the deferral owner small. Pin exposures first queued from error callbacks and immediate unindexed-key returns. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 130 +++++++++++++++++++++++++++++++++- src/context.ts | 30 ++++++-- 2 files changed, 152 insertions(+), 8 deletions(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index e6797c3..5aeed75 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6367,12 +6367,138 @@ describe("Context", () => { const response = buildHoldoutResponse([winnerAfterHoldout({})], []); const context = new Context(sdk, contextOptions, contextParams, response); const assign = jest.spyOn(context, "_assign"); - expect(context.variableValue("not.indexed", "APP_FALLBACK")).toEqual("APP_FALLBACK"); - expect(context.peekVariableValue("not.indexed", "APP_FALLBACK")).toEqual("APP_FALLBACK"); + const iterator = Array.prototype[Symbol.iterator]; + let emptyWalks = 0; + try { + // eslint-disable-next-line no-extend-native + Array.prototype[Symbol.iterator] = function () { + if (this.length === 0) emptyWalks++; + return iterator.call(this); + }; + const value = context.variableValue("not.indexed", "APP_FALLBACK"); + const peeked = context.peekVariableValue("not.indexed", "APP_FALLBACK"); + // eslint-disable-next-line no-extend-native + Array.prototype[Symbol.iterator] = iterator; + expect(value).toEqual("APP_FALLBACK"); + expect(peeked).toEqual("APP_FALLBACK"); + expect(emptyWalks).toBe(0); + } finally { + // eslint-disable-next-line no-extend-native + Array.prototype[Symbol.iterator] = iterator; + } expect(assign).not.toHaveBeenCalled(); expect(context._deferredLogs).toBeUndefined(); }); + it("arms the timer for an exposure first queued from a replayed error callback", () => { + const strict = { + ...holdoutVarExperiment({}), + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + }; + const other = { + ...winnerAfterHoldout({}), + variants: [ + { name: "A", config: null }, + { name: "B", config: '{"other.key":"OTHER"}' }, + ], + }; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName === "error") ctx.variableValue("other.key", "D"); + }); + const context = new Context( + sdk, + { ...contextOptions, publishDelay: 100, eventLogger }, + contextParams, + buildHoldoutResponse([strict, other], []) + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("boom"); + }, + }); + context.attribute("user", user); + expect(context.variableValue("button.color", "D")).toBe("D"); + expect(context.pending()).toBe(1); + expect(context._publishTimeout).toBeDefined(); + clearTimeout(context._publishTimeout); + }); + + it("does not feed error-observer errors into the replay queue forever", () => { + let count = 0; + const consoleError = jest.spyOn(console, "error").mockImplementation(() => {}); + try { + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName === "exposure" || eventName === "error") { + if (++count < 20000) { + ctx.attribute("observer.seq", count); + ctx.variableValue("error.key", "D"); + } + } + }); + const experiment = winnerAfterHoldout({ + customFieldValues: [{ name: "bad", type: "future", value: "x" }], + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse( + [ + experiment, + { + ...holdoutVarExperiment({}), + id: 4, + name: "error_exp", + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ + filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }], + }), + variants: [ + { name: "A", config: null }, + { name: "B", config: '{"error.key":1}' }, + ], + }, + ], + [] + ) + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("observer getter"); + }, + }); + context.attribute("user", user); + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + expect(count).toBeLessThan(10); + expect(context._deferredLogs).toBeUndefined(); + } finally { + consoleError.mockRestore(); + } + }); + + it("does not feed repeated exposure callbacks into the drain forever", () => { + let count = 0; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName === "exposure" && ++count < 100) ctx.variableValue("button.color", "D"); + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([winnerAfterHoldout({})], []) + ); + context.customAssignment("exp_holdout_var_later_winner", 0); + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + expect(count).toBe(1); + expect(context.pending()).toBe(2); + expect(context._deferredLogs).toBeUndefined(); + }); + it("schedules the publish timer after a variable read's deferred exposures", () => { const response = buildHoldoutResponse([winnerAfterHoldout({})], []); const context = new Context(sdk, { ...contextOptions, publishDelay: 100 }, contextParams, response); diff --git a/src/context.ts b/src/context.ts index aac9879..8a3617d 100644 --- a/src/context.ts +++ b/src/context.ts @@ -197,6 +197,7 @@ export default class Context { // While a variable read runs, user eventLogger callbacks it would trigger are held here (the // list is created on first use) and replayed once every exposure of the read is queued. private _deferringLogs = false; + private _emittingError = false; private _deferredLogs?: [EventName, Record | Error][]; private _attrsSeq: number; private _attrsMapCache: Record | null; @@ -1111,11 +1112,13 @@ export default class Context { // replaying, so a nested read or treatment() made from a callback appends its own callbacks // behind the ones already queued. private _endDeferral() { - if (this._deferredLogs === undefined) { - this._deferringLogs = false; - return; - } + if (this._deferredLogs === undefined) this._deferringLogs = false; + else this._replayDeferredLogs(); + } + + private _replayDeferredLogs() { let exposed = false; + const reported = new Set(); try { let deferred: [EventName, Record | Error][] | undefined = this._deferredLogs; while (deferred !== undefined) { @@ -1126,7 +1129,14 @@ export default class Context { this._emitError(entry[1] as Error); } else { exposed = true; - this._logEvent(entry[0], entry[1] as Record); + const exposure = entry[1] as Exposure; + const identity = JSON.stringify([exposure.id, exposure.name, exposure.variant, exposure.exposedAt]); + // An observer that reads a repeatedly re-assigned experiment must not feed + // identical callbacks into this drain forever. Events remain queued for publish. + if (!reported.has(identity)) { + reported.add(identity); + this._logEvent(entry[0], entry[1] as Record); + } } } deferred = this._deferredLogs; @@ -1453,7 +1463,7 @@ export default class Context { } private _logError(error: Error) { - if (this._deferringLogs) { + if (this._deferringLogs && !this._emittingError) { (this._deferredLogs ??= []).push(["error", error]); return; } @@ -1461,11 +1471,19 @@ export default class Context { } private _emitError(error: Error) { + // Do not call an error observer recursively when its own reporting raises another error. + if (this._emittingError) return; if (this._eventLogger) { + // Errors raised by an error observer run inline under the existing observer guard, + // rather than feeding the deferred replay forever. Preserve a nesting caller's flag. + const wasEmitting = this._emittingError; + this._emittingError = true; try { this._eventLogger(this, "error", error); } catch (observerError) { console.error(observerError); + } finally { + this._emittingError = wasEmitting; } } } From 5e12071f65a716f20ee1dcd56daee0c00c664384 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 18:21:23 +0000 Subject: [PATCH 61/92] fix(context): bound callback replay by rounds instead of dropping callbacks Every held callback is delivered once in queue order, including errors raised by an error callback and repeated exposures. A replay that keeps receiving new events stops deferring after DEFERRED_REPLAY_ROUNDS rounds, so later callbacks run inline and stay bounded by the call stack as before deferral; reads always return, even when the clock advances. Removes the Set-based dedup (not available in all browser targets) and the error-observer suppression. Remeasure and document the read cost. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 15 +++-- src/__tests__/context.test.js | 102 ++++++++++++++++++++++++++++++++-- src/context.ts | 29 ++++------ 3 files changed, 116 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 659549e..4420f3e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -73,11 +73,11 @@ `publish()` matches 1.13.4 up to a few hundred attributes (7.3 vs 7.1 µs at 300) and costs about 30% more at 3,000 (about 52 vs 40 µs; unreleased main was about 77 µs). The new opt-in `includeSystemAttributes` adds about 10% on top. A - cached `variableValue()` (four experiments sharing a key) costs about 71 ns, down - from about 155 ns in 1.13.4, but about 4–6 ns more than unreleased main: about - 4 ns hold its `eventLogger` callbacks until all its exposures are queued (see - Fixed), the rest is the shared-key winner rule. `peekVariableValue()` costs about - 2–6 ns more than unreleased main. + cached `variableValue()` (four experiments sharing a key) costs about 70–78 ns, + down from about 155 ns in 1.13.4, but about 5–9 ns more than unreleased main + (measured on two hosts, Node 22, compiled CJS): most of it holds its + `eventLogger` callbacks until all its exposures are queued (see Fixed). + `peekVariableValue()` costs about 2–7 ns more than unreleased main. ### Fixed @@ -96,7 +96,10 @@ otherwise the caller default. Only the winner is exposed; each checked candidate's applicable holdouts still fire, as in Java. All exposures of one read are queued before its `exposure` and `error` callbacks run, so a callback that - calls `finalize()` still sends the winner. `treatment()` likewise queues an + calls `finalize()` still sends the winner. Callbacks a callback raises are replayed after + the ones already held, in queue order; an observer that keeps feeding new + events stops being deferred after a bounded number of rounds, so a read always + returns. `treatment()` likewise queues an experiment's and its holdouts' exposures before their `exposure` callbacks run (an audience `error` raised by `treatment()` itself is still reported first). `peekVariableValue()` exposes nothing. Keys no experiment defines return the default diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 5aeed75..e80b51c 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6432,7 +6432,7 @@ describe("Context", () => { try { const eventLogger = jest.fn((ctx, eventName) => { if (eventName === "exposure" || eventName === "error") { - if (++count < 20000) { + if (++count < 50000) { ctx.attribute("observer.seq", count); ctx.variableValue("error.key", "D"); } @@ -6474,14 +6474,14 @@ describe("Context", () => { }); context.attribute("user", user); expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); - expect(count).toBeLessThan(10); + expect(count).toBeLessThan(50000); expect(context._deferredLogs).toBeUndefined(); } finally { consoleError.mockRestore(); } }); - it("does not feed repeated exposure callbacks into the drain forever", () => { + it("delivers every callback of finite exposure feedback in queue order", () => { let count = 0; const eventLogger = jest.fn((ctx, eventName) => { if (eventName === "exposure" && ++count < 100) ctx.variableValue("button.color", "D"); @@ -6494,9 +6494,101 @@ describe("Context", () => { ); context.customAssignment("exp_holdout_var_later_winner", 0); expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); - expect(count).toBe(1); - expect(context.pending()).toBe(2); + expect(count).toBe(100); + expect(context.pending()).toBe(100); expect(context._deferredLogs).toBeUndefined(); + expect(context._deferringLogs).toBe(false); + }); + + it("returns from unbounded exposure feedback when the clock advances on every callback", () => { + let count = 0; + let now = timeOrigin; + Date.now.mockImplementation(() => now); + const consoleError = jest.spyOn(console, "error").mockImplementation(() => {}); + try { + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "exposure") return; + now += 2; + if (++count < 50000) ctx.variableValue("button.color", "D"); + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([winnerAfterHoldout({})], []) + ); + context.customAssignment("exp_holdout_var_later_winner", 0); + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + expect(count).toBeLessThan(50000); + expect(context._deferringLogs).toBe(false); + } finally { + consoleError.mockRestore(); + } + }); + + it("reports a re-exposure whose flags differ within the same drain", () => { + const reported = []; + const strict = { + ...winnerAfterHoldout({}), + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "plan" }, { value: "pro" }] }] }), + }; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + reported.push(data.audienceMismatch); + if (reported.length === 1) { + ctx.attribute("plan", "pro"); + ctx.treatment("exp_holdout_var_later_winner"); + } + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([strict], []) + ); + context.treatment("exp_holdout_var_later_winner"); + expect(reported).toEqual([true, false]); + expect(context.pending()).toBe(2); + }); + + it("reports an error raised inside an error callback", () => { + const errors = []; + const strict = (id, experimentName, key) => ({ + ...holdoutVarExperiment({}), + id, + name: experimentName, + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ [key]: 1 }) }, + ], + }); + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "error") return; + errors.push(data.message); + if (errors.length === 1) { + ctx.attribute("seq", 1); + ctx.variableValue("second.key", "D"); + } + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([strict(1, "e_first", "first.key"), strict(2, "e_second", "second.key")], []) + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("getter boom"); + }, + }); + context.attribute("user", user); + expect(context.variableValue("first.key", "D")).toBe("D"); + expect(errors).toHaveLength(2); }); it("schedules the publish timer after a variable read's deferred exposures", () => { diff --git a/src/context.ts b/src/context.ts index 8a3617d..71fcfdd 100644 --- a/src/context.ts +++ b/src/context.ts @@ -21,6 +21,8 @@ type CustomFieldValue = { type: CustomFieldValueType; }; +// Feedback rounds a deferred-callback replay drains before later callbacks run inline. +const DEFERRED_REPLAY_ROUNDS = 32; export type ExperimentData = { id: number; name: string; @@ -197,7 +199,6 @@ export default class Context { // While a variable read runs, user eventLogger callbacks it would trigger are held here (the // list is created on first use) and replayed once every exposure of the read is queued. private _deferringLogs = false; - private _emittingError = false; private _deferredLogs?: [EventName, Record | Error][]; private _attrsSeq: number; private _attrsMapCache: Record | null; @@ -1116,27 +1117,25 @@ export default class Context { else this._replayDeferredLogs(); } + // Replays held callbacks in queue order, keeping deferral on so callbacks a callback raises join + // the queue behind the ones already held. A callback that keeps feeding new events would drain + // forever, so after DEFERRED_REPLAY_ROUNDS rounds deferral stops and later callbacks run inline, + // bounded by the call stack as before deferral existed. private _replayDeferredLogs() { let exposed = false; - const reported = new Set(); try { + let rounds = 0; let deferred: [EventName, Record | Error][] | undefined = this._deferredLogs; while (deferred !== undefined) { this._deferredLogs = undefined; + if (++rounds >= DEFERRED_REPLAY_ROUNDS) this._deferringLogs = false; for (let i = 0; i < deferred.length; i++) { const entry = deferred[i]; if (entry[0] === "error") { this._emitError(entry[1] as Error); } else { exposed = true; - const exposure = entry[1] as Exposure; - const identity = JSON.stringify([exposure.id, exposure.name, exposure.variant, exposure.exposedAt]); - // An observer that reads a repeatedly re-assigned experiment must not feed - // identical callbacks into this drain forever. Events remain queued for publish. - if (!reported.has(identity)) { - reported.add(identity); - this._logEvent(entry[0], entry[1] as Record); - } + this._logEvent(entry[0], entry[1] as Record); } } deferred = this._deferredLogs; @@ -1463,7 +1462,7 @@ export default class Context { } private _logError(error: Error) { - if (this._deferringLogs && !this._emittingError) { + if (this._deferringLogs) { (this._deferredLogs ??= []).push(["error", error]); return; } @@ -1471,19 +1470,11 @@ export default class Context { } private _emitError(error: Error) { - // Do not call an error observer recursively when its own reporting raises another error. - if (this._emittingError) return; if (this._eventLogger) { - // Errors raised by an error observer run inline under the existing observer guard, - // rather than feeding the deferred replay forever. Preserve a nesting caller's flag. - const wasEmitting = this._emittingError; - this._emittingError = true; try { this._eventLogger(this, "error", error); } catch (observerError) { console.error(observerError); - } finally { - this._emittingError = wasEmitting; } } } From fd76397b686464636082404e1f84092deff12173 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 19:40:39 +0000 Subject: [PATCH 62/92] fix(context): keep replay exhaustion sticky until the outer replay ends Once a replay spends DEFERRED_REPLAY_ROUNDS, nested variableValue()/treatment() calls made from callbacks run inline instead of opening a fresh deferral with a new budget, so runaway observer feedback stays stack-bounded as before deferral. Pin depth 1 within the budget and inline nesting after it; tighten feedback bounds. Document eventLogger delivery order in the README and per-API read cost. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 ++++++---- README.md | 6 ++++++ src/__tests__/context.test.js | 35 +++++++++++++++++++++++++++++++++-- src/context.ts | 14 ++++++++++---- 4 files changed, 55 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4420f3e..b53d6a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,10 +74,12 @@ and costs about 30% more at 3,000 (about 52 vs 40 µs; unreleased main was about 77 µs). The new opt-in `includeSystemAttributes` adds about 10% on top. A cached `variableValue()` (four experiments sharing a key) costs about 70–78 ns, - down from about 155 ns in 1.13.4, but about 5–9 ns more than unreleased main - (measured on two hosts, Node 22, compiled CJS): most of it holds its - `eventLogger` callbacks until all its exposures are queued (see Fixed). - `peekVariableValue()` costs about 2–7 ns more than unreleased main. + down from about 155 ns in 1.13.4, but up to about 9 ns more than unreleased + main, mostly for holding its `eventLogger` callbacks until all its exposures + are queued (see Fixed). `peekVariableValue()` costs about 2–15 ns more than + unreleased main. `treatment()` and `peek()` are unchanged. Measured on shared + hosts (Node 22, compiled CJS, four experiments sharing a key), so treat these + as approximate. ### Fixed diff --git a/README.md b/README.md index 903eb5b..fd43204 100644 --- a/README.md +++ b/README.md @@ -382,6 +382,12 @@ The data parameter depends on the type of event. Currently, the SDK logs the fol | `"goal"` | `track()` method succeeds | Goal data enqueued for publishing | | `"finalize"` | `finalize()` method succeeds the first time | undefined | +`"exposure"` and `"error"` events raised by one `variableValue()` call (and the +`"exposure"` events of one `treatment()` call) are delivered after all of that +call's exposures are queued, in the order they were raised, so a logger that +calls `publish()` or `finalize()` sends every one of them. Events a logger +triggers itself are delivered after the ones already waiting. + ### HTTP Request Timeout It is possible to set a timeout per individual HTTP request, overriding the global timeout set for all requests when instantiating the SDK object. diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index e80b51c..5dfcf18 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6474,7 +6474,7 @@ describe("Context", () => { }); context.attribute("user", user); expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); - expect(count).toBeLessThan(50000); + expect(count).toBeLessThan(2000); expect(context._deferredLogs).toBeUndefined(); } finally { consoleError.mockRestore(); @@ -6519,7 +6519,7 @@ describe("Context", () => { ); context.customAssignment("exp_holdout_var_later_winner", 0); expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); - expect(count).toBeLessThan(50000); + expect(count).toBeLessThan(2000); expect(context._deferringLogs).toBe(false); } finally { consoleError.mockRestore(); @@ -6591,6 +6591,37 @@ describe("Context", () => { expect(errors).toHaveLength(2); }); + const feedbackDepths = (limit) => { + let depth = 0; + const depths = []; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "exposure") return; + depths.push(++depth); + try { + if (depths.length < limit) ctx.variableValue("button.color", "D"); + } finally { + depth--; + } + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([winnerAfterHoldout({})], []) + ); + context.customAssignment("exp_holdout_var_later_winner", 0); + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + return depths; + }; + + it("keeps finite feedback within the replay rounds at depth 1", () => { + expect(feedbackDepths(31)).toEqual(Array(31).fill(1)); + }); + + it("runs feedback callbacks inline once the replay rounds are spent", () => { + expect(feedbackDepths(40)).toEqual([...Array(32).fill(1), 2, 3, 4, 5, 6, 7, 8, 9]); + }); + it("schedules the publish timer after a variable read's deferred exposures", () => { const response = buildHoldoutResponse([winnerAfterHoldout({})], []); const context = new Context(sdk, { ...contextOptions, publishDelay: 100 }, contextParams, response); diff --git a/src/context.ts b/src/context.ts index 71fcfdd..df82c9c 100644 --- a/src/context.ts +++ b/src/context.ts @@ -199,6 +199,8 @@ export default class Context { // While a variable read runs, user eventLogger callbacks it would trigger are held here (the // list is created on first use) and replayed once every exposure of the read is queued. private _deferringLogs = false; + // Set once a replay spends its rounds, until that replay ends: nested calls then run inline. + private _replayExhausted = false; private _deferredLogs?: [EventName, Record | Error][]; private _attrsSeq: number; private _attrsMapCache: Record | null; @@ -892,7 +894,7 @@ export default class Context { // Queue the experiment's and its holdouts' exposures before any callback runs, so an // eventLogger that finalizes on the first one still sends the holdout's. - if (this._deferringLogs) { + if (this._deferringLogs || this._replayExhausted) { this._triggerExposures(experimentName, assignment); } else { this._deferringLogs = true; @@ -1099,7 +1101,7 @@ export default class Context { // queued, so such a call sends all of them instead of sealing the context with one pending. // The replay lives in its own method so a warmed read, which defers nothing, stays small. private _variableValue(key: string, defaultValue: string): string { - if (this._deferringLogs) return this._resolveVariableValue(key, defaultValue, true); + if (this._deferringLogs || this._replayExhausted) return this._resolveVariableValue(key, defaultValue, true); this._deferringLogs = true; try { @@ -1123,12 +1125,15 @@ export default class Context { // bounded by the call stack as before deferral existed. private _replayDeferredLogs() { let exposed = false; + let rounds = 0; try { - let rounds = 0; let deferred: [EventName, Record | Error][] | undefined = this._deferredLogs; while (deferred !== undefined) { this._deferredLogs = undefined; - if (++rounds >= DEFERRED_REPLAY_ROUNDS) this._deferringLogs = false; + if (++rounds >= DEFERRED_REPLAY_ROUNDS) { + this._deferringLogs = false; + this._replayExhausted = true; + } for (let i = 0; i < deferred.length; i++) { const entry = deferred[i]; if (entry[0] === "error") { @@ -1142,6 +1147,7 @@ export default class Context { } } finally { this._deferringLogs = false; + if (rounds >= DEFERRED_REPLAY_ROUNDS) this._replayExhausted = false; // Only exposures need publishing; an error alone must not arm the timer. if (exposed) this._setTimeout(); } From af581a0e3123338bf254897384d1f3dc1f6829d8 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 21:05:49 +0000 Subject: [PATCH 63/92] test(context): pin treatment() exhaustion and its reset; tighten docs Cover nested treatment() feedback after the replay rounds are spent, deferral returning on a later read (also when its logger finalizes), and finite feedback staying at depth 1. Clear the exhaustion flag unconditionally when the replay ends, use an indexed candidate loop on the hot read path, narrow the README delivery-order note to exposure/error events and its bounded-round fallback, and give cached treatment()/peek() cost. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +- README.md | 8 ++- src/__tests__/context.test.js | 91 +++++++++++++++++++++++++++++++++++ src/context.ts | 7 +-- 4 files changed, 103 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b53d6a4..223af77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -77,7 +77,8 @@ down from about 155 ns in 1.13.4, but up to about 9 ns more than unreleased main, mostly for holding its `eventLogger` callbacks until all its exposures are queued (see Fixed). `peekVariableValue()` costs about 2–15 ns more than - unreleased main. `treatment()` and `peek()` are unchanged. Measured on shared + unreleased main; a cached `treatment()` or `peek()` costs about 1–2 ns more + (the assignment-rule and holdout checks above). Measured on shared hosts (Node 22, compiled CJS, four experiments sharing a key), so treat these as approximate. diff --git a/README.md b/README.md index fd43204..ff18174 100644 --- a/README.md +++ b/README.md @@ -385,8 +385,12 @@ The data parameter depends on the type of event. Currently, the SDK logs the fol `"exposure"` and `"error"` events raised by one `variableValue()` call (and the `"exposure"` events of one `treatment()` call) are delivered after all of that call's exposures are queued, in the order they were raised, so a logger that -calls `publish()` or `finalize()` sends every one of them. Events a logger -triggers itself are delivered after the ones already waiting. +calls `publish()` or `finalize()` sends every one of them. `"exposure"` +and `"error"` events a logger triggers itself are delivered after the ones +already waiting (other events, such as a `"goal"` from `track()`, are delivered +immediately); a logger that keeps triggering new events is switched to inline +delivery after a bounded number of rounds, so its later events arrive as they +are raised. ### HTTP Request Timeout diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 5dfcf18..cf3d32d 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6618,6 +6618,97 @@ describe("Context", () => { expect(feedbackDepths(31)).toEqual(Array(31).fill(1)); }); + it("runs treatment() feedback inline once the replay rounds are spent", () => { + let depth = 0; + const depths = []; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "exposure") return; + depths.push(++depth); + try { + if (depths.length < 40) ctx.treatment("exp_holdout_var_later_winner"); + } finally { + depth--; + } + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([winnerAfterHoldout({})], []) + ); + context.customAssignment("exp_holdout_var_later_winner", 0); + context.treatment("exp_holdout_var_later_winner"); + expect(depths).toEqual([...Array(32).fill(1), 2, 3, 4, 5, 6, 7, 8, 9]); + }); + + it("defers again in a later read after a replay spent its rounds", () => { + let depth = 0; + let limit = 40; + const depths = []; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "exposure") return; + depths.push(++depth); + try { + if (depths.length < limit) ctx.variableValue("button.color", "D"); + } finally { + depth--; + } + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([winnerAfterHoldout({})], []) + ); + context.customAssignment("exp_holdout_var_later_winner", 0); + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + depths.length = 0; + limit = 10; + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + expect(depths).toEqual(Array(10).fill(1)); + }); + + it("sends the winner when a later read finalizes after a replay spent its rounds", async () => { + publisher.publish.mockReturnValue(Promise.resolve()); + let mode = "loop"; + let count = 0; + let finalizing; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + if (mode === "loop") { + if (++count < 40) ctx.variableValue("loop.key", "D"); + } else if (data.name === "holdout_var" && finalizing === undefined) { + finalizing = ctx.finalize(); + } + }); + const loop = { + ...winnerAfterHoldout({}), + id: 3, + name: "exp_loop", + variants: [ + { name: "A", config: JSON.stringify({ "loop.key": "A" }) }, + { name: "B", config: JSON.stringify({ "loop.key": "B" }) }, + ], + }; + const response = buildHoldoutResponse( + [holdoutVarExperiment({}), winnerAfterHoldout({}), loop], + [alwaysHoldsOut({})] + ); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + context.customAssignment("exp_loop", 0); + expect(context.variableValue("loop.key", "D")).toBe("B"); + expect(count).toBe(40); + mode = "finalize"; + expect(context.variableValue("button.color", "APP_FALLBACK")).toEqual("WINNER_AFTER_HOLDOUT"); + await finalizing; + expect(context.pending()).toEqual(0); + const published = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0]; + expect(published.exposures.map((e) => e.name).filter((n) => n !== "exp_loop")).toEqual([ + "holdout_var", + "exp_holdout_var_later_winner", + ]); + }); + it("runs feedback callbacks inline once the replay rounds are spent", () => { expect(feedbackDepths(40)).toEqual([...Array(32).fill(1), 2, 3, 4, 5, 6, 7, 8, 9]); }); diff --git a/src/context.ts b/src/context.ts index df82c9c..0ec0906 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1064,8 +1064,9 @@ export default class Context { let selectedName = ""; let selected: Assignment | undefined; - for (const experiment of candidates) { - const experimentName = experiment.data.name; + // Indexed loop: a for...of here compiles to a larger body that slows every warmed read. + for (let i = 0; i < candidates.length; i++) { + const experimentName = candidates[i].data.name; const assignment = this._assign(experimentName); if (shouldQueueExposure) this._triggerApplicableHoldoutExposures(assignment); @@ -1147,7 +1148,7 @@ export default class Context { } } finally { this._deferringLogs = false; - if (rounds >= DEFERRED_REPLAY_ROUNDS) this._replayExhausted = false; + this._replayExhausted = false; // Only exposures need publishing; an error alone must not arm the timer. if (exposed) this._setTimeout(); } From a813be6b850144013f082fa929bd07f530e4214e Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 23:08:45 +0000 Subject: [PATCH 64/92] test(context): pin the iterator-free candidate walk; correct read cost A warmed shared-key read must not start an array iterator (the for...of mutant made reads about 2.7x slower). Replace the now-vacuous empty-walk check. The CHANGELOG cost note now reflects the measured direction: cached variable reads are about 3x faster than unreleased main and no longer allocate. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 18 ++++++++---------- src/__tests__/context.test.js | 29 ++++++++++++++++++----------- 2 files changed, 26 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 223af77..239c9ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -65,21 +65,19 @@ browser bundle). It declares Node `>=6.9.0`; the package still declares `>=6`, so Node 6.0–6.8 installs may warn. No helper types are exposed in the public API. - Each read now also checks the assignment-rule, holdout and missing-unit state. - Measured on Node 22 (synthetic warmed loops, one experiment, median of 5): a cached - `peek` costs about 2 ns more than 1.13.4 (16.5 vs 14.6 ns) and a cached `treatment` - about 7 ns more (47.8 vs 40.8 ns). Re-evaluating an audience after `setAttribute` + Measured on Node 22 (synthetic warmed loops, independent reviews on shared + hosts, approximate): a cached `peek` or `treatment` costs about 2–5 ns more than + 1.13.4. Re-evaluating an audience after `setAttribute` matches 1.13.4 with 300 attributes and is about 6% slower with 1,000 and 10% slower with 3,000. `getAttributes()` is faster than 1.13.4. A default `track()` + `publish()` matches 1.13.4 up to a few hundred attributes (7.3 vs 7.1 µs at 300) and costs about 30% more at 3,000 (about 52 vs 40 µs; unreleased main was about 77 µs). The new opt-in `includeSystemAttributes` adds about 10% on top. A - cached `variableValue()` (four experiments sharing a key) costs about 70–78 ns, - down from about 155 ns in 1.13.4, but up to about 9 ns more than unreleased - main, mostly for holding its `eventLogger` callbacks until all its exposures - are queued (see Fixed). `peekVariableValue()` costs about 2–15 ns more than - unreleased main; a cached `treatment()` or `peek()` costs about 1–2 ns more - (the assignment-rule and holdout checks above). Measured on shared - hosts (Node 22, compiled CJS, four experiments sharing a key), so treat these + cached `variableValue()` or `peekVariableValue()` (four experiments sharing a + key) costs about 21–26 ns, down from about 155 ns in 1.13.4 and about 65 ns on + unreleased main, and no longer allocates; a cached `treatment()` or `peek()` + costs about 1 ns more than unreleased main (the assignment-rule and holdout + checks above). Measured on shared hosts (Node 22, compiled CJS), so treat these as approximate. ### Fixed diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index cf3d32d..6c6a55e 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6367,27 +6367,34 @@ describe("Context", () => { const response = buildHoldoutResponse([winnerAfterHoldout({})], []); const context = new Context(sdk, contextOptions, contextParams, response); const assign = jest.spyOn(context, "_assign"); + expect(context.variableValue("not.indexed", "APP_FALLBACK")).toEqual("APP_FALLBACK"); + expect(context.peekVariableValue("not.indexed", "APP_FALLBACK")).toEqual("APP_FALLBACK"); + expect(assign).not.toHaveBeenCalled(); + expect(context._deferredLogs).toBeUndefined(); + }); + + it("walks a warmed shared key's candidates without an array iterator", () => { + const response = buildHoldoutResponse([holdoutVarExperiment({}), winnerAfterHoldout({})], []); + const context = new Context(sdk, contextOptions, contextParams, response); + const first = context.variableValue("button.color", "D"); + expect(first).not.toEqual("D"); const iterator = Array.prototype[Symbol.iterator]; - let emptyWalks = 0; + let walks = 0; + let value; + let peeked; try { // eslint-disable-next-line no-extend-native Array.prototype[Symbol.iterator] = function () { - if (this.length === 0) emptyWalks++; + walks++; return iterator.call(this); }; - const value = context.variableValue("not.indexed", "APP_FALLBACK"); - const peeked = context.peekVariableValue("not.indexed", "APP_FALLBACK"); - // eslint-disable-next-line no-extend-native - Array.prototype[Symbol.iterator] = iterator; - expect(value).toEqual("APP_FALLBACK"); - expect(peeked).toEqual("APP_FALLBACK"); - expect(emptyWalks).toBe(0); + value = context.variableValue("button.color", "D"); + peeked = context.peekVariableValue("button.color", "D"); } finally { // eslint-disable-next-line no-extend-native Array.prototype[Symbol.iterator] = iterator; } - expect(assign).not.toHaveBeenCalled(); - expect(context._deferredLogs).toBeUndefined(); + expect([value, peeked, walks]).toEqual([first, first, 0]); }); it("arms the timer for an exposure first queued from a replayed error callback", () => { From 391fb9f6c364170040cb3f461c90567a9009e771 Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 23:46:33 +0000 Subject: [PATCH 65/92] fix(context): keep each call's exposure batch intact at the replay limit After a replay spends its rounds, later calls still hold their own callbacks until all of their exposures are queued and then deliver that batch, so a logger finalizing at the cutoff sends the winner too. Also bound a replay by delivered callbacks (DEFERRED_REPLAY_CALLBACKS) so a callback that raises several events per callback cannot grow the queue before round 32; fold _emitError into _logEvent; clear the variables of a cached assignment whose arm a refresh removed. Tests: whole batch at chain lengths 30-40, retained-callback bound, removed override arm; narrow two test titles to what they assert. README: the held-out fallback returns the default when its control arm lacks the key. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 100 +++++++++++++++++++++++++++++++++- src/context.ts | 69 +++++++++++++---------- 2 files changed, 138 insertions(+), 31 deletions(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 6c6a55e..14c26ed 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6087,7 +6087,7 @@ describe("Context", () => { expect(published.exposures.map((e) => e.name)).toEqual(["holdout_var", "exp_holdout_var_later_winner"]); }); - it("reports a nested read's callbacks after the outer read's exposures", () => { + it("queues no extra callbacks when a callback re-reads an already exposed key", () => { const names = []; let nested = false; const eventLogger = jest.fn((ctx, eventName, data) => { @@ -6488,7 +6488,7 @@ describe("Context", () => { } }); - it("delivers every callback of finite exposure feedback in queue order", () => { + it("delivers every callback of finite exposure feedback", () => { let count = 0; const eventLogger = jest.fn((ctx, eventName) => { if (eventName === "exposure" && ++count < 100) ctx.variableValue("button.color", "D"); @@ -6716,6 +6716,81 @@ describe("Context", () => { ]); }); + it.each([30, 31, 32, 33, 40])( + "sends a read's whole exposure batch when its logger finalizes after %i feedback callbacks", + async (chain) => { + publisher.publish.mockReturnValue(Promise.resolve()); + let count = 0; + let finalizing; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + if (data.name === "exp_loop") { + if (++count < chain) ctx.variableValue("loop.key", "D"); + else if (count === chain) ctx.variableValue("button.color", "APP_FALLBACK"); + } else if (data.name === "holdout_var" && finalizing === undefined) { + finalizing = ctx.finalize(); + } + }); + const loop = { + ...winnerAfterHoldout({}), + id: 3, + name: "exp_loop", + variants: [ + { name: "A", config: JSON.stringify({ "loop.key": "A" }) }, + { name: "B", config: JSON.stringify({ "loop.key": "B" }) }, + ], + }; + const response = buildHoldoutResponse( + [holdoutVarExperiment({}), winnerAfterHoldout({}), loop], + [alwaysHoldsOut({})] + ); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, response); + context.customAssignment("exp_loop", 0); + expect(context.variableValue("loop.key", "D")).toBe("B"); + await finalizing; + expect(context.isFinalized()).toBe(true); + expect(context.pending()).toBe(0); + const sent = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0].exposures; + expect(sent.map((e) => e.name).filter((n) => n !== "exp_loop")).toEqual([ + "holdout_var", + "exp_holdout_var_later_winner", + ]); + } + ); + + it("bounds the callbacks a replay retains when each callback raises two more", () => { + let count = 0; + let maxRetained = 0; + const consoleError = jest.spyOn(console, "error").mockImplementation(() => {}); + try { + const experiment = winnerAfterHoldout({ + customFieldValues: [ + { name: "a", type: "json", value: "{bad" }, + { name: "b", type: "json", value: "{bad" }, + ], + }); + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "exposure" && eventName !== "error") return; + maxRetained = Math.max(maxRetained, ctx._deferredLogs ? ctx._deferredLogs.length : 0); + if (++count > 20000) return; + ctx.customFieldValue("exp_holdout_var_later_winner", "a"); + ctx.customFieldValue("exp_holdout_var_later_winner", "b"); + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([experiment], []) + ); + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + // Without the callback budget each round doubles the retained list until round 32. + expect(maxRetained).toBeLessThanOrEqual(2048); + expect(context._deferredLogs).toBeUndefined(); + } finally { + consoleError.mockRestore(); + } + }); + it("runs feedback callbacks inline once the replay rounds are spent", () => { expect(feedbackDepths(40)).toEqual([...Array(32).fill(1), 2, 3, 4, 5, 6, 7, 8, 9]); }); @@ -7053,7 +7128,6 @@ describe("Context", () => { it.each([null, "", "[]", "0", "false", '"string"', "null", '{"other":1}'])( "returns the default when the winner config %p does not define the key", (selectedConfig) => { - // No selected config shape may leak inherited Object.prototype members. const winner = { ...protoKeyed(config), split: [1, 0] }; winner.variants = [{ name: "A", config: selectedConfig }, winner.variants[1]]; const context = new Context(sdk, contextOptions, contextParams, { experiments: [winner] }); @@ -7076,6 +7150,26 @@ describe("Context", () => { expect(context.variableValue("toString", "SENTINEL")).toBe("SENTINEL"); }); + it("returns the default when a refresh removes a cached override's arm", async () => { + const before = { + ...shared(1, [1, 0], {}), + variants: [ + { name: "A", config: '{"k":"a"}' }, + { name: "B", config: '{"k":"b"}' }, + { name: "C", config: '{"k":"c"}' }, + ], + split: [0.34, 0.33, 0.33], + }; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [before] }); + context.override("shared_1", 2); + expect(context.variableValue("k", "SENTINEL")).toBe("c"); + const after = { ...before, variants: before.variants.slice(0, 2), split: [0.5, 0.5] }; + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [after] })); + await context.refresh(); + expect(context.peekVariableValue("k", "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue("k", "SENTINEL")).toBe("SENTINEL"); + }); + it("keeps a retained unit's value and ordinary snapshot across a refresh", async () => { const before = { ...shared(1, [0, 1], {}), diff --git a/src/context.ts b/src/context.ts index 0ec0906..6d76894 100644 --- a/src/context.ts +++ b/src/context.ts @@ -21,8 +21,8 @@ type CustomFieldValue = { type: CustomFieldValueType; }; -// Feedback rounds a deferred-callback replay drains before later callbacks run inline. const DEFERRED_REPLAY_ROUNDS = 32; +const DEFERRED_REPLAY_CALLBACKS = 1024; export type ExperimentData = { id: number; name: string; @@ -199,7 +199,6 @@ export default class Context { // While a variable read runs, user eventLogger callbacks it would trigger are held here (the // list is created on first use) and replayed once every exposure of the read is queued. private _deferringLogs = false; - // Set once a replay spends its rounds, until that replay ends: nested calls then run inline. private _replayExhausted = false; private _deferredLogs?: [EventName, Record | Error][]; private _attrsSeq: number; @@ -894,7 +893,7 @@ export default class Context { // Queue the experiment's and its holdouts' exposures before any callback runs, so an // eventLogger that finalizes on the first one still sends the holdout's. - if (this._deferringLogs || this._replayExhausted) { + if (this._deferringLogs) { this._triggerExposures(experimentName, assignment); } else { this._deferringLogs = true; @@ -1087,7 +1086,6 @@ export default class Context { if (shouldQueueExposure && !selected.exposed) { selected.exposed = true; - // The loop above already fired this candidate's holdouts. this._triggerExposures(selectedName, selected, false); } @@ -1102,7 +1100,7 @@ export default class Context { // queued, so such a call sends all of them instead of sealing the context with one pending. // The replay lives in its own method so a warmed read, which defers nothing, stays small. private _variableValue(key: string, defaultValue: string): string { - if (this._deferringLogs || this._replayExhausted) return this._resolveVariableValue(key, defaultValue, true); + if (this._deferringLogs) return this._resolveVariableValue(key, defaultValue, true); this._deferringLogs = true; try { @@ -1117,32 +1115,31 @@ export default class Context { // behind the ones already queued. private _endDeferral() { if (this._deferredLogs === undefined) this._deferringLogs = false; + else if (this._replayExhausted) this._deliverDeferredLogs(); else this._replayDeferredLogs(); } - // Replays held callbacks in queue order, keeping deferral on so callbacks a callback raises join - // the queue behind the ones already held. A callback that keeps feeding new events would drain - // forever, so after DEFERRED_REPLAY_ROUNDS rounds deferral stops and later callbacks run inline, + // A callback that keeps feeding new events would drain forever (or grow the queue without + // bound), so once a replay has run DEFERRED_REPLAY_ROUNDS rounds or delivered + // DEFERRED_REPLAY_CALLBACKS callbacks, it stops queueing rounds: each later call still holds + // its own callbacks until all of its exposures are queued, then delivers that batch at once, // bounded by the call stack as before deferral existed. private _replayDeferredLogs() { let exposed = false; let rounds = 0; + let delivered = 0; try { let deferred: [EventName, Record | Error][] | undefined = this._deferredLogs; while (deferred !== undefined) { this._deferredLogs = undefined; - if (++rounds >= DEFERRED_REPLAY_ROUNDS) { + delivered += deferred.length; + if (++rounds >= DEFERRED_REPLAY_ROUNDS || delivered >= DEFERRED_REPLAY_CALLBACKS) { this._deferringLogs = false; this._replayExhausted = true; } for (let i = 0; i < deferred.length; i++) { - const entry = deferred[i]; - if (entry[0] === "error") { - this._emitError(entry[1] as Error); - } else { - exposed = true; - this._logEvent(entry[0], entry[1] as Record); - } + if (deferred[i][0] === "exposure") exposed = true; + this._logEvent(deferred[i][0], deferred[i][1]); } deferred = this._deferredLogs; } @@ -1154,6 +1151,21 @@ export default class Context { } } + private _deliverDeferredLogs() { + const deferred = this._deferredLogs as [EventName, Record | Error][]; + this._deferredLogs = undefined; + this._deferringLogs = false; + let exposed = false; + try { + for (let i = 0; i < deferred.length; i++) { + if (deferred[i][0] === "exposure") exposed = true; + this._logEvent(deferred[i][0], deferred[i][1]); + } + } finally { + if (exposed) this._setTimeout(); + } + } + private _peekVariable(key: string, defaultValue: string): string { return this._resolveVariableValue(key, defaultValue, false); } @@ -1451,7 +1463,7 @@ export default class Context { } } - private _logEvent(eventName: EventName, data?: Record) { + private _logEvent(eventName: EventName, data?: Record | Error) { if (this._eventLogger) { // A throwing custom eventLogger must never propagate out of this method: // every call site treats logging as a side effect, and letting an @@ -1473,17 +1485,7 @@ export default class Context { (this._deferredLogs ??= []).push(["error", error]); return; } - this._emitError(error); - } - - private _emitError(error: Error) { - if (this._eventLogger) { - try { - this._eventLogger(this, "error", error); - } catch (observerError) { - console.error(observerError); - } - } + this._logEvent("error", error); } private _unitHash(unitType: string) { @@ -1684,6 +1686,17 @@ export default class Context { } } + // A reused assignment whose arm a refresh removed has no variables any more. + for (const experimentName of Object.keys(assignments)) { + const assignment = assignments[experimentName]; + const experiment = Object.prototype.hasOwnProperty.call(index, experimentName) + ? index[experimentName] + : undefined; + if (experiment !== undefined && assignment.variant >= experiment.data.variants.length) { + assignment.variables = undefined; + } + } + this._index = index; this._indexVariables = indexVariables; this._assignments = assignments; From f0bf6d71c25954a21fcce6895a751f9d48659c7c Mon Sep 17 00:00:00 2001 From: lux worker Date: Tue, 24 Nov 2026 23:48:00 +0000 Subject: [PATCH 66/92] docs: describe the replay limit batch rule and held-out default Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 ++++--- README.md | 8 ++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 239c9ee..fe2b6d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -98,9 +98,10 @@ candidate's applicable holdouts still fire, as in Java. All exposures of one read are queued before its `exposure` and `error` callbacks run, so a callback that calls `finalize()` still sends the winner. Callbacks a callback raises are replayed after - the ones already held, in queue order; an observer that keeps feeding new - events stops being deferred after a bounded number of rounds, so a read always - returns. `treatment()` likewise queues an + the ones already held, in queue order; once a replay has run a bounded number of + rounds or callbacks, each later call delivers its own callbacks as soon as all of + its exposures are queued, so a read always returns and still sends its whole + batch. `treatment()` likewise queues an experiment's and its holdouts' exposures before their `exposure` callbacks run (an audience `error` raised by `treatment()` itself is still reported first). `peekVariableValue()` exposes nothing. Keys no experiment defines return the default diff --git a/README.md b/README.md index ff18174..084db30 100644 --- a/README.md +++ b/README.md @@ -233,7 +233,8 @@ ascending experiment id and uses the first one the user is in (assigned, overridden or assigned by a rule). Its variant's value is returned, or your default if that variant does not define the key; later experiments are never used instead. If the user is in none of them but one is held out by a holdout, -that experiment's control value is returned. Only the winning experiment gets an +the first held-out experiment's control value is returned, or your default if +its control arm does not define the key (no other experiment is checked). Only the winning experiment gets an exposure (plus any holdouts covering the experiments checked); a held-out experiment that supplies its control value records only its holdout's exposure. An experiment the user is not in, such as a strict audience mismatch, gets none; @@ -388,9 +389,8 @@ call's exposures are queued, in the order they were raised, so a logger that calls `publish()` or `finalize()` sends every one of them. `"exposure"` and `"error"` events a logger triggers itself are delivered after the ones already waiting (other events, such as a `"goal"` from `track()`, are delivered -immediately); a logger that keeps triggering new events is switched to inline -delivery after a bounded number of rounds, so its later events arrive as they -are raised. +immediately); after a bounded number of rounds or callbacks, each later call delivers its own +events as soon as all of that call's exposures are queued. ### HTTP Request Timeout From e4664fc9d2f414b89280207c76026ae18e255616 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 02:45:31 +0000 Subject: [PATCH 67/92] fix(context): restore a refreshed arm's variables; pin post-limit delivery A reused assignment whose arm a refresh removed gets the arm's current variables back once a later refresh restores it. Pin the post-limit path: treatment() keeps its holdout in the batch, every callback of a post-limit batch is delivered once in queue order, a post-limit error/exposure batch arms the publish timer, and a real two-way fan-out stays within the callback budget. Cover assigned and custom arms as well as overrides. README: later events arrive as one batch per call; rewrap the shared-key note. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 237 ++++++++++++++++++++++++++++++---- src/context.ts | 8 +- 2 files changed, 218 insertions(+), 27 deletions(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 14c26ed..b2f5ec8 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6759,35 +6759,196 @@ describe("Context", () => { ); it("bounds the callbacks a replay retains when each callback raises two more", () => { + const strict = (id, experimentName, key) => ({ + ...holdoutVarExperiment({}), + id, + name: experimentName, + holdoutIds: null, + split: [0, 1], + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ [key]: 1 }) }, + ], + }); let count = 0; + let errors = 0; let maxRetained = 0; - const consoleError = jest.spyOn(console, "error").mockImplementation(() => {}); + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "exposure" && eventName !== "error") return; + if (eventName === "error") errors++; + maxRetained = Math.max(maxRetained, ctx._deferredLogs ? ctx._deferredLogs.length : 0); + if (++count > 6000) return; + ctx.attribute("a", count); + ctx.variableValue("e1.key", "D"); + ctx.attribute("b", count); + ctx.variableValue("e2.key", "D"); + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse( + [winnerAfterHoldout({}), strict(5, "e1", "e1.key"), strict(6, "e2", "e2.key")], + [] + ) + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("boom"); + }, + }); + context.attribute("user", user); + expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); + // Without the callback budget each round doubles the held list until round 32. + expect(errors).toBeGreaterThan(2048); + expect(maxRetained).toBeLessThanOrEqual(1024); + expect(context._deferredLogs).toBeUndefined(); + }); + + const cutoffResponse = () => + buildHoldoutResponse( + [ + { + ...holdoutVarExperiment({}), + name: "exp_held", + variants: [ + { name: "A", config: JSON.stringify({ "cut.key": "CONTROL" }) }, + { name: "B", config: JSON.stringify({ "cut.key": "T" }) }, + ], + }, + { + ...winnerAfterHoldout({}), + name: "exp_win", + holdoutIds: [12], + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ "cut.key": "WIN" }) }, + ], + }, + { + ...winnerAfterHoldout({}), + id: 3, + name: "exp_loop", + variants: [ + { name: "A", config: JSON.stringify({ "loop.key": "A" }) }, + { name: "B", config: JSON.stringify({ "loop.key": "B" }) }, + ], + }, + ], + [ + alwaysHoldsOut({ name: "holdout_a" }), + alwaysHoldsOut({ id: 12, name: "holdout_b", split: [0, 1] }), + ] + ); + + const cutoff = async (chain, mode) => { + publisher.publish.mockReturnValue(Promise.resolve()); + const callbacks = []; + let count = 0; + let finalizing; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + if (data.name === "exp_loop") { + if (++count < chain) ctx.variableValue("loop.key", "D"); + else if (count === chain) { + if (mode === "treatment") ctx.treatment("exp_win"); + else ctx.variableValue("cut.key", "D"); + } + return; + } + callbacks.push(data.name); + if (finalizing === undefined) finalizing = ctx.finalize(); + }); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, cutoffResponse()); + context.customAssignment("exp_loop", 0); + if (mode === "treatment") context.override("exp_win", 1); + context.variableValue("loop.key", "D"); + await finalizing; + const sent = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0].exposures + .map((e) => e.name) + .filter((n) => n !== "exp_loop"); + return { callbacks, sent, pending: context.pending() }; + }; + + it.each([31, 32, 40])( + "sends a treatment()'s whole batch when its logger finalizes after %i feedback callbacks", + async (chain) => { + const result = await cutoff(chain, "treatment"); + expect(result.sent).toEqual(["exp_win", "holdout_b"]); + expect(result.pending).toBe(0); + } + ); + + it.each([31, 32, 40])( + "delivers every callback of a batch after %i feedback callbacks once, in queue order", + async (chain) => { + const result = await cutoff(chain, "variableValue"); + expect(result.callbacks).toEqual(["holdout_a", "holdout_b", "exp_win"]); + expect(result.sent).toEqual(["holdout_a", "holdout_b", "exp_win"]); + } + ); + + it("delivers a post-limit batch's error and exposure and arms the publish timer", () => { + const strict = { + ...holdoutVarExperiment({}), + name: "exp_strict", + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + variants: [ + { name: "A", config: JSON.stringify({ "s.key": "a" }) }, + { name: "B", config: JSON.stringify({ "s.key": "b" }) }, + ], + }; + const plain = { + ...winnerAfterHoldout({}), + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ "p.key": "P" }) }, + ], + }; + const events = []; + let errors = 0; + let done = false; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName === "exposure") events.push(`exposure:${data.name}`); + if (eventName !== "error") return; + if (++errors < 40) { + ctx.attribute("n", errors); + ctx.variableValue("s.key", "D"); + } else if (!done) { + done = true; + events.length = 0; + ctx.attribute("n", errors); + ctx.variableValue("s.key", "D"); + ctx.variableValue("p.key", "D"); + } else { + events.push("error"); + } + }); + const context = new Context( + sdk, + { ...contextOptions, publishDelay: 100000, eventLogger }, + contextParams, + buildHoldoutResponse([strict, plain], []) + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("boom"); + }, + }); + context.attribute("user", user); + context.variableValue("s.key", "D"); try { - const experiment = winnerAfterHoldout({ - customFieldValues: [ - { name: "a", type: "json", value: "{bad" }, - { name: "b", type: "json", value: "{bad" }, - ], - }); - const eventLogger = jest.fn((ctx, eventName) => { - if (eventName !== "exposure" && eventName !== "error") return; - maxRetained = Math.max(maxRetained, ctx._deferredLogs ? ctx._deferredLogs.length : 0); - if (++count > 20000) return; - ctx.customFieldValue("exp_holdout_var_later_winner", "a"); - ctx.customFieldValue("exp_holdout_var_later_winner", "b"); - }); - const context = new Context( - sdk, - { ...contextOptions, eventLogger }, - contextParams, - buildHoldoutResponse([experiment], []) - ); - expect(context.variableValue("button.color", "D")).toBe("WINNER_AFTER_HOLDOUT"); - // Without the callback budget each round doubles the retained list until round 32. - expect(maxRetained).toBeLessThanOrEqual(2048); - expect(context._deferredLogs).toBeUndefined(); + expect(events).toEqual(["error", "exposure:exp_holdout_var_later_winner"]); + expect(context.pending()).toBe(1); + expect(context._publishTimeout).toBeDefined(); } finally { - consoleError.mockRestore(); + clearTimeout(context._publishTimeout); } }); @@ -7150,6 +7311,32 @@ describe("Context", () => { expect(context.variableValue("toString", "SENTINEL")).toBe("SENTINEL"); }); + it.each(["override", "assigned", "custom"])( + "follows a cached %s arm that a refresh removes and a later refresh restores", + async (kind) => { + const variants = [ + { name: "A", config: '{"k":"a"}' }, + { name: "B", config: '{"k":"b"}' }, + { name: "C", config: '{"k":"c"}' }, + ]; + const before = { ...shared(1, [0, 0, 1], {}), variants }; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [before] }); + if (kind === "override") context.override("shared_1", 2); + if (kind === "custom") context.customAssignment("shared_1", 2); + expect(context.variableValue("k", "SENTINEL")).toBe("c"); + provider.getContextData.mockReturnValue( + Promise.resolve({ experiments: [{ ...before, variants: variants.slice(0, 2), split: [0, 1] }] }) + ); + await context.refresh(); + expect(context.peekVariableValue("k", "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue("k", "SENTINEL")).toBe("SENTINEL"); + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [before] })); + await context.refresh(); + expect(context.peekVariableValue("k", "SENTINEL")).toBe("c"); + expect(context.variableValue("k", "SENTINEL")).toBe("c"); + } + ); + it("returns the default when a refresh removes a cached override's arm", async () => { const before = { ...shared(1, [1, 0], {}), diff --git a/src/context.ts b/src/context.ts index 6d76894..2847d49 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1686,14 +1686,18 @@ export default class Context { } } - // A reused assignment whose arm a refresh removed has no variables any more. + // A reused assignment follows its arm across refreshes: no variables while a refresh has removed + // the arm, and the arm's current variables again once a later refresh restores it. for (const experimentName of Object.keys(assignments)) { const assignment = assignments[experimentName]; const experiment = Object.prototype.hasOwnProperty.call(index, experimentName) ? index[experimentName] : undefined; - if (experiment !== undefined && assignment.variant >= experiment.data.variants.length) { + if (experiment === undefined) continue; + if (assignment.variant >= experiment.data.variants.length) { assignment.variables = undefined; + } else if (assignment.variables === undefined && assignment.id === experiment.data.id) { + assignment.variables = experiment.variables[assignment.variant]; } } From 18f1da17594db42c09412b025b169ec164d41b96 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 02:47:35 +0000 Subject: [PATCH 68/92] docs: document removed-arm default and per-call batch delivery Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 +++++--- README.md | 16 ++++++++++------ 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe2b6d2..4d61c04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -100,11 +100,13 @@ calls `finalize()` still sends the winner. Callbacks a callback raises are replayed after the ones already held, in queue order; once a replay has run a bounded number of rounds or callbacks, each later call delivers its own callbacks as soon as all of - its exposures are queued, so a read always returns and still sends its whole - batch. `treatment()` likewise queues an + its exposures are queued, so runaway logger feedback stays bounded in stack and + memory and each call still sends its whole batch. `treatment()` likewise queues an experiment's and its holdouts' exposures before their `exposure` callbacks run (an audience `error` raised by `treatment()` itself is still reported first). `peekVariableValue()` - exposes nothing. Keys no experiment defines return the default + exposes nothing. A cached assignment whose arm a refresh removes returns the caller + default (1.13.4 kept serving the removed arm's value) and gets the arm's + values back if a later refresh restores it. Keys no experiment defines return the default again, as in 1.13.4, including names like `toString`; a variant config that defines such a key (`toString`, `constructor`, `__proto__`) no longer fails the context. Affected: anyone with two or more running experiments sharing a variable key. `variableKeys()` keeps its diff --git a/README.md b/README.md index 084db30..851991b 100644 --- a/README.md +++ b/README.md @@ -234,11 +234,15 @@ overridden or assigned by a rule). Its variant's value is returned, or your default if that variant does not define the key; later experiments are never used instead. If the user is in none of them but one is held out by a holdout, the first held-out experiment's control value is returned, or your default if -its control arm does not define the key (no other experiment is checked). Only the winning experiment gets an -exposure (plus any holdouts covering the experiments checked); a held-out -experiment that supplies its control value records only its holdout's exposure. -An experiment the user is not in, such as a strict audience mismatch, gets none; -call `treatment()` to record it. `peekVariableValue()` never queues an exposure. +its control arm does not define the key (no other experiment is checked). Only +the winning experiment gets an exposure (plus any holdouts covering the +experiments checked); a held-out experiment that supplies its control value +records only its holdout's exposure. An experiment the user is not in, such as a +strict audience mismatch, gets none; call `treatment()` to record it. +`peekVariableValue()` never queues an exposure. + +A cached `variableValue()` or `peekVariableValue()` does not allocate; see the +CHANGELOG for measured read costs. ### Peek at Treatment Variants @@ -390,7 +394,7 @@ calls `publish()` or `finalize()` sends every one of them. `"exposure"` and `"error"` events a logger triggers itself are delivered after the ones already waiting (other events, such as a `"goal"` from `track()`, are delivered immediately); after a bounded number of rounds or callbacks, each later call delivers its own -events as soon as all of that call's exposures are queued. +events together, once all of that call's exposures are queued. ### HTTP Request Timeout From 7afa2daa56fabcec6da7c9fbe6fe1f6e0539d3f4 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 04:17:16 +0000 Subject: [PATCH 69/92] test(context): pin switchback slot arm-following, post-limit timer and budget boundary Cover the period-less slot and custom/drawn period slots following their arm across refreshes, an error-only batch after the replay limit arming no timer, the callback budget boundary at exactly 1024, and the restore guard not adopting a different experiment id. Shorten the retained-callback test. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 101 +++++++++++++++++++++++++++++++++- 1 file changed, 100 insertions(+), 1 deletion(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index b2f5ec8..418c6a1 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6779,7 +6779,7 @@ describe("Context", () => { if (eventName !== "exposure" && eventName !== "error") return; if (eventName === "error") errors++; maxRetained = Math.max(maxRetained, ctx._deferredLogs ? ctx._deferredLogs.length : 0); - if (++count > 6000) return; + if (++count > 2500) return; ctx.attribute("a", count); ctx.variableValue("e1.key", "D"); ctx.attribute("b", count); @@ -6891,6 +6891,84 @@ describe("Context", () => { } ); + it("arms no publish timer for an error-only batch after the replay limit", () => { + const strict = { + ...holdoutVarExperiment({}), + name: "exp_strict", + holdoutIds: null, + audienceStrict: true, + audience: JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }), + variants: [ + { name: "A", config: JSON.stringify({ "s.key": "a" }) }, + { name: "B", config: JSON.stringify({ "s.key": "b" }) }, + ], + }; + let errors = 0; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "error" || ++errors > 40) return; + ctx.attribute("n", errors); + ctx.variableValue("s.key", "D"); + }); + const context = new Context( + sdk, + { ...contextOptions, publishDelay: 100000, eventLogger }, + contextParams, + buildHoldoutResponse([strict], []) + ); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("boom"); + }, + }); + context.attribute("user", user); + context.variableValue("s.key", "D"); + expect(errors).toBeGreaterThan(32); + expect(context.pending()).toBe(0); + expect(context._publishTimeout).toBeUndefined(); + }); + + it.each([ + [1023, false], + [1024, true], + ])("stops queueing rounds once a replay has delivered %i callbacks: %p", (width, exhausted) => { + const experiments = []; + for (let i = 0; i < width; i++) { + experiments.push({ + ...holdoutVarExperiment({}), + id: 100 + i, + name: `exp_w${i}`, + holdoutIds: null, + split: [0, 1], + fullOnVariant: 1, + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ [`w${i}`]: i }) }, + ], + }); + } + let fanned = false; + let after; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName !== "exposure") return; + if (!fanned) { + fanned = true; + for (let i = 1; i < width; i++) ctx.variableValue(`w${i}`, "D"); + } else if (after === undefined && ctx._deferringLogs !== undefined) { + after = ctx._replayExhausted; + } + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse(experiments, []) + ); + expect(context.variableValue("w0", "D")).toBe(0); + expect(after).toBe(exhausted); + expect(context.pending()).toBe(width); + }); + it("delivers a post-limit batch's error and exposure and arms the publish timer", () => { const strict = { ...holdoutVarExperiment({}), @@ -7337,6 +7415,27 @@ describe("Context", () => { } ); + it("does not restore a removed arm's variables once the experiment id changes", async () => { + const variants = [ + { name: "A", config: '{"k":"a"}' }, + { name: "B", config: '{"k":"b"}' }, + { name: "C", config: '{"k":"c"}' }, + ]; + const before = { ...shared(1, [0, 0, 1], {}), variants }; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [before] }); + context.override("shared_1", 2); + expect(context.variableValue("k", "SENTINEL")).toBe("c"); + provider.getContextData.mockReturnValue( + Promise.resolve({ experiments: [{ ...before, variants: variants.slice(0, 2), split: [0, 1] }] }) + ); + await context.refresh(); + expect(context.variableValue("k", "SENTINEL")).toBe("SENTINEL"); + // A different experiment now uses the name: the cached assignment must not adopt its arm. + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [{ ...before, id: 99 }] })); + await context.refresh(); + expect(context.peekVariableValue("k", "SENTINEL")).toBe("SENTINEL"); + }); + it("returns the default when a refresh removes a cached override's arm", async () => { const before = { ...shared(1, [1, 0], {}), From 3024f1fe3b20e17474a63032f01850d60d5e7054 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 12:49:10 +0000 Subject: [PATCH 70/92] test(context): pin restored prototype-named variables after refresh Kill the survived mutation that restores a cached arm with an ordinary-prototype object; assert toString, constructor and __proto__ values after remove then restore. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 418c6a1..000defa 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -7456,7 +7456,7 @@ describe("Context", () => { expect(context.variableValue("k", "SENTINEL")).toBe("SENTINEL"); }); - it("keeps a retained unit's value and ordinary snapshot across a refresh", async () => { + it("keeps a retained unit's value and prototype keys across remove and restore refreshes", async () => { const before = { ...shared(1, [0, 1], {}), variants: [ @@ -7468,18 +7468,27 @@ describe("Context", () => { const context = new Context(sdk, contextOptions, contextParams, { experiments: [before, plain] }); expect(context.variableValue("k", "SENTINEL")).toBe("OLD"); expect(context.treatment("plain")).toBe(1); - const after = { + const removed = { ...before, variants: [before.variants[0]] }; + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [removed, plain] })); + await context.refresh(); + expect(context.variableValue("k", "SENTINEL")).toBe("SENTINEL"); + const restored = { ...before, variants: [ - { name: "A", config: '{"k":"a1","valueOf":"V"}' }, - { name: "B", config: '{"k":"NEW"}' }, + { name: "A", config: '{"k":"a1"}' }, + { + name: "B", + config: '{"k":"NEW","valueOf":"V","toString":"T","constructor":"C","__proto__":"P"}', + }, ], }; - provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [after, plain] })); + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [restored, plain] })); await context.refresh(); - expect(context.peekVariableValue("k", "SENTINEL")).toBe("OLD"); - expect(context.variableValue("k", "SENTINEL")).toBe("OLD"); - expect(context.variableValue("valueOf", "SENTINEL")).toBe("SENTINEL"); + expect(context.variableValue("k", "SENTINEL")).toBe("NEW"); + expect(context.variableValue("valueOf", "SENTINEL")).toBe("V"); + expect(context.variableValue("toString", "SENTINEL")).toBe("T"); + expect(context.variableValue("constructor", "SENTINEL")).toBe("C"); + expect(context.variableValue("__proto__", "SENTINEL")).toBe("P"); expect(Object.getPrototypeOf(context._assignments.plain.variables)).toBe(Object.prototype); }); From 365f61f03b0bb66348b011aa6b1bc11074e216d3 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 17:44:23 +0000 Subject: [PATCH 71/92] fix(context): scope treatment() errors and count replay callbacks at dispatch treatment() now opens its deferral scope before assigning, so an audience error whose callback finalizes still sends the call's exposure. The replay counts callbacks as it delivers them, so callbacks already waiting keep queue order up to the budget. Neither replay path rearms the publish timer once a callback has drained the queue. Pin all three with tests that fail on the old behaviour, plus a shared key whose strict candidate errors before a later winner. README: a held-out fallback without the key means no later experiment supplies the value; treatment() errors are deferred too. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 170 +++++++++++++++++++++++++++++++--- src/context.ts | 41 ++++---- 2 files changed, 181 insertions(+), 30 deletions(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 000defa..5610810 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6928,12 +6928,15 @@ describe("Context", () => { expect(context._publishTimeout).toBeUndefined(); }); + // A 1024-wide round: one callback fans out to 1,023 more reads. Every callback already waiting + // is delivered in queue order before a read a callback makes; the read made from the last + // waiting callback (the 1,024th delivered) runs once the callback budget is spent. it.each([ - [1023, false], - [1024, true], - ])("stops queueing rounds once a replay has delivered %i callbacks: %p", (width, exhausted) => { + [1023, 1], + [1024, 2], + ])("keeps queue order up to the callback budget (%i callbacks)", (width, nestedDepth) => { const experiments = []; - for (let i = 0; i < width; i++) { + for (let i = 0; i <= width; i++) { experiments.push({ ...holdoutVarExperiment({}), id: 100 + i, @@ -6947,15 +6950,26 @@ describe("Context", () => { ], }); } + const names = []; + let depth = 0; + let nestedAt; let fanned = false; - let after; - const eventLogger = jest.fn((ctx, eventName) => { + let nested = false; + const eventLogger = jest.fn((ctx, eventName, data) => { if (eventName !== "exposure") return; - if (!fanned) { - fanned = true; - for (let i = 1; i < width; i++) ctx.variableValue(`w${i}`, "D"); - } else if (after === undefined && ctx._deferringLogs !== undefined) { - after = ctx._replayExhausted; + depth++; + try { + names.push(data.name); + if (data.name === `exp_w${width}`) nestedAt = depth; + if (!fanned) { + fanned = true; + for (let i = 1; i < width; i++) ctx.variableValue(`w${i}`, "D"); + } else if (!nested && data.name === `exp_w${width - 1}`) { + nested = true; + ctx.variableValue(`w${width}`, "D"); + } + } finally { + depth--; } }); const context = new Context( @@ -6965,8 +6979,11 @@ describe("Context", () => { buildHoldoutResponse(experiments, []) ); expect(context.variableValue("w0", "D")).toBe(0); - expect(after).toBe(exhausted); - expect(context.pending()).toBe(width); + // Every waiting callback was delivered, in the order its read was made, before the nested one. + expect(names.slice(0, width)).toEqual(Array.from({ length: width }, (_, i) => `exp_w${i}`)); + expect(names[width]).toBe(`exp_w${width}`); + expect(nestedAt).toBe(nestedDepth); + expect(context.pending()).toBe(width + 1); }); it("delivers a post-limit batch's error and exposure and arms the publish timer", () => { @@ -7034,6 +7051,133 @@ describe("Context", () => { expect(feedbackDepths(40)).toEqual([...Array(32).fill(1), 2, 3, 4, 5, 6, 7, 8, 9]); }); + const throwingPlan = (context) => { + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new Error("getter boom"); + }, + }); + context.attribute("user", user); + }; + const planAudience = JSON.stringify({ filter: [{ eq: [{ var: "user/plan" }, { value: "pro" }] }] }); + + it("sends a treatment()'s exposure when its own audience error callback finalizes", async () => { + publisher.publish.mockReturnValue(Promise.resolve()); + let finalizing; + const eventLogger = jest.fn((ctx, eventName) => { + if (eventName === "error" && finalizing === undefined) finalizing = ctx.finalize(); + }); + const audienced = { ...winnerAfterHoldout({}), audience: planAudience }; + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([audienced], []) + ); + throwingPlan(context); + expect(context.treatment("exp_holdout_var_later_winner")).toBe(1); + await finalizing; + expect(context.isFinalized()).toBe(true); + expect(context.pending()).toBe(0); + const sent = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0].exposures; + expect(sent.map((e) => e.name)).toEqual(["exp_holdout_var_later_winner"]); + }); + + it.each(["direct", "post-limit"])( + "sends a shared key's winner when a strict candidate's error callback finalizes (%s)", + async (mode) => { + publisher.publish.mockReturnValue(Promise.resolve()); + let count = 0; + let finalizing; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName === "exposure" && data.name === "exp_loop") { + if (++count < 40) ctx.variableValue("loop.key", "D"); + else ctx.variableValue("button.color", "APP_FALLBACK"); + return; + } + if (eventName === "error" && finalizing === undefined) finalizing = ctx.finalize(); + }); + const strict = { + ...holdoutVarExperiment({}), + name: "exp_strict", + holdoutIds: null, + audienceStrict: true, + audience: planAudience, + }; + const loop = { + ...winnerAfterHoldout({}), + id: 3, + name: "exp_loop", + variants: [ + { name: "A", config: JSON.stringify({ "loop.key": "A" }) }, + { name: "B", config: JSON.stringify({ "loop.key": "B" }) }, + ], + }; + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse([strict, winnerAfterHoldout({}), loop], []) + ); + throwingPlan(context); + if (mode === "direct") { + expect(context.variableValue("button.color", "APP_FALLBACK")).toBe("WINNER_AFTER_HOLDOUT"); + } else { + context.customAssignment("exp_loop", 0); + expect(context.variableValue("loop.key", "D")).toBe("B"); + } + await finalizing; + expect(context.isFinalized()).toBe(true); + expect(context.pending()).toBe(0); + const sent = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0].exposures; + expect(sent.map((e) => e.name)).toContain("exp_holdout_var_later_winner"); + } + ); + + it.each(["replay", "post-limit"])( + "does not rearm the publish timer after a callback finalizes (%s)", + async (mode) => { + publisher.publish.mockReturnValue(Promise.resolve()); + let count = 0; + let finalizing; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + if (data.name === "exp_loop") { + if (++count < 40) ctx.variableValue("loop.key", "D"); + else ctx.variableValue("button.color", "APP_FALLBACK"); + return; + } + if (finalizing === undefined) finalizing = ctx.finalize(); + }); + const loop = { + ...winnerAfterHoldout({}), + id: 3, + name: "exp_loop", + variants: [ + { name: "A", config: JSON.stringify({ "loop.key": "A" }) }, + { name: "B", config: JSON.stringify({ "loop.key": "B" }) }, + ], + }; + const context = new Context( + sdk, + { ...contextOptions, publishDelay: 100000, eventLogger }, + contextParams, + buildHoldoutResponse([winnerAfterHoldout({}), loop], []) + ); + if (mode === "replay") { + expect(context.variableValue("button.color", "APP_FALLBACK")).toBe("WINNER_AFTER_HOLDOUT"); + } else { + context.customAssignment("exp_loop", 0); + expect(context.variableValue("loop.key", "D")).toBe("B"); + } + await finalizing; + expect(context.isFinalized()).toBe(true); + expect(context.pending()).toBe(0); + expect(context._publishTimeout).toBeUndefined(); + } + ); + it("schedules the publish timer after a variable read's deferred exposures", () => { const response = buildHoldoutResponse([winnerAfterHoldout({})], []); const context = new Context(sdk, { ...contextOptions, publishDelay: 100 }, contextParams, response); diff --git a/src/context.ts b/src/context.ts index 2847d49..2b9ddd4 100644 --- a/src/context.ts +++ b/src/context.ts @@ -885,24 +885,26 @@ export default class Context { return this._assign(experimentName); } + // The whole call is one deferral scope, so an error logged while assigning (a throwing audience) + // reaches the eventLogger only after the call's exposures are queued. private _treatment(experimentName: string) { + if (this._deferringLogs) return this._treatmentInScope(experimentName); + + this._deferringLogs = true; + try { + return this._treatmentInScope(experimentName); + } finally { + this._endDeferral(); + } + } + + private _treatmentInScope(experimentName: string) { const assignment = this._assign(experimentName); if (!assignment.exposed) { assignment.exposed = true; - // Queue the experiment's and its holdouts' exposures before any callback runs, so an - // eventLogger that finalizes on the first one still sends the holdout's. - if (this._deferringLogs) { - this._triggerExposures(experimentName, assignment); - } else { - this._deferringLogs = true; - try { - this._triggerExposures(experimentName, assignment); - } finally { - this._endDeferral(); - } - } + this._triggerExposures(experimentName, assignment); } return assignment; @@ -1132,12 +1134,16 @@ export default class Context { let deferred: [EventName, Record | Error][] | undefined = this._deferredLogs; while (deferred !== undefined) { this._deferredLogs = undefined; - delivered += deferred.length; - if (++rounds >= DEFERRED_REPLAY_ROUNDS || delivered >= DEFERRED_REPLAY_CALLBACKS) { + if (++rounds >= DEFERRED_REPLAY_ROUNDS) { this._deferringLogs = false; this._replayExhausted = true; } for (let i = 0; i < deferred.length; i++) { + // Counted as delivered, so callbacks already waiting keep queue order up to the limit. + if (++delivered >= DEFERRED_REPLAY_CALLBACKS) { + this._deferringLogs = false; + this._replayExhausted = true; + } if (deferred[i][0] === "exposure") exposed = true; this._logEvent(deferred[i][0], deferred[i][1]); } @@ -1146,8 +1152,9 @@ export default class Context { } finally { this._deferringLogs = false; this._replayExhausted = false; - // Only exposures need publishing; an error alone must not arm the timer. - if (exposed) this._setTimeout(); + // Only exposures need publishing, and only while some remain: a callback may have published + // or finalized already, and an error alone must not arm the timer. + if (exposed && this._pending > 0) this._setTimeout(); } } @@ -1162,7 +1169,7 @@ export default class Context { this._logEvent(deferred[i][0], deferred[i][1]); } } finally { - if (exposed) this._setTimeout(); + if (exposed && this._pending > 0) this._setTimeout(); } } From abc1fbbfbcfa1b1456585de49b7e149498ba3918 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 19:23:44 +0000 Subject: [PATCH 72/92] test(context): pin replay exhaustion at exact callback boundary P2-only follow-up: observe the replay exhausted flag at 1023 vs 1024 callbacks. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 5610810..7c17f86 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -6953,6 +6953,7 @@ describe("Context", () => { const names = []; let depth = 0; let nestedAt; + let exhaustedAt; let fanned = false; let nested = false; const eventLogger = jest.fn((ctx, eventName, data) => { @@ -6966,6 +6967,7 @@ describe("Context", () => { for (let i = 1; i < width; i++) ctx.variableValue(`w${i}`, "D"); } else if (!nested && data.name === `exp_w${width - 1}`) { nested = true; + exhaustedAt = ctx._replayExhausted; ctx.variableValue(`w${width}`, "D"); } } finally { @@ -6983,6 +6985,7 @@ describe("Context", () => { expect(names.slice(0, width)).toEqual(Array.from({ length: width }, (_, i) => `exp_w${i}`)); expect(names[width]).toBe(`exp_w${width}`); expect(nestedAt).toBe(nestedDepth); + expect(exhaustedAt).toBe(width === 1024); expect(context.pending()).toBe(width + 1); }); From fe381412c0ba244990621ce74da3fb6d2736e904 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 22:49:51 +0000 Subject: [PATCH 73/92] test(context): cover replay stack and compatibility boundaries Add replay-exhaustion guards and mutation-backed assignment rule, numeric, restore, and forward-compatibility coverage. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 203 ++++++++++++++++++++++++++++++++++ src/context.ts | 16 +++ 2 files changed, 219 insertions(+) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 7c17f86..7beffd5 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -2393,6 +2393,124 @@ describe("Context", () => { }); }); + it("revalidates a same-outcome refresh with changed rules once, then reuses the assignment", async () => { + const context = new Context(sdk, contextOptions, contextParams, rulesContextResponse); + context.attribute("country", "US"); + expect(context.treatment("exp_test_abc")).toEqual(1); + const changed = clone(rulesContextResponse); + const rules = JSON.parse(changed.experiments.find((x) => x.name === "exp_test_abc").assignmentRules); + rules.rules.push({ + name: "Never", + type: "assign", + conditions: { value: false }, + environments: [], + variant: 0, + }); + changed.experiments.find((x) => x.name === "exp_test_abc").assignmentRules = JSON.stringify(rules); + provider.getContextData.mockReturnValue(Promise.resolve(changed)); + await context.refresh(); + const evaluate = jest.spyOn(context._audienceMatcher, "evaluateParsedRules"); + for (let i = 0; i < 3; i++) expect(context.treatment("exp_test_abc")).toEqual(1); + expect(evaluate).toHaveBeenCalledTimes(1); + expect(context.pending()).toEqual(1); + }); + + it("revalidates once after an unrelated attribute change, then reuses the assignment", () => { + const context = new Context(sdk, contextOptions, contextParams, rulesContextResponse); + context.attribute("country", "US"); + expect(context.treatment("exp_test_abc")).toEqual(1); + const evaluate = jest.spyOn(context._audienceMatcher, "evaluateParsedRules"); + context.attribute("age", 30); + for (let i = 0; i < 3; i++) expect(context.treatment("exp_test_abc")).toEqual(1); + expect(evaluate).toHaveBeenCalledTimes(1); + expect(context.pending()).toEqual(1); + }); + + // contracts numeric edge table: the variant is taken as written in the payload JSON. A later rule assigns + // `next`, and normal assignment gives 2, so selected, skipped and out-of-bounds outcomes all differ. + it.each([ + ["1.0", 0, 1], + ["1e0", 0, 1], + ["1.0000000000000001", 0, 1], + ["0.0", 1, 0], + ["-0", 1, 0], + ["1e-400", 1, 0], + ["1.5", 1, 1], + ["1e-9", 0, 0], + ["1e400", 1, 1], + ["-1e400", 1, 1], + ["1e999999999", 1, 1], + ["3", 1, 2], + ["-1", 1, 2], + ["2147483648", 1, 2], + ["-2147483649", 1, 2], + ["4294967297", 1, 2], + ["1e20", 1, 2], + ["99999999999999999999", 1, 2], + [`1${"0".repeat(400)}`, 1, 1], + ])("resolves an assign rule with variant %s (next rule %i) to %i", (variant, next, expected) => { + const cond = '{"and":[{"eq":[{"var":"country"},{"value":"US"}]}]}'; + const response = buildRulesResponse({ + audience: null, + assignmentRules: `{"rules":[{"name":"edge","type":"assign","conditions":${cond},"environments":[],"variant":${variant}},{"name":"next","type":"assign","conditions":${cond},"environments":[],"variant":${next}}]}`, + }); + const context = new Context(sdk, contextOptions, contextParams, response); + context.attribute("country", "US"); + expect(context.peek("exp_test_abc") + 0).toBe(expected); + expect(context.treatment("exp_test_abc") + 0).toBe(expected); + }); + + it.each([ + ["variants[0].config", (x) => delete x.variants[0].config], + ["variants[0].config", (x) => (x.variants[0].config = null)], + ["variants[0].name", (x) => delete x.variants[0].name], + ["variants[0].name", (x) => (x.variants[0].name = null)], + ["customFieldValues[0].type", (x) => delete x.customFieldValues[0].type], + ["customFieldValues[0].type", (x) => (x.customFieldValues[0].type = null)], + ["customFieldValues[0].value", (x) => delete x.customFieldValues[0].value], + ["customFieldValues[0].value", (x) => (x.customFieldValues[0].value = null)], + ["customFieldValues[0].name", (x) => delete x.customFieldValues[0].name], + ["customFieldValues[0].name", (x) => (x.customFieldValues[0].name = null)], + ["customFieldValues", (x) => delete x.customFieldValues], + ["customFieldValues", (x) => (x.customFieldValues = null)], + ["audience", (x) => delete x.audience], + ["audience", (x) => (x.audience = null)], + ["audienceStrict", (x) => delete x.audienceStrict], + ["audienceStrict", (x) => (x.audienceStrict = null)], + ["assignmentRules", (x) => delete x.assignmentRules], + ["assignmentRules", (x) => (x.assignmentRules = null)], + ["applications", (x) => delete x.applications], + ["applications", (x) => (x.applications = null)], + ["iteration", (x) => delete x.iteration], + ["iteration", (x) => (x.iteration = null)], + [ + "(reordered keys)", + (x) => { + const entries = Object.entries(x).reverse(); + for (const key of Object.keys(x)) delete x[key]; + for (const [key, value] of entries) x[key] = value; + x.variants = x.variants.map((v) => Object.fromEntries(Object.entries(v).reverse())); + }, + ], + ])( + "keeps the context and other experiments working when %s is absent, null or reordered", + async (field, edit) => { + const damaged = clone(rulesContextResponse); + edit(damaged.experiments.find((x) => x.name === "exp_test_abc")); + const context = new Context(sdk, contextOptions, contextParams, damaged); + expect(context.isReady()).toBe(true); + expect(context.isFailed()).toBe(false); + expect(context.treatment("exp_test_ab")).toEqual(expectedVariants["exp_test_ab"]); + expect(() => context.treatment("exp_test_abc")).not.toThrow(); + const refreshed = new Context(sdk, contextOptions, contextParams, rulesContextResponse); + expect(refreshed.treatment("exp_test_ab")).toEqual(expectedVariants["exp_test_ab"]); + provider.getContextData.mockReturnValue(Promise.resolve(damaged)); + await expect(refreshed.refresh()).resolves.toBeUndefined(); + expect(refreshed.treatment("exp_test_ab")).toEqual(expectedVariants["exp_test_ab"]); + expect(() => refreshed.treatment("exp_test_abc")).not.toThrow(); + } + ); + it("should return normal assignment when no rules match", () => { const context = new Context(sdk, contextOptions, contextParams, rulesContextResponse); context.attribute("country", "GB"); @@ -7181,6 +7299,55 @@ describe("Context", () => { } ); + it("survives a logger that recurses past the stack and stays usable", () => { + const depth = 6000; + const experiments = []; + for (let i = 0; i <= depth + 1; i++) { + experiments.push({ + ...holdoutVarExperiment({}), + id: 100 + i, + name: `exp_r${i}`, + holdoutIds: null, + split: [0, 1], + fullOnVariant: 1, + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ [`r${i}`]: i }) }, + ], + }); + } + let calls = 0; + let recurse = true; + const later = []; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + if (!recurse) { + later.push(data.name); + return; + } + if (++calls < depth) ctx.treatment(`exp_r${calls}`); + }); + const error = jest.spyOn(console, "error").mockImplementation(() => {}); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse(experiments, []) + ); + expect(() => context.treatment("exp_r0")).not.toThrow(); + expect(error.mock.calls.some(([e]) => e instanceof RangeError)).toBe(true); + error.mockRestore(); + expect(context._deferringLogs).toBe(false); + expect(context._replayExhausted).toBe(false); + expect(context._deferredLogs).toBeUndefined(); + const queued = context.pending(); + recurse = false; + expect(context.treatment(`exp_r${depth}`)).toBe(1); + expect(context.variableValue(`r${depth + 1}`, "D")).toBe(depth + 1); + expect(later).toEqual([`exp_r${depth}`, `exp_r${depth + 1}`]); + expect(context.pending()).toBe(queued + 2); + }); + it("schedules the publish timer after a variable read's deferred exposures", () => { const response = buildHoldoutResponse([winnerAfterHoldout({})], []); const context = new Context(sdk, { ...contextOptions, publishDelay: 100 }, contextParams, response); @@ -7562,6 +7729,42 @@ describe("Context", () => { } ); + it("keeps a retained unit's value and prototype keys across remove and restore refreshes", async () => { + const before = { + ...shared(1, [0, 1], {}), + variants: [ + { name: "A", config: '{"k":"a1"}' }, + { name: "B", config: '{"k":"OLD"}' }, + ], + }; + const plain = { ...shared(2, [0, 1], { other: 1 }), name: "plain" }; + const context = new Context(sdk, contextOptions, contextParams, { experiments: [before, plain] }); + expect(context.variableValue("k", "SENTINEL")).toBe("OLD"); + expect(context.treatment("plain")).toBe(1); + const removed = { ...before, variants: [before.variants[0]] }; + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [removed, plain] })); + await context.refresh(); + expect(context.variableValue("k", "SENTINEL")).toBe("SENTINEL"); + const restored = { + ...before, + variants: [ + { name: "A", config: '{"k":"a1"}' }, + { + name: "B", + config: '{"k":"NEW","valueOf":"V","toString":"T","constructor":"C","__proto__":"P"}', + }, + ], + }; + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [restored, plain] })); + await context.refresh(); + expect(context.variableValue("k", "SENTINEL")).toBe("NEW"); + expect(context.variableValue("valueOf", "SENTINEL")).toBe("V"); + expect(context.variableValue("toString", "SENTINEL")).toBe("T"); + expect(context.variableValue("constructor", "SENTINEL")).toBe("C"); + expect(context.variableValue("__proto__", "SENTINEL")).toBe("P"); + expect(Object.getPrototypeOf(context._assignments.plain.variables)).toBe(Object.prototype); + }); + it("does not restore a removed arm's variables once the experiment id changes", async () => { const variants = [ { name: "A", config: '{"k":"a"}' }, diff --git a/src/context.ts b/src/context.ts index 2b9ddd4..32ea66b 100644 --- a/src/context.ts +++ b/src/context.ts @@ -889,6 +889,14 @@ export default class Context { // reaches the eventLogger only after the call's exposures are queued. private _treatment(experimentName: string) { if (this._deferringLogs) return this._treatmentInScope(experimentName); + if (this._replayExhausted) { + this._deferringLogs = true; + try { + return this._treatmentInScope(experimentName); + } finally { + this._endDeferral(); + } + } this._deferringLogs = true; try { @@ -1103,6 +1111,14 @@ export default class Context { // The replay lives in its own method so a warmed read, which defers nothing, stays small. private _variableValue(key: string, defaultValue: string): string { if (this._deferringLogs) return this._resolveVariableValue(key, defaultValue, true); + if (this._replayExhausted) { + this._deferringLogs = true; + try { + return this._resolveVariableValue(key, defaultValue, true); + } finally { + this._endDeferral(); + } + } this._deferringLogs = true; try { From c1219815d9fb55a0d28a2e6537f9f73d3b28bbe7 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 22:50:23 +0000 Subject: [PATCH 74/92] docs: clarify shared-key callback and replay semantics Document treatment error batching, callback bounds, and stack behavior in the release notes and README. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 35 +++++++++++++++++++---------------- README.md | 22 +++++++++++----------- 2 files changed, 30 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d61c04..b66bbfd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -95,22 +95,25 @@ (`null`, `false`, `0` and `""` included), or the caller default if that variant lacks the key. With no winner, a held-out candidate supplies its control value, otherwise the caller default. Only the winner is exposed; each checked - candidate's applicable holdouts still fire, as in Java. All exposures of one read - are queued before its `exposure` and `error` callbacks run, so a callback that - calls `finalize()` still sends the winner. Callbacks a callback raises are replayed after - the ones already held, in queue order; once a replay has run a bounded number of - rounds or callbacks, each later call delivers its own callbacks as soon as all of - its exposures are queued, so runaway logger feedback stays bounded in stack and - memory and each call still sends its whole batch. `treatment()` likewise queues an - experiment's and its holdouts' exposures before their `exposure` callbacks run - (an audience `error` raised by `treatment()` itself is still reported first). `peekVariableValue()` - exposes nothing. A cached assignment whose arm a refresh removes returns the caller - default (1.13.4 kept serving the removed arm's value) and gets the arm's - values back if a later refresh restores it. Keys no experiment defines return the default - again, as in 1.13.4, including names like `toString`; a variant config that defines - such a key (`toString`, `constructor`, `__proto__`) no longer fails the context. Affected: anyone with two or more - running experiments sharing a variable key. `variableKeys()` keeps its - map-of-lists return shape. + candidate's applicable holdouts still fire, as in Java. All exposures of one + `variableValue()` or `treatment()` call are queued before that call's `exposure` + and `error` callbacks run (including an audience `error` raised while + `treatment()` assigns), so a callback that calls `finalize()` still sends them. + Callbacks a callback raises are replayed after the ones already held, in queue + order; once a replay has run a bounded number of rounds or callbacks, each later + call delivers its own callbacks as soon as all of its exposures are queued, so + runaway logger feedback stays bounded in memory and each call still sends its + whole batch. A logger that keeps calling `treatment()` or `variableValue()` + without end still overflows the stack, as in 1.13.4; the SDK now catches the + overflow in the logger instead of throwing it out of the call, and the context + stays usable. `peekVariableValue()` exposes nothing. A cached assignment whose + arm a refresh removes returns the caller default (1.13.4 kept serving the + removed arm's value) and gets the arm's values back if a later refresh restores + it. Keys no experiment defines return the default again, as in 1.13.4, including + names like `toString`; a variant config that defines such a key (`toString`, + `constructor`, `__proto__`) no longer fails the context. Affected: anyone with + two or more running experiments sharing a variable key. `variableKeys()` keeps + its map-of-lists return shape. - Failed publishes retain queued events in order; failed finalize stays open and can be retried. Concurrent flush/finalize waits for in-flight delivery. - Custom publisher failures and throwing event loggers no longer strand lifecycle diff --git a/README.md b/README.md index 851991b..b93c0bd 100644 --- a/README.md +++ b/README.md @@ -234,9 +234,9 @@ overridden or assigned by a rule). Its variant's value is returned, or your default if that variant does not define the key; later experiments are never used instead. If the user is in none of them but one is held out by a holdout, the first held-out experiment's control value is returned, or your default if -its control arm does not define the key (no other experiment is checked). Only -the winning experiment gets an exposure (plus any holdouts covering the -experiments checked); a held-out experiment that supplies its control value +its control arm does not define the key (no later experiment supplies the +value). Only the winning experiment gets an exposure (plus any holdouts covering +the experiments checked); a held-out experiment that supplies its control value records only its holdout's exposure. An experiment the user is not in, such as a strict audience mismatch, gets none; call `treatment()` to record it. `peekVariableValue()` never queues an exposure. @@ -387,14 +387,14 @@ The data parameter depends on the type of event. Currently, the SDK logs the fol | `"goal"` | `track()` method succeeds | Goal data enqueued for publishing | | `"finalize"` | `finalize()` method succeeds the first time | undefined | -`"exposure"` and `"error"` events raised by one `variableValue()` call (and the -`"exposure"` events of one `treatment()` call) are delivered after all of that -call's exposures are queued, in the order they were raised, so a logger that -calls `publish()` or `finalize()` sends every one of them. `"exposure"` -and `"error"` events a logger triggers itself are delivered after the ones -already waiting (other events, such as a `"goal"` from `track()`, are delivered -immediately); after a bounded number of rounds or callbacks, each later call delivers its own -events together, once all of that call's exposures are queued. +`"exposure"` and `"error"` events raised by one `variableValue()` or +`treatment()` call are delivered after all of that call's exposures are queued, +in the order they were raised, so a logger that calls `publish()` or +`finalize()` sends every one of them. `"exposure"` and `"error"` events a logger +triggers itself are delivered after the ones already waiting (other events, such +as a `"goal"` from `track()`, are delivered immediately); after a bounded number +of rounds or callbacks, each later call delivers its own events together, once +all of that call's exposures are queued. ### HTTP Request Timeout From e4d7e991f8ecb9a508435fc58d131982aea45c2f Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 23:41:55 +0000 Subject: [PATCH 75/92] fix(context): partition replay dispatch at callback budget Stop replay dispatch exactly at the callback budget and route the remainder through post-limit delivery without dropping queued events. Co-Authored-By: Claude Opus 5.5 --- src/context.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/context.ts b/src/context.ts index 32ea66b..ee362d1 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1156,12 +1156,18 @@ export default class Context { } for (let i = 0; i < deferred.length; i++) { // Counted as delivered, so callbacks already waiting keep queue order up to the limit. - if (++delivered >= DEFERRED_REPLAY_CALLBACKS) { + const cutoff = ++delivered >= DEFERRED_REPLAY_CALLBACKS; + if (cutoff) { this._deferringLogs = false; this._replayExhausted = true; + this._deferredLogs = deferred.slice(i + 1); } if (deferred[i][0] === "exposure") exposed = true; this._logEvent(deferred[i][0], deferred[i][1]); + if (cutoff) { + if (this._deferredLogs?.length) this._deliverDeferredLogs(); + break; + } } deferred = this._deferredLogs; } From 2062e21871564c12288627a0a1dfaf78e2197414 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 23:45:17 +0000 Subject: [PATCH 76/92] fix(context): partition replay dispatch at callback budget Deliver generated callbacks and the pre-existing remainder as separate post-limit batches so retained work stays bounded. Co-Authored-By: Claude Opus 5.5 --- src/context.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/context.ts b/src/context.ts index ee362d1..a5ade1c 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1157,15 +1157,21 @@ export default class Context { for (let i = 0; i < deferred.length; i++) { // Counted as delivered, so callbacks already waiting keep queue order up to the limit. const cutoff = ++delivered >= DEFERRED_REPLAY_CALLBACKS; + let remainder: [EventName, Record | Error][] | undefined; if (cutoff) { this._deferringLogs = false; this._replayExhausted = true; - this._deferredLogs = deferred.slice(i + 1); + remainder = deferred.slice(i + 1); + this._deferredLogs = undefined; } if (deferred[i][0] === "exposure") exposed = true; this._logEvent(deferred[i][0], deferred[i][1]); if (cutoff) { - if (this._deferredLogs?.length) this._deliverDeferredLogs(); + if (this._deferredLogs !== undefined) this._deliverDeferredLogs(); + if (remainder?.length) { + this._deferredLogs = remainder; + this._deliverDeferredLogs(); + } break; } } From a6ec49640ff02531bcb121722685aeee9201a6b1 Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 23:48:57 +0000 Subject: [PATCH 77/92] fix(context): bound post-limit replay delivery Drain the captured remainder directly after the callback budget so nested callbacks cannot recursively reopen replay scopes. Co-Authored-By: Claude Opus 5.5 --- src/context.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/context.ts b/src/context.ts index a5ade1c..ed150e2 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1169,6 +1169,7 @@ export default class Context { if (cutoff) { if (this._deferredLogs !== undefined) this._deliverDeferredLogs(); if (remainder?.length) { + this._replayExhausted = false; this._deferredLogs = remainder; this._deliverDeferredLogs(); } From fe83bc56b0fbc231971def2dc442ec75556d86ea Mon Sep 17 00:00:00 2001 From: lux worker Date: Wed, 25 Nov 2026 23:58:30 +0000 Subject: [PATCH 78/92] fix(context): enforce replay callback budget at dispatch Partition the cutoff remainder into one post-limit batch without reopening replay recursion. Co-Authored-By: Claude Opus 5.5 --- src/context.ts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/context.ts b/src/context.ts index ed150e2..c549c33 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1167,12 +1167,9 @@ export default class Context { if (deferred[i][0] === "exposure") exposed = true; this._logEvent(deferred[i][0], deferred[i][1]); if (cutoff) { - if (this._deferredLogs !== undefined) this._deliverDeferredLogs(); - if (remainder?.length) { - this._replayExhausted = false; - this._deferredLogs = remainder; - this._deliverDeferredLogs(); - } + const generated: [EventName, Record | Error][] = this._deferredLogs ?? []; + this._deferredLogs = generated.concat(remainder ?? []); + this._deliverDeferredLogs(); break; } } From 0d47aae96ed3da909782f04f0ef62241e147d48d Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 26 Nov 2026 04:21:36 +0000 Subject: [PATCH 79/92] test(release): reject multiple publish commands Ensure manual publish safety checks inspect every publish invocation and reject a second command. Co-Authored-By: Claude Opus 5.5 --- scripts/__tests__/check-release.test.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/__tests__/check-release.test.js b/scripts/__tests__/check-release.test.js index a3fd94d..38ef599 100644 --- a/scripts/__tests__/check-release.test.js +++ b/scripts/__tests__/check-release.test.js @@ -125,7 +125,9 @@ describe("publish workflow", () => { () => { const npmVersion = pinnedNpm; const effectiveDryRun = (run) => { - const line = run.split("\n").filter((l) => /\bnpm\s+publish\b/.test(l))[0]; + const lines = run.split("\n").filter((l) => /\bnpm\s+publish\b/.test(l)); + expect(lines).toHaveLength(1); + const line = lines[0]; const args = line .trim() .split(/\s+/) From 94c33b3980a62fb3010188935d602201a3b736b4 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 26 Nov 2026 14:16:21 +0000 Subject: [PATCH 80/92] fix(release): keep TS 3.9 declarations, own-key maps and SemVer tag order - Import switchback types with a separate `import type`: the inline `type` specifiers that came in with the #69 merge made the published declarations unreadable on TypeScript 3.9 and 4.4. CI now runs the 1.13.4 compatibility runner (TS 3.9/4.4/4.9) after the build. - Overrides, custom assignments, assigners, the assignment cache and the experiment index have no prototype, and units are defined as own keys, so experiments and unit types named like Object.prototype members (`constructor`, `__proto__`, ...) behave like any other name. Before, an experiment named `__proto__` was never cached and re-exposed on every treatment(). `getUnits()` still returns the plain 1.13.4 object. - check-release compares full SemVer precedence, so stable 1.14.0 is newer than npm latest 1.14.0-rc.1 instead of being refused. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build.yml | 9 ++ scripts/__tests__/check-release.test.js | 48 +++++++++- scripts/check-release.js | 28 +++++- src/__tests__/context.test.js | 118 ++++++++++++++++++++++++ src/context.ts | 35 ++++--- 5 files changed, 221 insertions(+), 17 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 32d2033..859b4c9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -44,3 +44,12 @@ jobs: - name: Run npm build run: npm run build + + # Published declarations must still compile for 1.13.4 consumers on TypeScript 3.9, 4.4 and 4.9. + - name: Check compatibility with the published 1.13.4 package + run: | + mkdir -p "$RUNNER_TEMP/baseline" + npm pack @absmartly/javascript-sdk@1.13.4 --ignore-scripts --pack-destination "$RUNNER_TEMP" + tar -xzf "$RUNNER_TEMP/absmartly-javascript-sdk-1.13.4.tgz" -C "$RUNNER_TEMP/baseline" + npm install --prefix "$RUNNER_TEMP/baseline/package" --omit=dev --ignore-scripts --no-audit --no-fund + node scripts/compatibility/run.js "$RUNNER_TEMP/baseline/package" . --report "$RUNNER_TEMP/compat.json" diff --git a/scripts/__tests__/check-release.test.js b/scripts/__tests__/check-release.test.js index 38ef599..a879425 100644 --- a/scripts/__tests__/check-release.test.js +++ b/scripts/__tests__/check-release.test.js @@ -4,7 +4,7 @@ const { readFileSync } = require("fs"); const { execFileSync } = require("child_process"); const path = require("path"); const yaml = require("js-yaml"); -const { majorOf, releaseTag, checkRepository } = require("../check-release"); +const { majorOf, releaseTag, checkRepository, compareVersions } = require("../check-release"); const pkg = require("../../package.json"); test("uses a non-semver lts tag for older major releases", () => { @@ -59,6 +59,52 @@ test.each(["1.15", "01.15.0", "1.15.0-01", "1.15.0-beta_1", "1.15.0\n"])( } ); +test("publishes a stable release over a prerelease of the same version as latest", () => { + for (const latest of ["1.14.0-rc.1", "1.14.0-beta.1", "1.14.0-alpha", "1.14.0-0", "1.14.0-rc.1+build.5"]) { + expect(releaseTag("1.14.0", latest, "v1.14.0")).toBe("latest"); + } + expect(() => releaseTag("1.13.9", "1.14.0-rc.1", "v1.13.9")).toThrow(/not newer than latest/); +}); + +// The SemVer 2.0.0 section 11 example, ascending, plus build metadata and hyphenated identifiers. +const SEMVER_ORDER = [ + "1.0.0-alpha", + "1.0.0-alpha.1", + "1.0.0-alpha.beta", + "1.0.0-beta", + "1.0.0-beta.2", + "1.0.0-beta.11", + "1.0.0-rc.1", + "1.0.0-rc-1.2", + "1.0.0-rc-1.10", + "1.0.0", + "1.0.1-0", + "1.0.1", +]; + +test("orders versions by SemVer precedence", () => { + for (let i = 0; i < SEMVER_ORDER.length; i++) { + for (let j = 0; j < SEMVER_ORDER.length; j++) { + expect([SEMVER_ORDER[i], SEMVER_ORDER[j], compareVersions(SEMVER_ORDER[i], SEMVER_ORDER[j])]).toEqual([ + SEMVER_ORDER[i], + SEMVER_ORDER[j], + Math.sign(i - j), + ]); + } + } +}); + +test("ignores build metadata when comparing versions", () => { + expect(compareVersions("1.0.0+build.2", "1.0.0+build.1")).toBe(0); + expect(compareVersions("1.0.0-rc.1+build.9", "1.0.0-rc.1")).toBe(0); + expect(compareVersions("1.0.0+build-1", "1.0.0-rc.1")).toBe(1); +}); + +test("compares numeric prerelease identifiers by value, beyond Number precision", () => { + expect(compareVersions("1.0.0-9007199254740993", "1.0.0-9007199254740992")).toBe(1); + expect(compareVersions("1.0.0-10", "1.0.0-9")).toBe(1); +}); + test("refuses an older same-major release instead of moving latest back", () => { expect(() => releaseTag("1.13.5", "1.14.0", "v1.13.5")).toThrow(/not newer than latest/); expect(() => releaseTag("1.14.0", "1.14.0", "v1.14.0")).toThrow(/not newer than latest/); diff --git a/scripts/check-release.js b/scripts/check-release.js index 9bde1c3..a53663f 100644 --- a/scripts/check-release.js +++ b/scripts/check-release.js @@ -25,6 +25,30 @@ function compareCore(a, b) { return 0; } +// SemVer 2.0.0 section 11: the core decides first; a prerelease ranks below its release; prerelease +// identifiers compare numerically when both are numeric, numeric below alphanumeric, else in ASCII order, +// and a longer list wins when every shared identifier is equal. Build metadata is ignored. +function compareVersions(a, b) { + const core = compareCore(a, b); + if (core !== 0) return core; + const prerelease = (v) => { + const text = v.split("+")[0].split("-").slice(1).join("-"); + return text ? text.split(".") : []; + }; + const x = prerelease(a); + const y = prerelease(b); + if (x.length === 0 || y.length === 0) return y.length - x.length === 0 ? 0 : x.length === 0 ? 1 : -1; + for (let i = 0; i < Math.min(x.length, y.length); i++) { + if (x[i] === y[i]) continue; + const xNumeric = /^\d+$/.test(x[i]); + const yNumeric = /^\d+$/.test(y[i]); + if (xNumeric && yNumeric) return BigInt(x[i]) > BigInt(y[i]) ? 1 : -1; + if (xNumeric !== yNumeric) return xNumeric ? -1 : 1; + return x[i] > y[i] ? 1 : -1; + } + return x.length === y.length ? 0 : x.length > y.length ? 1 : -1; +} + function releaseTag(packageVersion, latestVersion, gitTag) { const major = majorOf(packageVersion); const latestMajor = majorOf(latestVersion); @@ -37,7 +61,7 @@ function releaseTag(packageVersion, latestVersion, gitTag) { return ["alpha", "beta", "rc", "next"].includes(id) ? id : "next"; } if (major < latestMajor) return `v${major}-lts`; - if (compareCore(packageVersion, latestVersion) <= 0) { + if (compareVersions(packageVersion, latestVersion) <= 0) { throw new Error(`${packageVersion} is not newer than latest ${latestVersion}; choose a dist tag manually`); } return "latest"; @@ -96,4 +120,4 @@ if (require.main === module) { } } -module.exports = { majorOf, releaseTag, checkRepository }; +module.exports = { majorOf, releaseTag, checkRepository, compareVersions }; diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 7beffd5..2a108cc 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -7894,6 +7894,124 @@ describe("Context", () => { }); }); + describe("experiment names and unit types named like Object.prototype members", () => { + const memberNames = ["constructor", "toString", "valueOf", "hasOwnProperty", "__proto__"]; + const named = (experimentName, over = {}) => ({ ...shared(1, [0, 1], {}), name: experimentName, ...over }); + const exposures = (context) => context._exposures.map((x) => [x.name, x.variant, x.custom, x.overridden]); + + it.each(memberNames)("assigns and caches an experiment named %s like any other", async (member) => { + const context = new Context(sdk, contextOptions, contextParams, { experiments: [named(member)] }); + expect(context.peek(member)).toBe(1); + expect(context.treatment(member)).toBe(1); + expect(context.treatment(member)).toBe(1); + expect(exposures(context)).toEqual([[member, 1, false, false]]); + expect(Object.getPrototypeOf(context._assignments)).toBe(null); + provider.getContextData.mockReturnValue(Promise.resolve({ experiments: [named(member)] })); + await context.refresh(); + expect(context.treatment(member)).toBe(1); + expect(context.pending()).toBe(1); + }); + + it.each(memberNames)("applies and caches an override for an experiment named %s", (member) => { + const context = new Context(sdk, contextOptions, contextParams, { experiments: [named(member)] }); + context.override(member, 0); + expect(context.treatment(member)).toBe(0); + expect(context.treatment(member)).toBe(0); + expect(exposures(context)).toEqual([[member, 0, false, true]]); + }); + + it.each(memberNames)("applies and caches a custom assignment for an experiment named %s", (member) => { + const context = new Context(sdk, contextOptions, contextParams, { experiments: [named(member)] }); + context.customAssignment(member, 0); + expect(context.treatment(member)).toBe(0); + expect(context.treatment(member)).toBe(0); + expect(exposures(context)).toEqual([[member, 0, true, false]]); + }); + + it.each(memberNames)("does not apply an inherited %s as an override or custom assignment", (member) => { + const context = new Context(sdk, contextOptions, contextParams, { experiments: [named(member)] }); + expect(context.treatment(member)).toBe(1); + expect(exposures(context)).toEqual([[member, 1, false, false]]); + }); + + it.each(memberNames)("serves the base variant for an unknown experiment named %s", (member) => { + const context = new Context(sdk, contextOptions, contextParams, { experiments: [] }); + expect(context.peek(member)).toBe(0); + expect(context.treatment(member)).toBe(0); + expect(context.treatment(member)).toBe(0); + expect(exposures(context)).toEqual([[member, 0, false, false]]); + }); + + it.each(memberNames)("keeps a unit type named %s as an own unit and assigns from it", (unitType) => { + const context = new Context( + sdk, + contextOptions, + { units: {} }, + { experiments: [named("e", { unitType })] } + ); + expect(context.getUnit(unitType)).toBeUndefined(); + context.unit(unitType, "u1"); + expect(context.getUnit(unitType)).toBe("u1"); + expect(Object.prototype.hasOwnProperty.call(context.getUnits(), unitType)).toBe(true); + expect(Object.getPrototypeOf(context.getUnits())).toBe(Object.prototype); + expect(Object.getPrototypeOf(context._assigners)).toBe(null); + expect(() => context.unit(unitType, "u1")).not.toThrow(); + expect(() => context.unit(unitType, "u2")).toThrow(`Unit '${unitType}' UID already set.`); + const ordinary = new Context( + sdk, + contextOptions, + { units: { other: "u1" } }, + { + experiments: [named("e", { unitType: "other" })], + } + ); + expect(context.treatment("e")).toBe(ordinary.treatment("e")); + expect(context.treatment("e")).toBe(ordinary.treatment("e")); + expect(context._exposures.map((x) => [x.name, x.unit])).toEqual([["e", unitType]]); + }); + + it.each(memberNames)("publishes a unit type named %s", async (unitType) => { + publisher.publish.mockReturnValue(Promise.resolve()); + const context = new Context( + sdk, + contextOptions, + { units: {} }, + { experiments: [named("e", { unitType })] } + ); + context.unit(unitType, "u1"); + context.treatment("e"); + await context.publish(); + const published = publisher.publish.mock.calls[publisher.publish.mock.calls.length - 1][0].units; + expect(published).toEqual([{ type: unitType, uid: hashUnit("u1") }]); + }); + + it.each(memberNames)("holds out an experiment named %s like an ordinary one", (member) => { + // Split [1, 0] always holds the unit out, so the experiment serves control. + const holdout = { ...shared(9, [1, 0], {}), name: "h", holdoutType: "full" }; + const served = (experimentName) => { + const context = new Context(sdk, contextOptions, contextParams, { + experiments: [named(experimentName, { holdoutIds: [9] })], + holdouts: [holdout], + }); + const variants = [context.treatment(experimentName), context.treatment(experimentName)]; + return [ + variants, + context._exposures.map((x) => (x.name === experimentName ? "experiment" : x.name)), + ]; + }; + expect(served(member)).toEqual(served("ordinary")); + }); + + it("keeps getUnits() an ordinary object, as in 1.13.4", () => { + const context = new Context(sdk, contextOptions, contextParams, { experiments: [] }); + const unitMap = context.getUnits(); + expect(Object.getPrototypeOf(unitMap)).toBe(Object.prototype); + // eslint-disable-next-line no-prototype-builtins + expect(unitMap.hasOwnProperty("session_id")).toBe(true); + expect(String(unitMap)).toBe("[object Object]"); + }); + }); + it.each(["toString", "valueOf", "hasOwnProperty", "__proto__", "constructor"])( "returns the caller default for the unindexed prototype-named key %s", (key) => { diff --git a/src/context.ts b/src/context.ts index c04a766..02e5432 100644 --- a/src/context.ts +++ b/src/context.ts @@ -18,9 +18,12 @@ import { SWITCHBACK_ABSENT, SWITCHBACK_ELIGIBLE, SWITCHBACK_INELIGIBLE, - type SwitchbackServing, - type SwitchbackSources, } from "./switchback"; +// A separate `import type`: inline `type` specifiers would need TypeScript 4.5 to read the published +// declarations, and 1.13.4 consumers compile with 3.9. +import type { SwitchbackServing, SwitchbackSources } from "./switchback"; + +const hasOwn = (object: object, key: string) => Object.prototype.hasOwnProperty.call(object, key); type JSONPrimitive = string | number | boolean | null; type JSONObject = { [key: string]: JSONValue }; @@ -275,10 +278,13 @@ export default class Context { this._attrs = []; this._goals = []; this._exposures = []; - this._overrides = {}; - this._cassignments = {}; + // No prototype, so a name such as `constructor` or `__proto__` is an ordinary key. `_units` stays a + // plain object because `getUnits()` returns it, as in 1.13.4; its keys are written and read as own + // properties instead. + this._overrides = Object.create(null); + this._cassignments = Object.create(null); this._units = {}; - this._assigners = {}; + this._assigners = Object.create(null); this._holdoutAssignments = {}; this._audienceMatcher = new AudienceMatcher(); this._environmentName = null; @@ -399,7 +405,7 @@ export default class Context { } getUnit(unitType: string) { - return this._units[unitType]; + return hasOwn(this._units, unitType) ? this._units[unitType] : undefined; } unit(unitType: string, uid: string | number) { @@ -416,12 +422,13 @@ export default class Context { throw new Error(`Unit '${unitType}' must be a string or a number.`); } - const previous = this._units[unitType]; + const previous = this.getUnit(unitType); if (previous !== undefined && previous !== uid) { throw new Error(`Unit '${unitType}' UID already set.`); } - this._units[unitType] = uid; + // Defined, not assigned: assigning `__proto__` would replace the map's prototype. + Object.defineProperty(this._units, unitType, { value: uid, enumerable: true, writable: true, configurable: true }); this._invalidateAssignmentsPinnedWithMissingUnit(unitType); } @@ -790,7 +797,7 @@ export default class Context { !assignment.exposed && assignment.unitType != null && (assignment.isRuleMissingUnit || assignment.holdoutAssignments?.some((item) => item === null)) && - assignment.unitType in this._units + hasOwn(this._units, assignment.unitType) ) { delete this._assignments[experimentName]; return this._assign(experimentName); @@ -911,7 +918,7 @@ export default class Context { assignment.variant = 0; } else if (experiment.data.fullOnVariant === 0) { if (unitType !== null) { - if (unitType in this._units) { + if (hasOwn(this._units, unitType)) { const unit = this._unitHash(unitType); if (unit !== null) { const assigner = @@ -1907,12 +1914,12 @@ export default class Context { private _unitHash(unitType: string) { if (!this._hashes) { - this._hashes = {}; + this._hashes = Object.create(null) as Record; } if (!(unitType in this._hashes)) { // Never cache `null`: the unit can still be set later (see `_getHoldoutAssignment`). - if (!(unitType in this._units)) { + if (!hasOwn(this._units, unitType)) { return null; } @@ -1964,12 +1971,12 @@ export default class Context { return assignment; } - private _init(data: ContextData, assignments: Record = {}) { + private _init(data: ContextData, assignments: Record = Object.create(null)) { this._data = data; const client = this._sdk.getClient(); this._environmentName = typeof client?.getEnvironment === "function" ? client.getEnvironment() ?? null : null; - const index: Record = {}; + const index: Record = Object.create(null); const indexVariables: Record = {}; const holdoutsById: Record = {}; From e3b6827509f7337ecc4fc7a09b2043aca45df288 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 26 Nov 2026 14:49:36 +0000 Subject: [PATCH 81/92] test(context): pin unset prototype-named units and the mid-round replay remainder Remove a unit guard that _unitHash already covers and the replay-exhausted branches in treatment()/variableValue() that duplicated the ordinary path. New tests kill the surviving mutants: unset unit types named like Object members, cached missing-unit re-resolution, and callbacks still waiting when the replay budget runs out mid-round. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 84 +++++++++++++++++++++++++++++++++++ src/context.ts | 74 +++++++++++------------------- 2 files changed, 111 insertions(+), 47 deletions(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 2a108cc..17c5500 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -7107,6 +7107,55 @@ describe("Context", () => { expect(context.pending()).toBe(width + 1); }); + // 2,000 callbacks wait in one round, so the 1,024-callback budget is spent mid-round. The ones + // still waiting at the cutoff, and the read the cutoff callback makes, are each delivered once, + // in queue order, without another replay round. + it("delivers every callback still waiting when the budget runs out mid-round", () => { + const width = 2000; + const experiments = []; + for (let i = 0; i <= width; i++) { + experiments.push({ + ...holdoutVarExperiment({}), + id: 100 + i, + name: `exp_w${i}`, + holdoutIds: null, + split: [0, 1], + fullOnVariant: 1, + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ [`w${i}`]: i }) }, + ], + }); + } + const names = []; + let fanned = false; + let nested = false; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + names.push(data.name); + if (!fanned) { + fanned = true; + for (let i = 1; i < width; i++) ctx.variableValue(`w${i}`, "D"); + } else if (!nested && data.name === "exp_w1023") { + nested = true; + ctx.variableValue(`w${width}`, "D"); + } + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse(experiments, []) + ); + expect(context.variableValue("w0", "D")).toBe(0); + expect(names).toHaveLength(width + 1); + expect(new Set(names).size).toBe(width + 1); + expect(names.slice(0, 1024)).toEqual(Array.from({ length: 1024 }, (_, i) => `exp_w${i}`)); + expect(names.indexOf(`exp_w${width}`)).toBeGreaterThan(names.indexOf("exp_w1023")); + expect(context.pending()).toBe(width + 1); + expect(context._deferredLogs).toBeUndefined(); + }); + it("delivers a post-limit batch's error and exposure and arms the publish timer", () => { const strict = { ...holdoutVarExperiment({}), @@ -8002,6 +8051,41 @@ describe("Context", () => { expect(served(member)).toEqual(served("ordinary")); }); + it.each(memberNames)("treats an unset unit type named %s as missing", (unitType) => { + const context = new Context( + sdk, + contextOptions, + { units: {} }, + { experiments: [named("e", { unitType })] } + ); + expect(context.peek("e")).toBe(0); + expect(context.treatment("e")).toBe(0); + expect(context._exposures.map((x) => [x.name, x.assigned, x.unit])).toEqual([["e", false, unitType]]); + }); + + it.each(memberNames)("keeps a cached assignment whose unset unit type is named %s", (unitType) => { + // Split [1, 0] always holds out; with no unit the holdout entry is null, which marks the + // assignment for re-resolution once that unit is set (and only then). + const holdout = { ...shared(9, [1, 0], {}), name: "h", holdoutType: "full", unitType }; + const context = new Context( + sdk, + contextOptions, + { units: {} }, + { + experiments: [named("e", { unitType, holdoutIds: [9] })], + holdouts: [holdout], + } + ); + context.peek("e"); + const cached = context._assignments.e; + expect(cached.holdoutAssignments).toEqual([null]); + context.peek("e"); + expect(context._assignments.e).toBe(cached); + context.unit(unitType, "u1"); + context.peek("e"); + expect(context._assignments.e).not.toBe(cached); + }); + it("keeps getUnits() an ordinary object, as in 1.13.4", () => { const context = new Context(sdk, contextOptions, contextParams, { experiments: [] }); const unitMap = context.getUnits(); diff --git a/src/context.ts b/src/context.ts index 02e5432..3ac5aac 100644 --- a/src/context.ts +++ b/src/context.ts @@ -918,37 +918,35 @@ export default class Context { assignment.variant = 0; } else if (experiment.data.fullOnVariant === 0) { if (unitType !== null) { - if (hasOwn(this._units, unitType)) { - const unit = this._unitHash(unitType); - if (unit !== null) { - const assigner = - unitType in this._assigners - ? this._assigners[unitType] - : (this._assigners[unitType] = new VariantAssigner(unit)); - const eligible = - assigner.assign( - experiment.data.trafficSplit, - experiment.data.trafficSeedHi, - experiment.data.trafficSeedLo - ) === 1; - - assignment.assigned = true; - assignment.eligible = eligible; - - if (eligible) { - if (hasCustom) { - assignment.variant = this._cassignments[experimentName]; - assignment.custom = true; - } else { - assignment.variant = assigner.assign( - experiment.data.split, - experiment.data.seedHi, - experiment.data.seedLo - ); - } + const unit = this._unitHash(unitType); + if (unit !== null) { + const assigner = + unitType in this._assigners + ? this._assigners[unitType] + : (this._assigners[unitType] = new VariantAssigner(unit)); + const eligible = + assigner.assign( + experiment.data.trafficSplit, + experiment.data.trafficSeedHi, + experiment.data.trafficSeedLo + ) === 1; + + assignment.assigned = true; + assignment.eligible = eligible; + + if (eligible) { + if (hasCustom) { + assignment.variant = this._cassignments[experimentName]; + assignment.custom = true; } else { - assignment.variant = 0; + assignment.variant = assigner.assign( + experiment.data.split, + experiment.data.seedHi, + experiment.data.seedLo + ); } + } else { + assignment.variant = 0; } } } @@ -1261,15 +1259,6 @@ export default class Context { // reaches the eventLogger only after the call's exposures are queued. private _treatment(experimentName: string) { if (this._deferringLogs) return this._treatmentInScope(experimentName); - if (this._replayExhausted) { - this._deferringLogs = true; - try { - return this._treatmentInScope(experimentName); - } finally { - this._endDeferral(); - } - } - this._deferringLogs = true; try { return this._treatmentInScope(experimentName); @@ -1503,15 +1492,6 @@ export default class Context { // The replay lives in its own method so a warmed read, which defers nothing, stays small. private _variableValue(key: string, defaultValue: string): string { if (this._deferringLogs) return this._resolveVariableValue(key, defaultValue, true); - if (this._replayExhausted) { - this._deferringLogs = true; - try { - return this._resolveVariableValue(key, defaultValue, true); - } finally { - this._endDeferral(); - } - } - this._deferringLogs = true; try { return this._resolveVariableValue(key, defaultValue, true); From db9a38bedc41542256f31042437b8a9b1015cee6 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 26 Nov 2026 16:09:16 +0000 Subject: [PATCH 82/92] fix(context): keep every callback queued in the round the replay budget runs out At the 1,024-callback cutoff the round's remaining callbacks were kept, but callbacks that earlier callbacks of the same round had already queued for the next round were dropped: their exposures were published, but the eventLogger never heard about them. The remainder now carries both, after the callbacks the cutoff callback itself raises, which are delivered inline as in 1.13.4. Tests pin the delivered position of an extra read made before, at and after the cutoff, so the remainder order is fixed. CHANGELOG gains a Fixed line for experiments and unit types named like Object.prototype members. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++ src/__tests__/context.test.js | 101 +++++++++++++++++++--------------- src/context.ts | 14 +++-- 3 files changed, 73 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index af615f1..f1ad3df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -109,6 +109,12 @@ ### Fixed +- Experiments, overrides, custom assignments and unit types named like + `Object.prototype` members (`constructor`, `toString`, `__proto__`, ...) behave + like any other name. 1.13.4 returned `{}` as the variant, lost custom + assignments, threw for unknown experiments and for unit types such as + `toString`, and re-exposed an experiment named `__proto__` on every + `treatment()`. `getUnits()` still returns the same plain object. - Shared variable keys now pick and expose one experiment, as the Java SDK does. Previously `variableValue()` exposed every experiment it checked that had the key, including ones the unit was not in (for example a strict audience diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 17c5500..5bd83c3 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -7110,51 +7110,66 @@ describe("Context", () => { // 2,000 callbacks wait in one round, so the 1,024-callback budget is spent mid-round. The ones // still waiting at the cutoff, and the read the cutoff callback makes, are each delivered once, // in queue order, without another replay round. - it("delivers every callback still waiting when the budget runs out mid-round", () => { - const width = 2000; - const experiments = []; - for (let i = 0; i <= width; i++) { - experiments.push({ - ...holdoutVarExperiment({}), - id: 100 + i, - name: `exp_w${i}`, - holdoutIds: null, - split: [0, 1], - fullOnVariant: 1, - variants: [ - { name: "A", config: null }, - { name: "B", config: JSON.stringify({ [`w${i}`]: i }) }, - ], + // 2,000 callbacks wait in one round, so the 1,024-callback budget is spent mid-round. A read made + // from a callback before the cutoff, from the cutoff callback itself, or after it is delivered once + // with everything else: the cutoff callback's own callbacks first, then the round's remaining ones, + // then those earlier callbacks queued for the next round. After the cutoff, delivery is inline as in + // 1.13.4, so a read made from a later callback runs right after it. + it.each([ + ["exp_w5", 2000], + ["exp_w1022", 2000], + ["exp_w1023", 1024], + ["exp_w1500", 1501], + ])( + "delivers every callback when the budget runs out mid-round (extra read from %s)", + (trigger, position) => { + const width = 2000; + const experiments = []; + for (let i = 0; i <= width; i++) { + experiments.push({ + ...holdoutVarExperiment({}), + id: 100 + i, + name: `exp_w${i}`, + holdoutIds: null, + split: [0, 1], + fullOnVariant: 1, + variants: [ + { name: "A", config: null }, + { name: "B", config: JSON.stringify({ [`w${i}`]: i }) }, + ], + }); + } + const names = []; + let fanned = false; + let nested = false; + const eventLogger = jest.fn((ctx, eventName, data) => { + if (eventName !== "exposure") return; + names.push(data.name); + if (!fanned) { + fanned = true; + for (let i = 1; i < width; i++) ctx.variableValue(`w${i}`, "D"); + } else if (!nested && data.name === trigger) { + nested = true; + ctx.variableValue(`w${width}`, "D"); + } }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse(experiments, []) + ); + expect(context.variableValue("w0", "D")).toBe(0); + expect(names).toHaveLength(width + 1); + expect(new Set(names).size).toBe(width + 1); + expect(names.indexOf(`exp_w${width}`)).toBe(position); + expect(names.filter((n) => n !== `exp_w${width}`)).toEqual( + Array.from({ length: width }, (_, i) => `exp_w${i}`) + ); + expect(context.pending()).toBe(width + 1); + expect(context._deferredLogs).toBeUndefined(); } - const names = []; - let fanned = false; - let nested = false; - const eventLogger = jest.fn((ctx, eventName, data) => { - if (eventName !== "exposure") return; - names.push(data.name); - if (!fanned) { - fanned = true; - for (let i = 1; i < width; i++) ctx.variableValue(`w${i}`, "D"); - } else if (!nested && data.name === "exp_w1023") { - nested = true; - ctx.variableValue(`w${width}`, "D"); - } - }); - const context = new Context( - sdk, - { ...contextOptions, eventLogger }, - contextParams, - buildHoldoutResponse(experiments, []) - ); - expect(context.variableValue("w0", "D")).toBe(0); - expect(names).toHaveLength(width + 1); - expect(new Set(names).size).toBe(width + 1); - expect(names.slice(0, 1024)).toEqual(Array.from({ length: 1024 }, (_, i) => `exp_w${i}`)); - expect(names.indexOf(`exp_w${width}`)).toBeGreaterThan(names.indexOf("exp_w1023")); - expect(context.pending()).toBe(width + 1); - expect(context._deferredLogs).toBeUndefined(); - }); + ); it("delivers a post-limit batch's error and exposure and arms the publish timer", () => { const strict = { diff --git a/src/context.ts b/src/context.ts index 3ac5aac..a906d70 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1531,17 +1531,21 @@ export default class Context { const cutoff = ++delivered >= DEFERRED_REPLAY_CALLBACKS; let remainder: [EventName, Record | Error][] | undefined; if (cutoff) { + // Deferral ends with this callback, so a read it makes is delivered inline before it + // returns, as in 1.13.4. The rest of the batch follows: this round's waiting callbacks, + // then those its earlier callbacks queued for the next round. this._deferringLogs = false; this._replayExhausted = true; - remainder = deferred.slice(i + 1); + remainder = deferred.slice(i + 1).concat(this._deferredLogs ?? []); this._deferredLogs = undefined; } if (deferred[i][0] === "exposure") exposed = true; this._logEvent(deferred[i][0], deferred[i][1]); - if (cutoff) { - const generated: [EventName, Record | Error][] = this._deferredLogs ?? []; - this._deferredLogs = generated.concat(remainder ?? []); - this._deliverDeferredLogs(); + if (remainder !== undefined) { + if (remainder.length > 0) { + this._deferredLogs = remainder; + this._deliverDeferredLogs(); + } break; } } From 9bf3d5c5f3ad5d81c6d36bff8ca474be6034a3ac Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 26 Nov 2026 16:36:41 +0000 Subject: [PATCH 83/92] test(context): pin a second extra read queued before the replay cutoff With one read queued before the 1,024-callback cutoff and another from the cutoff callback, each is delivered once: the cutoff empties the next-round queue it takes over. Drops a stale duplicated comment. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/context.test.js | 44 ++++++++++++++++++++--------------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 5bd83c3..bd54ea3 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -7107,25 +7107,29 @@ describe("Context", () => { expect(context.pending()).toBe(width + 1); }); - // 2,000 callbacks wait in one round, so the 1,024-callback budget is spent mid-round. The ones - // still waiting at the cutoff, and the read the cutoff callback makes, are each delivered once, - // in queue order, without another replay round. // 2,000 callbacks wait in one round, so the 1,024-callback budget is spent mid-round. A read made // from a callback before the cutoff, from the cutoff callback itself, or after it is delivered once // with everything else: the cutoff callback's own callbacks first, then the round's remaining ones, // then those earlier callbacks queued for the next round. After the cutoff, delivery is inline as in // 1.13.4, so a read made from a later callback runs right after it. it.each([ - ["exp_w5", 2000], - ["exp_w1022", 2000], - ["exp_w1023", 1024], - ["exp_w1500", 1501], + [["exp_w5"], [2000]], + [["exp_w1022"], [2000]], + [["exp_w1023"], [1024]], + [["exp_w1500"], [1501]], + // Two extra reads, one queued before the cutoff and one from the cutoff callback: each is + // delivered once, so the cutoff empties the next-round queue it has taken over. + [ + ["exp_w5", "exp_w1023"], + [2001, 1024], + ], ])( - "delivers every callback when the budget runs out mid-round (extra read from %s)", - (trigger, position) => { + "delivers every callback when the budget runs out mid-round (extra reads from %j)", + (triggers, positions) => { const width = 2000; + const extra = triggers.map((_, k) => width + k); const experiments = []; - for (let i = 0; i <= width; i++) { + for (let i = 0; i < width + extra.length; i++) { experiments.push({ ...holdoutVarExperiment({}), id: 100 + i, @@ -7141,16 +7145,17 @@ describe("Context", () => { } const names = []; let fanned = false; - let nested = false; + const pendingTriggers = new Map(triggers.map((trigger, k) => [trigger, extra[k]])); const eventLogger = jest.fn((ctx, eventName, data) => { if (eventName !== "exposure") return; names.push(data.name); if (!fanned) { fanned = true; for (let i = 1; i < width; i++) ctx.variableValue(`w${i}`, "D"); - } else if (!nested && data.name === trigger) { - nested = true; - ctx.variableValue(`w${width}`, "D"); + } else if (pendingTriggers.has(data.name)) { + const read = pendingTriggers.get(data.name); + pendingTriggers.delete(data.name); + ctx.variableValue(`w${read}`, "D"); } }); const context = new Context( @@ -7160,13 +7165,14 @@ describe("Context", () => { buildHoldoutResponse(experiments, []) ); expect(context.variableValue("w0", "D")).toBe(0); - expect(names).toHaveLength(width + 1); - expect(new Set(names).size).toBe(width + 1); - expect(names.indexOf(`exp_w${width}`)).toBe(position); - expect(names.filter((n) => n !== `exp_w${width}`)).toEqual( + const total = width + extra.length; + expect(names).toHaveLength(total); + expect(new Set(names).size).toBe(total); + expect(extra.map((read) => names.indexOf(`exp_w${read}`))).toEqual(positions); + expect(names.filter((n) => !extra.some((read) => n === `exp_w${read}`))).toEqual( Array.from({ length: width }, (_, i) => `exp_w${i}`) ); - expect(context.pending()).toBe(width + 1); + expect(context.pending()).toBe(total); expect(context._deferredLogs).toBeUndefined(); } ); From 452fbbfdc3d5df3fee747caf2b1e209b23262c99 Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 26 Nov 2026 19:18:41 +0000 Subject: [PATCH 84/92] fix(switchback): hash only the encoded key bytes; revalidate audiences like a fresh read - The switchback cluster key is hashed from exactly the bytes the encoder returned. A TextEncoder polyfill can hand back a view over a larger buffer, which put the same cluster in a different arm than the native encoder. - A cached switchback slot treats an indeterminate (null-parent) strict audience as a match, as a fresh assignment does, so a unit that once failed the audience no longer stays on control while a fresh context with the same attributes serves its arm. A throwing getter still fails closed. - Comment cleanup from review. Co-Authored-By: Claude Opus 5.5 --- scripts/__tests__/check-release.test.js | 3 +- src/__tests__/context-switchback.test.js | 51 ++++++++++++++++++++++++ src/__tests__/context.test.js | 1 - src/__tests__/switchback.test.js | 28 +++++++++++++ src/context.ts | 6 +-- src/switchback.ts | 4 +- 6 files changed, 86 insertions(+), 7 deletions(-) diff --git a/scripts/__tests__/check-release.test.js b/scripts/__tests__/check-release.test.js index a879425..bd61cdb 100644 --- a/scripts/__tests__/check-release.test.js +++ b/scripts/__tests__/check-release.test.js @@ -200,8 +200,7 @@ describe("publish workflow", () => { 120000 ); - // Every publish step must contain exactly one `npm publish` (on its own line), so the effective dry-run - // check above covers all of them: a second command in a manual step could otherwise publish for real. + // The dry-run probe above inspects one command per step, so a second command would go unchecked. test("each publish step runs exactly one npm publish command", () => { for (const step of job.steps.filter((s) => /\bnpm\s+publish\b/.test(s.run || ""))) { const commands = step.run.split("\n").filter((l) => /\bnpm\s+publish\b/.test(l)); diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index 9cb5f01..d0584c4 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -699,6 +699,57 @@ describe("switchback serving through Context", () => { expect(await publishExposures(context)).toEqual([strictMismatchExposure(ANCHOR + HOUR)]); }); + // A strict audience read below a parent that is now null is indeterminate, which counts as a + // match on a fresh assignment; a slot cached while the audience failed must agree with it. + it("serves a cached strict-mismatch slot like a fresh context once its audience is indeterminate", () => { + const PLAN_AUDIENCE = '{"filter":[{"eq":[{"var":"user/plan"},{"value":"pro"}]}]}'; + const make = () => { + const experiment = sb(2, HOUR); + experiment.audience = PLAN_AUDIENCE; + experiment.audienceStrict = true; + experiment.fullOnVariant = 1; + return createContext(dataOf(experiment)); + }; + const error = jest.spyOn(console, "error").mockImplementation(() => {}); + try { + clock = ANCHOR + HOUR; + const cached = make(); + cached.attribute("user", { plan: "free" }); + expect(cached.peek("exp_sb")).toEqual(0); + cached.attribute("user", null); + const fresh = make(); + fresh.attribute("user", null); + expect(fresh.treatment("exp_sb")).toEqual(1); + expect(cached.treatment("exp_sb")).toEqual(1); + cached.attribute("user", { plan: "free" }); + expect(cached.treatment("exp_sb")).toEqual(0); + } finally { + error.mockRestore(); + } + }); + + it("keeps a cached strict-mismatch slot on control when an unrelated getter throws", () => { + const PLAN_AUDIENCE = '{"filter":[{"eq":[{"var":"user/plan"},{"value":"pro"}]}]}'; + const experiment = sb(2, HOUR); + experiment.audience = PLAN_AUDIENCE; + experiment.audienceStrict = true; + experiment.fullOnVariant = 1; + const eventLogger = jest.fn(); + const context = createContext(dataOf(experiment), undefined, eventLogger); + clock = ANCHOR + HOUR; + context.attribute("user", { plan: "free" }); + expect(context.peek("exp_sb")).toEqual(0); + const user = {}; + Object.defineProperty(user, "plan", { + get() { + throw new TypeError("getter boom"); + }, + }); + context.attribute("user", user); + expect(context.treatment("exp_sb")).toEqual(0); + expect(eventLogger.mock.calls.some(([, eventName]) => eventName === "error")).toBe(true); + }); + // Runs in period 1, whose draw is 1, so the variant 0 is the strict mismatch's control. it("publishes a strict audience mismatch exactly", async () => { const experiment = sb(2, HOUR); diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index bd54ea3..1d5263f 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -7099,7 +7099,6 @@ describe("Context", () => { buildHoldoutResponse(experiments, []) ); expect(context.variableValue("w0", "D")).toBe(0); - // Every waiting callback was delivered, in the order its read was made, before the nested one. expect(names.slice(0, width)).toEqual(Array.from({ length: width }, (_, i) => `exp_w${i}`)); expect(names[width]).toBe(`exp_w${width}`); expect(nestedAt).toBe(nestedDepth); diff --git a/src/__tests__/switchback.test.js b/src/__tests__/switchback.test.js index a4497cc..2cdf249 100644 --- a/src/__tests__/switchback.test.js +++ b/src/__tests__/switchback.test.js @@ -193,6 +193,34 @@ describe("switchback assigner", () => { }); }); +describe("switchback cluster-key encoding", () => { + // A TextEncoder polyfill can return a view over a larger backing buffer; only the view's bytes are + // the encoded key, so the arm must not change. + it("hashes only the encoded bytes when the encoder returns a view over a larger buffer", () => { + const native = global.TextEncoder; + const keys = ["region-😀", "store-42", "cafe\u0301", "x\ud800y"]; + const expected = keys.map((key) => assignSwitchbackPeriod(key, 0, 0, 0, 3)); + const expected10 = keys.map((key) => assignSwitchbackPeriod(key, 7, -5, -7, 10)); + try { + global.TextEncoder = class { + encode(value) { + const bytes = new native().encode(value); + const padded = new Uint8Array(bytes.length + 19); + padded.fill(0xa5); + padded.set(bytes, 7); + return padded.subarray(7, 7 + bytes.length); + } + }; + expect(keys.map((key) => assignSwitchbackPeriod(key, 0, 0, 0, 3))).toEqual(expected); + expect(keys.map((key) => assignSwitchbackPeriod(key, 7, -5, -7, 10))).toEqual(expected10); + global.TextEncoder = undefined; + expect(keys.map((key) => assignSwitchbackPeriod(key, 0, 0, 0, 3))).toEqual(expected); + } finally { + global.TextEncoder = native; + } + }); +}); + describe("switchback attribute paths", () => { it("matches every platform path case", () => { const cases = pathCases.cases; diff --git a/src/context.ts b/src/context.ts index a906d70..c6873c2 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1167,8 +1167,10 @@ export default class Context { if ((rule?.variant ?? null) !== (assignment.ruleVariant ?? null)) return false; if (!assignment.ruleOverride && data.audience && data.audience.length > 0) { + // An indeterminate result counts as a match, as on a fresh assignment, so a cached slot and a + // fresh context with the same attributes serve the same arm. const result = this._evaluateAudience(data.audience); - const audienceMismatch = result !== null ? !result : assignment.audienceMismatch; + const audienceMismatch = typeof result === "boolean" ? !result : false; if (audienceMismatch !== assignment.audienceMismatch) return false; } @@ -1621,7 +1623,6 @@ export default class Context { return this._attrs.map((x) => ({ name: x.name, value: x.value, setAt: x.setAt })); } - // Opt-in path: detect user-set sdk_name/sdk_version in the same pass instead of a separate name set. let userSetSdkName = false; let userSetSdkVersion = false; const userAttributes = this._attrs.map((x) => { @@ -2014,7 +2015,6 @@ export default class Context { data: experiment, variables, holdouts, - // Only a non-empty string carries rules; anything else (a malformed payload) has none. ruleKey: typeof experiment.assignmentRules === "string" && experiment.assignmentRules ? `${experiment.assignmentRules}:${this._environmentName}` diff --git a/src/switchback.ts b/src/switchback.ts index 36cb5fb..20ecb0a 100644 --- a/src/switchback.ts +++ b/src/switchback.ts @@ -18,7 +18,9 @@ export function requireValidArmCount(armCount: number) { // surrogate encodes as '?', as the platform's String.getBytes(UTF_8) does. export function baseHash(clusterUnit: string, cycleIndex: string, seedHi: number, seedLo: number): number { const key = toWellFormedString(`${clusterUnit}\u001f${cycleIndex}`, "?"); - const keyHash = murmur3_32(stringToUtf8Array(key).buffer); + // Copy to an exact-length buffer: an encoder may return a view over a larger one. + const bytes = stringToUtf8Array(key); + const keyHash = murmur3_32(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)); const buffer = new ArrayBuffer(12); const view = new DataView(buffer); From d0465fcd1ae6ba4f8a74847c9ab585d45b1d70bd Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 26 Nov 2026 19:39:21 +0000 Subject: [PATCH 85/92] fix(switchback): copy the cluster key with Uint8Array, which IE 10 has The exact-length copy used ArrayBuffer.prototype.slice, which IE 10 lacks and the browser build does not polyfill, so every eligible switchback read threw there. A Uint8Array copy hashes the same bytes and exists in IE 10. check-es5 now runs a switchback over 12 periods in an IE 10 realm without TextEncoder or ArrayBuffer.prototype.slice and requires Node's arms, so this cannot come back. A test now pins one exposure for a rule-won switchback slot whose strict audience fails across an unrelated attribute change. Co-Authored-By: Claude Opus 5.5 --- scripts/check-es5.js | 58 ++++++++++++++++++++++++ src/__tests__/context-switchback.test.js | 16 +++++++ src/switchback.ts | 6 +-- 3 files changed, 77 insertions(+), 3 deletions(-) diff --git a/scripts/check-es5.js b/scripts/check-es5.js index 6d41460..988c2ff 100644 --- a/scripts/check-es5.js +++ b/scripts/check-es5.js @@ -4,6 +4,9 @@ const path = require("path"); const acorn = require("acorn"); const vm = require("vm"); +// The arms Node (native TextEncoder) serves for this probe; IE 10 must serve the same ones. +const EXPECTED_IE10_SWITCHBACK_ARMS = [0, 2, 1, 0, 1, 2, 1, 0, 2, 1, 2, 0]; + let failed = false; for (const file of ["absmartly.js", "absmartly.min.js"]) { const target = path.resolve(__dirname, "../dist", file); @@ -44,6 +47,13 @@ for (const file of ["absmartly.js", "absmartly.min.js"]) { console.error(`dist/${file} breaks a null-parent audience on IE 10: ${error.message}`); failed = true; } + try { + checkIe10Switchback(target); + console.log(`IE 10 switchback OK: dist/${file}`); + } catch (error) { + console.error(`dist/${file} breaks a switchback on IE 10: ${error.message}`); + failed = true; + } } // IE 10 has no Reflect, Object.setPrototypeOf or __proto__. A null-parent audience path must stay @@ -84,4 +94,52 @@ function checkIe10NullParentAudience(target) { throw new Error(`expected variant 1 and 0 error events, got ${JSON.stringify(result)}`); } } +// IE 10 has no TextEncoder and no ArrayBuffer.prototype.slice. A switchback must still resolve its +// cluster's scheduled arm there, the same arm Node gives (12 hourly periods of a 3-arm schedule). +function checkIe10Switchback(target) { + const sandbox = { + setTimeout, + clearTimeout, + setInterval, + clearInterval, + Promise, + console: { ...console, error() {} }, + }; + sandbox.self = sandbox; + const context = vm.createContext(sandbox); + vm.runInContext("delete this.TextEncoder; delete ArrayBuffer.prototype.slice;", context); + vm.runInContext(fs.readFileSync(target, "utf8"), context, { timeout: 10000 }); + const probe = `(function () { + var errors = 0; + var sdk = new absmartly.SDK({ endpoint: "http://x/v1", apiKey: "k", application: "web", environment: "prod", + eventLogger: function (c, name) { if (name === "error") errors++; } }); + var exp = { id: 1, name: "sb", iteration: 1, unitType: "store_id", seedHi: -5, seedLo: -7, + split: [1 / 3, 1 / 3, 1 / 3], trafficSeedHi: 1, trafficSeedLo: 2, trafficSplit: [0, 1], fullOnVariant: 0, + applications: [{ name: "web" }], variants: [{ name: "A", config: null }, { name: "B", config: null }, + { name: "C", config: null }], audience: null, audienceStrict: false, customFieldValues: null, + randomizationType: "switchback", switchbackClusters: { store_id: "store_key" }, + switchbackStartAt: 1767225600000, switchbackPeriodMs: 3600000, switchbackCarryoverDurationMs: 0, + switchbackBurnInDurationMs: 0, switchbackBurnOutDurationMs: 0, switchbackDesignType: "balanced_block", + switchbackEstimand: "global_average_treatment_effect" }; + var arms = []; + var now = Date.now; + try { + for (var period = 0; period < 12; period++) { + Date.now = function () { return 1767225600000 + period * 3600000 + 1; }; + var ctx = sdk.createContextWith({ units: { store_id: "u" } }, { experiments: [exp] }); + ctx.attribute("store_key", "store-😀-42"); + arms.push(ctx.treatment("sb")); + } + } finally { + Date.now = now; + } + return { arms: arms, errors: errors }; + })()`; + const result = vm.runInContext(probe, context); + const expected = JSON.stringify(EXPECTED_IE10_SWITCHBACK_ARMS); + if (JSON.stringify(result.arms) !== expected || result.errors !== 0) { + throw new Error(`expected arms ${expected} and 0 error events, got ${JSON.stringify(result)}`); + } +} + process.exitCode = failed ? 1 : 0; diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index d0584c4..e6062a2 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -701,6 +701,22 @@ describe("switchback serving through Context", () => { // A strict audience read below a parent that is now null is indeterminate, which counts as a // match on a fresh assignment; a slot cached while the audience failed must agree with it. + // A rule win does not consult the audience, so an unrelated attribute change must not rebuild the + // slot and queue a second exposure for a unit the strict audience rejects. + it("keeps one exposure for a rule-won slot whose strict audience fails across an attribute change", async () => { + const experiment = sb(2, HOUR); + experiment.assignmentRules = ASSIGN_VARIANT_1; + experiment.audience = STRICT_GOLD_AUDIENCE; + experiment.audienceStrict = true; + const context = createContext(dataOf(experiment)); + clock = ANCHOR + HOUR; + expect(context.treatment("exp_sb")).toEqual(1); + context.attribute("unrelated", "x"); + expect(context.treatment("exp_sb")).toEqual(1); + const exposures = await publishExposures(context); + expect(exposures.map((x) => [x.name, x.variant, x.ruleOverride])).toEqual([["exp_sb", 1, true]]); + }); + it("serves a cached strict-mismatch slot like a fresh context once its audience is indeterminate", () => { const PLAN_AUDIENCE = '{"filter":[{"eq":[{"var":"user/plan"},{"value":"pro"}]}]}'; const make = () => { diff --git a/src/switchback.ts b/src/switchback.ts index 20ecb0a..4d65e41 100644 --- a/src/switchback.ts +++ b/src/switchback.ts @@ -18,9 +18,9 @@ export function requireValidArmCount(armCount: number) { // surrogate encodes as '?', as the platform's String.getBytes(UTF_8) does. export function baseHash(clusterUnit: string, cycleIndex: string, seedHi: number, seedLo: number): number { const key = toWellFormedString(`${clusterUnit}\u001f${cycleIndex}`, "?"); - // Copy to an exact-length buffer: an encoder may return a view over a larger one. - const bytes = stringToUtf8Array(key); - const keyHash = murmur3_32(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)); + // Copied into an exact-length array: an encoder may return a view over a larger buffer. The + // Uint8Array copy, unlike ArrayBuffer.prototype.slice, also exists in IE 10. + const keyHash = murmur3_32(new Uint8Array(stringToUtf8Array(key)).buffer); const buffer = new ArrayBuffer(12); const view = new DataView(buffer); From 4e205d63dd4317b299bf709d0aed4dccfaa33a9f Mon Sep 17 00:00:00 2001 From: lux worker Date: Thu, 26 Nov 2026 22:32:12 +0000 Subject: [PATCH 86/92] feat: ship the owner-selected 1.14.0 batch (owner decision 2026-11-26) Put back items 1-5, 7-15, 17 and 19 of the 1.14.0 inventory; 6, 16 and 18 stay reverted: - canonical UTF-8 unit hashing (only IDs with characters outside the BMP move) - required Exposure.ruleOverride, ready(): Promise - Client sends auth headers by default; `auth` is deprecated and `auth: true` warns; getUnauthed() is get(); getContext() calls get() - SDK ignores explicitly undefined client options - string application versions in ClientOptions; numeric X-Application-Version - timeout: 0 means no deadline - ABsmartly error brand; custom-field, invalid audience JSON and failed-flush diagnostics are logger error events - getUnits() returns a copy; custom clients must implement the getters The 1.13.4 compatibility runner accepts exactly these documented breaks and fails on any other difference. CHANGELOG, README and the release inventory record who is affected. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 63 ++- README.md | 9 +- release/1.14.0-compatibility.md | 98 ++--- scripts/compatibility/run.js | 67 ++- src/__tests__/client.test.js | 78 +++- src/__tests__/constructor-types.ts | 18 +- src/__tests__/context.test.js | 67 +-- src/__tests__/fixtures/unit-hash-1.13.4.json | 293 +++++++++++++ src/__tests__/release-compatibility.test.js | 427 ++++++++----------- src/__tests__/sdk.test.js | 17 +- src/__tests__/utils.test.js | 117 ++++- src/client.ts | 49 +-- src/context.ts | 68 ++- src/matcher.ts | 3 +- src/sdk.ts | 20 +- src/utils.ts | 35 +- 16 files changed, 949 insertions(+), 480 deletions(-) create mode 100644 src/__tests__/fixtures/unit-hash-1.13.4.json diff --git a/CHANGELOG.md b/CHANGELOG.md index f1ad3df..eed60e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,9 +10,10 @@ - Semantic-version expression operators (`semver_eq/gt/gte/lt/lte`) and `Evaluator.versionCompare`; old expression operators keep their conversion rules. - Optional `includeSystemAttributes` publishes `sdk_name` and `sdk_version` only. -- The `SDK` and `Client` constructors also accept a string application version - (`application: { name, version: "1.2.3" }`) through the new `ClientInputOptions` - overload. `ClientOptions` and the constructors' released signatures are unchanged. +- The `SDK` and `Client` constructors accept a string application version + (`application: { name, version: "1.2.3" }`): `ClientOptions.application.version` + is now `number | string`, and the deprecated `ClientInputOptions` is an alias of + `ClientOptions`. TypeScript code that reads `version` as a `number` must narrow it. - Tag-driven npm Trusted Publishing, a manual dry-run package preflight (it does not prove authentication works: npm may try to obtain an OIDC token but skips the upload), and a `repository` field in `package.json`, which npm provenance requires. @@ -34,6 +35,12 @@ ### Changed +- Unit IDs are hashed as canonical UTF-8, as the collector and the other SDKs hash + them. Unit IDs that contain a character outside the Basic Multilingual Plane + (such as an emoji) can get a different variant after upgrading: 1.13.4 hashed + each such character from its two UTF-16 surrogate halves. All other IDs keep their + 1.13.4 hash and variant, including ASCII, accented and CJK text, and IDs with an + unpaired surrogate. Who moves: units whose IDs contain characters outside the BMP. - Switchback experiments that are already running change assignment for this SDK: before, they were served as a sticky unit assignment on their `unitType` (or not at all), which did not follow the switchback schedule. Now each unit @@ -50,8 +57,8 @@ holdout suppression (explicit overrides still win). A rule win publishes `ruleOverride: true`; every other exposure publishes `ruleOverride: false`. Affected: experiments configured with rules, and custom publishers/event loggers - or wire consumers comparing complete exposure shapes. The type field is optional - so existing customer-authored `Exposure` literals still compile. + or wire consumers comparing complete exposure shapes. `Exposure.ruleOverride` is a + required field, so customer-authored `Exposure` literals must add it to compile. - Audiences and rule conditions always see configured non-empty `application` and `environment`; explicit user attributes win. Rule environment scope uses the configured environment. No synthetic `app_version` is injected or published; @@ -65,11 +72,39 @@ `absmartly-javascript-sdk`. Affected: export/dashboard filters matching the old agent exactly. Explicit customer agent strings are preserved. - `GET /context` sends SDK authentication/metadata headers as well as the existing - query parameters, like PUT. The low-level `request()`, `post()`, `put()` and - `getUnauthed()` keep their 1.13.4 header rules. - `X-Application-Version` sends only 1–18 ASCII digits (trimmed), or `0` otherwise. - Affected: proxies inspecting GET headers and apps configuring invalid version - headers that previously caused collector HTTP 400 errors. + query parameters, like PUT. `getContext()` calls `get()` directly, so a subclass + overriding `getUnauthed()` is no longer called for it. + `X-Application-Version` sends only 1–18 ASCII digits (trimmed), or `0` otherwise; + `getApplication()` still returns the configured version. Affected: proxies + inspecting GET headers and apps configuring invalid version headers that + previously caused collector HTTP 400 errors. +- Low-level `Client` requests send the API key headers by default: `request()`, + `post()`, `put()`, `get()` and the deprecated `getUnauthed()` (now the same as + `get()`) send them unless the request passes `auth: false`. 1.13.4's `request()` + sent them only with `auth: true`, `getUnauthed()` never did, and `post()`/`put()` + ignored `auth: false`. The `auth` option is deprecated: `auth: true` logs a + `console.warn` per request. Affected: code calling the `Client` directly. +- The `SDK` constructor ignores `agent`, `timeout`, `keepalive` and the other client + options when they are explicitly `undefined`, so the defaults apply (1.13.4 passed + `agent: undefined` through and the `Client` rejected it). +- `ready()` is declared `Promise` (1.13.4 declared `Promise`); it + resolves `true` as before, even when loading fails. +- `getUnits()` returns a copy: editing it no longer changes the context's units. + Use `unit()` or `units()`. Affected: code that set units through the returned map. +- Error messages use the `ABsmartly` brand: `"ABsmartly Context is not yet ready."`, + `"... is finalizing."` and `"... is finalized."` (1.13.4 wrote `ABSmartly`). + Affected: code matching those strings exactly. +- Diagnostics that 1.13.4 wrote with `console.error` are logger `error` events: an + invalid JSON custom field value (`null` is still returned; the message now ends with + the parser error), an unknown custom field type, and invalid audience JSON + (`Invalid audience JSON: ...`; the audience is still ignored). A `publish()` or + `finalize()` on a context that failed to load emits an `error` event + `Discarding N exposures and M goals because context failed to initialize` before + discarding them. Affected: event loggers that treat every `error` event as fatal, + and log scrapers. +- A custom `client` passed to the SDK must implement `getApplication()`, + `getEnvironment()` and `getAgent()` (the bundled `Client` has them); creating a + context with a client that lacks them throws a `TypeError`. - `variableValue()` no longer queues an exposure for an experiment the unit is not in (strict audience mismatch, or no unit for its unit type), even when that is the only experiment defining the key; 1.13.4 published one with @@ -81,8 +116,10 @@ - A per-request `timeout` now also bounds the retry budget; 1.13.4 always used the client timeout for it. Affected: callers passing a per-request `timeout` that differs from the client one, who now get more (or fewer) retries to match it. - `timeout: 0` keeps its 1.13.4 meaning: a request value of 0 falls back to the - client timeout, and a client timeout of 0 means no retries. + `timeout: 0` now means no deadline: a request value of 0 no longer falls back to + the client timeout, and the request retries up to `retries` times without a time + limit (1.13.4 used the client timeout, and did not retry when that was 0 too). Affected: callers configuring + `timeout: 0`, whose requests can now wait indefinitely for a slow server. - An audience whose evaluation throws now counts as a mismatch (fail closed) and emits one logger `error` event; in 1.13.4 it was ignored, so strict audiences could let users through. Affected: strict audiences with, for example, a throwing @@ -114,7 +151,7 @@ like any other name. 1.13.4 returned `{}` as the variant, lost custom assignments, threw for unknown experiments and for unit types such as `toString`, and re-exposed an experiment named `__proto__` on every - `treatment()`. `getUnits()` still returns the same plain object. + `treatment()`. - Shared variable keys now pick and expose one experiment, as the Java SDK does. Previously `variableValue()` exposed every experiment it checked that had the key, including ones the unit was not in (for example a strict audience diff --git a/README.md b/README.md index 75b2678..1ea8333 100644 --- a/README.md +++ b/README.md @@ -580,8 +580,13 @@ document.getElementById("checkout-btn").addEventListener("click", () => { ## Upgrading from 1.13.4 -1.14.0 retains the 1.x API, error strings and unit hashing (including legacy surrogate -encoding), Node 6 / npm 3 runtime floor and IE 10 browser target. The build and publish +1.14.0 retains the 1.x API, Node 6 / npm 3 runtime floor and IE 10 browser target. +Check the CHANGELOG's Changed section before upgrading: error strings now use the +`ABsmartly` brand, `getUnits()` returns a copy, low-level `Client` requests +authenticate by default, `timeout: 0` means no deadline, and some console +diagnostics are now logger `error` events. Unit IDs are now hashed as canonical UTF-8: an ID with a character +outside the Basic Multilingual Plane (such as an emoji) can get a different variant, +and every other ID keeps its 1.13.4 variant. The build and publish toolchain uses modern Node; that does not raise the consumer runtime floor. See [CHANGELOG.md](CHANGELOG.md) for the agreed targeting and wire changes and who is diff --git a/release/1.14.0-compatibility.md b/release/1.14.0-compatibility.md index 6d42b89..b234f7a 100644 --- a/release/1.14.0-compatibility.md +++ b/release/1.14.0-compatibility.md @@ -14,55 +14,55 @@ Classes: **a** additive; **b** agreed cross-SDK contract; **c** genuine bug fix; **d** unrelated compatibility/behaviour change (restore the published contract). This inventories public source/runtime differences, not just this PR's delta. -| Change since published 1.13.4 | Class | Action for 1.14.0 | -| ------------------------------------------------------------------------------------------------------------------------------------------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `ABsmartly` alias in CJS/ES/browser exports | a | Keep alongside `SDK`; no old entry point removed. | -| `Client.getApplication/getEnvironment/getAgent/get`, `ApplicationObject` | a | Keep; string application still accepted. | -| `Context.getSDK/getOptions/readyError` | a | Keep. | -| Optional experiment assignment rules, variant name, holdout IDs; new holdout model types | a/b | Keep optional; no new required customer payload fields. | -| `AudienceMatcher.parseRules/evaluateRules/evaluateParsedRules`, `RuleAction` | a/b | Keep assignment/split rules with strict types, environment scoping, malformed-rule isolation, override precedence and missing-unit pinning. | -| `semver_*` operators, `Evaluator.versionCompare` | a/b | Keep; old `stringConvert`, `eq`, `in`, match behaviour remains unchanged. | -| `includeSystemAttributes` option | a/b | Keep opt-in publishing of SDK name/version; never synthetic app/environment/app_version publishing. | -| Synthetic application/environment in evaluation, user values win | b | Keep and document affected targeting under Changed; empty names absent, no synthetic app_version. | -| Assignment rules override audience/traffic/full-on/custom/holdouts | b | Keep and document affected experiments under Changed. | -| Required `Exposure.ruleOverride` source field on main | d | Make optional for old model literals; runtime always emits true/false (b). | -| Holdout suppression, control variable fallback and holdout exposures | b | Keep; document payload-linked experiments under Changed. | -| Shared variable resolution/id ordering/map-of-lists | b | Keep; released return shape unchanged. | -| GET SDK auth/metadata headers | b | Keep; preserve query parameters. | -| Low-level `Client` auth rules: `request()` authenticated by default, `post`/`put` honoured `auth:false`, `getUnauthed` became authenticated | d | Restore 1.13.4 rules exactly: `request()` sends headers only with `auth: true`, `post`/`put` always authenticate, `getUnauthed` is a plain GET. The additive `get()` (used by `getContext`) authenticates unless `auth: false`. | -| `SDK` dropped client options passed as explicit `undefined` (`agent`, `timeout`, `keepalive`) | d | Restore 1.13.4 pass-through of every present key; `agent: undefined` again reaches the Client and is rejected. | -| Versioned SDK X-Agent | b | Add from generated package version; custom agent untouched. Direct `Client` default remains `javascript-client`. | -| String application version accepted; utility return widened | a/d | Keep strings through additive `ClientInputOptions`; preserve the exported numeric `ClientOptions.application.version` and the numeric utility overload for old readers. | -| Invalid/dotted application versions sent to collector Long header | c/b | Normalize GET and PUT to trimmed 1–18 ASCII digits or zero; retain full configured getter. | -| Every publish adds `sdkVersion`, required `PublishParams.sdkVersion` | d | Restore 1.13 body/type; collector `PublishRequest` ignores this unknown field. SDK version remains in X-Agent and opt-in attributes. | -| New normal-path auth deprecation warning | d | Remove; explicit auth still accepted without new stderr output. | -| Error brand casing `ABSmartly` → `ABsmartly` | d | Restore byte-identical 1.13 not-ready/finalizing/finalized messages. | -| Custom-field console diagnostics changed to logger error events and JSON parser suffix | d | Restore released console sink/messages, null return and no new error events. | -| Failed-context flush adds discard error event | d | Restore silent discard after initial load error; preserve settlement/queue cleanup. | -| `getUnits()` changes live map to defensive copy | d | Restore live map and original `Units` return type. | -| `getAttribute()` return changes from incorrect `undefined` declaration to `unknown` | c/d | Use `any` for compatibility with both strict and non-strict existing consumers; actual last-value behaviour unchanged. | -| `ready(): Promise` narrows to boolean and README claims old errors | d | Restore declared Promise; published runtime already resolves true even on failure. Correct README, do not invent migration. | -| `finalize()` inferred `true \| Promise` narrowed on main | d | Restore the released `true \| Promise` declaration, so old `=== true` guards compile; runtime was and remains Promise-only. | -| Canonical UTF-8 for astral/unpaired surrogate UIDs changes hashes/assignment | d | Restore legacy UTF-16-code-unit encoding for all 1.x hashes; canonical change preserved on next/major for 2.0. | -| Type-only inline imports raise declaration parser floor to TS4.5 | d | Restore old import syntax; TS3.9 consumer compile checks it. | -| New required getters on duck-typed custom clients | d | Guard getters so existing custom clients don't crash context installation/evaluation. | -| Abort shim reason/onabort/optional abort reason and idempotence | a/c | Keep native-standard cancellation bug fixes; no required method argument. | -| Fetch global detection and clear no-fetch error | c | Keep fallback selection fix (old no-global environment was unusable). | -| Query key escaping and malformed-surrogate normalization | c | Keep encoding fixes; ordinary URL values unchanged. | -| Per-request timeout bounds the retry budget (1.13.4 used the client timeout) | c | Keep; listed under Changed with who is affected, and covered by a mutant-killing test. | -| Invalid audience JSON stopped logging `console.error` | d | Restore the 1.13.4 console diagnostic; no logger `error` event. | -| Main made `timeout: 0` mean "no deadline" (request) and "retry forever" (client) | d | Restore 1.13.4: request 0 falls back to the client timeout, client 0 means no retries. Measured: main hangs > 8 s where 1.13.4 fails at ~3 s. | -| `getContext()` called `get()` directly, skipping a subclass `getUnauthed()` override | d | Route through `getUnauthed()` again, keeping the GET headers. | -| `rfdc` 1.4.1 (lockfile) puts ES2015 syntax into the browser bundle and needs `Map`/`Set` at load | d | Lockfile pins `rfdc` 1.3.1 (range `^1.3.0` unchanged); rfdc is still transpiled; `scripts/check-es5.js` fails the build unless `dist/` is ES5 and starts without native `Map`/`Set`. | -| Failed publisher loses events, synchronous failures and concurrent finalize races | c | Keep ordered restore/retry and promise settlement fixes. | -| Throwing event logger corrupts init/publish/finalize | c | Isolate observer exceptions; don't resend already-delivered batch. | -| Malformed/non-object variant config crashes or indexes invalid keys | c | Isolate invalid config; valid objects unchanged. | -| Audience evaluation exception fails open | c | An unexpected matcher error fails strict audiences closed with one `error` event. A path through a `null` attribute stays indeterminate (ignored), and an indeterminate result revalidates as a match, both exactly as in 1.13.4. | -| Unit hash caches missing unit forever | c | Don't memoize missing hash; rule/holdout late-unit handling retained. | -| New @babel/runtime production dependency and helper deduplication (owner call; kept) | a | Private build helper dependency, no exposed dependency types or major bump to existing dependencies; Node6 remains supported. | -| Node24 development tooling, husky/lint-staged, generate-version, build/prepare hooks | a | Build-only; package engines remain Node>=6/npm>=3, Babel CJS Node6 and IE10 browser targets unchanged. | -| Babel relative runtime paths, delete stale generated output, browser/CJS export packaging | c | Keep portable package output. | -| README restructuring/refreshPeriod correction | c | Keep; pin install/browser examples to 1.14.0 and replace misleading Breaking migration. | +| Change since published 1.13.4 | Class | Action for 1.14.0 | +| ------------------------------------------------------------------------------------------------------------------------------------------- | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ABsmartly` alias in CJS/ES/browser exports | a | Keep alongside `SDK`; no old entry point removed. | +| `Client.getApplication/getEnvironment/getAgent/get`, `ApplicationObject` | a | Keep; string application still accepted. | +| `Context.getSDK/getOptions/readyError` | a | Keep. | +| Optional experiment assignment rules, variant name, holdout IDs; new holdout model types | a/b | Keep optional; no new required customer payload fields. | +| `AudienceMatcher.parseRules/evaluateRules/evaluateParsedRules`, `RuleAction` | a/b | Keep assignment/split rules with strict types, environment scoping, malformed-rule isolation, override precedence and missing-unit pinning. | +| `semver_*` operators, `Evaluator.versionCompare` | a/b | Keep; old `stringConvert`, `eq`, `in`, match behaviour remains unchanged. | +| `includeSystemAttributes` option | a/b | Keep opt-in publishing of SDK name/version; never synthetic app/environment/app_version publishing. | +| Synthetic application/environment in evaluation, user values win | b | Keep and document affected targeting under Changed; empty names absent, no synthetic app_version. | +| Assignment rules override audience/traffic/full-on/custom/holdouts | b | Keep and document affected experiments under Changed. | +| Required `Exposure.ruleOverride` source field on main | b | Keep required (owner decision 2026-11-26); runtime always emits true/false. CHANGELOG Changed tells literal authors to add it. | +| Holdout suppression, control variable fallback and holdout exposures | b | Keep; document payload-linked experiments under Changed. | +| Shared variable resolution/id ordering/map-of-lists | b | Keep; released return shape unchanged. | +| GET SDK auth/metadata headers | b | Keep; preserve query parameters. | +| Low-level `Client` auth rules: `request()` authenticated by default, `post`/`put` honoured `auth:false`, `getUnauthed` became authenticated | b | Keep main (owner decision 2026-11-26): every request sends auth headers unless `auth: false`; `getUnauthed()` is a deprecated alias of `get()`. CHANGELOG Changed. | +| `SDK` dropped client options passed as explicit `undefined` (`agent`, `timeout`, `keepalive`) | c | Keep main (owner decision 2026-11-26): explicitly undefined options fall back to the defaults. CHANGELOG Changed. | +| Versioned SDK X-Agent | b | Add from generated package version; custom agent untouched. Direct `Client` default remains `javascript-client`. | +| String application version accepted; utility return widened | a/b | Keep main (owner decision 2026-11-26): `ClientOptions.application.version` is `number \| string`; `ClientInputOptions` is a deprecated alias. CHANGELOG Added. | +| Invalid/dotted application versions sent to collector Long header | c/b | Normalize GET and PUT to trimmed 1–18 ASCII digits or zero; retain full configured getter. | +| Every publish adds `sdkVersion`, required `PublishParams.sdkVersion` | d | Restore 1.13 body/type (kept reverted, owner decision 2026-11-26); collector `PublishRequest` ignores this unknown field. SDK version remains in X-Agent and opt-in attributes. | +| New normal-path auth deprecation warning | b | Keep (owner decision 2026-11-26): `auth: true` logs one `console.warn` per request. CHANGELOG Changed. | +| Error brand casing `ABSmartly` → `ABsmartly` | b | Keep `ABsmartly` (owner decision 2026-11-26). CHANGELOG Changed lists the three messages. | +| Custom-field console diagnostics changed to logger error events and JSON parser suffix | b | Keep logger `error` events and parser suffix (owner decision 2026-11-26); null return unchanged. CHANGELOG Changed. | +| Failed-context flush adds discard error event | b | Keep (owner decision 2026-11-26); settlement/queue cleanup unchanged. CHANGELOG Changed. | +| `getUnits()` changes live map to defensive copy | b | Keep the copy (owner decision 2026-11-26); `__proto__` unit types are copied as own keys. CHANGELOG Changed. | +| `getAttribute()` return changes from incorrect `undefined` declaration to `unknown` | c/d | Use `any` for compatibility with both strict and non-strict existing consumers; actual last-value behaviour unchanged. | +| `ready(): Promise` narrows to boolean and README claims old errors | b | Keep `Promise` (owner decision 2026-11-26); runtime already resolved true even on failure. README corrected, no invented migration. | +| `finalize()` inferred `true \| Promise` narrowed on main | d | Restore the released `true \| Promise` declaration, so old `=== true` guards compile; runtime was and remains Promise-only. | +| Canonical UTF-8 for astral/unpaired surrogate UIDs changes hashes/assignment | b | Adopt canonical UTF-8 (owner decision 2026-11-26): an ID with a character outside the BMP hashes as 4-byte UTF-8 and can change variant; BMP text and unpaired surrogates keep the 1.13.4 hash. Documented under CHANGELOG Changed. | +| Type-only inline imports raise declaration parser floor to TS4.5 | d | Restore old import syntax; TS3.9 consumer compile checks it. | +| New required getters on duck-typed custom clients | b | Keep required getters, no guards (owner decision 2026-11-26). CHANGELOG Changed. | +| Abort shim reason/onabort/optional abort reason and idempotence | a/c | Keep native-standard cancellation bug fixes; no required method argument. | +| Fetch global detection and clear no-fetch error | c | Keep fallback selection fix (old no-global environment was unusable). | +| Query key escaping and malformed-surrogate normalization | c | Keep encoding fixes; ordinary URL values unchanged. | +| Per-request timeout bounds the retry budget (1.13.4 used the client timeout) | c | Keep; listed under Changed with who is affected, and covered by a mutant-killing test. | +| Invalid audience JSON stopped logging `console.error` | b | Report it as a logger `error` event `Invalid audience JSON: ...` with no console output (owner decision 2026-11-26); audience still indeterminate. | +| Main made `timeout: 0` mean "no deadline" (request) and "retry forever" (client) | b | Keep main (owner decision 2026-11-26): request 0 has no deadline, client 0 retries up to `retries` without a time limit. CHANGELOG Changed. | +| `getContext()` called `get()` directly, skipping a subclass `getUnauthed()` override | b | Keep main (owner decision 2026-11-26): `getContext()` calls `get()`. CHANGELOG Changed. | +| `rfdc` 1.4.1 (lockfile) puts ES2015 syntax into the browser bundle and needs `Map`/`Set` at load | d | Lockfile pins `rfdc` 1.3.1 (range `^1.3.0` unchanged); rfdc is still transpiled; `scripts/check-es5.js` fails the build unless `dist/` is ES5 and starts without native `Map`/`Set`. | +| Failed publisher loses events, synchronous failures and concurrent finalize races | c | Keep ordered restore/retry and promise settlement fixes. | +| Throwing event logger corrupts init/publish/finalize | c | Isolate observer exceptions; don't resend already-delivered batch. | +| Malformed/non-object variant config crashes or indexes invalid keys | c | Isolate invalid config; valid objects unchanged. | +| Audience evaluation exception fails open | c | An unexpected matcher error fails strict audiences closed with one `error` event. A path through a `null` attribute stays indeterminate (ignored), and an indeterminate result revalidates as a match, both exactly as in 1.13.4. | +| Unit hash caches missing unit forever | c | Don't memoize missing hash; rule/holdout late-unit handling retained. | +| New @babel/runtime production dependency and helper deduplication (owner call; kept) | a | Private build helper dependency, no exposed dependency types or major bump to existing dependencies; Node6 remains supported. | +| Node24 development tooling, husky/lint-staged, generate-version, build/prepare hooks | a | Build-only; package engines remain Node>=6/npm>=3, Babel CJS Node6 and IE10 browser targets unchanged. | +| Babel relative runtime paths, delete stale generated output, browser/CJS export packaging | c | Keep portable package output. | +| README restructuring/refreshPeriod correction | c | Keep; pin install/browser examples to 1.14.0 and replace misleading Breaking migration. | ## Measurements diff --git a/scripts/compatibility/run.js b/scripts/compatibility/run.js index 8c71ead..a86d7c4 100644 --- a/scripts/compatibility/run.js +++ b/scripts/compatibility/run.js @@ -25,6 +25,41 @@ and pass --typescript-dir /tmp/compat-ts/node_modules. No root configuration cha The JSON report contains all changed declaration text and all runtime export names; it includes failures even when the command exits nonzero. Temporary files are removed.`); } +// Breaks from 1.13.4 the owner accepted for 1.14.0 (2026-11-26), each listed under CHANGELOG Changed. +// Only these exact differences pass; any other type error or runtime difference still fails the run. +const ACCEPTED_TYPE_ERRORS = [ + // `Exposure.ruleOverride` is required. + { + pattern: /error TS2741: Property 'ruleOverride' is missing in type '[^']*' but required in type 'Exposure'\.$/, + count: 1, + }, + // `ClientOptions.application.version` is `number | string`; the three released numeric readers must narrow it. + { pattern: /error TS2322: Type 'string \| number' is not assignable to type 'number'\.$/, count: 3 }, +]; +const ACCEPTED_TYPE_DETAIL = /^\s+Type 'string' is not assignable to type 'number'\.$/; +const ACCEPTED_RUNTIME_DIFFERENCES = [ + // Error strings use the `ABsmartly` brand. + 'runtime.errors.notReady.message: "ABSmartly Context is not yet ready." -> "ABsmartly Context is not yet ready."', + 'runtime.errors.finalized.message: "ABSmartly Context is finalized." -> "ABsmartly Context is finalized."', + // Canonical UTF-8 unit hashing: sweep entry 256 is the emoji UID "😀", outside the BMP. + "runtime.sweep.256.peek: 0 -> 1", + "runtime.sweep.256.treatment: 0 -> 1", +]; +function unacceptedTypeErrors(output) { + const counts = ACCEPTED_TYPE_ERRORS.map(() => 0); + const rest = []; + for (const line of output.split("\n")) { + if (!line.trim() || ACCEPTED_TYPE_DETAIL.test(line)) continue; + const index = ACCEPTED_TYPE_ERRORS.findIndex(({ pattern }) => pattern.test(line)); + if (index < 0) rest.push(line); + else counts[index]++; + } + ACCEPTED_TYPE_ERRORS.forEach(({ pattern, count }, i) => { + if (counts[i] !== count) + rest.push(`expected ${count} accepted error(s) matching ${pattern}, found ${counts[i]}`); + }); + return rest; +} function exec(command, args, options) { const result = child.spawnSync(command, args, { encoding: "utf8", ...options }); if (result.error) throw result.error; @@ -153,18 +188,38 @@ async function main() { ]) { const outcome = compile(tmp, path.join(compilerDir, "bin", "tsc"), pkg, `${alias}-${label}`); result.types[expected][label] = outcome; - console.log(`TypeScript ${expected} ${label}: ${outcome.passed ? "PASS" : "FAIL"}`); - if (!outcome.passed) { - console.error(outcome.output); + if (label === "candidate" && !outcome.passed) { + outcome.unaccepted = unacceptedTypeErrors(outcome.output); + outcome.accepted = outcome.unaccepted.length === 0; + } + const status = outcome.passed + ? "PASS" + : outcome.accepted + ? "PASS (accepted 1.14.0 breaks only)" + : "FAIL"; + console.log(`TypeScript ${expected} ${label}: ${status}`); + if (!outcome.passed) console.error(outcome.output); + if (!outcome.passed && !outcome.accepted) { + if (outcome.unaccepted) console.error(outcome.unaccepted.join("\n")); result.errors.push(`TypeScript ${expected} ${label} failed`); } } } try { result.runtime = await runtime(baseline, candidate); - if (result.runtime.errors && result.runtime.errors.length) { - result.errors.push(...result.runtime.errors.map((error) => `Runtime: ${error}`)); - for (const error of result.runtime.errors) console.error(`Runtime: ${error}`); + const differences = result.runtime.errors || []; + for (const error of differences) { + if (ACCEPTED_RUNTIME_DIFFERENCES.includes(error)) console.log(`Runtime (accepted): ${error}`); + else { + result.errors.push(`Runtime: ${error}`); + console.error(`Runtime: ${error}`); + } + } + for (const accepted of ACCEPTED_RUNTIME_DIFFERENCES) { + if (!differences.includes(accepted)) { + result.errors.push(`Runtime: accepted difference no longer observed: ${accepted}`); + console.error(result.errors[result.errors.length - 1]); + } } } catch (err) { result.errors.push(`Runtime: ${err.stack || err}`); diff --git a/src/__tests__/client.test.js b/src/__tests__/client.test.js index e958a6c..b702c14 100644 --- a/src/__tests__/client.test.js +++ b/src/__tests__/client.test.js @@ -846,7 +846,7 @@ describe("Client", () => { }); }); - it("request() should send headers without a warning when auth is explicitly true", (done) => { + it("request() should still send headers when auth is explicitly true (deprecated)", (done) => { fetch.mockResolvedValueOnce(responseMock(200, "OK", defaultMockResponse)); const warnSpy = jest.spyOn(console, "warn").mockImplementation(); @@ -875,7 +875,9 @@ describe("Client", () => { signal: expect.any(Object), }); - expect(warnSpy).not.toHaveBeenCalled(); + expect(warnSpy).toHaveBeenCalledWith( + "[ABsmartly] The `auth` option is deprecated. Auth headers are now sent by default. Remove `auth: true` from your request options." + ); expect(response).toEqual(defaultMockResponse); @@ -941,7 +943,7 @@ describe("Client", () => { }); }); - it("getUnauthed() should retain its unauthenticated 1.13 behaviour", (done) => { + it("getUnauthed() should forward to get()", (done) => { fetch.mockResolvedValueOnce(responseMock(200, "OK", defaultMockResponse)); const client = new Client(clientOptions); @@ -955,6 +957,14 @@ describe("Client", () => { expect(fetch).toHaveBeenCalledTimes(1); expect(fetch).toHaveBeenLastCalledWith(`${endpoint}/context?application=test_app&environment=test`, { method: "GET", + headers: { + "Content-Type": "application/json", + "X-API-Key": apiKey, + "X-Agent": "javascript-client", + "X-Environment": "test", + "X-Application": "test_app", + "X-Application-Version": 1000000, + }, body: undefined, keepalive: true, signal: expect.any(Object), @@ -1217,39 +1227,61 @@ describe("Client", () => { expect(client).toBeInstanceOf(Client); }); - it("should not retry when the client timeout is 0, as in 1.13.4", (done) => { - fetch.mockRejectedValue(new Error("connection refused")); + it("should still retry a failing-then-succeeding request when timeout is 0 (no deadline)", (done) => { + fetch + .mockResolvedValueOnce(responseMock(500, "server error", "server error text")) + .mockResolvedValueOnce(responseMock(200, "OK", defaultMockResponse)); + const client = new Client(Object.assign({}, clientOptions, { timeout: 0, retries: 5 })); - client.request({ method: "PUT", path: "/context" }).catch(() => { - expect(fetch).toHaveBeenCalledTimes(1); - done(); - }); + client + .request({ + method: "GET", + path: "/context", + }) + .then((response) => { + expect(fetch).toHaveBeenCalledTimes(2); + expect(response).toEqual(defaultMockResponse); + + done(); + }); + + advanceFakeTimers(); }); - it("should fall back to the client timeout when a request timeout is 0", (done) => { - // Like a real fetch, reject once the request's signal aborts. + // A request timeout of 0 means no deadline for that request, not "use the client timeout". + it("should not abort a request whose own timeout is 0, even with a client timeout", (done) => { + let aborted = false; fetch.mockImplementation( (_url, opts) => - new Promise((_resolve, reject) => { + new Promise((resolve) => { opts.signal.addEventListener("abort", () => { - const error = new Error("aborted"); - error.name = "AbortError"; - reject(error); + aborted = true; }); + setTimeout(() => resolve(responseMock(200, "OK", defaultMockResponse)), 500); }) ); const client = new Client(Object.assign({}, clientOptions, { timeout: 200, retries: 0 })); - client.request({ method: "GET", path: "/context", timeout: 0 }).then( - () => done(new Error("expected the request to be aborted")), - (error) => { - expect(error.message).toBe("aborted"); - done(); - } - ); + client.request({ method: "GET", path: "/context", timeout: 0 }).then((response) => { + expect(aborted).toBe(false); + expect(response).toEqual(defaultMockResponse); + done(); + }, done); + + jest.advanceTimersByTime(500); + }); + + it("should retry without a deadline until the retries run out when timeout is 0", (done) => { + fetch.mockRejectedValue(new Error("connection refused")); + const client = new Client(Object.assign({}, clientOptions, { timeout: 0, retries: 4 })); + + client.request({ method: "PUT", path: "/context" }).catch(() => { + expect(fetch).toHaveBeenCalledTimes(5); + done(); + }); - jest.advanceTimersByTime(200); + advanceFakeTimers(); }); }); }); diff --git a/src/__tests__/constructor-types.ts b/src/__tests__/constructor-types.ts index 31845c4..30a4017 100644 --- a/src/__tests__/constructor-types.ts +++ b/src/__tests__/constructor-types.ts @@ -1,22 +1,22 @@ import SDK from "../sdk"; import Client from "../client"; +import { getApplicationVersion } from "../utils"; -// Included in tsc: ConstructorParameters uses the final overload, which must remain the released type. -export function sdkApplicationVersion(options: ConstructorParameters[0]): number { +// Compile-time pins for the 1.14.0 public types: application.version accepts a number or a string. +export function sdkApplicationVersion(options: ConstructorParameters[0]): number | string { return typeof options.application === "string" ? 0 : options.application.version; } -export function clientApplicationVersion(options: ConstructorParameters[0]): number { +export function clientApplicationVersion(options: ConstructorParameters[0]): number | string { return typeof options.application === "string" ? 0 : options.application.version; } -import { getApplicationVersion } from "../utils"; -export function releasedUtilityReturnType(value: ReturnType): number { - return value + 1; -} +export const stringApplicationVersions = [ + new SDK({ endpoint: "e", apiKey: "k", environment: "p", application: { name: "web", version: "1.2.3" } }), + new Client({ endpoint: "e", apiKey: "k", environment: "p", application: { name: "web", version: "1.2.3" } }), +]; -export const releasedDirectUtilityTypes: [number, number, number | string] = [ +export const directUtilityTypes: [number | string, number | string] = [ getApplicationVersion("web"), - getApplicationVersion({ name: "web", version: 3 }), getApplicationVersion({ name: "web", version: "1.2.3" }), ]; diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index 1d5263f..9f96773 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -612,12 +612,12 @@ describe("Context", () => { expect(context.isFinalized()).toEqual(false); expect(() => context.data()).toThrow(); - expect(() => context.treatment("test")).toThrow("ABSmartly Context is not yet ready."); - expect(() => context.peek("test")).toThrow("ABSmartly Context is not yet ready."); - expect(() => context.experiments()).toThrow("ABSmartly Context is not yet ready."); - expect(() => context.variableKeys()).toThrow("ABSmartly Context is not yet ready."); - expect(() => context.variableValue("a", 17)).toThrow("ABSmartly Context is not yet ready."); - expect(() => context.peekVariableValue("a", 17)).toThrow("ABSmartly Context is not yet ready."); + expect(() => context.treatment("test")).toThrow("ABsmartly Context is not yet ready."); + expect(() => context.peek("test")).toThrow("ABsmartly Context is not yet ready."); + expect(() => context.experiments()).toThrow("ABsmartly Context is not yet ready."); + expect(() => context.variableKeys()).toThrow("ABsmartly Context is not yet ready."); + expect(() => context.variableValue("a", 17)).toThrow("ABsmartly Context is not yet ready."); + expect(() => context.peekVariableValue("a", 17)).toThrow("ABsmartly Context is not yet ready."); done(); }); @@ -1529,7 +1529,7 @@ describe("Context", () => { const context = new Context(sdk, contextOptions, contextParams, Promise.resolve(getContextResponse)); expect(context.isReady()).toEqual(false); - expect(() => context.peek("exp_test_ab")).toThrow("ABSmartly Context is not yet ready."); + expect(() => context.peek("exp_test_ab")).toThrow("ABsmartly Context is not yet ready."); done(); }); @@ -1541,12 +1541,12 @@ describe("Context", () => { context.treatment("exp_test_ab"); context.finalize().then(() => { - expect(() => context.peek("exp_test_ab")).toThrow("ABSmartly Context is finalized."); + expect(() => context.peek("exp_test_ab")).toThrow("ABsmartly Context is finalized."); done(); }); expect(context.isFinalizing()).toEqual(true); - expect(() => context.peek("exp_test_ab")).toThrow("ABSmartly Context is finalizing."); + expect(() => context.peek("exp_test_ab")).toThrow("ABsmartly Context is finalizing."); }); }); @@ -1991,13 +1991,13 @@ describe("Context", () => { expect(context.pending()).toEqual(1); context.finalize().then(() => { - expect(() => context.treatment("exp_test_ab")).toThrow("ABSmartly Context is finalized."); + expect(() => context.treatment("exp_test_ab")).toThrow("ABsmartly Context is finalized."); done(); }); expect(context.isFinalizing()).toEqual(true); - expect(() => context.treatment("exp_test_ab")).toThrow("ABSmartly Context is finalizing."); + expect(() => context.treatment("exp_test_ab")).toThrow("ABsmartly Context is finalizing."); }); it("should re-evaluate audience expression when attributes change in strict mode", (done) => { @@ -2233,7 +2233,7 @@ describe("Context", () => { const context = new Context(sdk, contextOptions, contextParams, Promise.resolve(getContextResponse)); expect(context.isReady()).toEqual(false); - expect(() => context.treatment("exp_test_ab")).toThrow("ABSmartly Context is not yet ready."); + expect(() => context.treatment("exp_test_ab")).toThrow("ABsmartly Context is not yet ready."); done(); }); @@ -8630,13 +8630,13 @@ describe("Context", () => { expect(context.pending()).toEqual(1); context.finalize().then(() => { - expect(() => context.variableValue("button.color", 17)).toThrow("ABSmartly Context is finalized."); + expect(() => context.variableValue("button.color", 17)).toThrow("ABsmartly Context is finalized."); done(); }); expect(context.isFinalizing()).toEqual(true); - expect(() => context.variableValue("button.color", 17)).toThrow("ABSmartly Context is finalizing."); + expect(() => context.variableValue("button.color", 17)).toThrow("ABsmartly Context is finalizing."); }); }); @@ -9803,7 +9803,7 @@ describe("Context", () => { expect(context.pending()).toEqual(0); expect(context.isFinalizing()).toEqual(false); expect(context.isFinalized()).toEqual(true); - expect(consoleErrorSpy).not.toHaveBeenCalled(); + expect(consoleErrorSpy).toHaveBeenCalled(); consoleErrorSpy.mockRestore(); done(); @@ -10622,30 +10622,33 @@ describe("Context", () => { expect(context.customFieldValue("exp_test_custom_fields", "false_boolean_field")).toEqual(false); }); - it("should console an error when JSON cannot be parsed", () => { + it("should log an error through eventLogger when JSON cannot be parsed", () => { + const eventLogger = jest.fn(); const errorSpy = jest.spyOn(console, "error"); - const context = new Context(sdk, contextOptions, contextParams, getContextResponse); + const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, getContextResponse); expect(context.pending()).toEqual(0); expect(context.customFieldValue("exp_test_abc", "json_invalid")).toEqual(null); - expect(errorSpy).toHaveBeenCalledTimes(1); - expect(errorSpy).toHaveBeenCalledWith( - "Failed to parse JSON custom field value 'json_invalid' for experiment 'exp_test_abc'" + const errors = eventLogger.mock.calls.filter(([, eventName]) => eventName === "error").map(([, , e]) => e); + expect(errors).toHaveLength(1); + expect(errors[0].message).toMatch( + /^Failed to parse JSON custom field value 'json_invalid' for experiment 'exp_test_abc': / ); + expect(errorSpy).not.toHaveBeenCalled(); }); - it("should console an error when a field type is invalid", () => { - const errorSpy = jest.spyOn(console, "error"); + it("should log an error through eventLogger when a field type is invalid", () => { const eventLogger = jest.fn(); + const errorSpy = jest.spyOn(console, "error"); const context = new Context(sdk, { ...contextOptions, eventLogger }, contextParams, getContextResponse); expect(context.pending()).toEqual(0); expect(context.customFieldValue("exp_test_custom_fields", "invalid_type_field")).toEqual(null); - expect(errorSpy).toHaveBeenCalledTimes(1); - expect(errorSpy).toHaveBeenCalledWith( - "Unknown custom field type 'invalid' for experiment 'exp_test_custom_fields' and key 'invalid_type_field' - you may need to upgrade to the latest SDK version" - ); - expect(eventLogger.mock.calls.filter(([, eventName]) => eventName === "error")).toHaveLength(0); + const errors = eventLogger.mock.calls.filter(([, eventName]) => eventName === "error").map(([, , e]) => e); + expect(errors.map((e) => e.message)).toEqual([ + "Unknown custom field type 'invalid' for experiment 'exp_test_custom_fields' and key 'invalid_type_field' - you may need to upgrade to the latest SDK version", + ]); + expect(errorSpy).not.toHaveBeenCalled(); }); }); @@ -11278,7 +11281,7 @@ describe("Context input handling and lifecycle regressions", () => { }); describe("error logging routed through eventLogger", () => { - it("should preserve custom field console diagnostics without new error events", () => { + it("should route custom field parse errors through eventLogger, not the console", () => { const eventLogger = jest.fn(); const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); @@ -11312,10 +11315,12 @@ describe("Context input handling and lifecycle regressions", () => { ); context.customFieldValue("exp", "bad_json"); - expect(errorSpy).toHaveBeenCalledWith( - "Failed to parse JSON custom field value 'bad_json' for experiment 'exp'" + expect(errorSpy).not.toHaveBeenCalled(); + const errors = eventLogger.mock.calls.filter(([, eventName]) => eventName === "error").map(([, , e]) => e); + expect(errors).toHaveLength(1); + expect(errors[0].message).toMatch( + /^Failed to parse JSON custom field value 'bad_json' for experiment 'exp': / ); - expect(eventLogger.mock.calls.filter(([, eventName]) => eventName === "error")).toHaveLength(0); errorSpy.mockRestore(); }); diff --git a/src/__tests__/fixtures/unit-hash-1.13.4.json b/src/__tests__/fixtures/unit-hash-1.13.4.json new file mode 100644 index 0000000..b2a7a51 --- /dev/null +++ b/src/__tests__/fixtures/unit-hash-1.13.4.json @@ -0,0 +1,293 @@ +{ + "bmp": { + "0": "GE7g56SxalU6ZqLvIV826A", + "80": "ntRx_pm6zV7q_cKHvGMLVw", + "101": "CPFmtUYOsHiCRjqpu3Owkw", + "202": "yWPqlhIe1FInQKJcwLME_Q", + "303": "qrJqErfLquV1llJmZ-k-9Q", + "404": "4L0VUCMrtEGIggbeIZg8_w", + "505": "-nt9pMXdEqCbUImUMT5ECQ", + "606": "_p5qtHzYLeobuuKb7kiXIg", + "707": "OaUp1OYprR2fe2rTNruUng", + "800": "WBg-dyJxDIrzufI54iFNfQ", + "808": "5v62Sogz_vI6qUi_pP4D6A", + "909": "uBBezJWxWc8NS1tOMqW2Cg", + "1010": "tACxEqIRewg2JdzYPzBGuQ", + "1111": "cbMKoWYbJIWo2ptfmo8J4A", + "1212": "rBH6puXfqncY-fdLqvHa2w", + "1313": "bO4PwIRi4-d06ObokPx8Og", + "1414": "DvLJ34XQj6SoS32fcGTiJQ", + "1515": "vj3jDcV-vHEXLty8rkrebA", + "1616": "OkbYaUExrmqathbaJ8E-8A", + "1717": "8Ke_H4IEc-gELzsx0pxYLA", + "1818": "DpwN-tHQLLB87qsPI4ZA2Q", + "1919": "DEF0tLzKodXaVOoxiByhig", + "2020": "QijHIGD8unU9ZSJuEBiJlQ", + "2121": "9zS9oAA3KqXo2vtKJL_H5g", + "2222": "OK7JwlE0YdBO5WRaZNkdaQ", + "2323": "1-OmYAJ7B_vsrt9kDJuauA", + "2424": "Tl31OQHzbskV4BZhRz4PUw", + "2525": "SgM3MLVwgnwKj3Vfz-IN-w", + "2626": "rSPfpWng55x5Vw91NhcTCQ", + "2727": "RLk9oLFFhaaWy9OL7kHqgQ", + "2828": "FnsiB2CJNoWgVsWI2wtVhQ", + "2929": "Aqqd7Js7ssWpWdqPYCYKpQ", + "3030": "KaKovMLba8d5tKsi1HCOqg", + "3131": "cxjlqlvvqgP3nRA9EE45wg", + "3232": "6Icrdg7v2KPrkq-xXRUGdg", + "3333": "gTXx1zbUHsKtjQKUYn686A", + "3434": "sxfEmGtbX7TakEDA_n62-w", + "3535": "5y-m49_Hr8rO_3SuxjrUMg", + "3636": "S-Yu2nGgAHB4FnR2zmYt9g", + "3737": "K6K8vjzCLXE1WKCrmVRMxQ", + "3838": "Ovg9raEIug3uwEiguDumRg", + "3939": "UH3l1d92mmDq8G88s1BAFg", + "4040": "x-GO8b31_UPrw4cXqbhJ4Q", + "4141": "2cuOVQZxqVICq-uqF1p50g", + "4242": "KAVvFtFYYfE_FnpidLZH8w", + "4343": "LsMEynQ6H2PSUDniQS32bg", + "4444": "yzzqd6ETTUfpHkcJ2l32ZA", + "4545": "Cb778M01yWxRecgSw8AD6g", + "4646": "dvzArCWqh6djQvU-yxYciw", + "4747": "XTmJasG4aWaLQvVBIa5mYw", + "4848": "1mM3nm6YB8V2e8guitgnUg", + "4949": "S8IkMDP3u__C5bQbYKT4wg", + "5050": "E7aH72B17ZpxIGq37nT9Kw", + "5151": "yHUByF9vdkfVrGYuAOMNaA", + "5252": "jWh9wbgIAplbiN8ecfc25g", + "5353": "TdzKL-xHFvBWepva-CPASA", + "5454": "s07t5lRS6ESgoGwuehri4A", + "5555": "O3V442XAPUy15oCgdjmOFQ", + "5656": "3TMGn1BNKA4dkpy8KTO8KA", + "5757": "Jyx0V8nb5hb69oxatjBmog", + "5858": "xgmPRI5of8r9cRwU0unJug", + "5959": "vbWMEXMJAsFqXuEUo1bbjA", + "6060": "s8uCigmTlPJe7ydUuHfgGg", + "6161": "ymCP0MIXIIVoP2CXfAG5Vw", + "6262": "9ivroAQxkwu20LSvpajyVQ", + "6363": "7iZsKG7Gcg15MOxc_Fc9Zw", + "6464": "hKTZtSjf4O6hRmMsTfZTRA", + "6565": "9xmAao0Ixy5l5ryT3ORA_A", + "6666": "vjyzYxkpqRnxDaClxGE9qA", + "6767": "GlHhpVmBJLNAzTvuifxDHw", + "6868": "JeoiO3UnfVPuW31udvTkGA", + "6969": "U9ZranQGSS8FswNMiTCdhw", + "7070": "wzDLSlk25_KYT5vnQsmLKQ", + "7171": "94C24IdjdNplCZ_PYTW-Hw", + "7272": "FpYueeEkrYoSnuFK5237qQ", + "7373": "NDZWdNjzS9Xj8ZX4uJXycw", + "7474": "--HmnzThvdbMLA9q2xBF_w", + "7575": "8REBdDDt0Rf4gziLXN6VaA", + "7676": "1mrxGjWcj5L8ITbY9WORFw", + "7777": "87MbnxjSGx-5EBohwbBu3Q", + "7878": "Rb14efRUdCNZsvceCUeyng", + "7979": "pBCkt3jNHB0O5CklocFBIg", + "8080": "didLISTDYSbgaQEJOS_vjg", + "8181": "tsPu90mX5zJfe6Q9EpgF1g", + "8282": "aNH3o75oUQMnVf5tRf21xw", + "8383": "bv3-mnUpldStq6yQe-pQAA", + "8484": "tjpq7ikrDxKi-V302IZzpg", + "8585": "b6Zx8JKhUnJhgxNrbk09pQ", + "8686": "LUCnFm7p5RuKt7rIB-qXKA", + "8787": "Ed9j2mYK-z4ePDHYGp7iIA", + "8888": "rFyv_V3IwtvFSWOfT1WBsw", + "8989": "STfR48y7z3_AaTiIHq-Wrw", + "9090": "ROzW9d2fw2YKvX_b-oT0nQ", + "9191": "wDrt_KC98HsJEDwLr29qCw", + "9292": "XRxZY78YO5MFekq4WM9BRA", + "9393": "UGBVR4GZyGF1yAFKrn1vYQ", + "9494": "Hhmt7_5TNUz8kQa8lYKS0w", + "9595": "jrSnHYvr8PIRlDn7x1AoeA", + "9696": "OsprLhqh6PdDKGUSL1Cedw", + "9797": "GtgbPjH4TJRWQMJ6N8HRTQ", + "9898": "kNZKB1OXJbj-hh9G36wTEg", + "9999": "OCgqOYkDOM1bqH-kSeL8pw", + "7f": "Bf9N_f6sW2MgSK5O6b--Sw", + "7ff": "e_o1eEeKh6V5zeRG_OD_XA", + "a0a": "pGR1pLfYody5C738Dv5QKg", + "b0b": "p1A7UfLiciO6cl-oIW5hnQ", + "c0c": "mkeFQkltN3D7Bo83j7UzJg", + "d0d": "2OwFhWLDluyA65cBpeWI0A", + "e0e": "fUK8XcB17V2SKU2Lh58qgg", + "f0f": "bCmQoZLvzmXlrXjvpNN6Bg", + "1a1a": "bvq_2jiz3ll317QS6NtYfQ", + "1b1b": "PVdxz6HD6o4xKoBH2wTc_Q", + "1c1c": "GczGIlYhhT3GQY137uvkxQ", + "1d1d": "mo9ppXeql2D7CeHSvOyeZQ", + "1e1e": "gSvcM8mMVTj23ZQ_sS3-cg", + "1f1f": "7UY303Q12xRAhvvCzxuDUQ", + "2a2a": "EwwMbyeTqYwfWHAHfOFbUg", + "2b2b": "wUsP_Tfk2OjJai0Tv1gEkw", + "2c2c": "K2xOUEYVssNlpEeMAwpoow", + "2d2d": "u6LSBgz8uahQbZK1Vp40Bg", + "2e2e": "eI6UGr295D5k9MtDrTNxcw", + "2f2f": "D6E9s17DCMmC8yq-7COD4g", + "3a3a": "PF1V5FA3W9yK5JBPs3iy6Q", + "3b3b": "ZxPA6Nkl12tKIMwPkjSOQw", + "3c3c": "NqQkD4QQ3s5QIwEa0OBRvg", + "3d3d": "exJ7QRU8Bk6xU94Jf54DGA", + "3e3e": "gIVcwOZgN-N1NLP3BjlDuw", + "3f3f": "6XmvyOH3jf9qag50LQZIoQ", + "4a4a": "8y0bzxYs4XDZ2FRFHysxcg", + "4b4b": "JwsTKVIoEpZ4h6koEvEo_g", + "4c4c": "QDtRS6VvqvQqH95R-8EnnQ", + "4d4d": "gqWE5WBhG9XK2JA8lQxdYw", + "4e4e": "nH_LrTXtMw7JkJDXDw8QFA", + "4f4f": "C8HJftxSwwm474uLFurCAw", + "5a5a": "ol5iYUJN9Rub84Nh8Isvpg", + "5b5b": "f_7beOXzDAYMTmjpPSoOkw", + "5c5c": "uulmAJ6GWDz0Pn1BDJyAXg", + "5d5d": "hzuWCRL12CedvMoxGfi8lw", + "5e5e": "xPm_jBrFWm4JxtFRb5WQ2w", + "5f5f": "HnthGNAlUejIDIu0jmqQhQ", + "6a6a": "zusOppa1nhWEGdfcDDXivQ", + "6b6b": "vASd_Be04ZB5AsgZzgla0Q", + "6c6c": "h0IXDSqo1Gz3usiPX_ozlw", + "6d6d": "XeAJZVUjZ7fucbgQTHuWxQ", + "6e6e": "Wew6MKLomKZ_d3D3OtruNg", + "6f6f": "J4QHPctakWPizMF5WYCL1A", + "7a7a": "Hb4wKqhQ0pgxC4EZOrov9g", + "7b7b": "CFVDq1sDqR3Zv-khbOaWZA", + "7c7c": "Ej5AT0OHcmPnS7tQooiVWw", + "7d7d": "uxz8OG1Pc3i2KLox8wvyUg", + "7e7e": "AvXOUHTHpPqtu_01lXP_Iw", + "7f7f": "jRsQ35GQrvdnRq385CSeTA", + "8a8a": "374RPsw1EGfbE9OhMB4jkg", + "8b8b": "5b7tvvhvg1vXkxg8nqbUdw", + "8c8c": "gxG3f70qwo9hUWe1rzdufg", + "8d8d": "UWrLyuCXS-vg9qAOe_lZDQ", + "8e8e": "JOQ00Tx_FY5PfXIZU4qhsw", + "8f8f": "khZ4R4Ycxd62xxyNd-ZixQ", + "9a9a": "kygArEAVxU8J8UJy_3DWaA", + "9b9b": "CJer_bDrLcBhaRlGPx9I4Q", + "9c9c": "pJ0Y9zBPEgGL1NtZrjwnRQ", + "9d9d": "rYjJVuv8WDZxSeeoA3S3Pw", + "9e9e": "kcpjOdVaYY_Y5ae6n699AQ", + "9f9f": "gJaxc8ESyjFDrjR1ZK8GJQ", + "a0a0": "E2mAIiaX2O7j9l2Xw1YxFA", + "a1a1": "mlxX2R8aUZ_9ZR6IqXzKdg", + "a2a2": "BhNk7cFgrZg_IBP11DKqCw", + "a3a3": "lhidDLsbTpoyTb-jZdUPew", + "a4a4": "DP4GNzfcXYMRyusAs2Tkyg", + "a5a5": "n05IX0N9tPfpGiB5_EsBQQ", + "a6a6": "7tH2y9x3Wwhy_Yl6Qb8duw", + "a7a7": "z-ScOwljuLRSiPo0Yrx7bg", + "a8a8": "yhiQOaM-PklQnQ4ZCBFO_g", + "a9a9": "fi_Q2raKHqH6SFWQTSrSZg", + "aaaa": "I_M_yE8R2GPUocU-rrQo3w", + "abab": "oph9fMOexKz7QGQzXJb7LQ", + "acac": "MhM9uTfCcA1VehlxO0sKTA", + "adad": "WLwen3L5oBmvM2TwQrX3Ew", + "aeae": "lZ9ahRypuAiSGgmKOTA4nQ", + "afaf": "mF-3CU0t0u1Muyipu8tn5w", + "b0b0": "KcJsJyQXqJm72Pnz0sqP-A", + "b1b1": "SiYeYClj4POIWchJzT33YA", + "b2b2": "ZKC_Cm-jCqSSpuBZqLvSgw", + "b3b3": "82Tbvo3N3JwyDg8HyV38Ow", + "b4b4": "gLKJjdWcSV-lwC2BPFtKDQ", + "b5b5": "cWkrss5VDxyeIdhg9g0HLw", + "b6b6": "3-ZpZublSUuGsiw5xRy91A", + "b7b7": "X0XCktttia3q4qGL41yqwg", + "b8b8": "AJRa_u9_Z1eGVJAqYtupBA", + "b9b9": "5x3Qda2dCzULAboX8g8MoA", + "baba": "ubZ2RyctNA8VGFjRbJnv5A", + "bbbb": "YeTEeHHFkfycWMZ-k_-p3g", + "bcbc": "J4dETjZSZ8tlSm5Kygd1cg", + "bdbd": "n58xiAypYMtDwhF5OyhKcw", + "bebe": "ABH-7XWTg2ckMIImu0BEgw", + "bfbf": "b2WAWAOU2ouNRfjE2BBJcg", + "c0c0": "MFq-ElQgEm-SD1rQhSuSgw", + "c1c1": "RAbhnNOrWSsW0TkZ-dgtSw", + "c2c2": "MMqCCVoV_Z5v5f7UVBaC1A", + "c3c3": "n4Zha1iTIGq69O3YBRcA5A", + "c4c4": "gvGXRQLK0JJFOFWCfmQyHQ", + "c5c5": "LqAnGWUsUQR5S8Jr-nXhJg", + "c6c6": "kzmYKdXVfTkR9NYyGKS0Ew", + "c7c7": "XC0wn7E0jaez0XxL7Qrp3A", + "c8c8": "4c037K8wNK8q31wRl_tDWg", + "c9c9": "TyLXkAYpwSuS9s5bQTDfDQ", + "caca": "Lz3XNVK2C9-hUym1K83EWQ", + "cbcb": "jypMLIP-X3l__45H1x-f8Q", + "cccc": "AJwdvYNz6JaKQohwUnKuMw", + "cdcd": "gs1C-OBqymh4IOs_zT9A_w", + "cece": "jNqeJpvhVreM41WSiV7dng", + "cfcf": "PEJrKj0Aw3SXz-pYQj9nRg", + "d0d0": "2iauOizBAylYIagnGENfEA", + "d1d1": "xg22GmUl9qkm6kYTwwBnJA", + "d2d2": "EDoOJQKNriMyhcWX_vSJjA", + "d3d3": "g6BoaCXRFxUSRxrglHCgoA", + "d4d4": "mtm49kih6JtMnWIKQegZ9w", + "d5d5": "3C50L6Vw7WkT4QN1rXFT0g", + "d6d6": "aLIAi_8yy-rrCpmodbvxPg", + "d7d7": "2GCpnAugMwNsNJ-u55imdg", + "d7ff": "qcaIxzosy8X9MVz4dgNxSw", + "d800": "QuYoIt2iC-pULZQeARIsKw", + "d8d8": "fJ5Zfs7FcmUxYej6YtN8DA", + "d9d9": "wqlQbfVmzU10p5O5o_McaA", + "dada": "T-jf2vRPtBvH9_JS5IODdQ", + "dbdb": "Z6lVzNH9yeTyD0tV61VK2g", + "dbff": "zAqDuzVaZivyWtpg5InI7g", + "dc00": "4msvGaROA1_H0fECsLodRQ", + "dcdc": "tCK5yffWK9XeJeuDH-7hgA", + "dddd": "aNW-0yBw6PDMO4eqnLWLcg", + "dede": "QmnD3hKtys1KuRQ_LnWG-g", + "dfdf": "kPeWWWPFVh2t8XubRJofGg", + "dfff": "ytYcKVKvhOss5BwcJIKEVA", + "e000": "q62piMpfoKEyNX3xci9b8g", + "e0e0": "sDNSjG2ZEKhuttze5Zn-mQ", + "e1e1": "6ThwVUzyGcaYkkiusATXCg", + "e2e2": "d2TPDwF-IjjbYu0erhgs8A", + "e3e3": "nVDPinLS_0HuCLuCORldLA", + "e4e4": "X-Wcr265hhcsjK9_8yWpUA", + "e5e5": "6HSHQSXaLSZ-2kUUWy_msA", + "e6e6": "RcKiUuNjv_RPJkI8mVb8Ww", + "e7e7": "zJQQ1nv5BqPAnzB1dwDmlw", + "e8e8": "Mov-PXJashp48tviQ3nZjA", + "e9e9": "iJqfy3t4cSiD2EvrdfWniQ", + "eaea": "wnBOwGb5OKmFXALbPV5dPg", + "ebeb": "mbg7TUvd0vPD-U8JUX-AJw", + "ecec": "sDldqlHtFy1AULMuQ_91Qg", + "eded": "sU2xUZ7nzx1AqawXvFss2g", + "eeee": "72b-Uj4dtoMTYigpO2nvTQ", + "efef": "53DvsAUHD78EDxMQBGK1lg", + "f0f0": "ExfElOdKRNtFbCTfBKyOAw", + "f1f1": "j0ypXr2BJHXmNvVZiw8IBw", + "f2f2": "uGTmty5ePn1sA0Tv3_rqXQ", + "f3f3": "-YKMad0eQv9t2T952UjMnA", + "f4f4": "VnEyfaci7xvA2nS8TpwouA", + "f5f5": "Qen4LsPHi0V2fr3p7oJzMw", + "f6f6": "Xq-YtS2MipwN4zuztxEAbQ", + "f7f7": "Pi3IcHK5FwnO5b12VoCpjA", + "f8f8": "6Jc9KMbz6rHwSZ_AZxiFmA", + "f9f9": "or4ayzhiqqyxitVYeRfaLg", + "fafa": "D82vvEwbbF_OzUV3EeG9wA", + "fbfb": "JjqTs_bxcUCEqeCkz-cWhA", + "fcfc": "fg5NQEPQCfgjdcV5-8CGlg", + "fdfd": "LgNE2RLwfon5aye0lPiaZw", + "fefe": "TBm59lmGQNiJ2XartiY8Ew", + "fffd": "u8_0H8ODWz5AmG1oG7cvLg", + "ffff": "EHa0wseHZghEctcy1rdw4A" + }, + "astral": { + "10000": { + "released": "qooXqIZcmZDi_JNl45dLPg", + "utf8": "ORyfhmRZxXo9touHRd6APg" + }, + "1f600": { + "released": "UZPmzZSM1wgB7ODAPbgfqA", + "utf8": "n7A8ppbyZ2kYleRaxSanVw" + }, + "1f9ea": { + "released": "Dt3leQGP-8nzwh1TYWFyRA", + "utf8": "Mc2Pxk90D57EYIUHk9NjIA" + }, + "2a6d6": { + "released": "_8BA7-4F_iQaJzW4Qts8ag", + "utf8": "4TgIBIq_JSeXRdDURBSumw" + }, + "10ffff": { + "released": "0aZsdAEC1UKqA6ghSLDJPQ", + "utf8": "ouAG23gEhWtfRRbBJHvb2g" + } + } +} diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index f148df5..d294ddb 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -246,23 +246,22 @@ describe("1.13.4 source and behaviour compatibility", () => { sdkFetch.mockReset(); }); - it("keeps the live units map and released error strings", async () => { + it("returns a copy from getUnits() and brands error strings ABsmartly", async () => { const sdk = new SDK(options); const context = sdk.createContextWith({ units: { user: "one" } }, { experiments: [] }); const units = context.getUnits(); units.session = "two"; - expect(context.getUnit("session")).toBe("two"); - expect(context.getUnits()).toBe(units); + expect(context.getUnit("session")).toBeUndefined(); + expect(context.getUnits()).not.toBe(units); + expect(context.getUnits()).toEqual({ user: "one" }); await context.finalize(); - expect(() => context.treatment("e")).toThrow("ABSmartly Context is finalized."); + expect(() => context.treatment("e")).toThrow("ABsmartly Context is finalized."); }); - it("accepts a released duck-typed custom client without new getters", () => { + it("requires a custom client to provide getApplication(), getEnvironment() and getAgent()", () => { const client = { getContext: () => Promise.resolve({ experiments: [] }), publish: () => Promise.resolve() }; const sdk = new SDK({ ...options, client }); - const context = sdk.createContextWith({ units: { user: "one" } }, { experiments: [] }); - expect(context.isReady()).toBe(true); - expect(context.treatment("e")).toBe(0); + expect(() => sdk.createContextWith({ units: { user: "one" } }, { experiments: [] })).toThrow(TypeError); }); it.each([null, "", 1004, " 1004 ", "3.2.1", -1, "١٠٠٤", "1234567890123456789"])( @@ -281,6 +280,133 @@ describe("1.13.4 source and behaviour compatibility", () => { } ); + it.each([ + ["omitted", undefined], + ["false", false], + ])("does not warn about the deprecated auth option when it is %s", async (_label, auth) => { + sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({}) }); + const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); + await new Client(options).request({ path: "/x", method: "GET", auth }); + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); + }); + + // With no deadline the first retry waits the full 50 ms backoff; a deadline clamp would cut it to + // `timeout - waited` (0 ms), so the retry would fire at once. + it("keeps the full retry backoff when timeout is 0", async () => { + jest.useFakeTimers(); + const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); + const random = jest.spyOn(Math, "random").mockReturnValue(0); + try { + sdkFetch + .mockRejectedValueOnce(new Error("connection refused")) + .mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({}) }); + const result = new Client({ ...options, timeout: 0, retries: 2 }).request({ path: "/x", method: "GET" }); + for (let i = 0; i < 5; i++) await Promise.resolve(); + expect(sdkFetch).toHaveBeenCalledTimes(1); + jest.advanceTimersByTime(49); + for (let i = 0; i < 5; i++) await Promise.resolve(); + expect(sdkFetch).toHaveBeenCalledTimes(1); + jest.advanceTimersByTime(1); + await expect(result).resolves.toEqual({}); + expect(sdkFetch).toHaveBeenCalledTimes(2); + } finally { + random.mockRestore(); + warn.mockRestore(); + jest.useRealTimers(); + } + }); + + it("reports a custom client without getApplication() when an audience is evaluated", () => { + const eventLogger = jest.fn(); + const client = { + getContext: () => Promise.resolve({ experiments: [] }), + publish: () => Promise.resolve(), + getEnvironment: () => "prod", + getAgent: () => "agent", + }; + const context = new SDK({ ...options, client, eventLogger }).createContextWith( + { units: { session_id: "u1" } }, + { experiments: [cacheProbeExperiment({ audience: '{"filter":[{"value":true}]}' })] } + ); + context.treatment("cacheProbe"); + const errors = eventLogger.mock.calls.filter(([, eventName]) => eventName === "error").map(([, , e]) => e); + expect(errors).toHaveLength(1); + expect(errors[0]).toBeInstanceOf(TypeError); + }); + + it("rejects publish() with includeSystemAttributes for a custom client without getAgent()", async () => { + const client = { + getContext: () => Promise.resolve({ experiments: [] }), + publish: () => Promise.resolve(), + getApplication: () => ({ name: "web", version: 0 }), + getEnvironment: () => "prod", + }; + const context = new SDK({ ...options, client }).createContextWith( + { units: { session_id: "u1" } }, + { experiments: [] }, + { publishDelay: -1, includeSystemAttributes: true } + ); + context.track("g"); + await expect(Promise.resolve().then(() => context.publish())).rejects.toThrow(TypeError); + }); + + it("uses the configured application, environment and agent getters of a custom client", async () => { + const publish = jest.fn(() => Promise.resolve()); + const client = { + getContext: () => Promise.resolve({ experiments: [] }), + publish, + getApplication: () => ({ name: "custom-app", version: 0 }), + getEnvironment: () => "custom-env", + getAgent: () => "custom-agent/1", + }; + const sdk = new SDK({ ...options, client }); + const context = sdk.createContextWith( + { units: { session_id: "u1" } }, + { + experiments: [ + { + ...cacheProbeExperiment(), + name: "systemNames", + audienceStrict: true, + audience: JSON.stringify({ + filter: [ + { + and: [ + { eq: [{ var: "application" }, { value: "custom-app" }] }, + { eq: [{ var: "environment" }, { value: "custom-env" }] }, + ], + }, + ], + }), + trafficSplit: [0, 1], + fullOnVariant: 1, + }, + ], + }, + { publishDelay: -1, includeSystemAttributes: true } + ); + expect(context.treatment("systemNames")).toBe(1); + await context.publish(); + const attributes = publish.mock.calls[0][0].attributes; + expect(attributes.find((a) => a.name === "sdk_name").value).toBe("custom-agent/1"); + }); + + it("reports the counts of the exposures and goals a failed context discards", async () => { + const eventLogger = jest.fn(); + const provider = { getContextData: () => Promise.reject(new Error("load failed")) }; + const context = new SDK({ ...options, provider, eventLogger }).createContext({ units: { session_id: "u1" } }); + await context.ready(); + context.treatment("a"); + context.track("g1"); + context.track("g2"); + await context.publish(); + const messages = eventLogger.mock.calls + .filter(([, eventName]) => eventName === "error") + .map(([, , error]) => error.message); + expect(messages).toContain("Discarding 1 exposures and 2 goals because context failed to initialize"); + }); + it("bounds retries by a per-request timeout that overrides the client timeout", async () => { sdkFetch.mockRejectedValue(new Error("connection refused")); const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); @@ -294,7 +420,7 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(sdkFetch).toHaveBeenCalledTimes(4); }); - it("logs an unparsable audience to the console as 1.13.4 did, without a logger error event", () => { + it("reports an unparsable audience through the eventLogger, not the console", () => { const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); const eventLogger = jest.fn(); const sdk = new SDK({ ...options, eventLogger }); @@ -313,22 +439,25 @@ describe("1.13.4 source and behaviour compatibility", () => { trafficSeedHi: 3, trafficSeedLo: 4, trafficSplit: [0, 1], - fullOnVariant: 0, + fullOnVariant: 1, applications: [{ name: "web" }], variants: [ { name: "A", config: null }, { name: "B", config: null }, ], audience: "{not json", - audienceStrict: false, + audienceStrict: true, customFieldValues: null, }, ], } ); - context.treatment("badaud"); - expect(errorSpy).toHaveBeenCalledWith(expect.any(SyntaxError)); - expect(eventLogger.mock.calls.filter(([, eventName]) => eventName === "error")).toHaveLength(0); + // Indeterminate, as in 1.13.4, not a mismatch: the strict full-on audience still serves variant 1. + expect(context.treatment("badaud")).toBe(1); + expect(errorSpy).not.toHaveBeenCalled(); + const errors = eventLogger.mock.calls.filter(([, eventName]) => eventName === "error").map(([, , e]) => e); + expect(errors).toHaveLength(1); + expect(errors[0].message).toMatch(/^Invalid audience JSON: /); errorSpy.mockRestore(); }); @@ -419,21 +548,33 @@ describe("1.13.4 source and behaviour compatibility", () => { }); it.each([ - ["request() without auth", (c) => c.request({ path: "/x", method: "GET" }), false], + ["request() without auth", (c) => c.request({ path: "/x", method: "GET" }), true], ["request() with auth true", (c) => c.request({ path: "/x", method: "GET", auth: true }), true], - ["post() with auth false", (c) => c.post({ path: "/x", auth: false }), true], - ["put() with auth false", (c) => c.put({ path: "/x", auth: false }), true], - ["getUnauthed()", (c) => c.getUnauthed({ path: "/x" }), false], - ["getUnauthed() with auth true", (c) => c.getUnauthed({ path: "/x", auth: true }), true], + ["request() with auth false", (c) => c.request({ path: "/x", method: "GET", auth: false }), false], + ["post() with auth false", (c) => c.post({ path: "/x", auth: false }), false], + ["put() with auth false", (c) => c.put({ path: "/x", auth: false }), false], + ["getUnauthed()", (c) => c.getUnauthed({ path: "/x" }), true], ["get() with auth false", (c) => c.get({ path: "/x", auth: false }), false], - ])("keeps the 1.13.4 auth header rule for %s", async (_label, call, sendsHeaders) => { + ])("sends auth headers by default unless auth is false: %s", async (_label, call, sendsHeaders) => { sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({}) }); + const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); await call(new Client(options)); + warn.mockRestore(); const request = sdkFetch.mock.calls[sdkFetch.mock.calls.length - 1][1]; if (sendsHeaders) expect(request.headers["X-API-Key"]).toBe("k"); else expect(request).not.toHaveProperty("headers"); }); + it("warns once per request that auth: true is deprecated", async () => { + sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({}) }); + const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); + await new Client(options).request({ path: "/x", method: "GET", auth: true }); + expect(warn).toHaveBeenCalledWith( + "[ABsmartly] The `auth` option is deprecated. Auth headers are now sent by default. Remove `auth: true` from your request options." + ); + warn.mockRestore(); + }); + it("does not re-evaluate assignment rules on cached reads after a same-outcome refresh", async () => { const experiment = (rules) => ({ id: 7, @@ -656,22 +797,29 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(sdkFetch.mock.calls[0][1]).not.toHaveProperty("headers"); }); - it("routes getContext() through a subclass's getUnauthed() override", async () => { + it("calls get() directly from getContext(), not a subclass's getUnauthed()", async () => { sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({ experiments: [] }) }); - const seen = []; + const unauthed = []; + const gets = []; class LoggingClient extends Client { getUnauthed(requestOptions) { - seen.push(requestOptions.path); + unauthed.push(requestOptions.path); return super.getUnauthed(requestOptions); } + get(requestOptions) { + gets.push(requestOptions.path); + return super.get(requestOptions); + } } await new LoggingClient(options).getContext(); - expect(seen).toEqual(["/context"]); + expect(unauthed).toEqual([]); + expect(gets).toEqual(["/context"]); expect(sdkFetch.mock.calls[0][1].headers["X-API-Key"]).toBe("k"); }); - describe("live units map additions", () => { - const liveExp = (extra) => ({ + it("does not change assignments when a caller edits the copy getUnits() returns", () => { + const sdk = new SDK(options); + const exp = { id: 13, name: "covered", iteration: 1, @@ -691,114 +839,16 @@ describe("1.13.4 source and behaviour compatibility", () => { audience: null, audienceStrict: false, customFieldValues: null, - ...extra, - }); - const splitRules = JSON.stringify({ - rules: [{ name: "s", type: "split", percentages: "0/100", conditions: null }], - }); - - it("re-resolves a peeked missing-unit split rule once the live map gains the unit", () => { - const context = new SDK(options).createContextWith( - { units: {} }, - { experiments: [liveExp({ assignmentRules: splitRules })] } - ); - expect(context.peek("covered")).toBe(0); - context.getUnits().user_id = "u1"; - expect(context.peek("covered")).toBe(1); - }); - - it("matches unit() for a holdout-covered experiment peeked before the unit existed", () => { - const holdout = { - id: 99, - name: "h", - iteration: 1, - unitType: "user_id", - seedHi: 1, - seedLo: 2, - split: [0, 1], - }; - const data = { experiments: [liveExp({ holdoutIds: [99] })], holdouts: [holdout] }; - const viaUnit = new SDK(options).createContextWith({ units: {} }, data); - viaUnit.peek("covered"); - viaUnit.unit("user_id", "u1"); - viaUnit.treatment("covered"); - const viaMap = new SDK(options).createContextWith({ units: {} }, data); - viaMap.peek("covered"); - viaMap.getUnits().user_id = "u1"; - viaMap.treatment("covered"); - const shape = (c) => c._exposures.map((x) => [x.name, x.variant, x.assigned]); - expect(shape(viaMap)).toEqual(shape(viaUnit)); - }); - - it("re-resolves via the live map after revalidation turns an assignment into a missing-unit pin", () => { - const rules = JSON.stringify({ - rules: [ - { - name: "us", - type: "assign", - variant: 0, - conditions: { eq: [{ var: "country" }, { value: "US" }] }, - }, - { - name: "gb", - type: "split", - percentages: "0/100", - conditions: { eq: [{ var: "country" }, { value: "GB" }] }, - }, - ], - }); - const sequence = (setUnit) => { - const context = new SDK(options).createContextWith( - { units: {} }, - { experiments: [liveExp({ assignmentRules: rules })] } - ); - context.attribute("country", "US"); - expect(context.peek("covered")).toBe(0); - context.attribute("country", "GB"); - expect(context.peek("covered")).toBe(0); - setUnit(context); - return context.peek("covered"); - }; - expect(sequence((context) => context.unit("user_id", "u1"))).toBe(1); - expect( - sequence((context) => { - context.getUnits().user_id = "u1"; - }) - ).toBe(1); - }); - - it("keeps the cached assignment while the unit is still missing", () => { - const context = new SDK(options).createContextWith( - { units: {} }, - { experiments: [liveExp({ assignmentRules: splitRules })] } - ); - context.peek("covered"); - const first = context._assignments.covered; - context.peek("covered"); - expect(context._assignments.covered).toBe(first); - }); - - it("does no live-units work on cached reads when nothing was resolved without its unit", () => { - const context = new SDK(options).createContextWith( - { units: { user_id: "u1" } }, - { experiments: [liveExp({})] } - ); - context.treatment("covered"); - const cached = context._assignments.covered; - let reads = 0; - let value = cached.isRuleMissingUnit; - Object.defineProperty(cached, "isRuleMissingUnit", { - get: () => { - reads++; - return value; - }, - set: (v) => { - value = v; - }, - }); - for (let i = 0; i < 50; i++) context.peek("covered"); - expect(reads).toBe(0); - }); + }; + const context = sdk.createContextWith({ units: {} }, { experiments: [exp] }); + expect(context.peek("covered")).toBe(0); + context.getUnits().user_id = "u1"; + expect(context.getUnit("user_id")).toBeUndefined(); + expect(context.treatment("covered")).toBe(0); + expect(context._exposures.map((x) => [x.name, x.assigned])).toEqual([["covered", false]]); + context.unit("user_id", "u1"); + const fresh = sdk.createContextWith({ units: { user_id: "u1" } }, { experiments: [exp] }); + expect(context.peek("covered")).toBe(fresh.peek("covered")); }); it("treats a nested audience path under a null attribute as missing, not a mismatch, as 1.13.4 did", () => { @@ -1122,113 +1172,4 @@ describe("1.13.4 source and behaviour compatibility", () => { const attributes = publisher.publish.mock.calls[0][0].attributes; expect(attributes).toEqual([expect.objectContaining({ name: "app_version", value: "2.3.4" })]); }); - - it("invalidates a cached missing-unit assignment when the live units map gains the unit", () => { - const sdk = new SDK(options); - const holdout = { id: 99, name: "h", iteration: 1, unitType: "user_id", seedHi: 1, seedLo: 2, split: [1, 0] }; - const exp = { - id: 13, - name: "covered", - iteration: 1, - unitType: "user_id", - seedHi: 1, - seedLo: 2, - split: [0.5, 0.5], - trafficSeedHi: 3, - trafficSeedLo: 4, - trafficSplit: [0, 1], - fullOnVariant: 0, - applications: [{ name: "web" }], - variants: [ - { name: "A", config: null }, - { name: "B", config: null }, - ], - audience: null, - audienceStrict: false, - customFieldValues: null, - holdoutIds: [99], - }; - const context = sdk.createContextWith({ units: {} }, { experiments: [exp], holdouts: [holdout] }); - expect(context.peek("covered")).toBe(0); - context.getUnits().user_id = "u1"; - context.treatment("covered"); - expect(context._exposures.map((x) => x.name)).toEqual(["h"]); - }); - - describe("a released duck-typed custom client without the new getters", () => { - const legacyClient = () => ({ - getContext: () => Promise.resolve({ experiments: [] }), - publish: jest.fn(() => Promise.resolve()), - }); - const strictCountryExperiment = { - id: 1, - name: "exp", - iteration: 1, - unitType: "session_id", - seedHi: 3603515, - seedLo: 233373850, - split: [0, 1], - trafficSeedHi: 449867249, - trafficSeedLo: 455443629, - trafficSplit: [0, 1], - fullOnVariant: 0, - applications: [{ name: "web" }], - variants: [ - { name: "A", config: null }, - { name: "B", config: null }, - ], - audience: JSON.stringify({ filter: [{ eq: [{ var: "country" }, { value: "US" }] }] }), - audienceStrict: true, - customFieldValues: null, - }; - - it("still evaluates audiences when only getApplication exists", () => { - const client = { ...legacyClient(), getApplication: () => ({ name: "web", version: 0 }) }; - const sdk = new SDK({ ...options, client }); - const context = sdk.createContextWith( - { units: { session_id: "e791e240fcd3df7d238cfc285f475e8152fcc0ec" } }, - { experiments: [strictCountryExperiment] } - ); - context.attribute("country", "US"); - expect(context.treatment("exp")).toBe(1); - }); - - it.each(["application", "environment"])("uses %s when only its getter exists", (attributeName) => { - const client = legacyClient(); - if (attributeName === "application") client.getApplication = () => ({ name: "web", version: 0 }); - else client.getEnvironment = () => "prod"; - const sdk = new SDK({ ...options, client }); - const value = attributeName === "application" ? "web" : "prod"; - const exp = { - ...strictCountryExperiment, - audience: JSON.stringify({ filter: [{ eq: [{ var: attributeName }, { value }] }] }), - }; - const context = sdk.createContextWith({ units: { session_id: "u1" } }, { experiments: [exp] }); - expect(context.treatment("exp")).toBe(1); - }); - - it("still evaluates audiences", () => { - const sdk = new SDK({ ...options, client: legacyClient() }); - const context = sdk.createContextWith( - { units: { session_id: "e791e240fcd3df7d238cfc285f475e8152fcc0ec" } }, - { experiments: [strictCountryExperiment] } - ); - context.attribute("country", "US"); - expect(context.treatment("exp")).toBe(1); - }); - - it("publishes sdk_version but no empty sdk_name", async () => { - const client = legacyClient(); - const sdk = new SDK({ ...options, client }); - const context = sdk.createContextWith( - { units: { session_id: "u" } }, - { experiments: [] }, - { includeSystemAttributes: true, publishDelay: -1 } - ); - context.track("goal"); - await context.publish(); - const names = client.publish.mock.calls[0][0].attributes.map((a) => a.name); - expect(names).toEqual(["sdk_version"]); - }); - }); }); diff --git a/src/__tests__/sdk.test.js b/src/__tests__/sdk.test.js index 7be27cd..ad00297 100644 --- a/src/__tests__/sdk.test.js +++ b/src/__tests__/sdk.test.js @@ -101,7 +101,9 @@ describe("SDK", () => { done(); }); - it("should ignore inherited and non-enumerable option keys, as 1.13.4 did", (done) => { + // Options are read by key, so a key that is undefined (own or inherited) is left out and the + // default applies, as on main; an inherited defined value is read like an own one. + it("should read inherited option keys and skip undefined ones", (done) => { const base = { application: "application", apiKey: "apikey", @@ -109,19 +111,17 @@ describe("SDK", () => { environment: "test", }; const options = Object.assign(Object.create({ timeout: 777, agent: undefined }), base); - Object.defineProperty(options, "retries", { value: 9, enumerable: false }); new SDK(options); // eslint-disable-line no-new const passed = Client.mock.calls[Client.mock.calls.length - 1][0]; - expect(Object.prototype.hasOwnProperty.call(passed, "timeout")).toBe(false); - expect(Object.prototype.hasOwnProperty.call(passed, "retries")).toBe(false); + expect(passed.timeout).toBe(777); expect(passed.agent).toBe(`absmartly-javascript-sdk/${SDK_VERSION}`); done(); }); - it("should pass explicitly undefined client options through, as 1.13.4 did", (done) => { + it("should drop explicitly undefined client options so the defaults apply", (done) => { const options = { application: "application", apiKey: "apikey", @@ -135,10 +135,9 @@ describe("SDK", () => { new SDK(options); // eslint-disable-line no-new const passed = Client.mock.calls[Client.mock.calls.length - 1][0]; - expect(Object.prototype.hasOwnProperty.call(passed, "agent")).toBe(true); - expect(passed.agent).toBeUndefined(); - expect(Object.prototype.hasOwnProperty.call(passed, "timeout")).toBe(true); - expect(Object.prototype.hasOwnProperty.call(passed, "keepalive")).toBe(true); + expect(passed.agent).toBe(`absmartly-javascript-sdk/${SDK_VERSION}`); + expect(Object.prototype.hasOwnProperty.call(passed, "timeout")).toBe(false); + expect(Object.prototype.hasOwnProperty.call(passed, "keepalive")).toBe(false); expect(Object.prototype.hasOwnProperty.call(passed, "retries")).toBe(false); done(); diff --git a/src/__tests__/utils.test.js b/src/__tests__/utils.test.js index 013073a..62bbd65 100644 --- a/src/__tests__/utils.test.js +++ b/src/__tests__/utils.test.js @@ -2,6 +2,8 @@ import { arrayEqualsShallow, base64UrlNoPadding, chooseVariant, + getApplicationName, + getApplicationVersion, hashUnit, isEqualsDeep, isNumeric, @@ -10,9 +12,23 @@ import { stringToUint8Array, toWellFormedString, } from "../utils"; +import releasedHashes from "./fixtures/unit-hash-1.13.4.json"; class SomeClass {} +describe("getApplicationName() and getApplicationVersion()", () => { + it("reads a string application as a name with version 0", () => { + expect(getApplicationName("web")).toBe("web"); + expect(getApplicationVersion("web")).toBe(0); + }); + + it("returns an application object's numeric or string version unchanged", () => { + expect(getApplicationName({ name: "web", version: 7 })).toBe("web"); + expect(getApplicationVersion({ name: "web", version: 7 })).toBe(7); + expect(getApplicationVersion({ name: "web", version: "1.2.3" })).toBe("1.2.3"); + }); +}); + describe("isObject()", () => { it("should return true with objects", (done) => { expect(isObject({})).toBe(true); @@ -237,17 +253,58 @@ describe("hashUnit()", () => { done(); }); - it("should preserve 1.13 astral/multibyte hashes", (done) => { - // 1.x keeps the released code-unit encoding to avoid reassigning existing units. - expect(hashUnit("😀")).toBe("-Z9RwqljCn9rjBPBgYvAwg"); - expect(hashUnit("😀😁")).toBe("OkTK8v8Dc9YXARX-1b6CmA"); - expect(hashUnit("世界你好")).toBe("v2CJG7YcjjWncKOSCzF2GA"); - expect(hashUnit("user_世界_123")).toBe("SCgk4OzXlFMvo1UMsP88fA"); + // Cross-SDK golden vectors (cross-sdk-tests scenarios 75-80 and 112): UTF-8 MD5, base64url. + it.each([ + ["", "1B2M2Y8AsgTpgAmY7PhCfg"], + ["special characters açb↓c", "4PIrO7lKtTxOcj2eMYlG7A"], + ["test", "CY9rzUYh03PK3k6DJie09g"], + ["testy", "K5I_V6RgP8c6sYKz-TVn8g"], + ["bleh@absmartly.com", "IuqYkNRfEx5yClel4j3NbA"], + ["test_user_123", "Inw3HDh_rVCfpy0NhDsq1A"], + ["ABC-123_xyz", "78Q1utpZbpcxZ9B_9VZbgw"], + ])("matches the cross-SDK golden hash for %j", (unit, hash) => { + expect(hashUnit(unit)).toBe(hash); + }); - done(); + // A character outside the BMP (such as an emoji) is one 4-byte UTF-8 sequence, so these units hash + // as the collector and the other SDKs hash them. 1.13.4 hashed them from two 3-byte surrogate halves. + it.each([ + ["😀", "KgLqw51xanDs83V5GFkntg", "-Z9RwqljCn9rjBPBgYvAwg"], + ["😀😁", "ZJuDalvUWRJnVtkspj-2bQ", "OkTK8v8Dc9YXARX-1b6CmA"], + ])("hashes %j with canonical UTF-8 (1.13.4 gave a different hash)", (unit, hash, released) => { + expect(hashUnit(unit)).toBe(hash); + expect(hash).not.toBe(released); + }); + + // Every other ID keeps its 1.13.4 hash: ASCII, accented and CJK text, and unpaired surrogates. These + // are the hashes the published 1.13.4 package returns. + it.each([ + ["世界你好", "v2CJG7YcjjWncKOSCzF2GA"], + ["user_世界_123", "SCgk4OzXlFMvo1UMsP88fA"], + ["açb↓c", "LxcqH5VC15rXfWfA_smreg"], + ])("keeps the 1.13.4 hash for %j", (unit, hash) => { + expect(hashUnit(unit)).toBe(hash); }); }); +// The published 1.13.4 package's hashes of "ux", one character per 256-code-point block of +// the Basic Multilingual Plane plus the surrogate and encoding-width edges, and of characters outside it. +// Only characters outside the BMP hash differently in 1.14.0; those now hash as canonical UTF-8. +describe("hashUnit() against 1.13.4", () => { + it.each(Object.entries(releasedHashes.bmp))("keeps the 1.13.4 hash for BMP code point U+%s", (codePoint, hash) => { + expect(hashUnit(`u${String.fromCharCode(parseInt(codePoint, 16))}x`)).toBe(hash); + }); + + it.each(Object.entries(releasedHashes.astral))( + "hashes code point U+%s as canonical UTF-8, not as 1.13.4 did", + (codePoint, { released: before, utf8 }) => { + const unit = `u${String.fromCodePoint(parseInt(codePoint, 16))}x`; + expect(hashUnit(unit)).toBe(utf8); + expect(utf8).not.toBe(before); + } + ); +}); + describe("chooseVariant()", () => { it("should return correct variant", (done) => { expect(chooseVariant([0.0, 1.0], 0.0)).toBe(1); @@ -315,17 +372,41 @@ describe("stringToUint8Array()", () => { done(); }); - it("should preserve the 1.13 encoding for every surrogate code unit", () => { - const cases = [ - ["\uD800", [0xed, 0xa0, 0x80]], - ["\uDC00", [0xed, 0xb0, 0x80]], - ["😀", [0xed, 0xa0, 0xbd, 0xed, 0xb8, 0x80]], - ["a\uD800b", [97, 0xed, 0xa0, 0x80, 98]], - ]; - for (const [input, bytes] of cases) { - const encoded = stringToUint8Array(input); - expect(Array.from(encoded)).toEqual(bytes); - expect(encoded.byteLength).toBe(encoded.buffer.byteLength); + // A surrogate pair is one 4-byte sequence; an unpaired surrogate keeps 1.13.4's 3-byte encoding, + // as the cross-SDK contract requires (an unpaired surrogate stays byte-identical to the release). + it.each([ + ["😀", [0xf0, 0x9f, 0x98, 0x80]], + ["a😀b", [97, 0xf0, 0x9f, 0x98, 0x80, 98]], + ["🧪", [0xf0, 0x9f, 0xa7, 0xaa]], + ["\uD800", [0xed, 0xa0, 0x80]], + ["\uDC00", [0xed, 0xb0, 0x80]], + ["a\uD800b", [97, 0xed, 0xa0, 0x80, 98]], + ["\uD800\uD800", [0xed, 0xa0, 0x80, 0xed, 0xa0, 0x80]], + ["\uDC00\uD800", [0xed, 0xb0, 0x80, 0xed, 0xa0, 0x80]], + ["\uD83D", [0xed, 0xa0, 0xbd]], + ["\uD83D\uD83D\uDE00", [0xed, 0xa0, 0xbd, 0xf0, 0x9f, 0x98, 0x80]], + ])("encodes %j", (input, bytes) => { + const encoded = stringToUint8Array(input); + expect(Array.from(encoded)).toEqual(bytes); + expect(encoded.byteLength).toBe(encoded.buffer.byteLength); + }); + + it("matches TextEncoder for every well-formed string", () => { + const encoder = new TextEncoder(); + for (const value of [ + "", + "test", + "açb↓c", + "世界你好", + "😀", + "a😀b😁c", + "\uFFFF", + "\u0800", + "\u07FF", + "𐀀", + "\uDBFF\uDFFF", + ]) { + expect([value, Array.from(stringToUint8Array(value))]).toEqual([value, Array.from(encoder.encode(value))]); } }); }); diff --git a/src/client.ts b/src/client.ts index df6eedf..5ca349d 100644 --- a/src/client.ts +++ b/src/client.ts @@ -22,6 +22,7 @@ export type ClientRequestOptions = { path: string; method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS"; body?: Record; + /** @deprecated The API key is sent by default; set to false to suppress auth headers. */ auth?: boolean; signal?: AbortSignal | ABsmartlyAbortSignal; timeout?: number; @@ -36,7 +37,7 @@ const RETRY_DELAY_MS = 50; export type ClientOptions = { agent?: string; apiKey: string; - application: string | { name: string; version: number }; + application: string | ApplicationObject; endpoint: string; environment: string; retries?: number; @@ -51,9 +52,8 @@ function applicationVersionHeader(version: number | string): number | string { return /^[0-9]{1,18}$/.test(String(candidate)) ? candidate : 0; } -export type ClientInputOptions = Omit & { - application: string | ApplicationObject; -}; +/** @deprecated Identical to ClientOptions, which now accepts a string application version. */ +export type ClientInputOptions = ClientOptions; type NormalizedClientOptions = Omit, "application"> & { application: ApplicationObject; @@ -63,10 +63,7 @@ export default class Client { private readonly _opts: NormalizedClientOptions; private readonly _delay: number; - // The released signature is declared last, so ConstructorParameters keeps its 1.13.4 type. - constructor(opts: ClientInputOptions); - constructor(opts: ClientOptions); - constructor(opts: ClientInputOptions) { + constructor(opts: ClientOptions) { const merged: Record = Object.assign( { agent: "javascript-client", @@ -109,10 +106,8 @@ export default class Client { } getContext(options?: Partial) { - // Routed through getUnauthed() as in 1.13.4, so a subclass overriding it is still called. - return this.getUnauthed({ + return this.get({ ...options, - auth: options?.auth !== false, path: "/context", query: { application: this._opts.application.name, @@ -188,7 +183,13 @@ export default class Client { keepalive: this._opts.keepalive, }; - if (options.auth) { + if (options.auth === true) { + console.warn( + "[ABsmartly] The `auth` option is deprecated. Auth headers are now sent by default. Remove `auth: true` from your request options." + ); + } + + if (options.auth !== false) { opts.headers = { "Content-Type": "application/json", "X-API-Key": this._opts.apiKey, @@ -245,11 +246,15 @@ export default class Client { return tryOnce().catch((reason: Error & { _bail?: boolean }) => { console.warn(reason); + // timeout <= 0 means "no deadline": the retry budget is governed by + // `retries` alone, so the elapsed-time check below must not apply. + const hasDeadline = timeout > 0; + if (reason._bail || retries <= 0) { throw new Error(reason.message); } else if (tries >= retries) { throw new RetryError(tries, reason, url); - } else if (waited >= timeout || reason.name === "AbortError") { + } else if ((hasDeadline && waited >= timeout) || reason.name === "AbortError") { if (tryWith.timedout) { throw new TimeoutError(timeout); } @@ -258,7 +263,7 @@ export default class Client { } let delay = (1 << tries) * this._delay + 0.5 * Math.random() * this._delay; - if (waited + delay > timeout) { + if (hasDeadline && waited + delay > timeout) { delay = timeout - waited; } @@ -278,8 +283,7 @@ export default class Client { options.signal.addEventListener("abort", abort); } - // `||`, as in 1.13.4: a request timeout of 0 falls back to the client timeout rather than disabling it. - const timeout = options.timeout || this._opts.timeout || 0; + const timeout = options.timeout ?? this._opts.timeout ?? 0; const timeoutId = timeout > 0 ? setTimeout(() => { @@ -295,8 +299,7 @@ export default class Client { } }; - // The retry budget falls back to the default when the client timeout is null/undefined, as in 1.13.4. - return tryWith(this._opts.retries ?? DEFAULT_RETRIES, options.timeout || (this._opts.timeout ?? DEFAULT_TIMEOUT_MS)) + return tryWith(this._opts.retries ?? DEFAULT_RETRIES, timeout) .then((value: string) => { finalCleanUp(); return value; @@ -310,7 +313,6 @@ export default class Client { post(options: ClientRequestOptions) { return this.request({ ...options, - auth: true, method: "POST", }); } @@ -318,7 +320,6 @@ export default class Client { put(options: ClientRequestOptions) { return this.request({ ...options, - auth: true, method: "PUT", }); } @@ -334,16 +335,12 @@ export default class Client { get(options: ClientRequestOptions) { return this.request({ ...options, - auth: options.auth !== false, method: "GET", }); } - // Plain GET with 1.13 semantics: headers only when `auth: true` is passed. Use get() for SDK headers. + /** @deprecated Use get() instead. */ getUnauthed(options: ClientRequestOptions) { - return this.request({ - ...options, - method: "GET", - }); + return this.get(options); } } diff --git a/src/context.ts b/src/context.ts index c6873c2..e36800b 100644 --- a/src/context.ts +++ b/src/context.ts @@ -179,7 +179,7 @@ export type Exposure = { fullOn: boolean; custom: boolean; audienceMismatch: boolean; - ruleOverride?: boolean; + ruleOverride: boolean; }; export type Attribute = { @@ -346,7 +346,7 @@ export default class Context { return this._failedError; } - ready(): Promise { + ready(): Promise { if (this.isReady()) { return Promise.resolve(true); } @@ -474,8 +474,19 @@ export default class Context { ); } + // A copy, so callers cannot change the context's units. Defined key by key: a spread would turn a + // unit type named `__proto__` into the copy's prototype. getUnits(): Units { - return this._units; + const units: Units = {}; + for (const unitType of Object.keys(this._units)) { + Object.defineProperty(units, unitType, { + value: this._units[unitType], + enumerable: true, + writable: true, + configurable: true, + }); + } + return units; } units(units: Record) { @@ -609,9 +620,9 @@ export default class Context { private _checkNotFinalized() { if (this.isFinalized()) { - throw new Error("ABSmartly Context is finalized."); + throw new Error("ABsmartly Context is finalized."); } else if (this.isFinalizing()) { - throw new Error("ABSmartly Context is finalizing."); + throw new Error("ABsmartly Context is finalizing."); } } @@ -648,7 +659,7 @@ export default class Context { private _checkReady(expectNotFinalized?: boolean) { if (!this.isReady()) { - throw new Error("ABSmartly Context is not yet ready."); + throw new Error("ABsmartly Context is not yet ready."); } if (expectNotFinalized) { @@ -661,12 +672,11 @@ export default class Context { private _getSystemAttributes(): Record { const client = this._sdk.getClient(); const systemAttrs: Record = {}; - // A custom `client` passed to the SDK may predate either getter. - const applicationName = typeof client?.getApplication === "function" ? client.getApplication()?.name : undefined; + const applicationName = client.getApplication()?.name; if (typeof applicationName === "string" && applicationName.length > 0) { systemAttrs["application"] = applicationName; } - const environmentName = typeof client?.getEnvironment === "function" ? client.getEnvironment() : undefined; + const environmentName = client.getEnvironment(); if (typeof environmentName === "string" && environmentName.length > 0) { systemAttrs["environment"] = environmentName; } @@ -690,6 +700,13 @@ export default class Context { } private _evaluateAudience(audience: string): boolean | null { + try { + JSON.parse(audience); + } catch (error) { + // Invalid audience JSON is indeterminate (null), as in 1.13.4, and reported to the eventLogger. + this._logError(new Error(`Invalid audience JSON: ${(error as Error).message}`)); + return null; + } try { return this._audienceMatcher.evaluate(audience, this._getAttributesMap()); } catch (error) { @@ -793,15 +810,6 @@ export default class Context { if (experimentName in this._assignments) { const assignment = this._assignments[experimentName]; - if ( - !assignment.exposed && - assignment.unitType != null && - (assignment.isRuleMissingUnit || assignment.holdoutAssignments?.some((item) => item === null)) && - hasOwn(this._units, assignment.unitType) - ) { - delete this._assignments[experimentName]; - return this._assign(experimentName); - } if (hasOverride) { if ( assignment.overridden && @@ -1398,14 +1406,22 @@ export default class Context { if (field.value === "") return ""; return JSON.parse(field.value); } catch (e) { - console.error(`Failed to parse JSON custom field value '${key}' for experiment '${experimentName}'`); + this._logError( + new Error( + `Failed to parse JSON custom field value '${key}' for experiment '${experimentName}': ${ + (e as Error).message + }` + ) + ); return null; } case "boolean": return field.value === "true"; default: - console.error( - `Unknown custom field type '${field.type}' for experiment '${experimentName}' and key '${key}' - you may need to upgrade to the latest SDK version` + this._logError( + new Error( + `Unknown custom field type '${field.type}' for experiment '${experimentName}' and key '${key}' - you may need to upgrade to the latest SDK version` + ) ); return null; } @@ -1633,7 +1649,7 @@ export default class Context { const client = this._sdk.getClient(); const systemAttributes: Attribute[] = []; - const agent = typeof client?.getAgent === "function" ? client.getAgent() : undefined; + const agent = client.getAgent(); if (!userSetSdkName && typeof agent === "string" && agent.length > 0) { systemAttributes.push({ name: "sdk_name", value: agent, setAt: systemSetAt }); } @@ -1678,6 +1694,12 @@ export default class Context { } if (this._failed) { + this._logError( + new Error( + `Discarding ${this._exposures.length} exposures and ${this._goals.length} goals because context failed to initialize` + ) + ); + this._pending = 0; this._exposures = []; this._goals = []; @@ -1959,7 +1981,7 @@ export default class Context { private _init(data: ContextData, assignments: Record = Object.create(null)) { this._data = data; const client = this._sdk.getClient(); - this._environmentName = typeof client?.getEnvironment === "function" ? client.getEnvironment() ?? null : null; + this._environmentName = client.getEnvironment() ?? null; const index: Record = Object.create(null); const indexVariables: Record = {}; diff --git a/src/matcher.ts b/src/matcher.ts index f9c1de8..b5723fe 100644 --- a/src/matcher.ts +++ b/src/matcher.ts @@ -35,8 +35,7 @@ export class AudienceMatcher { let audience; try { audience = JSON.parse(audienceString); - } catch (error) { - console.error(error); + } catch (_error) { return null; } diff --git a/src/sdk.ts b/src/sdk.ts index 5a69455..cae2a65 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -1,4 +1,4 @@ -import Client, { ClientInputOptions, ClientOptions, ClientRequestOptions } from "./client"; +import Client, { ClientOptions, ClientRequestOptions } from "./client"; import Context, { ContextData, ContextOptions, ContextParams, Exposure, Goal } from "./context"; import { ContextPublisher, PublishParams } from "./publisher"; import { ContextDataProvider } from "./provider"; @@ -33,11 +33,7 @@ export default class SDK { private _provider: ContextDataProvider; private readonly _client: Client; - // The released signature is declared last, so ConstructorParameters keeps its 1.13.4 type; - // the first overload additionally accepts a string application version. - constructor(options: ClientInputOptions & SDKOptions); - constructor(options: ClientOptions & SDKOptions); - constructor(options: ClientInputOptions & SDKOptions) { + constructor(options: ClientOptions & SDKOptions) { const clientOptions = SDK._extractClientOptions(options); options = Object.assign({}, options); @@ -47,8 +43,8 @@ export default class SDK { this._provider = options.provider || new ContextDataProvider(); } - private static _extractClientOptions(options: ClientInputOptions & SDKOptions): ClientInputOptions { - const clientOptionKeys: (keyof ClientInputOptions)[] = [ + private static _extractClientOptions(options: ClientOptions & SDKOptions): ClientOptions { + const clientOptionKeys: (keyof ClientOptions)[] = [ "application", "agent", "apiKey", @@ -58,19 +54,17 @@ export default class SDK { "retries", "timeout", ]; - const extracted: Partial = { + const extracted: Partial = { agent: `absmartly-javascript-sdk/${SDK_VERSION}`, }; - // Every own enumerable key is passed through, even when its value is undefined: the same key set - // 1.13.4 read with Object.entries (so `agent: undefined` still overrides the default and is rejected). for (const key of clientOptionKeys) { - if (options != null && Object.prototype.propertyIsEnumerable.call(options, key)) { + if (options?.[key] !== undefined) { extracted[key] = options[key] as never; } } - return extracted as ClientInputOptions; + return extracted as ClientOptions; } getContextData(requestOptions: ClientRequestOptions) { diff --git a/src/utils.ts b/src/utils.ts index f66f7a0..a2d6ba9 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -3,12 +3,8 @@ import { md5 } from "./md5"; export const getApplicationName = (app: string | { name: string; version: number | string }): string => typeof app !== "string" ? app.name : app; -export function getApplicationVersion(app: string | { name: string; version: number }): number; -export function getApplicationVersion(app: string | { name: string; version: number | string }): number | string; -export function getApplicationVersion(app: string | { name: string; version: number }): number; -export function getApplicationVersion(app: string | { name: string; version: number | string }): number | string { - return typeof app !== "string" ? app.version : 0; -} +export const getApplicationVersion = (app: string | { name: string; version: number | string }): number | string => + typeof app !== "string" ? app.version : 0; function isBrowser() { return typeof window !== "undefined" && typeof window.document !== "undefined"; @@ -179,32 +175,45 @@ export function toWellFormedString(value: string, replacement = "\ufffd"): strin return result; } -// Encodes each UTF-16 code unit on its own, exactly as 1.13 did, so unit hashes (and so variant -// assignment) don't move in a 1.x release. A character outside the BMP is therefore encoded as two -// 3-byte surrogate sequences, not 4-byte UTF-8; the canonical encoding is planned for 2.0. +// UTF-8, as the collector and the other SDKs hash units: a surrogate pair (a character outside the +// BMP, such as an emoji) is one 4-byte sequence. An unpaired surrogate keeps its 3-byte encoding from +// 1.13.4, as the cross-SDK contract requires, so only IDs with characters outside the BMP hash +// differently from 1.13.4. export function stringToUint8Array(value: string) { const n = value.length; const array = new Array(value.length); let k = 0; for (let i = 0; i < n; ++i) { - const c = value.charCodeAt(i); + let c = value.charCodeAt(i); + if (c >= 0xd800 && c <= 0xdbff && i + 1 < n) { + const next = value.charCodeAt(i + 1); + if (next >= 0xdc00 && next <= 0xdfff) { + c = ((c - 0xd800) << 10) + (next - 0xdc00) + 0x10000; + ++i; + } + } if (c < 0x80) { array[k++] = c; } else if (c < 0x800) { array[k++] = (c >> 6) | 192; array[k++] = (c & 63) | 128; - } else { + } else if (c < 0x10000) { array[k++] = (c >> 12) | 224; array[k++] = ((c >> 6) & 63) | 128; array[k++] = (c & 63) | 128; + } else { + array[k++] = (c >> 18) | 240; + array[k++] = ((c >> 12) & 63) | 128; + array[k++] = ((c >> 6) & 63) | 128; + array[k++] = (c & 63) | 128; } } - return Uint8Array.from(array); + return new Uint8Array(array); } // Standard UTF-8, for keys that must match the platform's String.getBytes(UTF_8) byte for byte -// (switchback cluster keys). Unit hashing keeps stringToUint8Array above; pass a well-formed string. +// (switchback cluster keys, made well-formed first). Unit hashing uses stringToUint8Array above. export function stringToUtf8Array(value: string) { if (typeof TextEncoder !== "undefined") { return new TextEncoder().encode(value); From 068989e121338b9583085e18b2c8557d28e28b75 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 00:27:54 +0000 Subject: [PATCH 87/92] fix: parse a valid audience once; review fixes for the 1.14.0 batch - Invalid audience JSON is only re-parsed when evaluate() is already null, so the added diagnostic no longer parses every audience twice (first assignment was about 50% slower). - `auth: true` warns once per request, not once per retry. - The compatibility runner checks accepted type breaks on every candidate compile (a vanished break fails) and compares each sweep UID's unit hash, not just its variant. - CHANGELOG: the `application.version` type change moves to Changed; how each missing custom-client getter fails, including createContext()'s rejected ready(); negative timeouts behave like 0. - Tests: a lone low-surrogate pair, a goal-only discard event, per-request warning, null client options, negative timeouts, the fetched-context getter failure and a single parse per audience. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 28 +++++--- release/1.14.0-compatibility.md | 4 +- scripts/compatibility/run.js | 11 ++-- scripts/compatibility/runtime.js | 8 +-- src/__tests__/release-compatibility.test.js | 73 +++++++++++++++++++++ src/__tests__/utils.test.js | 1 + src/client.ts | 12 ++-- src/context.ts | 20 +++--- 8 files changed, 122 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eed60e9..7f1d77c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,10 +10,6 @@ - Semantic-version expression operators (`semver_eq/gt/gte/lt/lte`) and `Evaluator.versionCompare`; old expression operators keep their conversion rules. - Optional `includeSystemAttributes` publishes `sdk_name` and `sdk_version` only. -- The `SDK` and `Client` constructors accept a string application version - (`application: { name, version: "1.2.3" }`): `ClientOptions.application.version` - is now `number | string`, and the deprecated `ClientInputOptions` is an alias of - `ClientOptions`. TypeScript code that reads `version` as a `number` must narrow it. - Tag-driven npm Trusted Publishing, a manual dry-run package preflight (it does not prove authentication works: npm may try to obtain an OIDC token but skips the upload), and a `repository` field in `package.json`, which npm provenance requires. @@ -87,6 +83,11 @@ - The `SDK` constructor ignores `agent`, `timeout`, `keepalive` and the other client options when they are explicitly `undefined`, so the defaults apply (1.13.4 passed `agent: undefined` through and the `Client` rejected it). +- `ClientOptions.application.version` is `number | string`, so the `SDK` and `Client` + constructors accept a string application version (`application: { name, version: +"1.2.3" }`); the deprecated `ClientInputOptions` is an alias of `ClientOptions`. + Affected: TypeScript code that reads `application.version` as a `number`, which must + now narrow it. - `ready()` is declared `Promise` (1.13.4 declared `Promise`); it resolves `true` as before, even when loading fails. - `getUnits()` returns a copy: editing it no longer changes the context's units. @@ -103,8 +104,14 @@ discarding them. Affected: event loggers that treat every `error` event as fatal, and log scrapers. - A custom `client` passed to the SDK must implement `getApplication()`, - `getEnvironment()` and `getAgent()` (the bundled `Client` has them); creating a - context with a client that lacks them throws a `TypeError`. + `getEnvironment()` and `getAgent()` (the bundled `Client` has them). Without + `getEnvironment()`, `createContextWith()` throws a `TypeError`, and a context from + `createContext()` never becomes ready: its `ready()` rejects with that `TypeError` + (1.13.4's never rejected), and Node reports an unhandled rejection if nothing waits + on it. Without `getApplication()`, evaluating an audience or assignment rule emits + a `TypeError` logger `error` event and the audience counts as a mismatch. Without + `getAgent()`, `publish()` with `includeSystemAttributes` rejects with a `TypeError`. + Affected: applications passing their own `client` object. - `variableValue()` no longer queues an exposure for an experiment the unit is not in (strict audience mismatch, or no unit for its unit type), even when that is the only experiment defining the key; 1.13.4 published one with @@ -116,10 +123,11 @@ - A per-request `timeout` now also bounds the retry budget; 1.13.4 always used the client timeout for it. Affected: callers passing a per-request `timeout` that differs from the client one, who now get more (or fewer) retries to match it. - `timeout: 0` now means no deadline: a request value of 0 no longer falls back to - the client timeout, and the request retries up to `retries` times without a time - limit (1.13.4 used the client timeout, and did not retry when that was 0 too). Affected: callers configuring - `timeout: 0`, whose requests can now wait indefinitely for a slow server. + `timeout: 0` (or a negative value) now means no deadline: a request value of 0 no + longer falls back to the client timeout, and the request retries up to `retries` + times without a time limit (1.13.4 used the client timeout, and did not retry when that was 0 too). Affected: callers configuring + `timeout: 0` or a negative timeout, whose requests can now wait indefinitely for a + slow server. - An audience whose evaluation throws now counts as a mismatch (fail closed) and emits one logger `error` event; in 1.13.4 it was ignored, so strict audiences could let users through. Affected: strict audiences with, for example, a throwing diff --git a/release/1.14.0-compatibility.md b/release/1.14.0-compatibility.md index b234f7a..b87274a 100644 --- a/release/1.14.0-compatibility.md +++ b/release/1.14.0-compatibility.md @@ -45,13 +45,13 @@ This inventories public source/runtime differences, not just this PR's delta. | `finalize()` inferred `true \| Promise` narrowed on main | d | Restore the released `true \| Promise` declaration, so old `=== true` guards compile; runtime was and remains Promise-only. | | Canonical UTF-8 for astral/unpaired surrogate UIDs changes hashes/assignment | b | Adopt canonical UTF-8 (owner decision 2026-11-26): an ID with a character outside the BMP hashes as 4-byte UTF-8 and can change variant; BMP text and unpaired surrogates keep the 1.13.4 hash. Documented under CHANGELOG Changed. | | Type-only inline imports raise declaration parser floor to TS4.5 | d | Restore old import syntax; TS3.9 consumer compile checks it. | -| New required getters on duck-typed custom clients | b | Keep required getters, no guards (owner decision 2026-11-26). CHANGELOG Changed. | +| New required getters on duck-typed custom clients | b | Keep required getters, no guards (owner decision 2026-11-26). CHANGELOG Changed lists how each missing getter fails, including `createContext()`'s rejected `ready()`. | | Abort shim reason/onabort/optional abort reason and idempotence | a/c | Keep native-standard cancellation bug fixes; no required method argument. | | Fetch global detection and clear no-fetch error | c | Keep fallback selection fix (old no-global environment was unusable). | | Query key escaping and malformed-surrogate normalization | c | Keep encoding fixes; ordinary URL values unchanged. | | Per-request timeout bounds the retry budget (1.13.4 used the client timeout) | c | Keep; listed under Changed with who is affected, and covered by a mutant-killing test. | | Invalid audience JSON stopped logging `console.error` | b | Report it as a logger `error` event `Invalid audience JSON: ...` with no console output (owner decision 2026-11-26); audience still indeterminate. | -| Main made `timeout: 0` mean "no deadline" (request) and "retry forever" (client) | b | Keep main (owner decision 2026-11-26): request 0 has no deadline, client 0 retries up to `retries` without a time limit. CHANGELOG Changed. | +| Main made `timeout: 0` mean "no deadline" (request) and "retry forever" (client) | b | Keep main (owner decision 2026-11-26): request 0 (or negative) has no deadline, client 0 retries up to `retries` without a time limit. CHANGELOG Changed. | | `getContext()` called `get()` directly, skipping a subclass `getUnauthed()` override | b | Keep main (owner decision 2026-11-26): `getContext()` calls `get()`. CHANGELOG Changed. | | `rfdc` 1.4.1 (lockfile) puts ES2015 syntax into the browser bundle and needs `Map`/`Set` at load | d | Lockfile pins `rfdc` 1.3.1 (range `^1.3.0` unchanged); rfdc is still transpiled; `scripts/check-es5.js` fails the build unless `dist/` is ES5 and starts without native `Map`/`Set`. | | Failed publisher loses events, synchronous failures and concurrent finalize races | c | Keep ordered restore/retry and promise settlement fixes. | diff --git a/scripts/compatibility/run.js b/scripts/compatibility/run.js index a86d7c4..f4b9dd0 100644 --- a/scripts/compatibility/run.js +++ b/scripts/compatibility/run.js @@ -42,6 +42,7 @@ const ACCEPTED_RUNTIME_DIFFERENCES = [ 'runtime.errors.notReady.message: "ABSmartly Context is not yet ready." -> "ABsmartly Context is not yet ready."', 'runtime.errors.finalized.message: "ABSmartly Context is finalized." -> "ABsmartly Context is finalized."', // Canonical UTF-8 unit hashing: sweep entry 256 is the emoji UID "😀", outside the BMP. + 'runtime.sweep.256.hash: "-Z9RwqljCn9rjBPBgYvAwg" -> "KgLqw51xanDs83V5GFkntg"', "runtime.sweep.256.peek: 0 -> 1", "runtime.sweep.256.treatment: 0 -> 1", ]; @@ -188,18 +189,18 @@ async function main() { ]) { const outcome = compile(tmp, path.join(compilerDir, "bin", "tsc"), pkg, `${alias}-${label}`); result.types[expected][label] = outcome; - if (label === "candidate" && !outcome.passed) { + if (label === "candidate") { outcome.unaccepted = unacceptedTypeErrors(outcome.output); outcome.accepted = outcome.unaccepted.length === 0; } - const status = outcome.passed - ? "PASS" - : outcome.accepted + const status = outcome.accepted ? "PASS (accepted 1.14.0 breaks only)" + : outcome.passed && !outcome.unaccepted + ? "PASS" : "FAIL"; console.log(`TypeScript ${expected} ${label}: ${status}`); if (!outcome.passed) console.error(outcome.output); - if (!outcome.passed && !outcome.accepted) { + if (outcome.unaccepted ? !outcome.accepted : !outcome.passed) { if (outcome.unaccepted) console.error(outcome.unaccepted.join("\n")); result.errors.push(`TypeScript ${expected} ${label} failed`); } diff --git a/scripts/compatibility/runtime.js b/scripts/compatibility/runtime.js index 615ad30..33e90d9 100644 --- a/scripts/compatibility/runtime.js +++ b/scripts/compatibility/runtime.js @@ -66,7 +66,7 @@ function errorOf(fn) { } } -async function measure(api) { +async function measure(api, hashUnit) { const events = []; const published = []; let providerCalls = 0; @@ -138,7 +138,7 @@ async function measure(api) { ]); for (const uid of uids) { const ctx = sdk.createContextWith({ units: { session_id: uid } }, fixture, contextOptions); - sweep.push({ uid, peek: ctx.peek("checkout"), treatment: ctx.treatment("checkout") }); + sweep.push({ uid, hash: hashUnit(uid), peek: ctx.peek("checkout"), treatment: ctx.treatment("checkout") }); } // The sweep must not pollute the lifecycle trace. return { values, states, errors, events: lifecycleEvents, published, providerCalls, sweep }; @@ -217,8 +217,8 @@ module.exports = async function compareRuntime(baselinePath, candidatePath) { let after; try { Date.now = () => CLOCK; - before = await measure(baseline); - after = await measure(candidate); + before = await measure(baseline, require(path.join(baselineDir, "lib", "utils")).hashUnit); + after = await measure(candidate, require(path.join(candidateDir, "lib", "utils")).hashUnit); } finally { Date.now = oldNow; } diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index d294ddb..56d61ce 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -407,6 +407,79 @@ describe("1.13.4 source and behaviour compatibility", () => { expect(messages).toContain("Discarding 1 exposures and 2 goals because context failed to initialize"); }); + it("warns about auth: true once per request, not once per retry, on every request", async () => { + sdkFetch + .mockRejectedValueOnce(new Error("connection refused")) + .mockRejectedValueOnce(new Error("connection refused")) + .mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({}) }); + const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); + const deprecation = () => warn.mock.calls.filter(([message]) => /deprecated/.test(String(message))).length; + try { + const client = new Client({ ...options, retries: 3 }); + await client.request({ path: "/x", method: "GET", auth: true }); + expect(sdkFetch).toHaveBeenCalledTimes(3); + expect(deprecation()).toBe(1); + await client.request({ path: "/x", method: "GET", auth: true }); + expect(deprecation()).toBe(2); + } finally { + warn.mockRestore(); + } + }); + + it("passes a null client option through to the Client, unlike an undefined one", () => { + expect(() => new SDK({ ...options, agent: null })).toThrow(); + expect(new SDK({ ...options, agent: undefined }).getClient().getAgent()).toBe( + `absmartly-javascript-sdk/${SDK_VERSION}` + ); + }); + + it("treats a negative timeout like 0: retries without a deadline", async () => { + sdkFetch.mockRejectedValue(new Error("connection refused")); + const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); + try { + const client = new Client({ ...options, timeout: 3000, retries: 3 }); + const error = await client.request({ path: "/x", method: "GET", timeout: -1 }).catch((e) => e); + expect(error.name).toBe("RetryError"); + expect(sdkFetch).toHaveBeenCalledTimes(4); + } finally { + warn.mockRestore(); + } + }); + + it("reports a discarded goal-only queue of a failed context", async () => { + const eventLogger = jest.fn(); + const provider = { getContextData: () => Promise.reject(new Error("load failed")) }; + const context = new SDK({ ...options, provider, eventLogger }).createContext({ units: { session_id: "u1" } }); + await context.ready(); + context.track("g1"); + await context.publish(); + const messages = eventLogger.mock.calls + .filter(([, eventName]) => eventName === "error") + .map(([, , error]) => error.message); + expect(messages).toContain("Discarding 0 exposures and 1 goals because context failed to initialize"); + }); + + it("rejects ready() of a fetched context whose custom client lacks getEnvironment()", async () => { + const client = { getContext: () => Promise.resolve({ experiments: [] }), publish: () => Promise.resolve() }; + const context = new SDK({ ...options, client }).createContext({ units: { session_id: "u1" } }); + await expect(context.ready()).rejects.toThrow(TypeError); + }); + + it("parses a valid audience once per evaluation", () => { + const parse = jest.spyOn(JSON, "parse"); + try { + const context = new SDK(options).createContextWith( + { units: { session_id: "u1" } }, + { experiments: [cacheProbeExperiment({ audience: '{"filter":[{"value":true}]}' })] } + ); + parse.mockClear(); + context.peek("cacheProbe"); + expect(parse.mock.calls.filter(([text]) => text === '{"filter":[{"value":true}]}')).toHaveLength(1); + } finally { + parse.mockRestore(); + } + }); + it("bounds retries by a per-request timeout that overrides the client timeout", async () => { sdkFetch.mockRejectedValue(new Error("connection refused")); const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); diff --git a/src/__tests__/utils.test.js b/src/__tests__/utils.test.js index 62bbd65..2530604 100644 --- a/src/__tests__/utils.test.js +++ b/src/__tests__/utils.test.js @@ -383,6 +383,7 @@ describe("stringToUint8Array()", () => { ["a\uD800b", [97, 0xed, 0xa0, 0x80, 98]], ["\uD800\uD800", [0xed, 0xa0, 0x80, 0xed, 0xa0, 0x80]], ["\uDC00\uD800", [0xed, 0xb0, 0x80, 0xed, 0xa0, 0x80]], + ["\uDC00\uDC00", [0xed, 0xb0, 0x80, 0xed, 0xb0, 0x80]], ["\uD83D", [0xed, 0xa0, 0xbd]], ["\uD83D\uD83D\uDE00", [0xed, 0xa0, 0xbd, 0xf0, 0x9f, 0x98, 0x80]], ])("encodes %j", (input, bytes) => { diff --git a/src/client.ts b/src/client.ts index 5ca349d..45c57cf 100644 --- a/src/client.ts +++ b/src/client.ts @@ -173,6 +173,12 @@ export default class Client { } } + if (options.auth === true) { + console.warn( + "[ABsmartly] The `auth` option is deprecated. Auth headers are now sent by default. Remove `auth: true` from your request options." + ); + } + const controller = new AbortController(); const tryOnce = () => { @@ -183,12 +189,6 @@ export default class Client { keepalive: this._opts.keepalive, }; - if (options.auth === true) { - console.warn( - "[ABsmartly] The `auth` option is deprecated. Auth headers are now sent by default. Remove `auth: true` from your request options." - ); - } - if (options.auth !== false) { opts.headers = { "Content-Type": "application/json", diff --git a/src/context.ts b/src/context.ts index e36800b..be19192 100644 --- a/src/context.ts +++ b/src/context.ts @@ -700,19 +700,23 @@ export default class Context { } private _evaluateAudience(audience: string): boolean | null { + let result: boolean | null; try { - JSON.parse(audience); - } catch (error) { - // Invalid audience JSON is indeterminate (null), as in 1.13.4, and reported to the eventLogger. - this._logError(new Error(`Invalid audience JSON: ${(error as Error).message}`)); - return null; - } - try { - return this._audienceMatcher.evaluate(audience, this._getAttributesMap()); + result = this._audienceMatcher.evaluate(audience, this._getAttributesMap()); } catch (error) { this._logError(error as Error); return false; } + // Invalid audience JSON is indeterminate (null), as in 1.13.4, and reported to the eventLogger. It is + // only parsed again when the result is already null, so a valid audience is parsed once. + if (result === null) { + try { + JSON.parse(audience); + } catch (error) { + this._logError(new Error(`Invalid audience JSON: ${(error as Error).message}`)); + } + } + return result; } // `now` is the clock reading a switchback resolves its period at; read here when not given. From 0e352d7da58cf4c3fc096015136ba015f0d57557 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 01:45:14 +0000 Subject: [PATCH 88/92] fix: review P3s for the 1.14.0 batch - CHANGELOG: a custom client without getApplication() makes reads of an experiment with assignment rules throw a TypeError; wrap the application-version and timeout entries. - Inventory: the application-version row points at CHANGELOG Changed. - Tests: a mismatching strict audience is parsed once; the getApplication() rule throw; the compatibility runner's accepted-break matcher (moved to scripts/compatibility/accepted.js so jest can load it) and its sweep hash. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 17 ++++---- release/1.14.0-compatibility.md | 2 +- .../__tests__/compatibility-accepted.test.js | 40 +++++++++++++++++++ scripts/compatibility/accepted.js | 40 +++++++++++++++++++ scripts/compatibility/run.js | 37 +---------------- src/__tests__/release-compatibility.test.js | 33 +++++++++++++++ 6 files changed, 125 insertions(+), 44 deletions(-) create mode 100644 scripts/__tests__/compatibility-accepted.test.js create mode 100644 scripts/compatibility/accepted.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f1d77c..41786b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -84,8 +84,9 @@ options when they are explicitly `undefined`, so the defaults apply (1.13.4 passed `agent: undefined` through and the `Client` rejected it). - `ClientOptions.application.version` is `number | string`, so the `SDK` and `Client` - constructors accept a string application version (`application: { name, version: -"1.2.3" }`); the deprecated `ClientInputOptions` is an alias of `ClientOptions`. + constructors accept a string application version + (`application: { name, version: "1.2.3" }`); the deprecated `ClientInputOptions` + is an alias of `ClientOptions`. Affected: TypeScript code that reads `application.version` as a `number`, which must now narrow it. - `ready()` is declared `Promise` (1.13.4 declared `Promise`); it @@ -108,8 +109,10 @@ `getEnvironment()`, `createContextWith()` throws a `TypeError`, and a context from `createContext()` never becomes ready: its `ready()` rejects with that `TypeError` (1.13.4's never rejected), and Node reports an unhandled rejection if nothing waits - on it. Without `getApplication()`, evaluating an audience or assignment rule emits - a `TypeError` logger `error` event and the audience counts as a mismatch. Without + on it. Without `getApplication()`, evaluating an audience emits a `TypeError` + logger `error` event and the audience counts as a mismatch, and `treatment()`, + `peek()` and `variableValue()` of an experiment with assignment rules throw that + `TypeError` to the caller. Without `getAgent()`, `publish()` with `includeSystemAttributes` rejects with a `TypeError`. Affected: applications passing their own `client` object. - `variableValue()` no longer queues an exposure for an experiment the unit is not @@ -125,9 +128,9 @@ differs from the client one, who now get more (or fewer) retries to match it. `timeout: 0` (or a negative value) now means no deadline: a request value of 0 no longer falls back to the client timeout, and the request retries up to `retries` - times without a time limit (1.13.4 used the client timeout, and did not retry when that was 0 too). Affected: callers configuring - `timeout: 0` or a negative timeout, whose requests can now wait indefinitely for a - slow server. + times without a time limit (1.13.4 used the client timeout, and did not retry when + that was 0 too). Affected: callers configuring `timeout: 0` or a negative timeout, + whose requests can now wait indefinitely for a slow server. - An audience whose evaluation throws now counts as a mismatch (fail closed) and emits one logger `error` event; in 1.13.4 it was ignored, so strict audiences could let users through. Affected: strict audiences with, for example, a throwing diff --git a/release/1.14.0-compatibility.md b/release/1.14.0-compatibility.md index b87274a..22843fb 100644 --- a/release/1.14.0-compatibility.md +++ b/release/1.14.0-compatibility.md @@ -32,7 +32,7 @@ This inventories public source/runtime differences, not just this PR's delta. | Low-level `Client` auth rules: `request()` authenticated by default, `post`/`put` honoured `auth:false`, `getUnauthed` became authenticated | b | Keep main (owner decision 2026-11-26): every request sends auth headers unless `auth: false`; `getUnauthed()` is a deprecated alias of `get()`. CHANGELOG Changed. | | `SDK` dropped client options passed as explicit `undefined` (`agent`, `timeout`, `keepalive`) | c | Keep main (owner decision 2026-11-26): explicitly undefined options fall back to the defaults. CHANGELOG Changed. | | Versioned SDK X-Agent | b | Add from generated package version; custom agent untouched. Direct `Client` default remains `javascript-client`. | -| String application version accepted; utility return widened | a/b | Keep main (owner decision 2026-11-26): `ClientOptions.application.version` is `number \| string`; `ClientInputOptions` is a deprecated alias. CHANGELOG Added. | +| String application version accepted; utility return widened | a/b | Keep main (owner decision 2026-11-26): `ClientOptions.application.version` is `number \| string`; `ClientInputOptions` is a deprecated alias. CHANGELOG Changed. | | Invalid/dotted application versions sent to collector Long header | c/b | Normalize GET and PUT to trimmed 1–18 ASCII digits or zero; retain full configured getter. | | Every publish adds `sdkVersion`, required `PublishParams.sdkVersion` | d | Restore 1.13 body/type (kept reverted, owner decision 2026-11-26); collector `PublishRequest` ignores this unknown field. SDK version remains in X-Agent and opt-in attributes. | | New normal-path auth deprecation warning | b | Keep (owner decision 2026-11-26): `auth: true` logs one `console.warn` per request. CHANGELOG Changed. | diff --git a/scripts/__tests__/compatibility-accepted.test.js b/scripts/__tests__/compatibility-accepted.test.js new file mode 100644 index 0000000..4e3b25d --- /dev/null +++ b/scripts/__tests__/compatibility-accepted.test.js @@ -0,0 +1,40 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ +const fs = require("fs"); +const path = require("path"); +const { unacceptedTypeErrors, ACCEPTED_RUNTIME_DIFFERENCES } = require("../compatibility/accepted"); + +const ruleOverride = + "consumer.ts(53,7): error TS2741: Property 'ruleOverride' is missing in type '{ id: number; }' but required in type 'Exposure'."; +const version = "consumer.ts(170,2): error TS2322: Type 'string | number' is not assignable to type 'number'."; +const detail = " Type 'string' is not assignable to type 'number'."; +const accepted = [ruleOverride, version, detail, version, detail, version, detail].join("\n"); + +test("accepts exactly the documented 1.14.0 type breaks", () => { + expect(unacceptedTypeErrors(accepted)).toEqual([]); +}); + +test("fails when an accepted type break disappears or repeats", () => { + expect(unacceptedTypeErrors("")).toHaveLength(2); + expect(unacceptedTypeErrors([version, version, version].join("\n"))).toHaveLength(1); + expect(unacceptedTypeErrors(`${accepted}\n${version}`)).toHaveLength(1); +}); + +test("fails on any other type error", () => { + const other = "consumer.ts(9,1): error TS2305: Module has no exported member 'Context'."; + expect(unacceptedTypeErrors(`${accepted}\n${other}`)).toEqual([other]); +}); + +test("accepts only the emoji UID's hash and variant change in the runtime sweep", () => { + const sweep = ACCEPTED_RUNTIME_DIFFERENCES.filter((line) => line.startsWith("runtime.sweep.")); + expect(sweep.map((line) => line.split(":")[0])).toEqual([ + "runtime.sweep.256.hash", + "runtime.sweep.256.peek", + "runtime.sweep.256.treatment", + ]); +}); + +test("the runtime sweep records each UID's unit hash, and UID 256 is the emoji", () => { + const source = fs.readFileSync(path.join(__dirname, "../compatibility/runtime.js"), "utf8"); + expect(source).toMatch(/sweep\.push\(\{ uid, hash: hashUnit\(uid\),/); + expect(source).toMatch(/Array\.from\(\{ length: 256 \}, \(_, i\) => `user-\$\{i\}`\)\.concat\(\[\s*"😀",/); +}); diff --git a/scripts/compatibility/accepted.js b/scripts/compatibility/accepted.js new file mode 100644 index 0000000..0e85e96 --- /dev/null +++ b/scripts/compatibility/accepted.js @@ -0,0 +1,40 @@ +"use strict"; + +// Breaks from 1.13.4 the owner accepted for 1.14.0 (2026-11-26), each listed under CHANGELOG Changed. +// Only these exact differences pass; any other type error or runtime difference still fails the run. +const ACCEPTED_TYPE_ERRORS = [ + // `Exposure.ruleOverride` is required. + { + pattern: /error TS2741: Property 'ruleOverride' is missing in type '[^']*' but required in type 'Exposure'\.$/, + count: 1, + }, + // `ClientOptions.application.version` is `number | string`; the three released numeric readers must narrow it. + { pattern: /error TS2322: Type 'string \| number' is not assignable to type 'number'\.$/, count: 3 }, +]; +const ACCEPTED_TYPE_DETAIL = /^\s+Type 'string' is not assignable to type 'number'\.$/; +const ACCEPTED_RUNTIME_DIFFERENCES = [ + // Error strings use the `ABsmartly` brand. + 'runtime.errors.notReady.message: "ABSmartly Context is not yet ready." -> "ABsmartly Context is not yet ready."', + 'runtime.errors.finalized.message: "ABSmartly Context is finalized." -> "ABsmartly Context is finalized."', + // Canonical UTF-8 unit hashing: sweep entry 256 is the emoji UID "😀", outside the BMP. + 'runtime.sweep.256.hash: "-Z9RwqljCn9rjBPBgYvAwg" -> "KgLqw51xanDs83V5GFkntg"', + "runtime.sweep.256.peek: 0 -> 1", + "runtime.sweep.256.treatment: 0 -> 1", +]; +function unacceptedTypeErrors(output) { + const counts = ACCEPTED_TYPE_ERRORS.map(() => 0); + const rest = []; + for (const line of output.split("\n")) { + if (!line.trim() || ACCEPTED_TYPE_DETAIL.test(line)) continue; + const index = ACCEPTED_TYPE_ERRORS.findIndex(({ pattern }) => pattern.test(line)); + if (index < 0) rest.push(line); + else counts[index]++; + } + ACCEPTED_TYPE_ERRORS.forEach(({ pattern, count }, i) => { + if (counts[i] !== count) + rest.push(`expected ${count} accepted error(s) matching ${pattern}, found ${counts[i]}`); + }); + return rest; +} + +module.exports = { ACCEPTED_TYPE_ERRORS, ACCEPTED_RUNTIME_DIFFERENCES, unacceptedTypeErrors }; diff --git a/scripts/compatibility/run.js b/scripts/compatibility/run.js index f4b9dd0..794649e 100644 --- a/scripts/compatibility/run.js +++ b/scripts/compatibility/run.js @@ -7,6 +7,7 @@ const os = require("os"); const path = require("path"); const child = require("child_process"); const runtime = require("./runtime"); +const { ACCEPTED_RUNTIME_DIFFERENCES, unacceptedTypeErrors } = require("./accepted"); function usage() { console.log(`Usage: node scripts/compatibility/run.js BASELINE_PACKAGE CANDIDATE_PACKAGE [--typescript-dir DIR] [--report FILE] @@ -25,42 +26,6 @@ and pass --typescript-dir /tmp/compat-ts/node_modules. No root configuration cha The JSON report contains all changed declaration text and all runtime export names; it includes failures even when the command exits nonzero. Temporary files are removed.`); } -// Breaks from 1.13.4 the owner accepted for 1.14.0 (2026-11-26), each listed under CHANGELOG Changed. -// Only these exact differences pass; any other type error or runtime difference still fails the run. -const ACCEPTED_TYPE_ERRORS = [ - // `Exposure.ruleOverride` is required. - { - pattern: /error TS2741: Property 'ruleOverride' is missing in type '[^']*' but required in type 'Exposure'\.$/, - count: 1, - }, - // `ClientOptions.application.version` is `number | string`; the three released numeric readers must narrow it. - { pattern: /error TS2322: Type 'string \| number' is not assignable to type 'number'\.$/, count: 3 }, -]; -const ACCEPTED_TYPE_DETAIL = /^\s+Type 'string' is not assignable to type 'number'\.$/; -const ACCEPTED_RUNTIME_DIFFERENCES = [ - // Error strings use the `ABsmartly` brand. - 'runtime.errors.notReady.message: "ABSmartly Context is not yet ready." -> "ABsmartly Context is not yet ready."', - 'runtime.errors.finalized.message: "ABSmartly Context is finalized." -> "ABsmartly Context is finalized."', - // Canonical UTF-8 unit hashing: sweep entry 256 is the emoji UID "😀", outside the BMP. - 'runtime.sweep.256.hash: "-Z9RwqljCn9rjBPBgYvAwg" -> "KgLqw51xanDs83V5GFkntg"', - "runtime.sweep.256.peek: 0 -> 1", - "runtime.sweep.256.treatment: 0 -> 1", -]; -function unacceptedTypeErrors(output) { - const counts = ACCEPTED_TYPE_ERRORS.map(() => 0); - const rest = []; - for (const line of output.split("\n")) { - if (!line.trim() || ACCEPTED_TYPE_DETAIL.test(line)) continue; - const index = ACCEPTED_TYPE_ERRORS.findIndex(({ pattern }) => pattern.test(line)); - if (index < 0) rest.push(line); - else counts[index]++; - } - ACCEPTED_TYPE_ERRORS.forEach(({ pattern, count }, i) => { - if (counts[i] !== count) - rest.push(`expected ${count} accepted error(s) matching ${pattern}, found ${counts[i]}`); - }); - return rest; -} function exec(command, args, options) { const result = child.spawnSync(command, args, { encoding: "utf8", ...options }); if (result.error) throw result.error; diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 56d61ce..2c67004 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -465,6 +465,39 @@ describe("1.13.4 source and behaviour compatibility", () => { await expect(context.ready()).rejects.toThrow(TypeError); }); + it("parses a mismatching strict audience once per evaluation", () => { + const audience = '{"filter":[{"value":false}]}'; + const parse = jest.spyOn(JSON, "parse"); + try { + const context = new SDK(options).createContextWith( + { units: { session_id: "u1" } }, + { experiments: [cacheProbeExperiment({ audience, audienceStrict: true })] } + ); + parse.mockClear(); + expect(context.peek("cacheProbe")).toBe(0); + expect(parse.mock.calls.filter(([text]) => text === audience)).toHaveLength(1); + } finally { + parse.mockRestore(); + } + }); + + it("throws a TypeError reading a rule experiment through a custom client without getApplication()", () => { + const client = { + getContext: () => Promise.resolve({ experiments: [] }), + publish: () => Promise.resolve(), + getEnvironment: () => "prod", + getAgent: () => "agent", + }; + const experiment = cacheProbeExperiment({ + assignmentRules: JSON.stringify({ rules: [{ type: "assign", variant: 1, conditions: { value: true } }] }), + }); + const context = new SDK({ ...options, client, eventLogger() {} }).createContextWith( + { units: { session_id: "u1" } }, + { experiments: [experiment] } + ); + expect(() => context.peek("cacheProbe")).toThrow(TypeError); + }); + it("parses a valid audience once per evaluation", () => { const parse = jest.spyOn(JSON, "parse"); try { From e339a795a03a448ee1abc9cf04da40e65b5f4709 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 02:30:38 +0000 Subject: [PATCH 89/92] test(compat): pin how strictly the runner matches accepted type breaks The same error for another type, an unaccepted error's own detail lines and a non-error compiler line are all reported. Co-Authored-By: Claude Opus 5.5 --- .../__tests__/compatibility-accepted.test.js | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/scripts/__tests__/compatibility-accepted.test.js b/scripts/__tests__/compatibility-accepted.test.js index 4e3b25d..ce1b4b5 100644 --- a/scripts/__tests__/compatibility-accepted.test.js +++ b/scripts/__tests__/compatibility-accepted.test.js @@ -38,3 +38,23 @@ test("the runtime sweep records each UID's unit hash, and UID 256 is the emoji", expect(source).toMatch(/sweep\.push\(\{ uid, hash: hashUnit\(uid\),/); expect(source).toMatch(/Array\.from\(\{ length: 256 \}, \(_, i\) => `user-\$\{i\}`\)\.concat\(\[\s*"😀",/); }); + +test("does not accept the same errors for a different type", () => { + const otherType = ruleOverride.replace("type 'Exposure'", "type 'Goal'"); + expect(unacceptedTypeErrors(accepted.replace(ruleOverride, otherType))).toContain(otherType); + const otherAssign = "consumer.ts(9,1): error TS2322: Type 'string | number' is not assignable to type 'boolean'."; + expect(unacceptedTypeErrors(`${accepted}\n${otherAssign}`)).toEqual([otherAssign]); +}); + +test("reports an unaccepted error's own detail lines", () => { + const other = "consumer.ts(9,1): error TS2322: Type 'Foo' is not assignable to type 'Bar'."; + const otherDetail = " Property 'x' is missing in type 'Foo'."; + expect(unacceptedTypeErrors(`${accepted}\n${other}\n${otherDetail}`)).toEqual([other, otherDetail]); +}); + +test("reports a compiler message line that is not an error", () => { + const message = "error: TS5083: Cannot read file 'tsconfig.json'."; + const note = "consumer.ts(1,1): message TS6000: something unexpected"; + expect(unacceptedTypeErrors(`${accepted}\n${note}`)).toEqual([note]); + expect(unacceptedTypeErrors(`${accepted}\n${message}`)).toEqual([message]); +}); From 77813d1261836f20fa76e2c332c11a05647a0ac7 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 02:39:46 +0000 Subject: [PATCH 90/92] test(compat): pin the detail-line anchor and the accepted Exposure property Co-Authored-By: Claude Opus 5.5 --- scripts/__tests__/compatibility-accepted.test.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/scripts/__tests__/compatibility-accepted.test.js b/scripts/__tests__/compatibility-accepted.test.js index ce1b4b5..afdcf50 100644 --- a/scripts/__tests__/compatibility-accepted.test.js +++ b/scripts/__tests__/compatibility-accepted.test.js @@ -58,3 +58,13 @@ test("reports a compiler message line that is not an error", () => { expect(unacceptedTypeErrors(`${accepted}\n${note}`)).toEqual([note]); expect(unacceptedTypeErrors(`${accepted}\n${message}`)).toEqual([message]); }); + +test("reports a top-level error that matches the accepted detail text", () => { + const topLevel = "consumer.ts(9,1): error TS2322: Type 'string' is not assignable to type 'number'."; + expect(unacceptedTypeErrors(`${accepted}\n${topLevel}`)).toEqual([topLevel]); +}); + +test("does not accept another missing Exposure property", () => { + const otherProperty = ruleOverride.replace("'ruleOverride'", "'foo'"); + expect(unacceptedTypeErrors(accepted.replace(ruleOverride, otherProperty))).toContain(otherProperty); +}); From b18198a89944017b4858a7bc60b47a1ebfefdd28 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 03:00:26 +0000 Subject: [PATCH 91/92] test(es5): run every IE 10 probe without ES2015 typed-array methods Jervasion round 6: the switchback probe kept Uint8Array.prototype.slice, so a cluster-key copy using it passed the gate but throws in IE 10. All three probes (startup, null-parent audience, switchback) now share one IE 10 realm with no Map/Set, Reflect, setPrototypeOf, __proto__, TextEncoder, ArrayBuffer slice/isView or ES2015 typed-array methods. typed-array slice(), ArrayBuffer slice() and map() copies now fail the build; Uint8Array.from is polyfilled by the bundle. Also from the review's suggestions: publish steps must match one plain `npm publish ... --tag "$DIST_TAG"` command, release/PUBLISHING.md documents recovering from a cancelled or failed tag run, and a comment that restated its assertion is gone. Co-Authored-By: Claude Opus 5.5 --- release/PUBLISHING.md | 7 + scripts/__tests__/check-release.test.js | 10 +- scripts/check-es5.js | 139 ++++++++++---------- src/__tests__/release-compatibility.test.js | 1 - 4 files changed, 81 insertions(+), 76 deletions(-) diff --git a/release/PUBLISHING.md b/release/PUBLISHING.md index f159e77..050f46d 100644 --- a/release/PUBLISHING.md +++ b/release/PUBLISHING.md @@ -18,6 +18,13 @@ group `npm-publish-absmartly-javascript-sdk`, with `cancel-in-progress: false`. Registry/tag validation and publishing run inside that same locked job, so concurrent release tags cannot both validate against a stale `latest` and then move it backwards. +If a tag run is cancelled or fails before the publish step, nothing reached npm: +re-run the failed job from the Actions page (same tag, same commit). If it failed +after npm accepted the version, do not re-tag; `npm view @absmartly/javascript-sdk@` +confirms the upload, and `npm dist-tag add @absmartly/javascript-sdk@ ` +fixes a missing or wrong distribution tag. Never delete and re-push a tag to retry: a +moved tag no longer matches the published provenance. + `workflow_dispatch` is **always a dry run** and is a package preflight only: it checks the version, tag selection, build and package contents. npm's dry run skips the authenticated publish request, so it does not prove OIDC (or any token) works; the diff --git a/scripts/__tests__/check-release.test.js b/scripts/__tests__/check-release.test.js index bd61cdb..160d553 100644 --- a/scripts/__tests__/check-release.test.js +++ b/scripts/__tests__/check-release.test.js @@ -200,12 +200,14 @@ describe("publish workflow", () => { 120000 ); - // The dry-run probe above inspects one command per step, so a second command would go unchecked. + // The dry-run probe above inspects one command per step, so each publish step must be exactly one + // single-line `npm publish` command with plain flags: no second command, separator or substitution. test("each publish step runs exactly one npm publish command", () => { for (const step of job.steps.filter((s) => /\bnpm\s+publish\b/.test(s.run || ""))) { - const commands = step.run.split("\n").filter((l) => /\bnpm\s+publish\b/.test(l)); - expect({ step: step.name, commands: commands.length }).toEqual({ step: step.name, commands: 1 }); - expect(commands[0]).toMatch(/^\s*npm publish\b/); + expect({ step: step.name, run: step.run.trim() }).toEqual({ + step: step.name, + run: expect.stringMatching(/^npm publish(?: --[a-z-]+(?: [a-z]+)?)+ --tag "\$DIST_TAG"$/), + }); } }); diff --git a/scripts/check-es5.js b/scripts/check-es5.js index 988c2ff..551d2b7 100644 --- a/scripts/check-es5.js +++ b/scripts/check-es5.js @@ -7,6 +7,51 @@ const vm = require("vm"); // The arms Node (native TextEncoder) serves for this probe; IE 10 must serve the same ones. const EXPECTED_IE10_SWITCHBACK_ARMS = [0, 2, 1, 0, 1, 2, 1, 0, 2, 1, 2, 0]; +// IE 10 lacks native Map/Set, Reflect, Object.setPrototypeOf, __proto__, TextEncoder, +// ArrayBuffer.prototype.slice, ArrayBuffer.isView and every ES2015 typed-array method; its typed +// arrays have only buffer, byteLength, byteOffset, length, set and subarray. Each probe runs the bundle +// in a fresh realm with all of these removed. +const IE10_PRELUDE = ` + delete this.Map; + delete this.Set; + delete this.WeakMap; + delete this.WeakSet; + delete this.Reflect; + delete this.TextEncoder; + delete Object.setPrototypeOf; + delete Object.prototype.__proto__; + delete ArrayBuffer.prototype.slice; + delete ArrayBuffer.isView; + (function () { + var TypedArray = Object.getPrototypeOf(Uint8Array); + var keep = ["constructor", "buffer", "byteLength", "byteOffset", "length", "set", "subarray"]; + Object.getOwnPropertyNames(TypedArray.prototype).forEach(function (name) { + if (keep.indexOf(name) < 0) delete TypedArray.prototype[name]; + }); + Object.getOwnPropertySymbols(TypedArray.prototype).forEach(function (symbol) { + delete TypedArray.prototype[symbol]; + }); + delete TypedArray.from; + delete TypedArray.of; + })(); +`; + +function ie10Realm(target) { + const sandbox = { + setTimeout, + clearTimeout, + setInterval, + clearInterval, + Promise, + console: { ...console, error() {} }, + }; + sandbox.self = sandbox; + const context = vm.createContext(sandbox); + vm.runInContext(IE10_PRELUDE, context); + vm.runInContext(fs.readFileSync(target, "utf8"), context, { timeout: 10000 }); + return context; +} + let failed = false; for (const file of ["absmartly.js", "absmartly.min.js"]) { const target = path.resolve(__dirname, "../dist", file); @@ -17,65 +62,28 @@ for (const file of ["absmartly.js", "absmartly.min.js"]) { failed = true; continue; } - try { - const sandbox = { - console, - setTimeout, - clearTimeout, - setInterval, - clearInterval, - Promise, - Map: undefined, - Set: undefined, - WeakMap: undefined, - WeakSet: undefined, - }; - sandbox.self = sandbox; - vm.runInNewContext(fs.readFileSync(target, "utf8"), sandbox, { timeout: 10000 }); - if (typeof sandbox.absmartly?.SDK !== "function") - throw new Error("SDK did not load without native collections"); - console.log(`ES5 and legacy startup OK: dist/${file}`); - } catch (error) { - console.error(`dist/${file} does not start without native Map/Set: ${error.message}`); - failed = true; - continue; - } - try { - checkIe10NullParentAudience(target); - console.log(`IE 10 null-parent audience OK: dist/${file}`); - } catch (error) { - console.error(`dist/${file} breaks a null-parent audience on IE 10: ${error.message}`); - failed = true; - } - try { - checkIe10Switchback(target); - console.log(`IE 10 switchback OK: dist/${file}`); - } catch (error) { - console.error(`dist/${file} breaks a switchback on IE 10: ${error.message}`); - failed = true; + for (const [label, check] of [ + ["legacy startup", checkIe10Startup], + ["null-parent audience", checkIe10NullParentAudience], + ["switchback", checkIe10Switchback], + ]) { + try { + check(ie10Realm(target)); + console.log(`IE 10 ${label} OK: dist/${file}`); + } catch (error) { + console.error(`dist/${file} breaks ${label} on IE 10: ${error.message}`); + failed = true; + } } } -// IE 10 has no Reflect, Object.setPrototypeOf or __proto__. A null-parent audience path must stay -// indeterminate there (as in 1.13.4), not fail closed. Runs the bundle in a fresh realm with those removed. -function checkIe10NullParentAudience(target) { - const prelude = ` - delete this.Reflect; - delete Object.setPrototypeOf; - delete Object.prototype.__proto__; - `; - const sandbox = { - setTimeout, - clearTimeout, - setInterval, - clearInterval, - Promise, - console: { ...console, error() {} }, - }; - sandbox.self = sandbox; - const context = vm.createContext(sandbox); - vm.runInContext(prelude, context); - vm.runInContext(fs.readFileSync(target, "utf8"), context, { timeout: 10000 }); +function checkIe10Startup(context) { + if (vm.runInContext("typeof absmartly !== 'undefined' && typeof absmartly.SDK", context) !== "function") + throw new Error("SDK did not load"); +} + +// A null-parent audience path must stay indeterminate on IE 10 (as in 1.13.4), not fail closed. +function checkIe10NullParentAudience(context) { const probe = `(function () { var errors = 0; var sdk = new absmartly.SDK({ endpoint: "http://x/v1", apiKey: "k", application: "web", environment: "prod", @@ -94,21 +102,10 @@ function checkIe10NullParentAudience(target) { throw new Error(`expected variant 1 and 0 error events, got ${JSON.stringify(result)}`); } } -// IE 10 has no TextEncoder and no ArrayBuffer.prototype.slice. A switchback must still resolve its -// cluster's scheduled arm there, the same arm Node gives (12 hourly periods of a 3-arm schedule). -function checkIe10Switchback(target) { - const sandbox = { - setTimeout, - clearTimeout, - setInterval, - clearInterval, - Promise, - console: { ...console, error() {} }, - }; - sandbox.self = sandbox; - const context = vm.createContext(sandbox); - vm.runInContext("delete this.TextEncoder; delete ArrayBuffer.prototype.slice;", context); - vm.runInContext(fs.readFileSync(target, "utf8"), context, { timeout: 10000 }); + +// A switchback must resolve its cluster's scheduled arm on IE 10, the same arm Node gives (12 hourly +// periods of a 3-arm schedule). +function checkIe10Switchback(context) { const probe = `(function () { var errors = 0; var sdk = new absmartly.SDK({ endpoint: "http://x/v1", apiKey: "k", application: "web", environment: "prod", diff --git a/src/__tests__/release-compatibility.test.js b/src/__tests__/release-compatibility.test.js index 2c67004..28e2998 100644 --- a/src/__tests__/release-compatibility.test.js +++ b/src/__tests__/release-compatibility.test.js @@ -150,7 +150,6 @@ describe("1.13.4 source and behaviour compatibility", () => { context.attribute("age", 1); experiments.forEach((experiment) => expect(context.treatment(experiment.name)).toBe(1)); expect(context.treatment("ordinary")).toBe(1); - // Nothing tried to parse a rule set that is not a non-empty string. expect(errorSpy).not.toHaveBeenCalled(); } finally { errorSpy.mockRestore(); From 750ba5b47c0626da26fc5209dace92e4eaff1ef6 Mon Sep 17 00:00:00 2001 From: lux worker Date: Fri, 27 Nov 2026 03:16:39 +0000 Subject: [PATCH 92/92] docs(release): dist-tag repair is run locally by a package owner Co-Authored-By: Claude Opus 5.5 --- release/PUBLISHING.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/release/PUBLISHING.md b/release/PUBLISHING.md index 050f46d..411209d 100644 --- a/release/PUBLISHING.md +++ b/release/PUBLISHING.md @@ -21,8 +21,10 @@ release tags cannot both validate against a stale `latest` and then move it back If a tag run is cancelled or fails before the publish step, nothing reached npm: re-run the failed job from the Actions page (same tag, same commit). If it failed after npm accepted the version, do not re-tag; `npm view @absmartly/javascript-sdk@` -confirms the upload, and `npm dist-tag add @absmartly/javascript-sdk@ ` -fixes a missing or wrong distribution tag. Never delete and re-push a tag to retry: a +confirms the upload, and an owner with publish rights on the package runs +`npm dist-tag add @absmartly/javascript-sdk@ ` locally to fix a missing +or wrong distribution tag (the workflow publishes through OIDC with no token, so it +cannot run this). Never delete and re-push a tag to retry: a moved tag no longer matches the published provenance. `workflow_dispatch` is **always a dry run** and is a package preflight only: it checks