Optimizely migration

Bring the section test. Review every change.

Patchwork reads Optimizely's documented v2 experiment format and shows what can move into a section test. Inspect the plan first, resolve blockers, then create an unapproved draft. Nothing is launched or changed in Optimizely.

Open a site's overview and select “Import an Optimizely section test.” Workspace owners and editors can import.

Supported today

Optimizely migration compatibility
CapabilityMigration behavior
Optimizely v2 experiment JSONPaste an export, or find experiments by project and select one using your own Optimizely token.
Text and HTML changesText, inner HTML, class names, image src and anchor href changes inside one captured section. New link destinations are listed for review before confirmation; rejected content blocks the import.
StylingInline styles and CSS are checked and scoped to the new variant.
Hide and removehide:true adds visibility:hidden and preserves layout space. remove:true adds display:none and preserves the DOM node for later changes. False flags leave the existing style unchanged; use an explicit style edit to show an element.
Insert HTML or imagesinsert_html accepts a value containing HTML. insert_image accepts one img fragment or an HTTPS/root-relative image URL. Use before, after, append or prepend. Inserting before or after the captured section root is blocked; insertions within it are supported.
Rearrange elementsAn attribute change can include rearrange:{insertSelector,operator}. Move matched nodes before, after, into the beginning or into the end of one destination inside the section. Source order is preserved; ancestor cycles and moves outside the section are blocked.
Change dependenciesDependencies name change IDs in the same action. Prerequisites run first even when listed later; changes without dependencies retain export order. Missing, duplicate or cyclic IDs block import. Remote or asynchronous payloads remain unsupported.
Link destinationsHTTPS, root-relative, fragment, mailto and tel links are supported. Single and batch previews list destinations introduced by href, HTML or insertion changes. Confirming a stale preview after a destination changes is blocked. Insecure HTTP, protocol-relative, executable and bare path-relative URLs are rejected.
Traffic and variation weightsWhole-percent Web holdback or experiment allocation and valid variation weights are preserved. Conflicting values block import.
Saved pagesOne referenced page can be read through the API or supplied in a pages export array. The same targeting and activation restrictions apply.
Batch migrationPreview up to 30 items in the form, processed three at a time. Select each reviewed experiment for draft creation; failures retain their own outcomes and unchanged retries return existing drafts.
Page targetingOne page definition with immediate, manual, URL-change, DOM-change, reviewed callback or polling activation and AND/OR/NOT combinations of exact, simple, substring and regex URL matches. Capture one representative HTTPS URL on an allowed origin. Review the captured section on every matching page template. Existing imports retain their saved mode.
Conversion metricsOpt in to map up to five increasing unique-visitor metrics into primary and secondary goals: page-scoped clicks, URL-targeted pageviews and global custom events. Unsupported metric settings block mapping.
Approval and launchImports are review drafts. Approve challengers and validate mapped goals and instrumentation, or configure a new goal when using manual mode.
Source ID mappingsNew imports retain source project, experiment, page, variation and mapped-event IDs beside destination IDs. Read them through Patchwork's authenticated provenance endpoint; no source credentials or raw exports are stored in that record.
Custom JavaScript, redirects and extensionsArbitrary variant JavaScript, redirects and extensions remain blocked. Reviewed page-activation callbacks and polling functions are supported with confirmation and CSP requirements, as described below.
Audience targetingReferenced audiences preserve AND/OR/NOT conditions for string custom attributes, raw query parameters, preferred language, visitor-local time/day windows, browser/version and device/class conditions. Exact, substring, exists, regex and numeric range matches are supported; prefix remains a Patchwork extension for custom attributes. Supply audience and attribute definitions with exports; API imports read them automatically. Changed definitions require a fresh preview.
Other audience conditions, schedules and multiple-page definitionsGeolocation, cookies, sticky referrers/campaigns, platform conditions, JavaScript, behavioral audiences and external profiles remain separate work. The preview reports blockers.
Browser SDK, visitor assignments and historical resultsInstall the Patchwork snippet for the opt-in Web API coverage described below and collect fresh results. Source visitor assignments and historical results are not imported.

Map conversion goals, then validate measurement

Metric mapping is optional. Select it in the importer or send metric_mode: "map". The first source metric becomes the primary goal; up to four more become secondary goals. Each metric must explicitly use aggregator: "unique" and scope: "visitor", with an increasing winning direction. Manual mode is the default and creates no goals.

API imports read event definitions and their pages automatically. Export imports need events: [eventDefinition] and metric_pages: [pageDefinition]; a referenced experiment page already supplied in pages can be reused. Click and pageview goals require immediate activation on one saved page definition, captured over HTTPS on your site's allowed origins. Click goals keep both their selector and page restriction.

Global custom events use window.patchwork.track("event_key") after initialization and any required consent. To retain supported window.optimizely event calls, register the source project and use the opt-in browser API below. Install the snippet on conversion pages as well as experiment pages, and verify events before launch.

Revenue, event totals, session metrics, ratios, decreasing goals, property filters, attribution windows and page-specific custom events require rebuilding. Mapping goal definitions does not preserve visitor IDs, assignments, historical results, exposure attribution or Optimizely's statistics. Patchwork measures conversions among visitors exposed to the section; collect a fresh baseline and validate that population. Previews create nothing; confirmed imports create the draft and its goals atomically.

Migrate an inventory and keep a report

Open your site's Optimizely importer and choose the batch workflow. Supply a JSON array with a unique key, page_url and selector for each experiment, plus experiment_id for API reads or experiment for an export. Preview first, inspect each translated variant and check each experiment you want to import. Set metric_mode: "map" on each item that should map metrics, with events and metric_pages for export items. Review its mapped goals alongside the variants.

The API accepts up to three items per request at /api/v1/sites/SITE_ID/imports/optimizely/batch/preview and /batch/import. Put the shared optimizely_token on the request, outside items. Each imported item needs confirm: true and its own preview_digest. A successful HTTP response includes per-item outcomes; check those outcomes even when the response is HTTP 200.

Download the inventory report to keep blockers, source IDs and draft links. It excludes tokens, raw exports and HTML/CSS. Reports can restore unfinished API items after you re-enter your token and preview again. Export-based retries need the original manifest. Keep the tab open: only an in-flight chunk may finish after leaving; there is no durable background job or saved server-side batch progress.

Roadmap to API and SDK compatibility

