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/.github/workflows/cross-sdk.yml b/.github/workflows/cross-sdk.yml new file mode 100644 index 0000000..f0d9968 --- /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@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + path: javascript-sdk + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + repository: absmartly/cross-sdk-tests + ref: ada8952293a8d4ebf81f8de038f4e7a406d98870 + path: cross-sdk-tests + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: '24' + cache: npm + cache-dependency-path: javascript-sdk/package-lock.json + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # 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@b7c566a772e6b6bfb58ed0dc250532a479d7789f # 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..de5463b --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,59 @@ +name: Publish to npm + +on: + push: + tags: + - 'v*' + workflow_dispatch: + +permissions: + contents: read + id-token: write + +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@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + + - name: Setup Node.js + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # 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 + + # 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: 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/.prettierignore b/.prettierignore index 2d45652..4281bcb 100644 --- a/.prettierignore +++ b/.prettierignore @@ -6,5 +6,7 @@ js lib types package-lock.json + +.claude # Vendored byte-for-byte from absmartly/abs; never reformat. src/__tests__/fixtures/switchback diff --git a/CHANGELOG.md b/CHANGELOG.md index 72471d1..41786b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,15 +1,219 @@ # Changelog -## 1.14.0 (unreleased) - -Earlier release notes are on the [GitHub releases page](https://github.com/absmartly/javascript-sdk/releases); the [Migration Guide](README.md#migration-guide-113x--1140) lists the other changes in 1.14.0. +## 1.14.0 ### Added -- Switchback experiments (R33, cluster-defined): an experiment with `randomizationType: "switchback"` is served by cluster and period through the existing `treatment()`, `peek()`, `variableValue()` and `peekVariableValue()`, matching the collector and java-sdk. `ExperimentData` gains the optional `randomizationType`, `switchbackClusters`, `switchbackClusterValues`, `switchbackStartAt`, `switchbackPeriodMs`, `switchbackCarryoverDurationMs`, `switchbackBurnInDurationMs`, `switchbackBurnOutDurationMs`, `switchbackDesignType` and `switchbackEstimand` fields. There is no new method or option. See [Switchback Experiments](README.md#switchback-experiments). -- Known limitation: JavaScript cannot tell `3.0` from `3`, so a cluster attribute set to an integral float is keyed like the integer (`"3"`), where other SDKs give a float no cluster value. A cluster map with two or more linked unit types, one named like an array index (`"1"`), cannot keep its declared order in JavaScript, so it is served as an ineligible control (variant 0, no exposure). +- `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, 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. +- Switchback experiments (R33, cluster-defined): an experiment with + `randomizationType: "switchback"` is served by cluster and period through the + existing `treatment()`, `peek()`, `variableValue()` and `peekVariableValue()`, + matching the collector and java-sdk. `ExperimentData` gains the optional + `randomizationType`, `switchbackClusters`, `switchbackClusterValues`, + `switchbackStartAt`, `switchbackPeriodMs`, `switchbackCarryoverDurationMs`, + `switchbackBurnInDurationMs`, `switchbackBurnOutDurationMs`, + `switchbackDesignType` and `switchbackEstimand` fields. There is no new method + or option. See [Switchback Experiments](README.md#switchback-experiments). +- Known limitation: JavaScript cannot tell `3.0` from `3`, so a cluster + attribute set to an integral float is keyed like the integer (`"3"`), where + other SDKs give a float no cluster value. A cluster map with two or more + linked unit types, one named like an array index (`"1"`), cannot keep its + declared order in JavaScript, so it is served as an ineligible control + (variant 0, no exposure). ### Changed -- Shared variable keys pick and expose one experiment, as the Java SDK does. Before, `variableValue()` exposed every experiment it checked that had the key, including ones the unit was not in (for example a strict audience mismatch or a switchback that gives way), which recorded users in experiments they never saw; and 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. Now 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, and returns its variant's value (`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 (an out-of-range overridden, custom or full-on winner is exposed with that variant; a silent switchback winner, before its schedule starts or with an ineligible cluster, returns control and records nothing); each checked candidate's applicable holdouts still fire, as in Java. `peekVariableValue()` exposes nothing. A `variableValue()` read queues all its exposures before its `exposure` and `error` callbacks run, and a `treatment()` with holdouts queues its exposures before their `exposure` callbacks (an audience `error` raised by `treatment()` itself is still reported first), so a callback that calls `finalize()` or `publish()` sends every one of them; such a callback now sees them already pending. 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. A cached `variableValue()` or `peekVariableValue()` (four experiments sharing a key) is about 3x faster than the previous unreleased build (about 21–26 vs 65 ns, versus about 155 ns in 1.13.4) and no longer allocates; `treatment()` and `peek()` are unchanged within noise (shared-host measurements, approximate). A cached assignment or switchback slot 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, including names like `toString` or `__proto__`; a variant config that defines such a key (`toString`, `constructor`, `__proto__`) no longer fails the context. Who moves: anyone with two or more running experiments sharing a variable key, and anyone counting exposures from `variableValue()` on an experiment the unit is not in (use `treatment()` to record those). -- 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 gets its cluster's scheduled variant for the current period unless an override, assignment rule, strict audience mismatch, full-on setting, a not-yet-started schedule (control, no exposure), a traffic miss or `customAssignment()` decides it first (see Switchback Experiments in the README for the exact order), and exposures are recorded once per period under the serving unit, while that period's assignment stays cached. Who moves: customers who run switchback experiments. The switchback support itself does not change unit experiments or context data without switchbacks; the separate shared-variable-key fix above can change their variable reads. +- 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 + gets its cluster's scheduled variant for the current period unless an + override, assignment rule, strict audience mismatch, full-on setting, a + not-yet-started schedule (control, no exposure), a traffic miss or + `customAssignment()` decides it first (see Switchback Experiments in the + README for the exact order), and exposures are recorded once per period under + the serving unit, while that period's assignment stays cached. Who moves: + customers who run switchback experiments. The switchback support itself does + not change unit experiments or context data without switchbacks; the separate + shared-variable-key fix can change their variable reads. +- 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. `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; + 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. `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). +- `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. + 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). 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 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 + 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. 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. + `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 + 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. +- Each read now also checks the assignment-rule, holdout and missing-unit state. + 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()` 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 + +- 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()`. +- 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 (a silent switchback winner, before its schedule starts or + with an ineligible cluster, returns control and records nothing); each checked + 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 or switchback slot 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 + 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 and starts in IE 10 with only a Promise polyfill: + the lockfile pins `rfdc` 1.3.1 (the dependency range is still `^1.3.0`), since + 1.4 ships ES2015 syntax and needs `Map`/`Set` when it loads. `rfdc` is still + transpiled, and the build fails if `dist/` is not ES5 or does not start without + native `Map`/`Set`. +- 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/README.md b/README.md index e9a586b..1ea8333 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 @@ -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 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', - 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 } ``` @@ -229,24 +234,27 @@ 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. A switchback that wins but is silent (before its schedule starts, or with an ineligible cluster) returns its control value and records nothing, and later experiments are still not used. `peekVariableValue()` never queues an exposure. +A cached `variableValue()` or `peekVariableValue()` does not allocate; see the +CHANGELOG for measured read costs. + ### 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. ```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 } ``` @@ -264,14 +272,14 @@ 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, }); ``` ### Switchback Experiments -A switchback experiment randomizes *clusters* over time instead of units. A cluster is a value of a context attribute, for example a store's region. Every unit in the same cluster sees the same variant during a period, and the variant changes on a fixed time grid. There is nothing new to call: `treatment()`, `peek()`, `variableValue()` and `peekVariableValue()` serve switchback experiments, and the A/B Smartly collector sends their configuration with the context data. +A switchback experiment randomizes _clusters_ over time instead of units. A cluster is a value of a context attribute, for example a store's region. Every unit in the same cluster sees the same variant during a period, and the variant changes on a fixed time grid. There is nothing new to call: `treatment()`, `peek()`, `variableValue()` and `peekVariableValue()` serve switchback experiments, and the A/B Smartly collector sends their configuration with the context data. ```javascript context.units({ store_id: "store-1234" }); @@ -302,7 +310,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", }); ``` @@ -320,7 +328,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, }); ``` @@ -337,34 +345,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, }); ``` @@ -374,15 +386,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); + } + }, }); ``` @@ -390,24 +402,24 @@ 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 | - -`"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. +| 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 | + +`"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 @@ -416,11 +428,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 @@ -431,11 +447,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); @@ -453,36 +473,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"); + } }); ``` @@ -492,29 +512,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 ``` @@ -526,24 +543,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(); @@ -551,57 +568,36 @@ 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() }); }); ``` -## Migration Guide (1.13.x → 1.14.0) - -Version 1.14.0 contains a few breaking changes. Most applications will not need code changes, but review the items below. +## Upgrading from 1.13.4 -### `ready()` no longer resolves with the Error object on failure +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. -**Before:** `ready()` resolved with the Error object on failure (e.g., `const result = await context.ready()` would give you the Error). +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. -**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. ### Switchback experiments are served @@ -620,6 +616,7 @@ An audience filter that throws while being evaluated is treated as a mismatch, s **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-lock.json b/package-lock.json index f41e88d..c6ef8a1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -37,12 +37,14 @@ "@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", "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", @@ -1927,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", @@ -1951,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", @@ -1999,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", @@ -3494,9 +3540,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" @@ -3598,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", @@ -4734,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", @@ -4837,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", @@ -7456,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" @@ -7654,6 +7728,12 @@ "dev": true, "license": "MIT" }, + "node_modules/listr2/node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "dev": true + }, "node_modules/listr2/node_modules/string-width": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", @@ -8756,10 +8836,9 @@ } }, "node_modules/rfdc": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", - "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", - "license": "MIT" + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.3.1.tgz", + "integrity": "sha512-r5a3l5HzYlIC68TpmYKlxWjmOP6wiPJ1vWv2HeLhNsRZMrCkxeqxiHlQ21oXmQ4F3SiryXBHhAD7JZqvOJjFmg==" }, "node_modules/rimraf": { "version": "3.0.2", @@ -11475,6 +11554,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", @@ -11490,6 +11578,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", @@ -11526,6 +11624,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": { @@ -12711,9 +12830,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": { @@ -12783,13 +12902,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", @@ -13554,6 +13670,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", @@ -13623,6 +13748,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", @@ -15590,13 +15725,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": { @@ -15723,6 +15857,12 @@ "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", "dev": true }, + "rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "dev": true + }, "string-width": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", @@ -16510,9 +16650,9 @@ "dev": true }, "rfdc": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", - "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==" + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.3.1.tgz", + "integrity": "sha512-r5a3l5HzYlIC68TpmYKlxWjmOP6wiPJ1vWv2HeLhNsRZMrCkxeqxiHlQ21oXmQ4F3SiryXBHhAD7JZqvOJjFmg==" }, "rimraf": { "version": "3.0.2", diff --git a/package.json b/package.json index c96e472..94293ad 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", @@ -25,7 +29,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", @@ -36,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" }, @@ -69,12 +73,14 @@ "@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", "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/1.14.0-compatibility.md b/release/1.14.0-compatibility.md new file mode 100644 index 0000000..22843fb --- /dev/null +++ b/release/1.14.0-compatibility.md @@ -0,0 +1,94 @@ +# 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 | 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 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. | +| 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 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 (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. | +| 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 + +- 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 (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. + +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..411209d --- /dev/null +++ b/release/PUBLISHING.md @@ -0,0 +1,52 @@ +# 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. +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. + +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 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 +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 +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, +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..160d553 --- /dev/null +++ b/scripts/__tests__/check-release.test.js @@ -0,0 +1,226 @@ +/* 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, compareVersions } = 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"); +}); + +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); +}); + +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("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/); + 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/); +}); + +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("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({ + 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(2); + 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"); + } + }); + + // 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. 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", + timeout: 30000, + }); + } catch (_) { + pinnedNpmAvailable = false; + } + (pinnedNpmAvailable || process.env.CI ? test : test.skip)( + "npm 11.6.2 parses every manual publish command as an effective dry run", + () => { + const npmVersion = pinnedNpm; + const effectiveDryRun = (run) => { + 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+/) + .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, + timeout: 30000, + }).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 + ); + + // 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 || ""))) { + expect({ step: step.name, run: step.run.trim() }).toEqual({ + step: step.name, + run: expect.stringMatching(/^npm publish(?: --[a-z-]+(?: [a-z]+)?)+ --tag "\$DIST_TAG"$/), + }); + } + }); + + 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(); + expect(workflow.permissions["id-token"]).toBe("write"); + expect(publishSteps).toHaveLength(2); + expect(publishSteps.map((step) => step.if)).toEqual([ + "github.event_name == 'workflow_dispatch'", + "github.event_name == 'push'", + ]); + for (const step of publishSteps) expect(step.env.NODE_AUTH_TOKEN).toBeUndefined(); + expect(JSON.stringify(workflow)).not.toContain("NPM_TOKEN"); + }); +}); diff --git a/scripts/__tests__/compatibility-accepted.test.js b/scripts/__tests__/compatibility-accepted.test.js new file mode 100644 index 0000000..afdcf50 --- /dev/null +++ b/scripts/__tests__/compatibility-accepted.test.js @@ -0,0 +1,70 @@ +/* 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*"😀",/); +}); + +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]); +}); + +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); +}); diff --git a/scripts/check-es5.js b/scripts/check-es5.js new file mode 100644 index 0000000..551d2b7 --- /dev/null +++ b/scripts/check-es5.js @@ -0,0 +1,142 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ +const fs = require("fs"); +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]; + +// 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); + try { + acorn.parse(fs.readFileSync(target, "utf8"), { ecmaVersion: 5 }); + } catch (error) { + console.error(`dist/${file} is not ES5: ${error.message}`); + failed = true; + continue; + } + 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; + } + } +} + +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", + 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)}`); + } +} + +// 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", + 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/scripts/check-release.js b/scripts/check-release.js new file mode 100644 index 0000000..a53663f --- /dev/null +++ b/scripts/check-release.js @@ -0,0 +1,123 @@ +/* eslint-disable @typescript-eslint/no-var-requires, no-shadow */ +/* global BigInt */ +const { execFileSync } = require("child_process"); +const { appendFileSync } = require("fs"); +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. +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 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; +} + +// 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); + if (gitTag !== `v${packageVersion}`) { + throw new Error("Git tag must match v"); + } + const prerelease = packageVersion.split("+")[0].split("-").slice(1).join("-"); + if (prerelease) { + const id = prerelease.split(".")[0].toLowerCase(); + return ["alpha", "beta", "rc", "next"].includes(id) ? id : "next"; + } + if (major < latestMajor) return `v${major}-lts`; + if (compareVersions(packageVersion, latestVersion) <= 0) { + throw new Error(`${packageVersion} is not newer than latest ${latestVersion}; choose a dist tag manually`); + } + 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); + 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, checkRepository, compareVersions }; 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/consumer.ts b/scripts/compatibility/consumer.ts new file mode 100644 index 0000000..351be79 --- /dev/null +++ b/scripts/compatibility/consumer.ts @@ -0,0 +1,195 @@ +/* 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 Client, { 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(); +const finalized: true | Promise = context.finalize(); +if (finalized === true) { + void finalized; +} +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; + +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; + +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/scripts/compatibility/run.js b/scripts/compatibility/run.js new file mode 100644 index 0000000..794649e --- /dev/null +++ b/scripts/compatibility/run.js @@ -0,0 +1,211 @@ +#!/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"); +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] + +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 +(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; + if (label === "candidate") { + outcome.unaccepted = unacceptedTypeErrors(outcome.output); + outcome.accepted = outcome.unaccepted.length === 0; + } + 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.unaccepted ? !outcome.accepted : !outcome.passed) { + if (outcome.unaccepted) console.error(outcome.unaccepted.join("\n")); + result.errors.push(`TypeScript ${expected} ${label} failed`); + } + } + } + try { + result.runtime = await runtime(baseline, candidate); + 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}`); + 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..33e90d9 --- /dev/null +++ b/scripts/compatibility/runtime.js @@ -0,0 +1,245 @@ +/* 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()) { + 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, hashUnit) { + 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, 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 }; +} + +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, require(path.join(baselineDir, "lib", "utils")).hashUnit); + after = await measure(candidate, require(path.join(candidateDir, "lib", "utils")).hashUnit); + } 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, + }; +}; diff --git a/src/__tests__/client.test.js b/src/__tests__/client.test.js index ca943c4..b702c14 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"); @@ -225,6 +224,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", query: { a: 1 }, @@ -273,6 +273,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", query: { a: 1 }, @@ -316,6 +317,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", query: { a: 1 }, @@ -366,6 +368,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", query: { a: 1 }, @@ -585,6 +588,7 @@ describe("Client", () => { client .request({ + auth: true, method: "POST", path: "/context", query: { a: 1 }, @@ -622,6 +626,7 @@ describe("Client", () => { client .request({ + auth: true, method: "POST", path: "/context", query: { a: 1 }, @@ -659,6 +664,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", query: { a: 1, b: "ã=á" }, @@ -717,6 +723,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", query: {}, @@ -752,6 +759,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", }) @@ -785,6 +793,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", }) @@ -956,6 +965,7 @@ describe("Client", () => { "X-Application": "test_app", "X-Application-Version": 1000000, }, + body: undefined, keepalive: true, signal: expect.any(Object), }); @@ -975,7 +985,7 @@ describe("Client", () => { .publish({ units, publishedAt, - sdkVersion: SDK_VERSION, + goals, exposures, attributes, @@ -996,7 +1006,7 @@ describe("Client", () => { body: JSON.stringify({ units, publishedAt, - sdkVersion: SDK_VERSION, + goals, exposures, attributes, @@ -1019,7 +1029,7 @@ describe("Client", () => { .publish({ units, publishedAt, - sdkVersion: SDK_VERSION, + goals: [], exposures: [], }) @@ -1039,7 +1049,6 @@ describe("Client", () => { body: JSON.stringify({ units, publishedAt, - sdkVersion: SDK_VERSION, }), signal: expect.any(Object), }); @@ -1059,7 +1068,7 @@ describe("Client", () => { client .publish({ units, - sdkVersion: SDK_VERSION, + goals: [], exposures: [], }) @@ -1079,7 +1088,6 @@ describe("Client", () => { body: JSON.stringify({ units, publishedAt: publishedAt + 100, - sdkVersion: SDK_VERSION, }), signal: expect.any(Object), }); @@ -1098,6 +1106,7 @@ describe("Client", () => { client .request({ + auth: true, method: "PUT", path: "/context", }) @@ -1122,7 +1131,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 +1146,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(); }); @@ -1213,16 +1222,8 @@ 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); }); @@ -1247,5 +1248,40 @@ describe("Client", () => { advanceFakeTimers(); }); + + // 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) => { + opts.signal.addEventListener("abort", () => { + 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((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(); + }); + + advanceFakeTimers(); + }); }); }); diff --git a/src/__tests__/constructor-types.ts b/src/__tests__/constructor-types.ts new file mode 100644 index 0000000..30a4017 --- /dev/null +++ b/src/__tests__/constructor-types.ts @@ -0,0 +1,22 @@ +import SDK from "../sdk"; +import Client from "../client"; +import { getApplicationVersion } from "../utils"; + +// 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 | string { + return typeof options.application === "string" ? 0 : options.application.version; +} + +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 directUtilityTypes: [number | string, number | string] = [ + getApplicationVersion("web"), + getApplicationVersion({ name: "web", version: "1.2.3" }), +]; diff --git a/src/__tests__/context-switchback.test.js b/src/__tests__/context-switchback.test.js index 4a7c765..e6062a2 100644 --- a/src/__tests__/context-switchback.test.js +++ b/src/__tests__/context-switchback.test.js @@ -6,7 +6,6 @@ import { VariantAssigner } from "../assigner"; import { assignSwitchbackPeriod } from "../switchback"; import { ContextPublisher } from "../publisher"; import { ContextDataProvider } from "../provider"; -import { SDK_VERSION } from "../version"; jest.mock("../client"); jest.mock("../sdk"); @@ -700,6 +699,73 @@ 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. + // 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 = () => { + 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); @@ -717,7 +783,6 @@ describe("switchback serving through Context", () => { publishedAt: ANCHOR + HOUR + 9, units: [{ type: UNIT_TYPE, uid: UID_HASH }], hashed: true, - sdkVersion: SDK_VERSION, exposures: [strictMismatchExposure(ANCHOR + HOUR + 5)], attributes: [{ name: CLUSTER_PATH, value: CLUSTER_KEY, setAt: ANCHOR }], }) @@ -1059,7 +1124,6 @@ describe("switchback serving through Context", () => { publishedAt: ANCHOR + HOUR + 9, units: [{ type: UNIT_TYPE, uid: UID_HASH }], hashed: true, - sdkVersion: SDK_VERSION, exposures: [ exposure(1, "exp_sb", EXPECTED_2_ARMS[0], ANCHOR + 5, true, true), exposure(1, "exp_sb", EXPECTED_2_ARMS[1], ANCHOR + HOUR + 7, true, true), @@ -1788,7 +1852,6 @@ describe("switchback serving through Context", () => { publishedAt: ANCHOR + 9, units: [{ type: UNIT_TYPE, uid: UID_HASH }], hashed: true, - sdkVersion: SDK_VERSION, exposures: [ ruleExposure("exp_rule", 1, ANCHOR + 5), exposure(2, "exp_miss", 0, ANCHOR + 5, true, false), diff --git a/src/__tests__/context.test.js b/src/__tests__/context.test.js index f16a09a..9f96773 100644 --- a/src/__tests__/context.test.js +++ b/src/__tests__/context.test.js @@ -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, @@ -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, @@ -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"); @@ -6928,12 +7046,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 +7068,28 @@ describe("Context", () => { ], }); } + const names = []; + let depth = 0; + let nestedAt; + let exhaustedAt; 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; + exhaustedAt = ctx._replayExhausted; + ctx.variableValue(`w${width}`, "D"); + } + } finally { + depth--; } }); const context = new Context( @@ -6965,9 +7099,82 @@ describe("Context", () => { buildHoldoutResponse(experiments, []) ); expect(context.variableValue("w0", "D")).toBe(0); - expect(after).toBe(exhausted); - expect(context.pending()).toBe(width); - }); + 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); + }); + + // 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]], + // 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 reads from %j)", + (triggers, positions) => { + const width = 2000; + const extra = triggers.map((_, k) => width + k); + const experiments = []; + for (let i = 0; i < width + extra.length; 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; + 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 (pendingTriggers.has(data.name)) { + const read = pendingTriggers.get(data.name); + pendingTriggers.delete(data.name); + ctx.variableValue(`w${read}`, "D"); + } + }); + const context = new Context( + sdk, + { ...contextOptions, eventLogger }, + contextParams, + buildHoldoutResponse(experiments, []) + ); + expect(context.variableValue("w0", "D")).toBe(0); + 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(total); + expect(context._deferredLogs).toBeUndefined(); + } + ); it("delivers a post-limit batch's error and exposure and arms the publish timer", () => { const strict = { @@ -7034,6 +7241,182 @@ 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("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); @@ -7415,6 +7798,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"}' }, @@ -7456,7 +7875,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 +7887,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); }); @@ -7535,6 +7963,159 @@ 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.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(); + 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) => { @@ -7724,7 +8305,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -7954,7 +8535,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + attributes: [ { name: "age", @@ -8003,7 +8584,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -8209,7 +8790,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + goals: [ { achievedAt: 1611141535729, @@ -8368,7 +8949,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + goals: [ { name: "goal1", @@ -8476,7 +9057,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -8600,7 +9181,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + goals: [ { name: "goal1", @@ -8654,7 +9235,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + goals: [ { achievedAt: 1611141535729, @@ -8715,7 +9296,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -8796,7 +9377,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + goals: [ { name: "goal2", @@ -9019,7 +9600,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -9071,7 +9652,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -9643,7 +10224,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -9711,7 +10292,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -9788,7 +10369,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 2, @@ -9837,7 +10418,7 @@ describe("Context", () => { publishedAt: 1611141535729, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 3, @@ -9909,7 +10490,7 @@ describe("Context", () => { publishedAt: 1611141535829, units: publishUnits, hashed: true, - sdkVersion: SDK_VERSION, + exposures: [ { id: 1, @@ -10043,27 +10624,31 @@ describe("Context", () => { 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, eventLogger }, 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)); + 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 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(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", - }) - ); + 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(); }); }); @@ -10696,7 +11281,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 route custom field parse errors through eventLogger, not the console", () => { const eventLogger = jest.fn(); const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); @@ -10731,7 +11316,11 @@ describe("Context input handling and lifecycle regressions", () => { context.customFieldValue("exp", "bad_json"); expect(errorSpy).not.toHaveBeenCalled(); - expect(eventLogger).toHaveBeenCalledWith(context, "error", expect.any(Error)); + 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': / + ); 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__/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 new file mode 100644 index 0000000..28e2998 --- /dev/null +++ b/src/__tests__/release-compatibility.test.js @@ -0,0 +1,1280 @@ +import { JsonExpr } from "../jsonexpr/jsonexpr"; +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"; + +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", + 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("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); + 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.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.each(["fetch", "with-data", "refresh"])( + "treats non-string assignment rules as no rules via %s", + async (creation) => { + const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {}); + 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); + expect(errorSpy).not.toHaveBeenCalled(); + } finally { + errorSpy.mockRestore(); + } + } + ); + + 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 { + 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(() => {}); + 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(); + }); + + 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")).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."); + }); + + 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 }); + expect(() => sdk.createContextWith({ units: { user: "one" } }, { experiments: [] })).toThrow(TypeError); + }); + + 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.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("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 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 { + 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(() => {}); + 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("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 }); + 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: 1, + applications: [{ name: "web" }], + variants: [ + { name: "A", config: null }, + { name: "B", config: null }, + ], + audience: "{not json", + audienceStrict: true, + customFieldValues: null, + }, + ], + } + ); + // 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(); + }); + + 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 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); + } + 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("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}`); + }); + + 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"); + }); + + it.each([ + ["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], + ["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], + ])("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, + 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" }] } }; + 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("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("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("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("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" } }, + { 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); + 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 = { + 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 }); + expect(sdkFetch.mock.calls[0][1]).not.toHaveProperty("headers"); + }); + + it("calls get() directly from getContext(), not a subclass's getUnauthed()", async () => { + sdkFetch.mockResolvedValue({ ok: true, status: 200, json: () => Promise.resolve({ experiments: [] }) }); + const unauthed = []; + const gets = []; + class LoggingClient extends Client { + getUnauthed(requestOptions) { + unauthed.push(requestOptions.path); + return super.getUnauthed(requestOptions); + } + get(requestOptions) { + gets.push(requestOptions.path); + return super.get(requestOptions); + } + } + await new LoggingClient(options).getContext(); + expect(unauthed).toEqual([]); + expect(gets).toEqual(["/context"]); + expect(sdkFetch.mock.calls[0][1].headers["X-API-Key"]).toBe("k"); + }); + + 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, + 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, + }; + 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", () => { + 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.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("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(); + }); + + 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.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 }), + ], + [ + "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) => { + 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(() => {}); + 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.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(() => {}); + 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); + 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, + 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 }); + 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" })]); + }); +}); diff --git a/src/__tests__/sdk.test.js b/src/__tests__/sdk.test.js index 7a0ad73..ad00297 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); @@ -100,6 +101,48 @@ describe("SDK", () => { 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", + endpoint: "localhost:8080", + environment: "test", + }; + const options = Object.assign(Object.create({ timeout: 777, agent: undefined }), base); + + new SDK(options); // eslint-disable-line no-new + + const passed = Client.mock.calls[Client.mock.calls.length - 1][0]; + expect(passed.timeout).toBe(777); + expect(passed.agent).toBe(`absmartly-javascript-sdk/${SDK_VERSION}`); + + done(); + }); + + it("should drop explicitly undefined client options so the defaults apply", (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(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(); + }); + it("should set default values for unspecified client options", (done) => { const options = { application: "application", @@ -117,7 +160,7 @@ describe("SDK", () => { Object.assign( {}, { - agent: "absmartly-javascript-sdk", + agent: `absmartly-javascript-sdk/${SDK_VERSION}`, }, options ) 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/__tests__/utils.test.js b/src/__tests__/utils.test.js index 0331d0c..2530604 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,16 +253,56 @@ 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"); - 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()", () => { @@ -316,101 +372,43 @@ 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 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; + // 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]], + ["\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) => { + const encoded = stringToUint8Array(input); + expect(Array.from(encoded)).toEqual(bytes); + expect(encoded.byteLength).toBe(encoded.buffer.byteLength); + }); - expect(fallbackHash).toBe(nativeHash); - } - done(); - }); + 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 c0f5fe1..45c57cf 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 { + const candidate = typeof version === "number" ? version : typeof version === "string" ? version.trim() : ""; + return /^[0-9]{1,18}$/.test(String(candidate)) ? candidate : 0; +} + +/** @deprecated Identical to ClientOptions, which now accepts a string application version. */ +export type ClientInputOptions = ClientOptions; + 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) { @@ -164,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 = () => { @@ -174,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", @@ -187,7 +196,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), }; } diff --git a/src/context.ts b/src/context.ts index 86dd339..be19192 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"; import { assignSwitchbackPeriod, @@ -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 }; @@ -149,6 +152,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; // Set only for a switchback experiment: its generation, carried over a refresh while its // switchback identity is unchanged, and its cluster sources (null on the legacy path). switchback?: { generation: number; sources: SwitchbackSources | null }; @@ -270,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; @@ -335,7 +346,7 @@ export default class Context { return this._failedError; } - ready() { + ready(): Promise { if (this.isReady()) { return Promise.resolve(true); } @@ -394,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) { @@ -411,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); } @@ -462,8 +474,19 @@ export default class Context { ); } - getUnits() { - return { ...this._units }; + // 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 { + 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) { @@ -472,7 +495,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; } @@ -488,9 +512,10 @@ export default class Context { getAttributes() { const attributes: Record = {}; - for (const attr of this._attrs) { + // 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; } @@ -518,7 +543,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); } @@ -664,25 +690,37 @@ export default class Context { return this._attrsMapCache; } const attrs: Record = this._getSystemAttributes(); - for (const attr of this._attrs) { + // 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; } private _evaluateAudience(audience: string): boolean | null { + let result: boolean | 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. - private _assign(experimentName: string, now?: number) { + private _assign(experimentName: string, now?: number): Assignment { const experimentMatches = (experiment: ExperimentData, assignment: Assignment) => { return ( experiment.id === assignment.id && @@ -695,7 +733,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) { @@ -708,9 +746,10 @@ export default class Context { } if (this._attrsSeq > (assignment.attrsSeq ?? 0) || ruleKeyChanged) { - const attrs = this._getAttributesMap(); - - 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(); // 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; @@ -726,12 +765,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; @@ -861,17 +897,11 @@ 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 - ? `${experiment.data.assignmentRules}:${this._environmentName}` - : ""; - - const rule = - experiment.data.assignmentRules && experiment.data.assignmentRules.length > 0 - ? this._resolveRule(experiment, attrs, false) - : null; + assignment.ruleKey = experiment.ruleKey ?? ""; + + const rule = experiment.ruleKey ? this._resolveRule(experiment, this._getAttributesMap(), false) : null; const ruleVariant = rule?.variant ?? null; assignment.ruleVariant = ruleVariant; @@ -900,37 +930,35 @@ export default class Context { assignment.variant = 0; } else if (experiment.data.fullOnVariant === 0) { if (unitType !== null) { - if (unitType in this._units) { - 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; } } } @@ -1151,8 +1179,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; } @@ -1239,25 +1269,25 @@ export default class Context { } } + // 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 now = this._switchbackClock(experimentName, undefined); const assignment = this._assign(experimentName, now); 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, now); - } else { - this._deferringLogs = true; - try { - this._triggerExposures(experimentName, assignment, now); - } finally { - this._endDeferral(); - } - } + this._triggerExposures(experimentName, assignment, now); } return assignment; @@ -1484,7 +1514,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); - this._deferringLogs = true; try { return this._resolveVariableValue(key, defaultValue, true); @@ -1515,14 +1544,32 @@ 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. + 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).concat(this._deferredLogs ?? []); + this._deferredLogs = undefined; + } if (deferred[i][0] === "exposure") exposed = true; this._logEvent(deferred[i][0], deferred[i][1]); + if (remainder !== undefined) { + if (remainder.length > 0) { + this._deferredLogs = remainder; + this._deliverDeferredLogs(); + } + break; + } } deferred = this._deferredLogs; } @@ -1530,7 +1577,7 @@ export default class Context { this._deferringLogs = false; this._replayExhausted = false; // Only exposures need publishing; an error alone must not arm the timer. - if (exposed) this._setTimeout(); + if (exposed && this._pending > 0) this._setTimeout(); } } @@ -1545,7 +1592,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(); } } @@ -1591,28 +1638,27 @@ 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 = {}; - for (const x of this._attrs) userNames[x.name] = true; - const addSystemAttribute = (attrName: string, value: unknown) => { - if (!Object.prototype.hasOwnProperty.call(userNames, attrName)) { - allAttributes.push({ name: attrName, value, setAt: systemSetAt }); - } - }; - - addSystemAttribute("sdk_name", client.getAgent()); - 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 })); } - for (const x of this._attrs) { - allAttributes.push({ name: x.name, value: x.value, setAt: x.setAt }); - } + 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 }; + }); - return allAttributes; + const client = this._sdk.getClient(); + const systemAttributes: Attribute[] = []; + const agent = client.getAgent(); + 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 @@ -1652,12 +1698,6 @@ 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` @@ -1683,7 +1723,6 @@ export default class Context { uid: this._unitHash(entry[0]), })), hashed: true, - sdkVersion: SDK_VERSION, }; if (this._goals.length > 0) { @@ -1886,12 +1925,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; } @@ -1943,11 +1982,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; - this._environmentName = this._sdk.getClient().getEnvironment() ?? null; + const client = this._sdk.getClient(); + this._environmentName = client.getEnvironment() ?? null; - const index: Record = {}; + const index: Record = Object.create(null); const indexVariables: Record = {}; const holdoutsById: Record = {}; @@ -2001,6 +2041,10 @@ export default class Context { data: experiment, variables, holdouts, + ruleKey: + typeof experiment.assignmentRules === "string" && experiment.assignmentRules + ? `${experiment.assignmentRules}:${this._environmentName}` + : "", }; if (experiment.randomizationType === "switchback") { diff --git a/src/jsonexpr/evaluator.ts b/src/jsonexpr/evaluator.ts index 5c52ff0..24d3563 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); } @@ -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; @@ -125,8 +127,14 @@ export class Evaluator { let target = this.vars ?? {}; for (let index = 0; index < frags.length; ++index) { const frag = frags[index]; + let value; + try { + value = target[frag]; + } catch (error) { + if (target == null) this.nullParentError = error; + throw error; + } - const value = target[frag]; if (value !== undefined) { target = value; continue; diff --git a/src/jsonexpr/jsonexpr.ts b/src/jsonexpr/jsonexpr.ts index 84414c7..29e6028 100644 --- a/src/jsonexpr/jsonexpr.ts +++ b/src/jsonexpr/jsonexpr.ts @@ -40,9 +40,33 @@ const operators = { }; export class JsonExpr { + /** @internal */ + 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; + } + } + + /** + * @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) { + this._nullParentError = undefined; + try { + return this.evaluateBooleanExpr(expr, vars); + } catch (error) { + if (this._nullParentError === undefined || error !== this._nullParentError) throw error; + console.error(error); + return null; + } } evaluateExpr(expr: TData[] | Record, vars: Record) { diff --git a/src/matcher.ts b/src/matcher.ts index d54c3c5..b5723fe 100644 --- a/src/matcher.ts +++ b/src/matcher.ts @@ -41,7 +41,9 @@ export class AudienceMatcher { if (audience && audience.filter) { if (Array.isArray(audience.filter) || isObject(audience.filter)) { - return this._jsonExpr.evaluateBooleanExpr(audience.filter, vars); + return typeof this._jsonExpr.evaluateAudienceExpr === "function" + ? this._jsonExpr.evaluateAudienceExpr(audience.filter, vars) + : this._jsonExpr.evaluateBooleanExpr(audience.filter, vars); } } @@ -86,7 +88,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/switchback.ts b/src/switchback.ts index 5a84154..4d65e41 100644 --- a/src/switchback.ts +++ b/src/switchback.ts @@ -1,5 +1,5 @@ import { murmur3_32 } from "./murmur3_32"; -import { stringToUint8Array, toWellFormedString } from "./utils"; +import { stringToUtf8Array, toWellFormedString } from "./utils"; // Switchback experiments (R33, cluster-defined): a port of java-sdk's internal Switchback* classes, // which port the platform's SwitchbackAssignment and the Collector's ContextAPI.switchbackServing. @@ -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(stringToUint8Array(key).buffer); + // 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); diff --git a/src/utils.ts b/src/utils.ts index 30feace..a2d6ba9 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -175,26 +175,59 @@ export function toWellFormedString(value: string, replacement = "\ufffd"): strin return result; } +// 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) { + 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 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 new Uint8Array(array); +} + +// Standard UTF-8, for keys that must match the platform's String.getBytes(UTF_8) byte for byte +// (switchback cluster keys, made well-formed first). Unit hashing uses stringToUint8Array above. +export function stringToUtf8Array(value: string) { if (typeof TextEncoder !== "undefined") { - return new Uint8Array(new TextEncoder().encode(value)); + return new TextEncoder().encode(value); } 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 (c >= 0xd800 && c <= 0xdbff && i + 1 < value.length) { + const next = value.charCodeAt(i + 1); 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; } if (c < 0x80) { utf8.push(c); diff --git a/tsconfig.json b/tsconfig.json index acd4126..8f89305 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, @@ -27,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"] +} 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"], }, ],