Ordered from easier changes to harder systems work. Supported subsets are available today; planned items are not implemented. Full compatibility requires versioned contract tests and source-account validation across this list.

  1. 1. Default audience, metadata and Web traffic holdback

    Small · Supported subset

    Recognize everyone, ignore documented timestamp metadata and translate whole-percent Web holdback into traffic allocation.

    Completion check: Official-shaped exports import; conflicting or fractional allocation is blocked.

  2. 2. Additional declarative visual changes

    Small · Supported subset

    Text, HTML, classes, image sources, links, hide/remove flags, HTML/image insertion and element rearrangement compile inside one captured section. Action-local dependencies order prerequisites. New link destinations are listed in single and batch previews and covered by confirmation.

    Completion check: Contract tests cover ordering, visibility, insertion context, moves and boundaries. Confirmed content survives persistence, REST round-trips, publishing, runtime rendering and original-node restoration. Unsafe content, dependency cycles and expansion beyond the variant byte budget block import. Dynamic future-match polling remains planned.

  3. 3. Project experiment discovery

    Small–medium · Supported subset

    Paginated project experiment list, customer picker and documented read-only API endpoint.

    Completion check: Fixed upstream host, bounded pages, tenant/editor authorization and no token persistence.

  4. 4. Saved-page references

    Medium · Supported subset

    Resolve one referenced page through the API or a supplied export; support single-URL, URL-set and global pages, with immediate, manual, URL-change, DOM-change, callback and polling activation and exact, simple, substring and regex URL conditions combined by AND/OR/NOT.

    Completion check: Page IDs and project ownership agree. Archived, unknown or multi-page targeting blocks import. Unconditional global pages retain separate representative URLs and activation settings; contradictory restrictions are rejected. Exact rules preserve query/fragment distinctions; Simple rules ignore them.

  5. 5. Batch migration and inventory reports

    Medium · Supported subset

    Preview an inventory, confirm each selected test, create drafts in bounded chunks and download source-to-destination reports. Saved reports can resume API reads; export sources need their original exports.

    Completion check: Per-item confirmation, partial failures and unchanged retries are covered. No auto-launch. Durable background jobs and server-side progress persistence remain planned.

  6. 6. Conversion metrics and event mappings

    Medium · Supported subset

    Opt-in mapping of up to five increasing unique-visitor metrics: page-scoped clicks, URL-targeted pageviews and global custom events, with primary and secondary goals. Metric pages retain all four URL match types and their AND/OR/NOT conditions, including unconditional global pageviews/clicks. Bounce and exit rates remain planned. Custom events require Patchwork instrumentation. Revenue, totals, sessions, ratios and property filters remain planned.

    Completion check: Test page restrictions, fresh preview confirmation, atomic goal creation and retry safety. Unsupported aggregation blocks mapping; visitor identity, exposure attribution and statistics still require fresh validation.

  7. 7. REST resource compatibility

    Medium–large · In progress

    Opt-in bindings expose project/experiment metadata, lifecycle actions, prelaunch variation creation/content/weights/status, unique-visitor metrics, URL-targeted page and click/custom event CRUD, plus audience/attribute list/read/create/update/archive. Page conditions and experiment audience references can change before launch. Stable public variation IDs and immutable import provenance are retained. Pages support single_url/url_set/global types and immediate/manual/url_changed/dom_changed/callback/polling activation; settings and non-immediate or nondefault policy API names freeze at measurement. Experiment DELETE archives and unarchive restores paused while preserving IDs and history. Both publish after commit; repeat DELETE refreshes delivery before 410. Never-started restores retain review and first-launch checks. Concluded history and native winners cannot be reopened. Project lists support up to 100 repeated, distinct ID filters with tenant scoping before numeric pagination and filtered counts. Experiment lists accept include_classic=false and fail true explicitly. Project/experiment creation, project archiving and live content/allocation edits remain planned.

    Completion check: Contract tests cover shapes, methods, errors, permissions, pagination, goal repair, CSS GET/PATCH round-trips, native and AI variation bindings, review rollback, creation-bearing publish retries, archive/unarchive publication recovery, prelaunch restored review, broken-projection archival and measured-history protection. Real Postgres tests cover import/edit/native-revision/lifecycle flows, launch serialization and registry cleanup.

  8. 8. Browser JavaScript API compatibility

    Large · In progress

    Opt-in web-1 runtime: queued commands/functions, pre-initialization disable (full or tracking-only), consent-aware persistent string user attributes, tagged custom events, global activation and named-page reactivation/deactivation, hold/send logging, state/data/visitor getters including consented browser IDs, versions and device classes, lifecycle/action/analytics listeners and all six documented DOM/timing/URL utilities. Saved API-name attributes resolve after later definition publication in both runtimes. Published source IDs follow native revisions. Campaign IDs are separate from experiment IDs. Named-page commands preserve unrelated DOM and the global page-view ID. Imports and page resources preserve manual/URL-change/DOM-change/callback/polling activation settings and API names; manual pages wait for explicit page commands in the matching adapter. URL-change pages reevaluate on initial load and path/query/hash changes; other pages retain their hash activation. DOM-change pages reevaluate after external mutations and persistently render delayed/replaced sections, without re-triggering themselves or unrelated pageviews. Visibility observers are replaced safely and per-source conflict retries are bounded. Reviewed synchronous callback/polling activation functions are preserved through imports, REST and publication, run only after consent in the matching adapter, and use bounded polling and stale-callback invalidation. Web bucketVisitor persists visitor-scoped ID/index choices across adapter and extended native loads, follows source IDs through revisions and clears on consent denial. Feature SDK forced decisions, element/JavaScript conditions and cross-origin identity remain planned.

    Completion check: Contract tests cover pre/post-initialization calls, rendering, holdback, SPA/anchor behavior, reentrant consent, page-cache recovery, per-tab bounded queue ownership and clock-skew normalization. Compiled-SDK tests in Edge cover utility HTML parsing/order, DOM replacements, pseudo-class state and shared URL observer cleanup. A persisted import emits valid tagged conversions; a production canary verifies tags and source IDs through Basin. Live vendor validation and full SDK coverage remain outstanding.

  9. 9. Full URL targeting, activation and audiences

    Large · Supported subset

    All four URL match types combine with AND/OR/NOT in imports, pages, goals and both runtimes. Empty AND is unconditional; explicit global pages canonicalize empty definitions, preserve their page_type and support owned sample-URL metadata edits after launch. Exact/simple keep vendor normalization; substring is case insensitive, and case-sensitive full-URL JavaScript regexes strip vendor preview parameters. Existing rules retain their mode. Prelaunch condition edits update linked native rules/goals; JSONB retries preserve timestamps. Server regex preview uses bounded workers. The CDN selects an optional condition runtime. Anchor-only navigation preserves ordinary activation; declared URL-change pages reevaluate the full URL. Broad URL sets conservatively conflict on the same section. String-attribute/preferred-language and raw query audiences are supported, including JavaScript regex and inclusive numeric-string ranges. Visitor-local time_and_day rules preserve weekday lists and inclusive minute windows through imports, audience resources and runtime publication. Consent gates clock snapshots; global/named reactivation samples a fresh time and retained SDK decisions keep their decision clock. Forty-two offline vendor time vectors include time-zone and daylight-saving checks in compiled native/SDK profiles. Missing Web values are known nonmatches and may be negated. Optional native profiles isolate the UA parser from ordinary bundles; a complete 96 KiB SDK includes supported audience and visitor browser APIs for all projects. browser_version, device and device_type leaves use a pinned UA parser with synchronous hints. Site/project/visitor profiles retain coarse IDs/classes; versions refresh on each physical page when available, otherwise using the last known version. Consent denial clears profiles, and raw UA is never persisted or tagged. Offline fixtures cover 216 browser/device decisions, 26 UA projections and 13 provider/persistence cases, plus the 41 prior comparison/query vectors. The captured profile contract has no automatic expiry; live cross-session parity remains unverified. Acquisition records share the existing environment cleanup namespace for native 0.18/0.19 interoperability. Unverified 0.20 records are discarded on upgrade to avoid restoring pre-revocation state. Campaign, referrer and traffic-source audiences retain raw first-touch campaign/referrer and last non-direct source with consented site/project/visitor scope, SDK visitor getters and no telemetry-field expansion. Offline modules yield 318 decisions, 30 provider profiles and 14 persistence sequences; no automatic expiry or vendor redirect-relay parity is claimed. Cookie formats, platform audiences and element/JavaScript conditions remain planned. Page deactivation/undo policy extensions are supported with default-preserving imports, immutable measured settings, adapter-only runtime retention and consent-safe cleanup.

    Completion check: Fixture coverage verifies inclusion/exclusion, known absent values and unavailable context under NOT, ID/API-name aliases, project isolation, consent and native/adapter decisions. A confirmed persisted import runs through the compiled snippet. Live vendor validation remains outstanding.

  10. 10. Scheduling, traffic and assignment compatibility

    Large · In progress

    Project-controlled URL variation/audience forcing, opt-in tracking, disabled previews with PUBLIC, persistent running choices and native/SDK QA profiles are supported. Privacy writes publish automatically with safe retries, closed defaults and payload limits. Draft previews remain outside ordinary allocation, exposure history and measurement. Web bucketVisitor assignment is supported for published variations with consent and normal eligibility gates. Schedules, general vendor sticky allocation, Feature SDK forced decisions, exclusions, mutual exclusion and holdouts remain planned.

    Completion check: Golden decision vectors match supported Optimizely versions, with controlled identity and rollout changes.

  11. 11. Integrations and publishing governance

    Large · Planned

    Webhooks, analytics integrations, audit history, publishing approvals, scoped tokens and enterprise access controls.

    Completion check: Signed retries and idempotency, audited role boundaries and reversible release controls.

  12. 12. Feature Experimentation APIs and SDKs

    Very large · Planned

    Datafiles, environments, typed variables, user contexts, decide/track APIs and server SDK adapters.

    Completion check: Separately versioned SDK contract suites cover decisions, event dispatch, config refresh and offline behavior.

  13. 13. Multi-page tests, redirects, multivariate and personalization

    Very large · Planned

    Experiences spanning pages, redirect variants, multivariate combinations, adaptive allocation and personalization campaigns.

    Completion check: Cross-page identity and measurement remain consistent; redirect destinations and consent are explicitly controlled.

  14. 14. Advanced statistics and historical reporting

    Very large · Planned

    Sequential inference, multiple comparisons, revenue metrics, segments and historical report imports.

    Completion check: Document statistical differences and validate against known datasets; historical reports never masquerade as newly collected measurements.

  15. 15. Custom JavaScript and extensions

    Very large · Planned

    Reviewed page-activation functions are supported with import confirmation, CSP requirements and post-measurement edit guards. Arbitrary visual changes, project scripts and extensions still need an executable-code workflow with provenance and release controls.

    Completion check: Resolve the browser security model, review, CSP and rollback requirements before enabling execution; existing imports continue to block arbitrary code.

Contract references: Browser/device audience targeting, Pinned UA parser, Time/day audience targeting, URL matching semantics, Disable Web Experimentation, Create and update audiences, Create custom attributes, Archive custom attributes, Browser user attributes, Audience definitions, Custom attribute definitions, Browser DOM, timing and URL utilities, Browser command queue, Browser custom events, Browser state getters, Browser static data, Browser listeners, Browser activation, Browser named page activation, Browser page deactivation and reactivation, Hold and send events, REST API overview, Experiment schema, List experiments, Read a page, URL targeting behavior, Visual change behavior and dependencies, Official v2 API schema, Create a page, Update a page, Archive a page, List events, Create a custom event, Create a click event, Update a click event, Read an event, Read a project, Update an experiment, API conventions, Experimentation workflow.

Use the API

Use a Patchwork API key for your workspace. Supply either the experiment JSON or optimizely_token and experiment_id. The connector makes GET requests only to api.optimizely.com, follows no redirects and stores no Optimizely token. Exports are limited to 1 MB; the API request limit is 2 MB.

curl https://patchwork.run/api/v1/sites/SITE_ID/imports/optimizely/preview \
  -H "Authorization: Bearer $PATCHWORK_API_KEY" \
  -H "Content-Type: application/json" \
  --data @migration.json

# migration.json contains:
{
  "page_url": "https://your-site.com/",
  "selector": "#hero",
  "experiment": { "...": "your Optimizely v2 experiment export" }
}

# Review the plan, then POST the same input to /import with:
# "confirm": true, "preview_digest": "the plan.digest from preview"

To discover experiments, POST project_id, optimizely_token and optional page/per_page to /api/v1/sites/SITE_ID/imports/optimizely/experiments. The response includes next_page. For a saved-page export, include pages: [pageDefinition] with the experiment; API imports resolve the single page automatically.

Preview responses include blockers, warnings and a digest. Import recalculates the plan against the selected page; changed content requires another preview. Repeating the same confirmation returns the same draft.

New imports return source_mapping_url. GET /api/v1/experiments/EXPERIMENT_ID/imports/optimizely with your Patchwork key to retrieve format_version: 1, source_project_id, source_experiment_id, source_page_id, preview_digest and variations/events arrays of source_id and destination_id pairs captured at import time. Later edits do not rewrite that provenance record. All workspace members can read their own mappings. The endpoint returns 404 for missing records, including older drafts imported before source mappings were introduced. Keep earlier inventory reports; there is no automatic backfill. This is a native Patchwork response, not an emulation of Optimizely's REST API.

Use the versioned REST compatibility API

Owners and editors can bind a source project and experiment IDs to explicit Patchwork destinations. Registration records resource definitions and ID routing. It does not approve, launch or publish. One source project binds to one site in your workspace; only selected imports appear in the compatibility API. Repeating unchanged registration returns changed: false. When choosing a different import of the same source test, pause its previous destination first and set replace_existing: true. The old draft and its history remain intact.

# After importing, explicitly choose the canonical Patchwork draft.
curl https://patchwork.run/api/v1/sites/SITE_ID/imports/optimizely/compatibility \
  -H "Authorization: Bearer $PATCHWORK_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{"project_id":"1000","experiment_ids":["PATCHWORK_EXPERIMENT_UUID"]}'

# Change your REST client's base URL to this prefix, and use its Patchwork key.
curl 'https://patchwork.run/api/compat/optimizely/v2/experiments?project_id=1000' \
  -H "Authorization: Bearer $PATCHWORK_API_KEY"

# Source ID 3000 routes to the draft chosen above.
curl -X PATCH 'https://patchwork.run/api/compat/optimizely/v2/experiments/3000?action=pause' \
  -H "Authorization: Bearer $PATCHWORK_API_KEY" \
  -H "Content-Type: application/json" --data '{}'
Implemented Optimizely Web REST operations
Operation under /api/compat/optimizely/v2Behavior
GET /projects and /projects/{id}Bound Web project metadata; name defaults to your site domain or the project_name supplied at registration.
PATCH /projects/{id}Edit the project name and description without changing the site's domain or allowed origins. Supported snippet privacy flags are documented below.
GET /experiments?project_id=... and /experiments/{id}Current name, lifecycle status, full URL, Web holdback, source variation IDs, section changes and mapped metric definitions.
PATCH /experiments/{id}Edit name and description, a complete variation list, prelaunch holdback in whole percentages expressed as basis points, or up to five unique-visitor metrics ordered primary first. Content, status, allocation and metric changes after first launch are blocked; unchanged retry fields are accepted.
PATCH /experiments/{id}?action=publish|start|pause|resumeUse the existing review and launch rules. Starting or resuming requires every allocated challenger to be reviewed, a goal, a valid entitlement and no overlapping section test.
DELETE /experiments/{id}; PATCH /experiments/{id}?action=unarchiveArchive returns 204 and removes delivery and public disabled previews. Unarchive requires {} and returns paused. IDs, approval and history are retained. See the archive retry and restoration rules below.
GET or POST /audiences; GET or PATCH /audiences/{id}Read and create audience definitions; edit metadata and unmeasured conditions. Archive with PATCH archived:true after detaching every experiment reference.
GET or POST /attributes; GET, PATCH or DELETE /attributes/{id}Manage custom string-attribute definitions. API keys must be unique within the project; referenced measured keys cannot change. DELETE archives an unused attribute and returns 204 on retries.
GET /pages?project_id=... and /pages/{id}Read reusable URL-targeted page definitions and current experiment reference counts.
POST /pages; PATCH or DELETE /pages/{id}Create a page and its pageview event, edit metadata and unused targeting, or archive an unused page. DELETE returns 204; an already archived page returns 410.
GET /events?project_id=... and /events/{id}Read registered click, custom and pageview events, including their patchwork_status: ready, unlinked or diverged. skip_views=true excludes pageviews; no Classic events are present.
POST /projects/{id}/custom_events; PATCH or DELETE /projects/{id}/custom_events/{event_id}Create a global custom event and native goal, edit its definition, or archive it when unreferenced. Repeated event DELETE returns 204.
POST /pages/{id}/events; PATCH or DELETE /pages/{id}/events/{event_id}Create page-scoped click goals and update their name, key, CSS selector or page. Updates keep all linked imported native goals consistent. Repeated event DELETE returns 204.
# Create a global conversion event; save the returned int64 event ID.
curl -X POST 'https://patchwork.run/api/compat/optimizely/v2/projects/1000/custom_events' \
  -H "Authorization: Bearer $PATCHWORK_API_KEY" \
  -H "Content-Type: application/json" --data '{"key":"purchase","name":"Purchase"}'

# Before first launch, assign it as the primary metric (replace EVENT_ID).
curl -X PATCH 'https://patchwork.run/api/compat/optimizely/v2/experiments/3000' \
  -H "Authorization: Bearer $PATCHWORK_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{"metrics":[{"event_id":"EVENT_ID","aggregator":"unique","scope":"visitor"}]}'

# On your site, after installing the Patchwork snippet:
# window.patchwork.track("purchase");

Edit and create variations

PATCH an experiment with every current variation, including archived ones. Existing entries use variation_id; omit it and supply a name and weight to create a challenger. Read IDs from GET before editing. This example assumes control 1, challenger 2 and page 6700.

{
  "variations": [
    {
      "variation_id": 1,
      "weight": 5000
    },
    {
      "variation_id": 2,
      "weight": 2500
    },
    {
      "name": "New CTA",
      "weight": 2500,
      "actions": [
        {
          "page_id": 6700,
          "changes": [
            {
              "type": "attribute",
              "selector": "#hero a",
              "attributes": {
                "text": "See plans",
                "href": "/plans"
              }
            }
          ]
        }
      ]
    }
  ]
}

Weights total 10,000 across active variations; paused and archived entries have zero weight. Keep the unchanged original and at most five nonarchived challengers. The complete list can contain up to 100 entries. Omit actions to retain current content; supplying actions replaces that variation's full change list against the captured original section. Repeating an identical creation-bearing variation array returns the same generated IDs. Omitting an existing entry is rejected instead of deleting it.

Content edits keep the public variation ID and create a new unapproved native revision. Approve that revision before starting; combining unreviewed content with start rolls back the whole request. Original import provenance and retired content remain intact, including when switching a source binding to another imported copy and back. Names and descriptions can change after launch; content, variation status and weights require an unmeasured draft. These operations are part of PATCH /experiments; Web v2 has no separate variation route.

Sending GET variations back unchanged preserves content, approval and public IDs, including custom CSS. An unapproved zero-weight challenger may appear paused after launch; retrying its original active request at zero weight is accepted without activating it. Requests that change nothing preserve last_modified.

Supported native revisions keep the same public variation ID and update its CSS mapping. Native additions and AI-generated challengers receive new compatible IDs in the same transaction as their content. Native editing keeps its existing approval rules; the REST adapter still requires review for its content revisions. Bound edits that cannot retain this API representation roll back. Original source mappings remain provenance, while GET shows the current revision. These IDs identify variations within their experiment. REST variation names accept up to 200 characters; native import and generation retain their existing shorter label limits.

Re-register existing bindings to populate their page, event, audience and attribute registry. Backfilling missing resources reports changed: true; an unchanged retry reports changed: false. Imported page names and keys use the source pageview labels when available, otherwise Page ID and page_ID. Registered pages are reusable single-URL resources. The registry defines shared events: later imports align their unmeasured native goals with it. A measured goal with a different definition returns 409 with the conflicting field. New resource IDs are JavaScript-safe integers generated by Patchwork and do not create resources in Optimizely. Pageview events are managed through their page. Custom calls use window.patchwork.track(key) or the opt-in Optimizely event command documented below.

Page resources support immediate exact, simple, substring and regex URL conditions, including AND/OR/NOT trees. Use page_type: url_set for reusable URL sets and provide a representative edit_url on the configured site domain that the conditions include. Changing a page URL or archiving a page/event requires detaching all experiment references first, including concluded and archived tests. Click selector, event page and custom key edits are blocked once any referencing experiment has started, including paused or historical tests. Create a new event for a new conversion definition. Prelaunch edits update linked native goals atomically; resource writes never start or publish experiments. Approve variants and use the experiment lifecycle when ready.

Event reads stay available when a linked native goal is missing or inconsistent. The Patchwork-specific patchwork_status field reports unlinked or diverged; only ready events can be assigned as metrics. PATCH repairs an unmeasured goal from the registered definition. An unused event can be archived without repairing it. Editing page category or other unrelated metadata preserves imported pageview names and keys.

Read the versioned OpenAPI schema. Collections return arrays with page/per_page pagination (25 by default, at most 100) and Link relations. Responses preserve signed int64 IDs as exact decimal JSON integers; clients handling very large IDs must use an int64-capable codec. Errors use the flat Optimizely-style code, message and uuid fields. Missing credentials return 401; invalid credentials return 403; unavailable resources return 404. Workspace keys share the native API's 120 requests per minute per key per server instance, with rate-limit headers. API source reads, JSON uploads and batch manifests preserve large decimal IDs before JavaScript can round them. Quoted decimal IDs are also accepted for writes; avoid exponent notation for large IDs.

Dates reflect Patchwork's import and registration timeline. Original vendor history is not imported. Native and compatibility writes serialize per site so concurrent launches cannot bypass overlap checks. Field edits and state transitions commit together. Publishing happens after commit. If publishing fails, 503 publishing_pending means the state was saved; repeat the same action to retry. Draft/review states appear as not_started. Reads reflect current Patchwork configuration; compatible running weights sum to 10,000 after excluding inactive variations. Source CSS stays subject to Patchwork's section boundary.

This API currently requires supported URL conditions, immediate, manual, URL-change or DOM-change activation, everyone or a supported imported audience, and one captured section. Unmapped native goals, older unmapped native variations, unsupported root changes, CSS changed outside the supported revision paths and shipped winner deployments can return 422 unsupported_configuration. Older CSS imports may need reconfirming the same source export or API read to prepare their representation; unchanged content keeps the same draft. New source content needs a fresh preview and an explicitly chosen destination. Older imports without source mappings cannot be registered automatically.

New imports and pages normalize exact and simple URLs for case, HTTP versus HTTPS, a leading www, and trailing path slashes. Exact matching keeps query values/order, initial fragments, other subdomains and nondefault ports distinct. The same rules apply to decisions, pageview goals, click restrictions, page state and overlap protection. Configure every actual serving origin separately; URL normalization does not expand the event-ingestion allowlist. Simple matching additionally ignores query strings and fragments, so campaign parameters do not prevent enrollment. It still distinguishes other subdomains, nondefault ports and different paths.

REST 0.21.0 supports combined URL conditions. Substring matches are case insensitive and ignore HTTP/HTTPS and trailing slashes while keeping www and query/fragment text in the searched URL. Regex matches use JavaScript's case-sensitive engine against the full serialized URL. Optimizely preview query parameters are removed without re-encoding the remaining query; an empty question mark remains. Combine exact, simple, substring and regex terms with and, or and not. This example includes product pages and excludes internal traffic:

[
  "and",
  {
    "type": "url",
    "match_type": "substring",
    "value": "/products/"
  },
  [
    "not",
    {
      "type": "url",
      "match_type": "regex",
      "value": "[?&]internal=1(?:&|#|$)"
    }
  ]
]

Send that tree as a JSON string in conditions, with page_type: url_set and an edit_url such as https://example.com/products/shoes. Limits: 100 nodes, depth 16, 16 KiB of UTF-8 JSON, and 2,048 characters per term. Invalid branches fail closed, including beneath not. Condition edits update linked draft experiments and goals atomically. Unchanged GET/PATCH echoes preserve timestamps after storage in JSONB. Measured definitions cannot change.

Global pages

REST 0.21.0 and imports support page_type: global. These pages match every HTTP/HTTPS location where the snippet is installed. The edit_url is a sample only, on a configured site domain; it does not narrow targeting. Review the captured section on every shared page template before launching. Event-ingestion origins remain unchanged.

{
  "project_id": 1000,
  "name": "All pages",
  "key": "all_pages",
  "page_type": "global",
  "edit_url": "https://example.com/",
  "conditions": "[\"and\"]"
}

An empty AND group is unconditional. Explicit global pages also normalize omitted conditions, an empty string, or JSON strings containing null or an empty array to that canonical group. Other page types still require valid definitions; an empty OR is invalid. A global page with restrictive conditions returns 422 instead of silently discarding those conditions. Global pageviews and clicks support the same unique-visitor metrics and activation settings as targeted pages. Manual and URL-change global pages still require the matching adapter and their declared trigger. Session-based bounce and exit rates remain unsupported.

Changing only an existing global page's sample edit_url is a metadata edit and is allowed after launch. Publish afterward to refresh delivery. Conditions and activation settings retain their measurement guards. Changing the page_type label alone does not narrow an unconditional rule; provide actual URL conditions before first launch to restrict it. Original capture data and import provenance remain unchanged.

Server regex checks run in isolated workers with a 100 ms evaluation budget; a timeout blocks the preview or returns 422 without saving the change. Visitor-side regex execution is synchronous JavaScript, so keep patterns efficient and test representative URLs. Combined URL sets conservatively conflict with other active or shipped experiments on the same section selector. Check each shared page template before launching. The CDN automatically selects the extended condition runtime when an experiment or goal needs it, or when a live source binding needs saved bucket assignments: the base native bundle stays below 16 KiB, the condition bundle below 20 KiB, and the Optimizely browser adapter below 96 KiB, before compression and inline configuration.

Existing imports and page resources keep their saved mode, including legacy strict full-URL matching. REST 0.21.0 reports the Patchwork-specific patchwork_url_matching field on pages: optimizely, simple, conditions or strict. Set it before any referencing experiment has measured traffic, then publish explicitly. This updates linked native rules and goals while preserving import provenance. Measured definitions cannot change; use new page and event identities for different semantics. A page condition with match_type: simple selects Simple mode; an exact condition selects normalized exact mode unless the page already uses strict mode. Substring/regex or combined conditions select conditions mode. An explicit extension must agree with the condition. Single exact/simple terms use their canonical condition URL as edit_url; combined rules keep their representative edit URL. Fragment-only navigation preserves ordinary activation; declared URL-change pages reevaluate it. Callback/polling activation is supported as documented below. Element-presence and JavaScript condition leaves remain planned.

Filter project discovery

REST 0.21.0 accepts repeated project ID filters, such as /projects?filter=id:1000&filter=id:2000&per_page=1. The result is the union of matching bound projects in your workspace, ordered by numeric ID. Filtering runs before pagination and counting. Link headers retain every filter; HEAD returns the same pagination headers with an empty body. Omit filters to list all bound projects.

Use at most 100 distinct filter=id: values with positive signed int64 project IDs. Unknown or foreign IDs produce no matches. Empty, malformed, duplicate or excessive filters return 400. Repetition is allowed only for filter; repeated page or per_page still fails. Generated clients can use an exploded form array. Values above JavaScript's safe integer range must remain decimal strings when constructing URLs.

Experiment lists also accept include_classic=false. The Web results are unchanged. include_classic=true returns 501 unsupported_operation because Classic resources remain unimplemented. Use lowercase true or false; malformed or repeated Boolean values return 400.

Archive and restore experiments

REST 0.21.0 supports DELETE /experiments/3000 and PATCH /experiments/3000?action=unarchive with an empty JSON object: {}. Archive returns 204 with no body. It removes the experiment from ordinary delivery and public disabled previews; GET and lists retain its archived metadata. Unarchive returns paused and never starts traffic automatically. If public disabled previews are enabled, the restored paused content becomes previewable again. Both operations require an owner or editor and publish after the database commit.

Source IDs, native variants, approval, allocation, goals, original import provenance and start/end timestamps are preserved. A never-started restored experiment keeps its review screen and editable prelaunch definitions. AI generation is unavailable in the restored paused state. Its first start or resume still validates review, goals, entitlement, overlap and size, then records its first start time. Restoring a measured experiment does not reset its first start time or permit measured edits.

A 503 publishing_pending means the state was saved but delivery may still show the previous config. Retry the same request. A repeated DELETE refreshes delivery before returning 410 already archived; treat that response as a completed archive. A repeated unarchive on paused returns 200. Retries preserve last_modified and do not emit duplicate milestones. Archiving still works if native edits broke the GET projection; restoring validates the projection and rolls back to archived on failure.

In-flight generation cannot be archived (409). Concluded experiments and native shipped winners can be archived, but concluded history and winner deployments cannot be reopened through this adapter (409). Create a fresh experiment for a new measurement period. Offline fixtures cover the vendor action/status contract, publication retries and native lifecycle integration; live account parity remains unverified.

Project/experiment creation, project archiving, REST campaign queries, multi-page variation actions and live content/allocation changes remain planned. Variation-specific events, event property filters and Classic resources are not supported. Unsupported operations fail explicitly. Optimizely OAuth, vendor result tokens, account metadata, advanced snippet settings and Feature SDK behavior remain planned. Browser web-1 support is documented below. Use a Patchwork key and install its snippet; no Optimizely token is read or stored by this API.

Declarative changes compile the captured section into a reviewed variant. Selectors must resolve in that snapshot or in content introduced by a prerequisite. This does not emulate Optimizely's polling for future matching elements. Output is limited to 100 KB per variant; expansion is checked during translation. REST reads represent the resulting HTML and styles rather than preserving the original edit list or dependency IDs. Fixtures and isolated Postgres integration tests cover these paths; behavior against a live Optimizely account remains unverified.

Opt-in browser API: web-1

Existing window.optimizely calls can use the supported commands below. Register your imported experiments, map the events you need, and publish the site before installing. Publishing an experiment through PATCH /experiments/ID?action=publish refreshes its site's browser mappings too. Stop the old tests and replace the old Optimizely script with this snippet, substituting your Patchwork site key and source project ID. An existing initialized SDK is preserved and reported as a conflict. Remove the vendor tag from tag managers and asynchronous loaders too; SDKs loaded later are not coordinated.

<script src="https://cdn.patchwork.run/s/tp_REPLACE.js?optimizely=1000" data-consent="required"></script>
<script>
  // Call from your consent manager after consent is granted.
  window.patchwork.consent(true);
</script>

The project query selects a separate compatibility runtime in the same response. The default snippet uses the extended native runtime for live source bindings and reads the same saved assignments without installing window.optimizely. Required consent defers visitor storage, experiment rendering and measurement. Revocation through patchwork.consent(false) clears this tab's queued events, custom attributes, manual bucket assignments and compatible decision history, stops tracking and restores the original section. Events submitted before required consent are dropped with a consent_required diagnostic.

Browser interfaceCurrent behavior
push({type:"user", attributes})Set custom attribute values by ID or API name. Strings persist after consent; null removes a value. Values set before required consent stay only in memory until granted and are discarded on revocation. Call activate to evaluate changed values for a new activation.
push({type:"bucketVisitor", experimentId, variationId?, variationIndex?})Choose a published variation by source experiment ID and either source variation ID or zero-based index. Supply exactly one choice field. The choice persists for this visitor and source project; another call changes it. Call activate or the named page command to apply a post-load choice. Consent, URL/audience/device eligibility, holdback, enrollment limits and manual-page gates still apply. Shipped winners and unpublished variations cannot be overridden.
push({type:"disable", scope?})Queue before initialization. Without scope, prevent identity storage, rendering and telemetry for this page. With scope:"tracking", keep rendering and identity but discard events, including this tab's saved held queue. Later disable calls report a diagnostic; load a fresh page without the command to enable again.
push({type:"event", eventName, tags})Track a linked custom event by API key. Flat string/number tags, including revenue and value, reach the raw event stream. Revenue uses integer hundredths of the reporting currency; reporting aggregations currently use unique visitors.
push({type:"activate"})Start a fresh page view: restore and reapply the section, then record pings, exposures and URL goals again. Unique-visitor results deduplicate those records. URL changes also activate automatically; anchor-only navigation preserves ordinary activation; declared URL-change pages reevaluate the full URL. Reentrant activation from a lifecycle callback is rejected.
push({type:"page", pageName, isActive?, tags?})Reactivate a registered page by API name, rechecking its targeting for the current full URL, including its fragment, and custom attributes. Omit isActive or use true to apply its sections and record its linked page-view goals with tags. false restores its sections, stops page clicks and removes its active decisions. Other pages and unmapped native experiments keep their DOM, exposures and global page-view ID. Custom events remain independent. Named commands do not emit a global activated event; reentrant calls from listeners are rejected.
push({type:"holdEvents"}) / sendEventsHold all logging while decisions and rendering continue, then release it. Consent remains a separate gate. Per-tab queues recover across normal navigation through sessionStorage: at most 24 hours, 500 events and 296 KiB. Copied or contested queues are discarded; unavailable shared storage uses memory only. Delivery is best effort.
addListener / removeListenerListen to lifecycle initialized, activated, pageActivated, pageDeactivated and campaignDecided; action applied; and analytics trackEvent. Provide a token to remove listeners. Late listeners receive future events. Callback failures are isolated.
get("state")Read active experiment IDs, experiment/page/campaign states, the variation map, decision strings/objects and redirect info. Filters accept isActive or a function. Traffic holdback remains active in state while showing original content.
get("data")Read current published project, page, event, experiment and A/B campaign definitions. Variation actions describe the compiled section and scoped CSS. Draft variation HTML and CSS are excluded; registered event metadata can be public before launch.
get("visitor_id") / get("visitor")Read the native visitor ID and consented custom string attributes after activation, plus browserId, browserVersion, device and device_type. These fields are included by the complete SDK even without a browser audience.
get("utils")Use the DOM, timing and URL utilities documented below. These calls run your own page code and return Promises or cleanup functions.
Queued functionsA function entry receives the API object. Functions and listeners run as your own site code. Existing queue references continue to accept pushes after initialization.
window.optimizely = window.optimizely || [];
window.optimizely.push({
  type: "addListener",
  filter: { type: "lifecycle", name: "activated" },
  token: "my-analytics",
  handler: function () {
    var state = window.optimizely.get("state");
    console.log(state.getActiveExperimentIds(), state.getVariationMap());
  }
});
// "signup" must be a linked custom event in this source project.
window.optimizely.push({
  type: "event", eventName: "signup",
  tags: { plan: "pro", revenue: 7502, value: 12.5 }
});

Named page activation

Use the page API name returned by get("data").pages[id].apiName. A named activation stays within the current logical page view and checks the current full URL, including its fragment. Ordinary anchor navigation preserves existing activation unless a named command or a declared URL-change page rechecks that URL. A global activation or SPA route change resets named deactivation overrides and evaluates immediate pages again. Consent revocation discards pending page commands and overrides. Page commands before required consent are rejected. Unknown names, pageId/force fields and invalid tags report diagnostics. Queued deactivation after consent suppresses that page's first render and automatic events. REST 0.21.0 and imports support immediate, manual, URL-change and DOM-change page definitions. Manual imports require a page ID and API key; preview lists those API names. A manual page starts inactive, and global activation, SPA navigation and consent re-grant leave it inactive until another named page command. The ordinary snippet and adapters for other projects exclude its experiments and page-click/page-view goals. Register the binding and install the matching adapter before using manual pages. Custom events stay independent. Activation settings and manual page API names freeze after a referencing experiment first launches, including paused and historical tests. Metadata can still change. Callback and polling functions are supported as described below; manual pages still require supported URL conditions. Imported settings survive persistence and registration; prelaunch registry edits become canonical. Existing immediate-only confirmation digests and destination IDs are preserved.

// "home" is a registered page API name.
window.optimizely.push({type: "page", pageName: "home", isActive: false});
// After the application has refreshed that page section:
window.optimizely.push({type: "page", pageName: "home", tags: {step: "checkout"}});

Callback and polling activation

Imports and REST pages support activation_type: callback and activation_type: polling. Supply activation_code as a synchronous function expression, up to 16 KiB of UTF-8. Preview shows the saved function and includes it in confirmation. The server parses it without running it; invocation expressions, async functions and generators are rejected. Activation code is published only for pages referenced by serving experiments or their metrics. Native snippets and other projects' adapters do not execute it.

// Callback: signal when the application is ready.
function(activate, options) {
  var button = document.querySelector("#open-checkout");
  if (!button) return;
  var open = function() { activate(); };
  button.addEventListener("click", open);
  return function() { button.removeEventListener("click", open); };
}

// Polling: return boolean true when ready.
function() { return !!document.querySelector("#checkout-ready"); }

These functions execute with your site's browser privileges and are not sandboxed. Review their side effects before import or a prelaunch REST update. Required consent gates compilation and execution. CSP must permit Function compilation, usually through script-src unsafe-eval; if that conflicts with your policy, use manual activation instead. Do not weaken CSP simply to migrate. Parse, runtime and CSP errors report generic diagnostics without logging source code. Other custom-JavaScript visual changes and project scripts remain unsupported.

A callback receives activate and options, whose isActive value reflects the current page state. Call activate() to check URL and normal eligibility gates, or activate with isActive: false to deactivate and restore the section. Functions initialize even outside the target URL; calling activate does not bypass targeting. Polling checks immediately and then every 50 ms until the function returns boolean true, or two seconds after DOM readiness or polling start, whichever is later. A successful predicate stops polling even if the URL does not match. Global activation and SPA navigation initialize a new trigger session. Source functions run only in the matching adapter.

Consent denial, page-cache suspension, navigation and disposal cancel polling and invalidate old activation callbacks. A callback may return a cleanup function, a Patchwork extension; cleanup runs in a microtask after the old session closes. Source code owns any listeners or timers it creates. The adapter cannot interrupt a function that blocks the browser thread. These timing and cleanup behaviors are fixture-tested; live vendor parity remains outstanding. The optional adapter budget is now 96 KiB before compression and configuration; base and extended native budgets remain 16 KiB and 20 KiB.

Page deactivation and retained changes

REST 0.21.0 adds patchwork_deactivation_enabled and patchwork_undo_on_deactivation to page create/update/read and import definitions. Both default to true, preserving existing behavior. Optimizely documents these page behaviors, but its public REST schema omits the settings, so these are explicit Patchwork extensions. Configure them before launch and publish the site afterward. Metadata edits and identical retries remain allowed after launch; policy changes and page API-name changes are blocked after measurement.

PATCH /api/compat/optimizely/v2/pages/6700
{"patchwork_deactivation_enabled":true,"patchwork_undo_on_deactivation":false}

// Alternative: keep an activated page active after its conditions stop matching.
{"patchwork_deactivation_enabled":false,"patchwork_undo_on_deactivation":true}

With automatic deactivation disabled, an activated page keeps its decision and rendered section when later automatic URL/DOM conditions fail. Its current nodes persist across SPA navigation and global activation without another rendered exposure; a later genuine dynamic replacement can produce a new exposure. Explicit page isActive:false still deactivates it. DOM-change pages keep repairing external replacements while active. Pages that have never activated still need their normal conditions and trigger.

With undo disabled, deactivation makes page and experiment state inactive and stops page conversions, exposure observers and dynamic repair, while leaving applied HTML and CSS visible. Reactivation restores the original section before applying a fresh decision, preventing nested wrappers. A DOM-change page still needs an external DOM mutation to reevaluate after returning to a matching URL; a URL change alone is not its trigger.

Nondefault policies require the matching project adapter even for immediate pages. Ordinary native delivery excludes these experiments and page goals. Retained sections can outlive URL targeting, so any running or shipped test on the same selector conservatively blocks launch, resume or shipping, even when the URLs are disjoint. Use separate sections or return to default policies before measuring. Consent denial, pagehide and SDK disposal always restore content and remove variation CSS. bfcache recovery starts clean.

Nondefault import settings enter confirmation digests; explicit true defaults retain old digests. SDK data and state expose deactivationEnabled and undoOnDeactivation. Cross-frame retention and cleanup behavior have fixture and compiled-browser coverage; live vendor parity remains unverified. Element-presence and JavaScript condition leaves remain planned.

Project-controlled URL previews

REST 0.21.0 supports web_snippet.enable_force_variation and web_snippet.exclude_disabled_experiments on bound projects. Forcing defaults off; disabled content defaults excluded. A privacy-setting write publishes automatically. If publication returns 503, retry the same flags: unchanged retries refresh delivery while preserving last_modified. Enabling public disabled previews validates the site's 296 KiB content limit and a maximum of 100 disabled experiments before committing.

PATCH /api/compat/optimizely/v2/projects/1000
{"web_snippet":{"enable_force_variation":true,"exclude_disabled_experiments":true}}

// Running variation; use a source variation ID, not an index.
https://your-site.example/?optimizely_x=VARIATION_ID
// Explicitly opt running preview traffic into measurement.
https://your-site.example/?optimizely_x=VARIATION_ID&optimizely_force_tracking=true

Comma-separated variation IDs may select multiple experiments; conflicting choices for one experiment, ambiguous IDs, repeated parameters and invalid values fail closed. Variation forcing suppresses other experiments and bypasses audience, device, traffic holdback and enrollment allocation. URL and page activation conditions still apply. Reserved Optimizely query parameters are removed for preview URL comparisons while application query encoding, order and fragments remain intact. Manual and conditional pages need their matching adapter and trigger; forcing does not activate them by itself.

optimizely_x_audiences accepts comma-separated source audience IDs. It substitutes those audience references while preserving AND/OR/NOT, source expression behavior, traffic holdback and enrollment gates. A forced variation choice persists with the current visitor after consent, through adapter/native reloads and stable source variation IDs. Consent denial clears it. Preview parameters are captured on page load; reload without them to leave preview mode. Unpublished choices never become ordinary assignments.

Setting exclude_disabled_experiments to false while forcing is enabled publicly delivers bound draft, review and paused variation content. Anyone who obtains the snippet can inspect it. optimizely_token=PUBLIC permits selection at runtime and is not a secret or authentication credential. Disabling the setting publishes fresh delivery, subject to snippet caching; it cannot recall downloaded content. Status, approval and history remain unchanged. Draft/paused previews never send telemetry, even with force_tracking. Unselected draft callback functions never initialize.

Patchwork preview telemetry is off by default. optimizely_force_tracking=true enables it for running experiments; explicit tracking disable still wins. Existing held events are preserved for a later ordinary page, and consent denial still clears recovery. Required consent gates storage, assignment persistence and rendering. optimizely_disable=true stops compatible startup. QA profiles also support optimizely_log=true, which logs public decision IDs without attribute values. The SDK exposes preview mode and effective tracking through get("patchwork").preview. Logging formats and disabled-preview tracking are Patchwork behavior tested with fixtures; live vendor parity remains unverified.

Ordinary native and condition profiles retain 16 KiB and 20 KiB budgets. Project forcing selects native QA below 32 KiB, or 64 KiB when browser/device matching is also needed. The complete SDK stays below 96 KiB before compression and configuration. Native QA does not install window.optimizely. Feature SDK forced decisions and signed private preview links remain separate work.

Persistent visitor bucketing

REST 0.21.0's browser runtime supports the Web bucketVisitor command. Use string IDs and either variationId or variationIndex. A published zero-weight variation can be selected. Changing a choice does not immediately rerender the current page or send an event; call activate, use the named page command, or wait for the next activation. State getters continue to describe the current activation until then. Normal eligibility and holdback remain in effect. Project-controlled URL previews are described above; Feature SDK forced-decision methods remain planned.

window.optimizely.push({type: "bucketVisitor", experimentId: "3000", variationId: "2"});
window.optimizely.push({type: "activate"});

Choices queued before required consent remain in memory until consent is granted. An explicit denial clears both pending and saved choices, even before tracking has started and on ordinary native pages. Saved choices are scoped to the site, project, experiment and current visitor. Each experiment has its own storage key, so tabs updating different experiments do not overwrite one shared map. The runtime accepts up to 1,000 choices per project; unavailable storage keeps choices in memory for the current tracking session.

Both the adapter and extended native runtime resolve stable source variation IDs to the currently published native revision. Paused experiments and unpublished or retired variations are not made public by this command. Another project's adapter honors its saved native choices while accepting bucket commands only for its own project. The base native runtime remains below 16 KiB; live source bindings select the extended profile below 20 KiB. Bucket choices do not transfer old Optimizely visitor identities or historical results. Post-call timing and holdback behavior are fixture-tested Patchwork behavior; live vendor parity validation remains outstanding.

URL-change activation

Set a registered page's activation_type to url_changed before launch, then publish the experiment. These pages evaluate on initial load and later pushState, replaceState, Back/Forward and hashchange navigation. Matching hash routes activate only the declared pages, keep unrelated DOM intact and retain the global page-view ID. Path/query navigation keeps the existing fresh global page-view behavior. Identical URL writes do nothing. Page clicks and views follow the active page, including fragment-specific conditions. When a route stops matching, its section is restored and page events stop. Deactivation and undo default to enabled; page policy extensions support additional behavior. Manual page commands also check the current fragment. Listener navigation is queued and bounded; obsolete routes never record an exposure. Outgoing sections are restored before another URL page claims the same section. Required consent defers activation, and disposal removes route observation. Native and other-project snippets exclude these experiments and their page goals. The native bundle retains its 16 KiB budget; the optional adapter now has a 52 KiB budget for page triggers and browser utilities.

DOM-change activation

REST 0.21.0 and imports support activation_type: dom_changed. Register the binding, set this trigger before measurement and publish. The matching adapter evaluates the page on load and after external insertions, removals, attribute changes or text changes. Mutations are coalesced. Matching pages keep watching for delayed or replaced sections beyond the ordinary 1.5-second renderer timeout. Other projects' adapters and the ordinary native snippet exclude these experiments and their page goals.

Unrelated mutations preserve other sections, the global page-view ID and pageview-goal count. Fresh host-rendered section nodes can receive the same assigned variation again; in-place changes inside a variation are repaired. Replacements release old visibility observers, and stale callbacks cannot record exposures. A visible replacement can emit another raw exposure, which unique-visitor results deduplicate. SDK-owned swaps and undo operations do not trigger themselves. A named deactivation lasts until the next external DOM trigger, a named command or a global activation.

DOM changes reevaluate the supported URL conditions, including current fragments. A hash-only navigation without a DOM change waits for that trigger; use url_changed when navigation itself should trigger evaluation. Outgoing sections are restored before new matching pages render. Required consent delays observation and rendering. Revocation, page-cache suspension and disposal remove observers and pending work.

Three consecutive repairs are allowed for the same original section node; a continuing conflict restores the original section, reports hydration_conflict and waits for a fresh host node or explicit reactivation. Structural fingerprint checks still apply. Modern MutationObserver support is required. This is the URL-condition subset of DOM activation: element-presence and JavaScript condition leaves remain planned. Complex framework hydration still needs site-specific testing.

Audience targeting and attributes

Imports resolve up to 30 referenced audiences and 100 project attributes, with 200 terms and 16 nesting levels per compiled tree. AND, OR and NOT preserve the source expression. Supported leaves are preferred language, string custom attributes and raw query parameters. Exact, substring, exists, regex and range comparisons are available; prefix remains a Patchwork extension for custom attributes. Missing custom values are absent and can be negated: NOT equals gold includes a visitor with no saved plan. This corrects the earlier unknown-value behavior using offline vendor comparison fixtures. A query context that is unavailable remains unknown, including under NOT. Unsupported conditions block the complete import. Conflicting definitions for a shared source ID cannot publish together. Registered rules become immutable after measurement; use new source IDs for different conditions rather than reinterpreting historical traffic.

Attribute values are isolated by site and source project. Set them through the opt-in adapter; later native snippet loads use the same saved values. Language targeting works in both runtimes. Each visitor can store 100 string values, up to 1,024 characters each and 16 KiB total. They are used for targeting and exposed by the visitor getter; they are not sent as event tags or used for results segmentation.

Values set using an API name before its attribute definition exists remain saved. Once that definition is published, both the adapter and native snippet resolve the saved name to its source ID on the next load. Web attribute values are strings or null; numeric and Boolean attributes belong to Optimizely's separate Feature SDK contract.

REST 0.21.0 supports list, read, create, update and archive for audiences and attributes. Audience conditions are JSON strings using the supported leaves above; experiment audience_conditions references their IDs with AND, OR and NOT. Names and descriptions remain editable after launch. Rules, attribute API keys and experiment audience references can change only before measurement. Shared resource edits affect every referencing draft; original import snapshots remain unchanged. Resource writes save configuration; use PATCH /experiments/ID?action=publish to refresh browser delivery.

Archive an audience with PATCH archived:true after detaching all experiment references, including historical tests. Attributes can be archived with PATCH or idempotent DELETE after removing them from active audience definitions. Archived resources remain readable. Re-register older bindings to adopt the canonical registry; until then, existing delivery keeps its original snapshot. Native launch and resume adopt definitions under the same site lock. A conflict with measured legacy targeting returns 409. Active project definitions, including unused resources, appear in the public browser data catalog.

window.optimizely = window.optimizely || [];
window.optimizely.push({type: "user", attributes: {plan: "gold"}});
// After a value changes, evaluate a new activation.
window.optimizely.push({type: "activate"});
// Remove the saved value on logout.
window.optimizely.push({type: "user", attributes: {plan: null}});

Query parameters, regex and range audiences

REST 0.21.0 imports and audience resources accept query leaves with name, match_type and value. Query names and values are case sensitive. Matching uses the first repeated parameter, preserves percent escapes and plus signs, and reads only the first value segment after equals. For example, campaign=spring+sale matches the literal spring+sale, and campaign=a=b supplies a. An empty or bare parameter is present for exists; an absent parameter is false and can be negated. Query conditions are reevaluated at activation rather than saved as sticky campaigns. URL fragments are not query parameters.

PATCH /api/compat/optimizely/v2/audiences/7000
{
  "conditions": "[\"and\",{\"type\":\"query\",\"name\":\"campaign\",\"match_type\":\"exact\",\"value\":\"spring+sale\"}]"
}

// Inside a JSON audience condition tree:
{"type": "custom_attribute", "name": "plan", "match_type": "regex", "value": "^gold(?:-member)?$"}
{"type": "custom_attribute", "name": "visits", "match_type": "range", "value": "1:5"}

Regex uses JavaScript matching without flags, including lookarounds; invalid patterns return 422. Browser regex evaluation is synchronous, so review expensive expressions. Range compares inclusive lower:upper bounds using numeric string prefixes: 3visits falls within 1:5, while text with no numeric prefix does not. Web attribute values remain strings; this does not enable numeric or Boolean Feature SDK attributes. Custom attribute IDs and API names resolve to the same stored definition. Defaults without a value mean exists; a provided value defaults to exact. Prefix remains supported only for custom attributes as a Patchwork extension.

The CDN automatically selects richer native profiles when these conditions are published: ordinary native below 16 KiB, conditions below 20 KiB and extended targeting below 32 KiB. Browser/device conditions add an optional 64 KiB native profile. The complete SDK has a 96 KiB budget and includes all supported audience matching, visitor fields and preview code; project settings still govern previews. Required consent gates decisions, stored attributes and rendering. Native pages never install window.optimizely. Retained decisions expose their decision-time query context, rather than relabeling an old decision after navigation.

Query values are used locally for decisions; they are not saved as user attributes, sent as event tags or included in preview diagnostics. Source fixtures cover raw encoding, repeated parameters, missing values, API persistence, consent and SPA decisions. Forty-one offline vectors derived from Optimizely's public comparison and query-provider modules check the supported operators. Those checks did not execute the complete vendor SDK or use a live account; full vendor parity remains unverified. Cookie formats, sticky referrer/campaign attribution, platform audiences and other condition families remain planned.

Visitor-local time and day targeting

REST 0.21.0 supports time_and_day audience leaves through imports and audience resources. The value format is HH:MM_HH:MM_weekday[,weekday...], with lowercase English weekday names. Clock components accept one or two digits from 00:00 through 24:00; hour 24 requires minute 00. Unknown weekdays, invalid clocks and extra fields return 422.

PATCH /api/compat/optimizely/v2/audiences/7000
{
  "conditions": "[\"and\",{\"type\":\"time_and_day\",\"value\":\"09:00_17:00_monday,tuesday,wednesday,thursday,friday\"}]"
}

Both endpoint minutes are inclusive: 09:00_17:00 includes 17:00:59 and excludes 17:01. Matching uses the visitor's local time zone, including daylight-saving changes. A reversed interval never matches. For an overnight window, combine separate day intervals with OR. This Friday-night example includes early Saturday:

["or",{"type":"time_and_day","value":"22:00_24:00_friday"},{"type":"time_and_day","value":"00:00_02:00_saturday"}]

Required consent gates time decisions. Global activation and named-page reactivation sample a fresh clock; the existing page does not expire on a timer. Conversions may continue after the time window while that decision remains active. SDK state getters retain the original decision time, including for latched pages. Clock snapshots stay in memory and are cleared on consent denial; no time-zone or weekday fields are added to saved user attributes or event tags. Missing clock context stays unknown under NOT. Import preview validates the definition without using the server's local clock to predict a visitor's eligibility. Experiment start/stop scheduling remains planned.

Time/day conditions select the existing 32 KiB native and 96 KiB SDK audience profiles automatically. Forty-two offline vendor-derived time vectors cover minute and weekday boundaries, six time zones and daylight-saving transitions. Compiled native and SDK fixtures verify those time-zone decisions, consent, named reactivation and URL previews. These fixtures do not establish live Optimizely account parity.

Campaign, referrer and traffic-source targeting

REST 0.21.0 imports and audience resources support campaign, referrer and source_type conditions. These use consented visitor profiles shared by native and SDK delivery. Campaign and traffic source accept exact, substring, regex, range and exists matching; omitted match_type means exact when a value is present, otherwise exists. Referrer accepts simple, exact, substring and regex. Regular expressions use JavaScript without flags. Definitions have a 1,024-character value limit, or 2,048 for referrers.

PATCH /api/compat/optimizely/v2/audiences/7000
{
  "conditions": "[\"and\",{\"type\":\"campaign\",\"match_type\":\"exact\",\"value\":\"spring+sale\"},{\"type\":\"source_type\",\"match_type\":\"exact\",\"value\":\"campaign\"},{\"type\":\"referrer\",\"match_type\":\"simple\",\"value\":\"https://partner.example/start\"}]"
}
ConditionMatching inputPersistence
campaignFirst raw utm_campaign value, including an empty or bare parameter. Percent escapes and plus signs remain raw; repeated parameters and equals signs use the first segment.First known value is sticky. An absent value can be supplied by a later activation, while an empty value remains sticky. Values are not truncated to the 20-character reporting dimension described in vendor help.
referrerFirst document.referrer string, or null for a known absent referrer. URL matching folds case for simple/exact/substring; regex remains case sensitive. Literal optimizely_ query parameters are removed before matching.First referrer is sticky, including null. Simple ignores query and fragment; exact retains them. This field is separate from the latest traffic-source classification.
source_typecampaign, search, referral or direct. A truthy utm_source, utm_campaign, gclid or otm_source takes priority. Empty parameters do not classify traffic as campaign.The last non-direct source wins. A later direct activation retains the prior non-direct source; another campaign, search or referral can replace it.

Missing campaign stays unknown under NOT, including an exists condition. This follows the captured required-field behavior: it cannot include a visitor through negation until a campaign value is known. A null referrer is a known nonmatch and can be negated. A blocked or unavailable provider stays unknown. Search classification uses the captured case-sensitive Google/Bing/Yahoo/Baidu URL heuristics. Domain comparison strips www and one optional digit, ignores ports, and treats other subdomains as separate referrals. These categories follow the vendor heuristics and are not a security classification.

Profiles are scoped to the site, source project and visitor. SDK visitor getters expose campaign, referrer and source_type even without an acquisition audience. Getters return copies of the last activation snapshot; retained decision state keeps its own snapshot. Consent denial clears acquisition storage and memory, including on a basic native page where this provider never loaded. Acquisition records now use an environment namespace that native 0.18 and 0.19 pages already clear. On upgrade from 0.20, saved campaign, referrer and traffic-source profiles reset: those records have no revocation marker that older pages understood, so their consent history cannot be verified. New records retain the documented persistence behavior. Storage failures use the current page's memory fallback. Acquisition-only native delivery uses the 32 KiB extended profile without the UA parser. Ordinary event payloads and tags do not gain these fields.

Stored provider values are capped at 16,384 characters; larger values remain unavailable rather than being truncated into a match. Records above 65,536 characters are not written. The captured providers have no automatic expiry. Their first-touch and last-non-direct behavior comes from 30 provider profiles, 318 offline decision vectors and 14 persistence sequences. Broader vendor help describes session and attribution behavior; live account and cross-session parity remain unverified. Optimizely redirect-relay state is not imported; attribution uses the browser URL and document.referrer. Cookies, OS/platform, first/returning-session and other audience families remain planned.

Browser, version and device targeting

REST 0.21.0 imports and audience resources support browser_version, device and device_type leaves with type and value fields, combined by AND, OR and NOT. Browser families use gc (Chrome, Chromium, Silk, Yandex, Maxthon and Chrome WebView), edge, ie, ff, opera, safari, ucbrowser or unknown. Add a numeric version-component prefix to target a release: gc130 matches 130.x, while gc13 does not match 130. Wildcards, comparison operators, match_type and unknown values return 422. Browser values have a 200-character limit and at most ten numeric components. Missing required browser/version fields remain unknown under NOT. The runtime requires modern JavaScript support.

PATCH /api/compat/optimizely/v2/audiences/7000
{
  "conditions": "[\"and\",{\"type\":\"browser_version\",\"value\":\"gc130\"},{\"type\":\"device_type\",\"value\":\"desktop_laptop\"}]"
}
ConditionValuesMeaning
browser_versiongc130, safari17.5, edge, ff128?Family and optional numeric version components.
deviceiphone, ipad, tablet, mobile, desktopApple models, other tablets, other phones, or desktop/fallback devices.
device_typephone, tablet, desktop_laptop, otherBroader classes: phone includes iPhone, and tablet includes iPad.

Classification uses UAParser.js 1.0.41 and synchronous browser hints, matching the captured vendor parser. It uses user-agent data rather than viewport width. Desktop-mode iPads depend on available touch and standalone hints. The parser considers up to 500 user-agent characters, with the captured Apple hardware-token fallback. No extra network request is needed. Browser families, device models and device classes are separate projections; unusual TVs, consoles or unrecognized agents can fall into different fallback groups.

After consent, profiles are saved separately for the site, source project and visitor. Browser IDs and device classes remain sticky across reloads. Browser versions refresh on each physical page when available; an unavailable new version retains the last known version. The page caches its parsed UA data, so changing emulation settings requires a fresh page. Clear site data or use a separate profile to change saved coarse fields. Consent denial clears profile storage and memory, including from a basic native page where the parser never loaded. Blocked storage uses a per-page memory fallback. Raw UA strings are never saved in these profiles or added to event tags.

The complete SDK exposes browserId, browserVersion, device and device_type through get("visitor") after consent and activation, even when no browser audience is configured. The SDK has a 96 KiB budget and includes all supported audience and preview engines; project privacy settings still govern previews. Native pages keep the parser in an optional 64 KiB profile. Every parser bundle includes its MIT notice. Importing the SDK does not initialize the parser before consent or install UAParser or jQuery ua globals.

// After the SDK loads; visitor is unavailable before consent/activation.
const visitor = window.optimizely.get("visitor");
if (visitor) {
  console.log(visitor.browserId, visitor.browserVersion, visitor.device, visitor.device_type);
}

Fixtures cover 26 UA projections, 216 browser/device decisions and 13 provider/persistence cases, including cross-project and cross-visitor isolation and last-known version fallback. Compiled Chromium fixtures run these profiles with controlled UA/hint inputs in both native and SDK delivery. The captured provider/storage contract has no automatic profile expiry; live cross-session parity remains unverified. These checks did not execute the complete vendor SDK or use a live vendor account. Platform/OS audiences, cookie formats, sticky referrer/campaign attribution and other unsupported families remain planned.

Browser utilities

UtilityBehavior and cleanup
waitForElement(selector)Resolve a Promise with the first matching DOM element, including elements added later.
observeSelector(selector, callback, options)Notify new matches asynchronously. Options: once, timeout (milliseconds or null), onTimeout. Return an unobserve function.
poll(callback, delay)Run at the requested interval; return a stop function.
waitUntil(conditionFn)Resolve a Promise with the first synchronous truthy result. Async predicates are rejected.
onUrlChange(callback)Notify path, query and fragment changes; return a stop function. Fragment changes still preserve native experiment activation.
persistHtml(html, selector, placement)Maintain HTML at matching anchors. Placement: before (default), after, afterbegin or beforeend. Reinsert removed roots; return a function that removes the injected nodes and stops reinsertion.

Utility calls can run before tracking consent and create no visitor identity or telemetry. Their callbacks and HTML changes belong to your page code: use returned cleanup functions when that code should stop, including consent or experiment lifecycle changes. Imported experiments continue to use validated declarative changes. Utilities allow 200 active jobs per SDK instance. Invalid inputs fail visibly; callback errors stop the affected job. Unresolved waits reject with AbortError when the SDK is disposed.

window.optimizely.push(function (api) {
  var utils = api.get("utils");
  utils.waitForElement(".signup-button").then(function (button) {
    button.classList.add("ready");
  });
  var stop = utils.observeSelector(".price", function (element) {
    element.classList.add("highlight");
  }, { timeout: 6000 });
  // Call stop() when your integration is torn down.
});

Browser IDs are exact decimal strings. Native revisions keep their public variation IDs. Campaign getters and campaign/action listeners use the original campaign_id when supplied in the export or API response. Reconfirm the same source to backfill older imports, then publish again; the import identity and revisions stay intact. Missing campaign identity produces campaign_identity_missing rather than inventing an ID. Captured campaign IDs also appear as source_campaign_id in native source-mapping responses.

Holdback visitors have an assigned variation in state and decision strings while seeing original content. Check isInExperimentHoldback or isInCampaignHoldback before labeling an analytics event as an exposure. A queued conversion before section visibility is logged but does not count in results until a prior section exposure exists. Delayed event times are rebased against dispatch time to compensate for device clock skew; events older than 24 hours are discarded. Tags and source IDs are retained in the enriched raw event table, while current results continue to use unique visitors. An incomplete project mapping makes its opt-in script inactive until the mapping is repaired and republished.

patchwork-web-1 uses native visitor identity, fresh assignment and section exposure measurement. Historical visitor assignments and results remain separate migration work. Tags are limited to 32 flat properties and 2 KiB encoded data. Unsupported commands, getters, filters and unknown events emit console diagnostics and a patchwork:compatibility-error event; get("patchwork") exposes the latest diagnostic codes. Feature SDK forced decisions, cross-origin identity and Feature Experimentation SDKs remain on the roadmap. Fixtures exercise the compiled browser bundle from a persisted import through conversion beacons; a live Optimizely account has not been used for parity validation. The compiled utility API is also tested in an isolated Edge browser with outbound requests blocked.

See the incident article, feature comparison and API documentation. The connector is built against the official Optimizely v2 schema; your source-account access is checked by Optimizely.