diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..a3c9464 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,8 @@ +# Internal to this repository's tests, not part of the API: the schema +# `graphql!` checks every package against, the Admin schema 2026-10, without +# network access. It reaches the projects `trybuild` compiles for the +# compile-fail tests, which have no schema file of their own. The macro +# honours it only for the packages `shopify_api` and `shopify_api-tests` +# (trybuild's name for its projects), never for another crate. +[env] +SHOPIFY_API_INTERNAL_TEST_SCHEMA = { value = "crates/shopify_api/graphql/admin.schema.json", relative = true } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f5e16c5..c33fdd5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,109 +7,83 @@ on: branches: - master +permissions: + contents: read + env: + CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 - TEST_SHOP_NAME: "${{ secrets.TEST_SHOP_NAME }}" - TEST_KEY: "${{ secrets.TEST_KEY }}" - RUST_LOG: "debug" jobs: ci-pass: name: CI is green runs-on: ubuntu-latest needs: - - style - - test - - docs + - check + - features + - msrv + - package + - audit + - windows steps: - run: exit 0 - style: - name: Check Style - + check: + name: fmt, clippy, tests, docs runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v1 - - - name: Install rust - uses: actions-rs/toolchain@v1 - with: - toolchain: stable - components: rustfmt - profile: minimal - override: true - - - name: cargo fmt -- --check - uses: actions-rs/cargo@v1 - with: - command: fmt - args: -- --check - - - name: temporary workaround - fmt all files under src - run: cargo fmt -- --check $(find . -name '*.rs' -print) - - test: - name: ${{ matrix.name }} - needs: [style] - - runs-on: ${{ matrix.os || 'ubuntu-latest' }} - - strategy: - matrix: - name: - - linux / stable - # - macOS / stable - - include: - - name: linux / stable - # - name: macOS / stable - # os: macOS-latest - + - uses: actions/checkout@v7 + - uses: jdx/mise-action@v5 + - uses: Swatinem/rust-cache@v2 + - run: mise run check + + # In its own job, so the build of nothing else can lend the client a + # feature it does not declare (`mise run check` runs it too). + features: + name: no default features, each feature alone + runs-on: ubuntu-latest steps: - - name: Checkout - uses: actions/checkout@v1 - - - name: Install rust - uses: actions-rs/toolchain@v1 - with: - toolchain: ${{ matrix.rust || 'stable' }} - target: ${{ matrix.target }} - profile: minimal - override: true - - - name: Build - uses: actions-rs/cargo@v1 - with: - command: build - args: ${{ matrix.features }} + - uses: actions/checkout@v7 + - uses: jdx/mise-action@v5 + - uses: Swatinem/rust-cache@v2 + - run: mise run check:features - - name: Test - uses: actions-rs/cargo@v1 - with: - command: test - args: ${{ matrix.features }} ${{ matrix.test-features }} -- --test-threads=1 - - docs: - name: Docs + msrv: + name: Rust 1.88 runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v2 - - - name: Install Rust - uses: actions-rs/toolchain@v1 - with: - toolchain: stable - profile: minimal - override: true + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@1.88 + - uses: Swatinem/rust-cache@v2 + - run: cargo check --workspace --all-features --locked + + # What `cargo publish --workspace` uploads: each crate builds from its own + # files, with the license, and nothing that needs the network. + package: + name: cargo package + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: jdx/mise-action@v5 + - uses: Swatinem/rust-cache@v2 + - run: cargo package --workspace --locked - - name: Check documentation - env: - RUSTDOCFLAGS: -D warnings - uses: actions-rs/cargo@v1 - with: - command: doc - args: --no-deps --document-private-items --all-features + audit: + name: advisories, licenses, sources + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: jdx/mise-action@v5 + - run: mise run audit + + # Paths read from `Cargo.toml` follow other rules on Windows (drive + # prefixes, `\`): the tests of those rules run there too. + windows: + name: paths on Windows + runs-on: windows-latest + steps: + - uses: actions/checkout@v7 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - run: cargo test -p shopify_api_graphql --lib --locked + - run: cargo test -p shopify_api --features cli --bin shopify-api --locked diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 06e2908..b7421e7 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -3,7 +3,11 @@ name: Release on: push: tags: - - "*" + - "v*" + - "[0-9]*" + +permissions: + contents: read jobs: call-ci: @@ -16,16 +20,10 @@ jobs: needs: - call-ci steps: - - name: Checkout sources - uses: actions/checkout@v2 - - - name: Install stable toolchain - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: stable - override: true - - - run: cargo publish --token ${CRATES_TOKEN} + - uses: actions/checkout@v7 + - uses: jdx/mise-action@v5 + # The three crates at once, in dependency order: when one fails to + # build, none is published. + - run: cargo publish --workspace --locked env: - CRATES_TOKEN: ${{ secrets.CRATES_TOKEN }} + CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_TOKEN }} diff --git a/.gitignore b/.gitignore index 604f452..19866d8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -/target +target/ .DS_Store Makefile .env diff --git a/CHANGELOG.md b/CHANGELOG.md index 967882e..67c1273 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,84 @@ # Changelog +## 1.0.0-rc.2 (2026-10-27) + +The second release candidate: rc.1 and the changes under "Since 1.0.0-rc.1" +below. Cargo only takes it when asked for: `shopify_api = "=1.0.0-rc.2"`. + +## 1.0.0-rc.1 (2026-10-26) + +The release candidate of 1.0.0: everything under 1.0.0 below. Cargo only +takes it when asked for: `shopify_api = "=1.0.0-rc.1"`. + +## 1.0.0 (Unreleased) + +A rewrite around operations checked at compile time. See [MIGRATION.md](MIGRATION.md). + +### Since 1.0.0-rc.1 + +- Fixed: `verify_app_proxy` and `sign_app_proxy` sort the `name=value` strings, as Shopify does, not the names. A request with a parameter whose name extends another one by a byte that sorts before `=` (`page` and `page2`, `filter` and `filter.v.price.gte`) was refused though Shopify signed it. +- Added: `Error::Auth` has `status` and `oauth_code` (`OAuthErrorCode`), the HTTP status and OAuth `error` code of the token endpoint's refusal, and `held`, set when the failure is that of a renewal another request ran; `Error::token_endpoint_status`, `Error::oauth_code` and `Error::is_held_auth_failure` read them. They are filled for client credentials, refresh, code exchange and token exchange, and `None` for an Auth error that is not a refusal (an answer that does not read as a token, no refresh token). The text of the errors does not change. +- Added: `crate = path` as the first argument of `graphql!` (`graphql!(crate = ::my_framework::shopify_api, "…", x = 1)`, `graphql! { crate = …; pub mod a = "…"; }`) and `input!` (`input!(crate = …, TypeName { … })`): the path of `shopify_api` in the generated code, `::shopify_api` by default, for a crate that uses the macros through a framework re-exporting them without depending on `shopify_api` itself. The path is absolute; `$crate` is refused. The schema is still that of the calling crate. + +### Added + +- `graphql!`, which checks a query or mutation against Shopify's Admin schema while the crate compiles and generates the types of its variables and result. Inline (`graphql!("…", first = 10)`), named (`graphql! { pub mod name = "…"; }`) or read from a file (`file("…graphql")`). +- Input values written as literals in an inline `graphql!`, checked against the schema at the token: `product = { id: id, status: ACTIVE, descriptionHtml: null, vendor?: vendor, seo: { title: t }, metafields: [for m in &rows if cond => { … }] }`. Field names are the GraphQL ones (`type` included); an unknown or repeated field, a missing required field (each one named), `null` on a non-null type, an unknown enum value (the valid ones listed) and a value of the wrong form are compile errors; deprecated fields and enum values warn. `field?: value` leaves the field out for `None`; an `Option` given to `field: value` does not compile, since `null` would clear the field. `raw(string)` sends an enum value unchecked. Rust expressions are checked by traits whose errors name the GraphQL type. Literals are written straight to JSON, with no `serde_json::Value` in between. +- `input!(TypeName { … })` builds an input object ahead of the call, with the same checks, as an `InputObject`: one Rust type per GraphQL name, the same in every module and crate, so that the values of several `input!` go in one `Vec`. +- `Maybe` (`Absent`, `Null`, `Value`), for `field?:` when `null` is a choice made at run time. +- Values Shopify would not read as written are refused. A `Float` must be finite (NaN and infinity were sent as `null`), an `Int` must fit in 32 bits, a non-null `JSON` must not be `null` at its top. An integer literal out of range, alone, negated, in parentheses or in a list `[…]`, is a compile error at the literal; `Some(…)`, `vec![…]` and other forms are checked at run time. A value known at run time, in a literal, an `input!`, a module's `Variables` or `Operation::variable`, is kept as refused, and the operation fails with `Error::InvalidValue { path, reason, detail }` before anything is sent: `` invalid value at `$product.metafields[2].value`: not a finite Float ``. The message names the place and the reason (`InvalidValueReason`), never the value; a serializer's message is in `sensitive_detail()`. An `InputObject` that is refused fails to serialize on its own. Nothing in the code of the macros panics on a value. +- No name the macros generate is in scope where the values are evaluated: a local, closure, function or constant of yours with the name of a generated item stays yours. +- One `graphql! { … }` holds several modules, `;` between them. A module's `Variables` runs as it is, `shopify.execute(module::Variables { … })`, and it names each input object its variables may hold: `pub type MetafieldsSetInput = InputObject<…>`. +- Deprecated fields, arguments, input fields and enum values are compiler warnings with Shopify's reason. +- `graphql!` refuses a nullable variable whose default is `null` where a non-null value is expected, an input field given twice in one input object, and one key selected twice with arguments that differ in kind (`1` and `1.0`, `"A"` and `A`) or in the order of an input object's fields, which Shopify tells apart. One response key may name different fields on two different object types, and below them, when the shapes of the answers agree (SameResponseShape), even fields of different object types: their subfields merge into one struct, each optional unless both sides select it. A field of an object type selected without subfields at one of its places is refused. So is a block string whose lines are indented with different Unicode whitespace (U+00A0 and U+2003), on which the GraphQL parser would panic. +- `Operation`, what `graphql!` builds, or `Operation::new` for any text: `execute` and `execute_response` take `impl Into>`, a module's `Variables` included. `body()` is the exact JSON text sent, and `variable_json(name)` the text of one variable; `with_name` sets the `operationName`. +- No schema ships with the crates. Each crate that uses `graphql!` keeps the schema of its Admin API version in `graphql/admin.schema.json`, and operations are sent to the version they were checked against. The version is `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`, else the one of the schema file, else (first build, no file) the latest stable one: a new Shopify release never changes a build. A local package (of the workspace, or a path dependency) that cargo was asked to build downloads the file when it is missing or does not hold the pinned version, once per build; any other crate never downloads nor writes it, and fails to build when its file is missing or does not fit, a packaged crate in the verification of `cargo package` included. A packaged, vendored or checked-out crate (a `Cargo.toml.orig`, a `.cargo-checksum.json` or a `.cargo-ok` in the package directory, a `.cargo-ok` above it, or a path under `$CARGO_HOME`, with or without symbolic links resolved) never downloads: where a crate is decides only between a download and a compile error, never which schema it gets. `shopify-api schema download` refreshes the file, `--only` cuts it down to some operations. +- `schema = ""` in `[package.metadata.shopify_api]` names another schema file than `graphql/admin.schema.json`, relative to the package's `Cargo.toml`, for that package only. It must name a file inside the package, which `cargo package` ships: a relative path with `/` and portable names (no `:`, `\`, `<>"|?*` or control character, no name ending in `.` or a space, no device name such as `CON`); an absolute path, or one that climbs out with `..`, is an error (a symbolic link inside the package may point elsewhere). A dependency keeps the one its own `Cargo.toml` names. The file follows the rules of the default one (version, download, older format), `shopify-api schema download` and `shopify-api check` use it, and an edit of the key compiles the crate again. +- `@oneOf` input objects (`ProductSetIdentifiers`…) are checked at compile time: exactly one field, not `null`. +- `shopify-api check` checks `.graphql` files against the schema. +- Retries, on by default (four): a throttled request waits for what its cost needs, a `429` for its `Retry-After`, in seconds or as an HTTP date (up to `RetryPolicy::max_retry_after`, five minutes by default, else `Error::Throttled` with `retry_after`); queries are retried after a `5xx` or a network failure, mutations never, nor any document that cannot be read as queries only. `RetryPolicy`, and `RetryPolicy::none()` for none. `RetryPolicy` and `BulkWaitOptions` are `Clone` and `Debug`, not `Copy` nor `PartialEq`, so that they may later hold a callback. The jitter of the backoff is random on every platform. +- `Shopify::paginate`, `Page`. +- Bulk results read as they download, in memory that follows the line being read rather than the file: `bulk_query_stream` and `download_bulk_results_stream` return `BulkRows`, a `Stream` with `next_row` and `collect`. Lines may span chunks, end in `\r\n` or have no final newline; blank lines are skipped. A line that does not decode is an `Error::Decode` with its line number, and the stream goes on; a line longer than `max_line_length` (`DEFAULT_MAX_LINE_LENGTH`, 64 MiB) or a failed download ends it. `bulk_query_rows` and `download_bulk_results` collect the same stream. +- `bulk_query_grouped` (runs with `groupObjects`) and `download_bulk_results_grouped` return `BulkGroups`, each top-level object with the objects of its nested connections, one group in memory at a time. A child out of its group is an error, not a child in the wrong group; so is a child whose parent has no unaliased `id`, which the error names. +- `start_bulk_mutation_text` and `stage_bulk_variables_iter` take the variables from an iterator (a slice by reference too); the JSONL is written straight into the body of the upload, in memory once. +- Bulk operations checked at compile time: `graphql!(bulk("…"))`, `bulk(file("…"))`, inline or in a module. A bulk query is checked against Shopify's bulk rules for API 2026-10: one top-level field, a connection (not `node` or `nodes`); five connections at most, two levels deep below it; `edges { node { … } }` and nothing else (no `nodes`, `cursor`, `pageInfo`, nor `first`, `last`, `after`, `before`); `Node` objects; a nested connection written right in the `node` of its parent; an unaliased `id` on every node with nested connections (an error that asks for it, never added silently), and no other field aliased `id` there; no alias `_shopifyApiTypename` or starting with `__`; no string that the parser reads unlike GraphQL (a `\b` escape, which it reads as U+0010: write `\u0008`; a block string with a lone carriage return or indented with other whitespace than spaces and tabs); two connections of one node that may return the same type, such as two aliased `metafields`, are refused. What the guide does not show is refused. A bulk mutation is one mutation field, not a bulk operation, with one connection at most. +- The items of a bulk query are generated types: `Item`, each nested connection a `Vec` of its nodes. `Shopify::bulk_query` runs it, with `groupObjects` only when it has nested connections (Shopify is slower with it), and returns `BulkItems` (`next_item`, `collect`, `Stream`), one item in memory at a time, nested lines placed by `__parentId`, and by `__typename` where a node has several connections: the text sent selects it there as `_shopifyApiTypename: __typename`, and a `__typename` of the query is left as written. A line's `id` places its children only when it is a string: `id` may alias another field where no connection is nested. `start_bulk_query` and `download_bulk_items` split the steps; `BulkQuery::text` is the text sent. +- The variables of a bulk query, which Shopify does not take, are given as for any operation (literals and `input!` included) and written into its text as GraphQL literals, from the parsed operation: strings escaped as JSON, enum values bare (in input objects and lists too), input objects with unquoted keys, a variable without a value (a `None` in `Variables`) left out or given its default, an explicit `null` written `null`. The values are checked as for any operation; an enum value or a field that is not a GraphQL name fails with `InvalidValueReason::NotAGraphqlName`, an enum value `true`, `false` or `null` with `InvalidValueReason::ReservedEnumValue`. A variable that may hold `JSON` is refused at compile time. +- `Shopify::bulk_mutation` runs a `graphql!(bulk("mutation …"))` over an iterator of its `Variables`: every line is checked and written before anything is sent, then staged, run, and read as `BulkMutationResult` (`data`, `errors`, `index`, Shopify's `__lineNumber`). `start_bulk_mutation` only starts it. Typed bulk operations run at the Admin API version they were checked against. +- `Transport`, the HTTP layer as a trait, with `send_streaming` (a default goes through `send`), `StreamingResponse` and `BodyStream`. The default `ReqwestTransport` never follows a redirection, and streams: the timeout of a request bounds the wait for the headers and for each chunk, not the whole body. A client of your own goes through `transport::reqwest_0_13::from_builder`: reqwest appears in the API only under `transport::reqwest_0_13`, named after its major version, so that a later reqwest comes next to it. The client runs on Tokio. +- `testing::MockTransport` (`push_data`, `push_chunks`, `push_streaming`, `respond_with`…), and `testing::client`, which retries without waiting, even for a scripted `Retry-After`. `testing` also gives the signing helpers: `webhooks::sign`, `ShopifyApp::sign_query`, `sign_app_proxy`, `sign_session_token`. +- `oauth`: `ShopifyApp`, with install links, the verification of callbacks, admin launches and app proxy requests, the code exchange, session tokens and the token exchange. `verify_session_token` takes only the session tokens of Shopify admin: `dest` exactly `https://{shop}.myshopify.com` and `iss` exactly its `/admin`, compared whole; `SessionToken::user_id` is the staff member's ID. `verify_extension_session_token` takes the tokens of checkout and customer account UI extensions, which any buyer gets (a `dest` with or without `https://`, `iss` optional but then the admin's), as an `ExtensionSessionToken` with `shop()`, `customer()` (the customer's GID) and `claims()`: a type of its own, which does not exchange for a token, so that a buyer's token never passes for an admin session. `ShopifyApp::with_token_store` gives the clients it builds a `TokenStore`. +- An error shows nothing of what the crate did not write (`Error` documents the contract): no body, value or map key of an answer, no message of serde or of a `Serialize` implementation, no query string or user of an address. `Error::Http` displays the status, the address, the content type and the length of the body; `Error::raw_http_body` (or the `raw_body: RawBody` field) gives the body. `Error::Decode` displays the kind of mismatch, its line and column, and a path of the type's own field names and indexes, with `[key]` for a map key. `Error::Variables` names the variable that does not serialize. `Error::sensitive_detail` gives serde's message, the `Serialize` implementation's or the token endpoint's, all kept out of `Display` and `Debug` (`SensitiveDetail`). The `Debug` of `GraphqlErrors` counts the entries of partial `data`, and that of `GraphqlError` shows `extensions.code` and counts the other extensions (Shopify echoes an invalid variable's whole value in `extensions.value`). Shopify's own messages in `errors` and `userErrors` are shown as they are. `Error::Http` carries Shopify's `X-Request-Id`. +- `Error::Bulk { message, operation }` holds the operation that ended without completing, with its `error_code` and `partial_data_url`; `Error::Timeout { message, id }` the ID of the bulk operation waited for, to cancel it. + +### Changed + +- Tokens: 0.10 renewed a token before it expired and saved it with a `TokenStore`. 1.0 also renews when Shopify refuses one with a `401`; one renewal serves every clone of a client and the requests waiting for it; it runs in a task of its own, so a cancelled request does not lose a rotated refresh token; a failed renewal answers the requests waiting for it. Until a renewed token is saved, nothing is sent: each call tries a failed save again first, and fails with `Error::TokenStore`. A refresh answer without a refresh token keeps the current one. `Auth::with_token` starts from a stored token. +- Bulk operations: 0.10 ran, read, listed and waited for them, with typed statuses. 1.0 adds `bulk_query_rows` (the whole cycle), `start_bulk_mutation_text` (uploads the JSONL), `cancel_bulk_operation`, and polling that starts at one second and backs off. `BulkOperation` has numbers for its counts and `DateTime` for its dates; `BulkOperationStatus` and `BulkOperationType` serialize as Shopify writes them (`"COMPLETED"`, an unknown one as its text) and round-trip. +- Webhook subscriptions: 0.10 listed, added, deleted and auto-configured them. 1.0 has `webhook_subscriptions` (every page), `create_`, `update_` (in place, new) and `delete_webhook_subscription`, and `sync_webhook_subscriptions`, which updates in place, creates before it deletes, and returns what it did. `WebhookSubscription` dates are `DateTime`. Subscriptions are JSON only: `WebhookSubscriptionSpec` has no format, and `sync_webhook_subscriptions` updates an XML subscription of a desired topic and address to JSON. +- Webhook verification: 0.10 checked the HMAC. `Webhook::verify` also reads the headers (topic, shop, IDs; with or without `X-`, in any case, from any `(name, value)` pairs, `&http::HeaderMap` included), accepts several secrets during a rotation, and verifies JSON webhooks only, refusing a body whose first byte is not `{` (whitespace and a byte order mark before it included): the launch queries, session tokens and app proxy requests the client secret also signs, which an app proxy query can make read as XML, or as JSON after a tab, can never pass for a webhook. `Webhook::verify_payload_shop` checks that a destructive webhook names, in its payload, the unsigned shop of its headers. `Debug` of a `Webhook` shows the length of its body, not the body. +- Schema download: `schema::download_public_admin_schema` and `download_admin_schema` take an `ApiVersion`. +- `ShopDomain` refuses anything but `` or `.myshopify.com`, `http://` included; 0.10 appended `.myshopify.com` to any text. +- Without a pinned version, an operation of `graphql!` goes to the version of its schema, and an untyped call to `ApiVersion::DEFAULT`, 2026-10 (0.10: 2026-04). The crate's own operations go to a pinned version without a warning. + +### Breaking + +- `Shopify::new(shop, auth)` and `Shopify::builder`; `ShopifyAuth` is `Auth`; `ShopifyConfig` is gone; `replace_auth`, `token_url`, the public `api_version` field, `request_client_credentials_token` and `refresh_token_with_credentials` are gone (the client asks for its tokens itself). `DEFAULT_API_VERSION`, `MIN_API_VERSION` and `VERSION` are `ApiVersion::DEFAULT`, `ApiVersion::MINIMUM` and `USER_AGENT`; `ApiVersion::new` takes a `&str`. +- `ShopifyAPIError` is `Error`, which no longer converts from `reqwest::Error` or `serde_json::Error`. `MissingGraphqlData` is gone: an answer without `data` gives `Value::Null`. +- `TokenStore::save_token(&str, TokenData)` is `save(&ShopDomain, &TokenData)`; `TokenData` is `#[non_exhaustive]`, built with `TokenData::new`; `expires_within` takes a `std::time::Duration`. +- `graphql` returns `data` as a `Value` and `graphql_as` reads it as a type; `post_graphql` and the `graphql-client` feature are gone; the untyped calls send no `operationName`. +- `GraphqlResponse` is `RawResponse`; the `shopify_api::graphql` module is private (`graphql` is the macro); `parse_jsonl` takes bytes; the staged upload and connection types are internal. +- The warp wrapper, the webhook payload structs, `utils` (`retry_async`, `read_json_tree`) and `graphql_at_path` are gone, as are `run_bulk_queries`, `run_bulk_mutations` and `BulkConcurrencyOptions`, and the features `debug`, `graphql-client`, `warp-wrapper`, `hmac`, `sha2`, `warp` and `graphql_client`. +- One verb per meaning in the bulk API: `start_bulk_*` only starts, `bulk_query*` and `bulk_mutation` start, wait and read. 0.10's `run_bulk_query(query)`, which only started, is `start_bulk_query(query)`, which also takes a `graphql!(bulk(…))` query; `run_bulk_query_with_grouping(query, true)` is `start_bulk_query(GroupObjects(query))`; `run_bulk_mutation(mutation, path)` is `start_bulk_mutation_staged(mutation, path, None)`, and `start_bulk_mutation_text(mutation, &rows)` uploads the rows first. +- Webhooks verify JSON bodies only: `webhooks::verify_hmac` and `Webhook::verify` refuse an XML body, which 0.10 verified. Move XML subscriptions to JSON before deploying (`sync_webhook_subscriptions`, `update_webhook_subscription`); see MIGRATION.md. `WebhookSubscription` is `#[non_exhaustive]`, with new required fields: a JSON stored by 0.10 no longer reads back. +- `Error::InvalidApiVersion { version, minimum }` is `{ version, reason }`; `Error::Timeout(String)` is `Timeout { message, id }`. +- Rust 1.88, edition 2024. + +### Packaging + +- The three crates are released together, each requiring the exact version of the others, and published at once (`cargo publish --workspace`). Each package includes the license. `cargo test` of the published `shopify_api` runs offline. +- Security: `Cargo.lock` picks up `ctutils` 0.4.6 for RUSTSEC-2026-0385. chrono 0.4.39 or newer. + ## 0.10.1 - Security: refresh `Cargo.lock` to pick up fixes for RUSTSEC-2026-0185, -0285, -0338, -0339, -0340, -0342, -0346, -0348, -0349, -0382 and -0383 (`quinn-proto`, `rustls`, `rustls-webpki`, `webpki-root-certs`). diff --git a/Cargo.lock b/Cargo.lock index 335f123..394b747 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "android_system_properties" version = "0.1.6" @@ -96,12 +102,6 @@ dependencies = [ "pkg-config", ] -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - [[package]] name = "base64" version = "0.23.1" @@ -114,15 +114,6 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - [[package]] name = "block-buffer" version = "0.12.1" @@ -175,7 +166,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", - "cpufeatures 0.3.1", + "cpufeatures", "rand_core", ] @@ -186,10 +177,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", - "js-sys", "num-traits", "serde", - "wasm-bindgen", "windows-link", ] @@ -254,15 +243,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" -[[package]] -name = "colored" -version = "3.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "combine" version = "4.6.9" @@ -295,15 +275,6 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - [[package]] name = "cpufeatures" version = "0.3.1" @@ -314,13 +285,12 @@ dependencies = [ ] [[package]] -name = "crypto-common" -version = "0.1.7" +name = "crc32fast" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" dependencies = [ - "generic-array", - "typenum", + "cfg-if", ] [[package]] @@ -334,38 +304,22 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.3" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574" +checksum = "fe3e9d21d39e6f39ff46e03d5b621424f88ee23d8a1672c6bfc9ccc7f2da4f6a" dependencies = [ "cmov", ] -[[package]] -name = "deranged" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer 0.10.4", - "crypto-common 0.1.7", -] - [[package]] name = "digest" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ - "block-buffer 0.12.1", + "block-buffer", "const-oid", - "crypto-common 0.2.2", + "crypto-common", "ctutils", ] @@ -386,6 +340,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "errno" version = "0.3.14" @@ -408,6 +368,17 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "foreign-types" version = "0.3.2" @@ -453,12 +424,6 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" -[[package]] -name = "futures-sink" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" - [[package]] name = "futures-task" version = "0.3.34" @@ -472,22 +437,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", - "futures-sink", "futures-task", "pin-project-lite", "slab", ] -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - [[package]] name = "getrandom" version = "0.2.17" @@ -516,13 +470,10 @@ dependencies = [ ] [[package]] -name = "graphql-introspection-query" -version = "0.3.0" +name = "glob" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e063446242093b0acecc78a2313801e6c4faafa3501277b409a2b1972eff5d85" -dependencies = [ - "serde", -] +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" [[package]] name = "graphql-parser" @@ -535,66 +486,10 @@ dependencies = [ ] [[package]] -name = "graphql_client" -version = "0.16.0" +name = "hashbrown" +version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0f04840854efa7b06377d86fab117f598f5f5c95727067463417ccaf8aa7635" -dependencies = [ - "graphql_query_derive", - "serde", - "serde_json", -] - -[[package]] -name = "graphql_client_codegen" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa0141e66c8d0302f8a586df12ad5d0cf87c0fa8c391f2f5b5dc296312dce569" -dependencies = [ - "graphql-introspection-query", - "graphql-parser", - "heck", - "proc-macro2", - "quote", - "serde", - "serde_json", - "syn 2.0.119", -] - -[[package]] -name = "graphql_query_derive" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e16ecf9bb87a6760cf5227f66cbe48bad7b89505aeb002aa9439ea090e6038a3" -dependencies = [ - "graphql_client_codegen", - "proc-macro2", - "syn 2.0.119", -] - -[[package]] -name = "headers" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc2700e3fe555c3310aa7286cac6167449f2c87e0eb58769c9208a1c58a1d106" -dependencies = [ - "base64 0.22.1", - "bytes", - "headers-core", - "http", - "httpdate", - "mime", - "sha1", -] - -[[package]] -name = "headers-core" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4" -dependencies = [ - "http", -] +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" [[package]] name = "heck" @@ -602,13 +497,19 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "hmac" version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" dependencies = [ - "digest 0.11.3", + "digest", ] [[package]] @@ -650,12 +551,6 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - [[package]] name = "hybrid-array" version = "0.4.15" @@ -721,7 +616,7 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ - "base64 0.23.1", + "base64", "bytes", "futures-channel", "futures-util", @@ -765,9 +660,9 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", @@ -779,9 +674,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", @@ -792,9 +687,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -806,15 +701,15 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ "displaydoc", "icu_collections", @@ -827,15 +722,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.3.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", @@ -867,6 +762,16 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -973,15 +878,6 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - [[package]] name = "log" version = "0.4.34" @@ -1001,19 +897,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] -name = "mime" -version = "0.3.17" +name = "miniz_oxide" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - -[[package]] -name = "mime_guess" -version = "2.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" dependencies = [ - "mime", - "unicase", + "adler2", + "simd-adler32", ] [[package]] @@ -1044,12 +934,6 @@ dependencies = [ "tempfile", ] -[[package]] -name = "num-conv" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" - [[package]] name = "num-traits" version = "0.2.19" @@ -1059,15 +943,6 @@ dependencies = [ "autocfg", ] -[[package]] -name = "num_threads" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4" -dependencies = [ - "libc", -] - [[package]] name = "once_cell" version = "1.21.4" @@ -1123,55 +998,12 @@ dependencies = [ "vcpkg", ] -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-link", -] - [[package]] name = "percent-encoding" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" -[[package]] -name = "pin-project" -version = "1.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "pin-project-lite" version = "0.2.17" @@ -1193,12 +1025,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "powerfmt" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" - [[package]] name = "proc-macro2" version = "1.0.107" @@ -1306,25 +1132,15 @@ dependencies = [ "rand_core", ] -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags", -] - [[package]] name = "reqwest" version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" dependencies = [ - "base64 0.23.1", + "base64", "bytes", "futures-core", - "futures-util", "http", "http-body", "http-body-util", @@ -1334,7 +1150,6 @@ dependencies = [ "hyper-util", "js-sys", "log", - "mime_guess", "native-tls", "percent-encoding", "pin-project-lite", @@ -1342,9 +1157,6 @@ dependencies = [ "rustls", "rustls-pki-types", "rustls-platform-verifier", - "serde", - "serde_json", - "serde_urlencoded", "sync_wrapper", "tokio", "tokio-native-tls", @@ -1407,7 +1219,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", + "log", "once_cell", + "ring", "rustls-pki-types", "rustls-webpki", "subtle", @@ -1505,18 +1319,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "scoped-tls" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - [[package]] name = "security-framework" version = "3.7.0" @@ -1590,13 +1392,11 @@ dependencies = [ ] [[package]] -name = "serde_path_to_error" -version = "0.1.20" +name = "serde_spanned" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" dependencies = [ - "itoa", - "serde", "serde_core", ] @@ -1612,17 +1412,6 @@ dependencies = [ "serde", ] -[[package]] -name = "sha1" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", -] - [[package]] name = "sha2" version = "0.11.1" @@ -1630,8 +1419,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", - "cpufeatures 0.3.1", - "digest 0.11.3", + "cpufeatures", + "digest", ] [[package]] @@ -1642,36 +1431,56 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] name = "shopify_api" -version = "0.10.1" +version = "1.0.0-rc.2" dependencies = [ - "base64 0.22.1", - "bytes", + "base64", "chrono", "clap", - "graphql_client", + "futures-core", + "graphql-parser", + "hex", "hmac", - "log", "reqwest", "serde", "serde_json", - "serde_path_to_error", + "serde_urlencoded", "sha2", - "simple_logger", - "thiserror 2.0.21", + "shopify_api_graphql", + "shopify_api_macros", "tokio", - "warp", + "tracing", + "trybuild", ] [[package]] -name = "signal-hook-registry" -version = "1.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +name = "shopify_api_graphql" +version = "1.0.0-rc.2" dependencies = [ - "errno", - "libc", + "graphql-parser", + "proc-macro2", + "quote", + "serde", + "serde_json", + "toml", + "ureq", +] + +[[package]] +name = "shopify_api_macros" +version = "1.0.0-rc.2" +dependencies = [ + "proc-macro2", + "quote", + "shopify_api_graphql", + "syn 3.0.9", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "simd_cesu8" version = "1.2.0" @@ -1688,18 +1497,6 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" -[[package]] -name = "simple_logger" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7038d0e96661bf9ce647e1a6f6ef6d6f3663f66d9bf741abf14ba4876071c17" -dependencies = [ - "colored", - "log", - "time", - "windows-sys 0.61.2", -] - [[package]] name = "slab" version = "0.4.12" @@ -1782,6 +1579,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "target-tuple" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "876fef147edbcbddc8ac5cbbba92c7b86519e314e86638596c09673b2ed01e7f" + [[package]] name = "tempfile" version = "3.27.0" @@ -1795,6 +1598,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -1835,43 +1647,11 @@ dependencies = [ "syn 3.0.9", ] -[[package]] -name = "time" -version = "0.3.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" -dependencies = [ - "deranged", - "libc", - "num-conv", - "num_threads", - "powerfmt", - "serde_core", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" - -[[package]] -name = "time-macros" -version = "0.2.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" -dependencies = [ - "num-conv", - "time-core", -] - [[package]] name = "tinystr" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", "zerovec", @@ -1885,16 +1665,14 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" -version = "1.54.0" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", "mio", - "parking_lot", "pin-project-lite", - "signal-hook-registry", "socket2", "tokio-macros", "windows-sys 0.61.2", @@ -1932,18 +1710,44 @@ dependencies = [ ] [[package]] -name = "tokio-util" -version = "0.7.20" +name = "toml" +version = "1.1.8+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "pin-project-lite", - "tokio", + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", ] +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + [[package]] name = "tower" version = "0.5.3" @@ -1995,7 +1799,6 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ - "log", "pin-project-lite", "tracing-core", ] @@ -2016,16 +1819,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] -name = "typenum" -version = "1.20.1" +name = "trybuild" +version = "1.0.122" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +checksum = "62db9c92d704393fbf2132041720cc80b689f2d3f28521015c2ac866223c11b8" +dependencies = [ + "glob", + "serde", + "serde_derive", + "serde_json", + "target-tuple", + "termcolor", + "toml", +] [[package]] -name = "unicase" -version = "2.10.0" +name = "typenum" +version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "unicode-ident" @@ -2039,6 +1851,35 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" +[[package]] +name = "ureq" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + [[package]] name = "url" version = "2.5.8" @@ -2051,6 +1892,12 @@ dependencies = [ "serde", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8_iter" version = "1.0.4" @@ -2069,12 +1916,6 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - [[package]] name = "walkdir" version = "2.5.0" @@ -2094,33 +1935,6 @@ dependencies = [ "try-lock", ] -[[package]] -name = "warp" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0a808122a8a77eecdabaefd88ddb1913c4be5ea1465399f63ba64c7aa705fea" -dependencies = [ - "bytes", - "futures-util", - "headers", - "http", - "http-body", - "http-body-util", - "log", - "mime", - "mime_guess", - "percent-encoding", - "pin-project", - "scoped-tls", - "serde", - "serde_json", - "serde_urlencoded", - "tokio", - "tokio-util", - "tower-service", - "tracing", -] - [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -2212,6 +2026,15 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "webpki-roots" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "winapi-util" version = "0.1.11" @@ -2362,6 +2185,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + [[package]] name = "writeable" version = "0.6.4" @@ -2370,9 +2199,9 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "yoke" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -2431,9 +2260,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.8" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ "yoke", "zerofrom", @@ -2442,15 +2271,21 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", "syn 3.0.9", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 41a1cba..0a6d32d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,56 +1,54 @@ -[package] -name = "shopify_api" -description = "Shopify API client" -documentation = "https://docs.rs/shopify_api" -readme = "README.md" -repository = "https://github.com/0xtlt/shopify_api" -version = "0.10.1" -edition = "2021" -rust-version = "1.85" -keywords = ["shopify", "api", "client"] -categories = ["api-bindings", "web-programming"] +[workspace] +resolver = "3" +members = [ + "crates/shopify_api", + "crates/shopify_api_graphql", + "crates/shopify_api_macros", +] + +[workspace.package] +version = "1.0.0-rc.2" +edition = "2024" +rust-version = "1.88" license = "MIT" +repository = "https://github.com/0xtlt/shopify_api" authors = ["Thomas Tastet"] -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -reqwest = { version = "0.13.5", default-features = false, features = ["form", "json", "multipart"] } -serde_json = { version = "1", default-features = false } -serde = { version = "1", default-features = false, features = ["derive"] } -chrono = { version = "0.4", features = ["serde"] } -tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"] } -log = "0.4" -simple_logger = "5.2.0" -thiserror = "2.0.21" -hmac = { version = "0.13.0", optional = true } -sha2 = { version = "0.11.0", optional = true } -base64 = { version = "0.22", optional = true } -warp = { version = "0.4.3", optional = true, default-features = false, features = [] } -bytes = { version = "1.12", optional = true } -graphql_client = { version = "0.16.0", optional = true } -serde_path_to_error = { version = "0.1", optional = true } -clap = { version = "4.6.7", features = ["derive"], optional = true } +[workspace.dependencies] +# The three crates are released together: each one requires the exact +# version of the others, since the macro emits code for that runtime. +shopify_api = { path = "crates/shopify_api", version = "=1.0.0-rc.2" } +shopify_api_graphql = { path = "crates/shopify_api_graphql", version = "=1.0.0-rc.2" } +shopify_api_macros = { path = "crates/shopify_api_macros", version = "=1.0.0-rc.2" } -[[bin]] -name = "shopify-api" -path = "src/bin/shopify-api.rs" -required-features = ["cli"] +base64 = "0.23" +chrono = { version = "0.4.39", default-features = false, features = ["clock", "serde", "std"] } +clap = { version = "4.6", features = ["derive", "env"] } +futures-core = { version = "0.3.31", default-features = false } +graphql-parser = "0.4" +hex = "0.4" +hmac = "0.13" +proc-macro2 = "1" +quote = "1" +reqwest = { version = "0.13.5", default-features = false } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +serde_urlencoded = "0.7" +sha2 = "0.11" +syn = { version = "3", features = ["full"] } +tokio = { version = "1", default-features = false } +tracing = { version = "0.1", default-features = false, features = ["std"] } +toml = { version = "1", default-features = false, features = ["std", "parse", "serde", "display"] } +trybuild = "1" +ureq = "3.4" -[dev-dependencies] -tokio = { version = "1", features = ["full"] } +[workspace.lints.rust] +unsafe_code = "forbid" +unused_must_use = "deny" +missing_debug_implementations = "warn" -[features] -default = ["rustls"] -warp-wrapper = ["warp", "bytes"] -graphql-client = ["graphql_client"] -full = ["webhooks", "graphql-client", "debug", "cli"] -rustls = ["reqwest/rustls"] -native-tls = ["reqwest/native-tls"] -webhooks = ["hmac", "sha2", "base64"] -debug = ["serde_path_to_error"] -cli = ["dep:clap"] -hmac = ["dep:hmac"] -sha2 = ["dep:sha2"] -warp = ["dep:warp"] -graphql_client = ["dep:graphql_client"] +[workspace.lints.clippy] +dbg_macro = "deny" +todo = "deny" +unimplemented = "deny" +mod_module_files = "deny" diff --git a/MIGRATION.md b/MIGRATION.md new file mode 100644 index 0000000..6725919 --- /dev/null +++ b/MIGRATION.md @@ -0,0 +1,314 @@ +# Upgrading from 0.10 to 1.0 + +1.0 does most of what 0.10 did, under new names, and adds operations checked +at compile time. A few things are gone without a replacement in the crate: +the typed webhook payloads and the warp wrapper (a handler is a few lines, +see [Webhooks](#webhooks)), the concurrent bulk helpers, and `utils`. Most +code changes in three places: building the client, the error type, and +GraphQL calls. + +From 0.9 or older (`rest_query` and the REST module): 0.10 removed REST and +moved to GraphQL; see the 0.10.0 entry of [CHANGELOG.md](CHANGELOG.md), then +this guide. + +## Building the client + +```rust,ignore +// 0.10 +let shopify = Shopify::new("my-shop", ShopifyAuth::AccessToken(token), ShopifyConfig::default())?; + +// 1.0 +let shopify = Shopify::new("my-shop", Auth::access_token(token))?; +``` + +| 0.10 | 1.0 | +| --- | --- | +| `ShopifyAuth::AccessToken(token)` | `Auth::access_token(token)` | +| `ShopifyAuth::client_credentials(id, secret)` | `Auth::client_credentials(id, secret)` | +| `ShopifyAuth::ClientCredentials { current_token: Some(token), .. }` | `Auth::client_credentials(id, secret).with_token(token)` | +| `ShopifyAuth::expiring_offline_token(id, secret, token)` | `Auth::expiring_token(id, secret, token)` | +| `ShopifyConfig { api_version, .. }` | `Shopify::builder(shop).api_version(ApiVersion::V2026_07)` | +| `ShopifyConfig { token_store, .. }` | `.token_store(store)` | +| `ShopifyConfig { token_refresh_leeway, .. }` | `.refresh_leeway(duration)` (a `std::time::Duration`) | +| `ShopifyConfig { user_agent, .. }` | `.user_agent(text)` | +| `ShopifyConfig { shared_secret, .. }` | Gone: pass the secret to `webhooks::Webhook::verify` | +| `ApiVersion::new(text)`, from an `impl Into` | `ApiVersion::new(&str)`, `text.parse::()`, or `ApiVersion::V2026_07` | +| `ApiVersion::try_from(string)` (a `String`) | `ApiVersion::try_from(string.as_str())` | +| `version.as_str()` | `version.to_string()` (`Display`) | +| `shopify.api_version` (a public field) | `shopify.api_version()` | +| `DEFAULT_API_VERSION`, `MIN_API_VERSION` | `ApiVersion::DEFAULT` (2026-10), `ApiVersion::MINIMUM` | +| `VERSION` | `USER_AGENT` | +| `shopify.replace_auth(auth)` | Build another client: see below | +| `shopify.get_shop()`, `shop_domain()` | `shopify.shop()`, a `ShopDomain` | +| `shopify.get_query_url()` | `shopify.graphql_url(version)` | +| `shopify.token_url()` | Gone: the client asks for its tokens itself | +| `shopify.request_client_credentials_token(id, secret)` | `Shopify::new(shop, Auth::client_credentials(id, secret))?`, then `shopify.access_token().await?` (the token, obtained if need be), then `shopify.token().await` (the whole `TokenData`, `None` until a first token is obtained) | +| `shopify.refresh_token_with_credentials(id, secret, refresh)` | `Auth::expiring_token(id, secret, token)`: the client refreshes before expiry and on a `401`, and saves with its `TokenStore` | + +`replace_auth` swapped the token of a client in place. A client's +credentials are now fixed: when a shop reinstalls the app, or its token +changes otherwise, build a new client with the new token, and replace the old +one wherever it is held (its clones keep the old token). + +`TokenStore::save_token(shop: &str, token: TokenData)` is +`TokenStore::save(shop: &ShopDomain, token: &TokenData)`, and returns a boxed +error of yours; `TokenStoreFuture` is `transport::BoxFuture`. While a save +fails, the client sends nothing: each call tries the save again first, and +fails with `Error::TokenStore`. `TokenData` has the same fields, two more for +online tokens, and reads the JSON 0.10 stored. It is `#[non_exhaustive]`: build +it with `TokenData::new(token)` (0.10's `TokenData::never_expiring`), then set +its fields, instead of a struct literal. `expires_within` takes a +`std::time::Duration`. + +The shop must now be `` or `.myshopify.com` (with or without +`https://`): 0.10 accepted any text, `http://` included, and appended +`.myshopify.com`. An `http://` address is refused. + +**Retries are on by default.** 0.10 returned `Throttled` at the first +throttle. 1.0 retries up to four times: a throttled request waits for what +its cost needs, a `429` for its `Retry-After` (up to five minutes), a query +for a backoff after a `5xx` or a network failure. To keep 0.10's behaviour: +`Shopify::builder(shop).retry(RetryPolicy::none())`. + +Without a pinned version, an operation of `graphql!` goes to the version its +schema was checked against (the `api-version` of your `Cargo.toml`, else the +one of the schema file, else the latest on the first build), and an untyped +call to 2026-10: `ApiVersion::default()` and `ApiVersion::DEFAULT` move from +2026-04 to 2026-10. 0.10 sent everything to 2026-04 by default: pin it with +`.api_version(ApiVersion::V2026_04)` to keep that. + +## Errors + +`ShopifyAPIError` is `Error`, and `shopify_api::Result` is available. + +| 0.10 | 1.0 | +| --- | --- | +| `ConnectionFailed(reqwest::Error)` | `Transport { url, source }` | +| An `error_for_status` failure | `Http { status, url, content_type, request_id, raw_body }`: it displays the status, the address, the content type and the length of the body, never the body; `error.raw_http_body()` gives the whole body, secrets included; `error.status()`, `error.is_unauthorized()` | +| `Throttled` | `Throttled { retries, cost, retry_after }`, once the retries are spent or when `Retry-After` exceeds `max_retry_after` | +| `GraphqlErrors(Vec)` | `Graphql(GraphqlErrors { errors, data })` | +| `JsonParseError`, `NotWantedJsonFormat`, `NotJson`, `ResponseBroken` | `Decode { path, message, detail }`: a body that is not JSON, or `data` that does not fit its type. `path` and `message` hold no text of the answer (a map key is `[key]`); serde's message is `error.sensitive_detail()` | +| Variables that do not serialize | `Variables { message, detail }`: what a `Serialize` implementation wrote is `error.sensitive_detail()`, not the message | +| A `Float` that is NaN or infinite, an `Int` beyond 32 bits, `null` for a non-null `JSON`, sent as they were | `InvalidValue { path, reason, detail }`, before anything is sent: `` invalid value at `$product.metafields[2].value`: not a finite Float `` | +| `Authentication(text)` | `Auth { message, detail }`: what the token endpoint wrote is `error.sensitive_detail()` | +| `MissingGraphqlData` | Gone: an answer without `data` (and without `errors`) gives `Value::Null` to `graphql`; `graphql_as` and `execute` then fail with `Decode` unless the type reads `null` | +| `InvalidApiVersion { version, minimum }` | `InvalidApiVersion { version, reason }`: `reason` says why the text is not a version shopify_api calls | +| `Timeout(String)` | `Timeout { message, id }`: `id` is the bulk operation waited for, which keeps running (cancel it with `cancel_bulk_operation`) | +| `InvalidHeaderValue`, `Other` | Gone | + +`Error` no longer converts from `reqwest::Error` or `serde_json::Error`: a +`?` on a `serde_json` result in a function that returns +`shopify_api::Result` needs your own error type, or `map_err`. + +## GraphQL calls + +```rust,ignore +// 0.10: a struct per answer, written by hand, and a json! of variables. +#[derive(Deserialize)] +struct ShopQuery { shop: Shop } +#[derive(Deserialize)] +struct Shop { name: String } +let data: ShopQuery = shopify.graphql("query { shop { name } }", &json!({})).await?; + +// 1.0: checked when the crate compiles, typed from the selection. +let data = shopify.execute(graphql!("query { shop { name } }")).await?; +println!("{}", data.shop.name); + +// 1.0, still untyped: `graphql_as` reads `data` as your type. +let data: ShopQuery = shopify.graphql_as("query { shop { name } }", ()).await?; +``` + +| 0.10 | 1.0 | +| --- | --- | +| `graphql::(query, &variables)` | `graphql_as::(query, variables)`, or `execute(graphql!(…))` | +| `graphql_raw(query, &variables)` | `graphql_raw(query, variables)`, a `RawResponse` | +| `graphql_at_path(query, &variables, &[Key("a"), Key("b")])` | `graphql(…)` then `value.pointer("/a/b")`, or a typed operation | +| `post_graphql::(variables)` (`graphql-client` feature) | `execute(graphql!(…))`: no schema file or build step to keep | +| `types::{Decimal, DateTime, JSON, UnsignedInt64}` | Gone: `graphql!` maps every scalar | + +Variables are now anything that serializes to an object, by value or by +reference, or `()` for none. + +The untyped calls send no `operationName`. To name one, for Shopify's logs: +`shopify.execute(Operation::::new(query).with_name("Name"))`. + +| 0.10 | 1.0 | +| --- | --- | +| `GraphqlResponse` | `RawResponse` (`data` as a `Value`), or `Response` from `execute_response` | +| `GraphqlError` | `GraphqlError`, with `message`, `locations`, `path`, `extensions` and `code()` | +| `shopify_api::graphql::*` (the module) | The module is private: `shopify_api::graphql` is the macro, the types are at the root | + +With `graphql!`, an input object is a literal checked against the schema, +in place of a `json!` value: + +```rust,ignore +// 0.10 +shopify.graphql::(mutation, &json!({ "product": { "id": id, "title": title } })).await?; + +// 1.0 +shopify.execute(graphql!( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }", + product = { id: id, title: title }, +)).await?; +``` + +## Bulk operations + +| 0.10 | 1.0 | +| --- | --- | +| `run_bulk_query(query)` → `BulkOperationPayload` | `start_bulk_query(query)` → `BulkOperation`; user errors are `Error::UserErrors` | +| `run_bulk_query_with_grouping(query, true)` | `start_bulk_query(GroupObjects(query))` (`bulk::GroupObjects`); with `false`, `start_bulk_query(query)` | +| `run_bulk_mutation(mutation, staged_upload_path)` | `start_bulk_mutation_staged(mutation, path, None)`, or `start_bulk_mutation_text(mutation, &rows)`, which uploads the rows | +| `stage_upload_jsonl(&rows)` | `stage_bulk_variables(&rows)` | +| `get_bulk_operation(id)` | `bulk_operation(id)` | +| `list_bulk_operations(BulkOperationsFilter { .. })` | `bulk_operations(BulkOperationsFilter::new().first(10))`, a `Page` | +| `wait_for_bulk(id, BulkWaitOptions { .. })` | `wait_for_bulk_operation(id, BulkWaitOptions::new().timeout(…))` | +| `Shopify::download_bulk_jsonl(url)` | `shopify.download_bulk_results(url)`, or `bulk_query_rows` for the whole cycle; `download_bulk_results_stream(url)` and `bulk_query_stream` read the rows as they download | +| `run_bulk_queries`, `run_bulk_mutations`, `BulkConcurrencyOptions` | Gone: call the single versions in a loop | +| `ShopifyBulkOperation`, `ShopifyBulkStatus` | `bulk::BulkOperation`, `bulk::BulkOperationStatus` | +| `ShopifyBulkErrorCode` | `BulkOperation::error_code`, a `String` | +| `BulkOperationPayload` | `BulkOperation`, its `userErrors` as `Error::UserErrors` | +| `BulkOperationConnection`, `BulkOperationEdge`, `PageInfo` | `Page` | +| `StagedUploadResource`, `StagedUploadParameter`, `StagedMediaUploadTarget`, `StagedUploadsCreateInput` | Internal: `stage_bulk_variables` does the upload | +| `ShopifyUserError` | `UserError` | +| `parse_jsonl(&str)` | `bulk::parse_jsonl(&[u8])`: `parse_jsonl(text.as_bytes())` | + +In 1.0, `start_bulk_*` only starts an operation and returns it, and +`bulk_query*` and `bulk_mutation` start, wait and read: 0.10's `run_bulk_*` +only started. `start_bulk_query` takes a text or a typed query. + +New in 1.0: a query or a mutation declared with `graphql!(bulk("…"))` is +checked when the crate compiles, and `bulk_query` and `bulk_mutation` read +its results as generated types, in place of a hand-written struct and +`bulk_query_rows` or `bulk_query_grouped`. + +`object_count`, `root_object_count` and `file_size` are numbers, and +`created_at` and `completed_at` are `chrono::DateTime`. +`wait_for_bulk_operation` returns the operation once it ends, as 0.10's +`wait_for_bulk` did: `Ok` with `status = Failed` (or `Canceled`) for one that +did not complete, so keep checking `status`. The calls that start, wait and +read (`bulk_query_rows`, `bulk_query_stream`, `bulk_query_grouped`, and the +typed `bulk_query` and `bulk_mutation`) fail instead, with an `Error::Bulk` +whose `operation` holds it, with its `error_code` and `partial_data_url`. A +wait that ran out is an `Error::Timeout` whose `id` is the operation's, +which keeps running. + +## Webhooks + +The `webhooks` feature verifies and reads webhooks without a web framework, so +the `warp-wrapper` feature, `Shopify::warp_wrapper` and the `ShopifyWebhook` +payload structs (`Order`, `Customer`, `InventoryItem`, `InventoryLevel`, +`Address`…) are gone: declare the fields you read in a struct of yours. With +warp, what `warp_wrapper` did: + +```rust,ignore +use bytes::Bytes; +use serde::Deserialize; +use shopify_api::webhooks::Webhook; +use warp::http::{HeaderMap, StatusCode}; +use warp::Filter; + +#[derive(Deserialize)] +struct Order { + id: u64, + name: String, +} + +let secret = std::env::var("SHOPIFY_API_SECRET")?; +let webhooks = warp::path("webhooks") + .and(warp::post()) + .and(warp::header::headers_cloned()) + .and(warp::body::bytes()) + .map(move |headers: HeaderMap, body: Bytes| { + // Checks the signature, and reads the topic, the shop and the IDs. + let Ok(webhook) = Webhook::verify(&headers, body, &secret) else { + return StatusCode::UNAUTHORIZED; + }; + match webhook.topic() { + "orders/create" => match webhook.payload::() { + Ok(order) => println!("{} on {}", order.name, webhook.shop()), + Err(_) => return StatusCode::BAD_REQUEST, + }, + "app/uninstalled" => { + // The shop of the headers is not signed: check the payload's. + if webhook.verify_payload_shop().is_err() { + return StatusCode::UNAUTHORIZED; + } + // … forget the shop. + } + _ => {} + } + StatusCode::OK + }); +``` + +With axum, `async fn(headers: HeaderMap, body: Bytes)` takes the same two +values (see the docs of `shopify_api::webhooks`). `Webhook::verify` requires +the `X-Shopify-Topic` and `X-Shopify-Shop-Domain` headers, which Shopify always +sends, and only verifies JSON webhooks, whose body starts with `{` as its +first byte, with no whitespace or byte order mark before it: the client +secret also signs texts an installer of the app can read and make look like +XML, or like JSON after some whitespace. `sync_webhook_subscriptions` updates an XML subscription of a +desired topic and address to JSON; +`webhooks::verify_hmac(secret, body, header)` checks the signature without +reading the headers, and refuses a body whose first byte is not `{`, the same +rule as `Webhook::verify`. + +| 0.10 | 1.0 | +| --- | --- | +| `shopify.verify_hmac(data, header)` | `webhooks::verify_hmac(secret, data, header)`, **JSON only**: an XML body is refused | +| `WebhookSubscription { id, topic, format, uri }` | `WebhookSubscription` is `#[non_exhaustive]`, with more fields (`filter`, `include_fields`, `metafield_namespaces`, `name`, `api_version`, `created_at`, `updated_at`), some required: it cannot be built with a literal, and a JSON stored by 0.10 no longer reads back as one | +| `list_webhooks()` | `webhook_subscriptions()`, every page | +| `add_webhook(address, topic, format)` | `create_webhook_subscription(&WebhookSubscriptionSpec::new(topic, address))`, always JSON | +| `delete_webhook(id)` | `delete_webhook_subscription(id)` | +| `webhook_auto_config(vec![(address, topic, format)])` | `sync_webhook_subscriptions(&[WebhookSubscriptionSpec::new(topic, address)])`, always JSON, which returns what it did | +| `delete_webhook(id)` then `add_webhook(…)`, to change a subscription | `update_webhook_subscription(id, &spec)`, which replaces its options in place | + +Topics are accepted as `orders/create` or `ORDERS_CREATE`. + +### If you subscribed in XML + +0.10 verified any body, and `add_webhook` and `webhook_auto_config` took a +format: XML subscriptions were supported. 1.0 refuses every XML body, at run +time: the code compiles, and each XML delivery fails verification once the +1.0 handler is deployed. In this order: + +1. Move the subscriptions to JSON before you deploy a 1.0 handler, with + 0.10 still running: `sync_webhook_subscriptions` (it updates an XML + subscription of a desired topic and address to JSON) or + `update_webhook_subscription(id, &spec)` for each one, both always JSON. + `webhook_subscriptions()` lists what is left in XML (`format`). +2. Adapt the parsing of the payloads to JSON (`webhook.payload::()`). +3. Deploy. XML deliveries that Shopify still retries, sent before the + switch, will be refused: Shopify keeps retrying them, then gives up. + +## OAuth and session tokens + +New in 1.0, under the `oauth` feature: `ShopifyApp`. Its +`verify_session_token` takes only the session tokens of Shopify admin, which +a staff member's browser sends; trust them to load a shop's stored token. +The token of a checkout or customer account UI extension, which any buyer +gets, verifies with `verify_extension_session_token`, as an +`ExtensionSessionToken` (`shop()`, `customer()`), and is refused by +`verify_session_token`. + +## Schema download + +| 0.10 | 1.0 | +| --- | --- | +| `download_public_admin_schema("2026-04")` | `schema::download_public_admin_schema(ApiVersion::V2026_04)` | +| `shopify.download_admin_schema()` | The same | +| `SHOPIFY_DEV_ADMIN_SCHEMA_PROXY` | `schema::PUBLIC_ADMIN_SCHEMA_ENDPOINT` | +| `ADMIN_SCHEMA_INTROSPECTION_QUERY` | `schema::INTROSPECTION_QUERY` | +| `shopify-api schema download --public --out file` | `api-version` in `[package.metadata.shopify_api]` of `Cargo.toml`: `graphql!` downloads it when cargo is asked to build the package, never for a dependency, or a packaged crate. `shopify-api schema download` refreshes it, `--introspection` for the raw result. `schema = "file"` next to `api-version` names another file than `graphql/admin.schema.json` | +| `shopify-api schema download --api-version 2026-07` | No flag: the command reads the version of the nearest `Cargo.toml`. For another version, or outside a package: `schema::download_public_admin_schema(ApiVersion::new("2026-07")?)` | + +`graphql!` reads the compact form it downloads, in `graphql/admin.schema.json`, +or in the file `schema = "…"` names in `[package.metadata.shopify_api]`. + +## Removed + +- `utils::retry_async` and `retry_sync`: the client retries what can be. +- `utils::read_json_tree`: `serde_json::Value::pointer`. +- `utils::deserialize_from_value` and `deserialize_from_str`: errors name the path of a mismatch. +- The `debug`, `graphql-client` and `warp-wrapper` features, and the `hmac`, `sha2`, `warp` and `graphql_client` features that 0.10 published for its optional dependencies: `webhooks` and `oauth` enable what they need. The `simple_logger` dependency: logs go through `tracing`. diff --git a/README.md b/README.md index b61875d..1e67d3f 100644 --- a/README.md +++ b/README.md @@ -5,160 +5,570 @@ [![MIT licensed](https://img.shields.io/crates/l/shopify_api.svg)](./LICENSE.txt) [![CI](https://github.com/0xtlt/shopify_api/actions/workflows/ci.yml/badge.svg)](https://github.com/0xtlt/shopify_api/actions/workflows/ci.yml) -An ergonomic Shopify Admin GraphQL API client for Rust. +A Shopify Admin GraphQL client for Rust, whose operations are checked against +Shopify's schema while your crate compiles. -Version `0.10` is a breaking refactor for Shopify Admin API `2026-04` and newer: +```rust,no_run +use shopify_api::{Auth, Shopify, graphql}; + +#[tokio::main] +async fn main() -> shopify_api::Result<()> { + let shopify = Shopify::new("my-shop", Auth::access_token("shpat_…"))?; + + let data = shopify + .execute(graphql!( + "query Products($first: Int!) { + products(first: $first) { nodes { id title totalInventory } } + }", + first = 10, + )) + .await?; + + for product in data.products.nodes { + println!("{}: {:?} in stock", product.title, product.total_inventory); + } + Ok(()) +} +``` -- GraphQL-first client -- `2026-04` minimum API version -- static access tokens, client credentials tokens, and expiring offline tokens -- dynamic GraphQL schema download -- Bulk operations using the 2026 `bulkOperation(id:)` and `bulkOperations` APIs +`data.products.nodes` is a `Vec` of structs generated from the selection, and +`total_inventory` an `Option` because the schema says it may be null. + +- **Checked operations.** A field, argument, enum value or variable that does + not exist is a compile error, with a suggestion. A deprecated one is a + compiler warning with Shopify's reason. +- **Typed variables and results**, input objects included, written as + literals checked field by field, with no build script and no generated file. +- **Tokens handled**: static tokens, the client credentials grant, expiring + offline tokens. Obtained, renewed before they expire, renewed once when + Shopify refuses one, and saved where you say. +- **Throttling handled**: a throttled request waits for what its cost needs, + then goes again. Queries are retried after a server error; mutations never + run twice. +- **The rest of an app's Admin API work**: pagination, bulk operations, + webhooks, OAuth and session tokens, a mock transport for tests, and any + API version from one line of `Cargo.toml`. ## Install ```toml [dependencies] -shopify_api = "0.10" -tokio = { version = "1", features = ["full"] } -serde = { version = "1", features = ["derive"] } -serde_json = "1" +shopify_api = "1" +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ``` -## Basic GraphQL +Rust 1.88 or newer, and a Tokio runtime: the default transport and the token +renewals run on Tokio. The first build downloads the Admin schema of the latest +stable version into `graphql/admin.schema.json`, next to your `Cargo.toml`: +commit it. Later builds keep that version until you change it. -```rust,no_run -use serde::Deserialize; -use shopify_api::{Shopify, ShopifyAuth, ShopifyConfig}; +## Operations + +### Inline + +`graphql!("…", name = value, …)` is an operation whose types are inferred: + +```rust,ignore +let data = shopify + .execute(graphql!( + "query($id: ID!) { order(id: $id) { name displayFinancialStatus totalPriceSet { shopMoney { amount currencyCode } } } }", + id = "gid://shopify/Order/1", + )) + .await?; + +let order = data.order.expect("an order"); +println!("{} {:?} {}", order.name, order.display_financial_status, order.total_price_set.shop_money.amount); +``` + +Values are converted to the variable's type: any integer for an `Int`, `&str` +or `String` for an `ID`, a bare value or an `Option` for a nullable variable, +a slice or an array for a list. A value of the wrong type does not compile. +An enum value is written bare, `sortKey = TITLE`, and checked. + +### Input objects + +An input object is written as an object literal, checked against the schema +field by field while the crate compiles: + +```rust,ignore +shopify.execute(graphql!( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { field message } } }", + product = { + id: product_id, // any Rust expression + title: format!("{name} (promo)"), + status: ACTIVE, // an enum value, checked + descriptionHtml: null, // sends null + vendor?: new_vendor, // an Option: None leaves the field out + seo: { title: seo_title }, // a nested object + metafields: [for m in &rows if !m.value.is_empty() => { + namespace: "custom", key: &m.key, value: &m.value, type: "single_line_text_field", + }], + }, +)).await?; +``` + +A field is written one of four ways: + +| Field | Sends | +| --- | --- | +| `title: value` | The value | +| `title: null` | `null`: Shopify clears the field | +| `title?: option` | The value of `Some`; nothing for `None`, so Shopify keeps what it has | +| `title?: maybe` | A `shopify_api::Maybe`: `Value`, `Null`, or nothing for `Absent` | + +`title: option` does not compile: sending `null` for `None` would clear the +field, so the error points to `title?:` or `title: null`. An unknown field, a +field given twice, a missing required field, `null` for a non-null field, an +unknown enum value and `?:` on a required field are compile errors at the +token. For an enum value known only at run time, `raw(value)` sends the +string unchecked: `status: raw(row.status)`. + +`input!` builds an input object ahead of the call, in a loop for instance. +Every `input!` of one GraphQL type gives the same Rust type, so the values of +two call sites go in one `Vec`: + +```rust,ignore +use shopify_api::input; + +let mut metafields = Vec::new(); +for row in &rows { + if row.color.is_empty() { continue; } + metafields.push(input!(MetafieldsSetInput { + ownerId: &row.product_id, namespace: "custom", key: "color", value: &row.color, + type: "single_line_text_field", compareDigest?: row.digest.as_deref(), + })); +} +shopify.execute(graphql!( + "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", + metafields = metafields, +)).await?; +``` + +A value of another input type is refused, the message naming the place and +the GraphQL type it expects: `` an item of `$metafields` expects a `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })` ``. +The type given may show only as `InputObject`, `N` a hash of its name. -#[derive(Deserialize)] -struct ShopQuery { - shop: Shop, +### Values Shopify would not read as written + +A value is checked when it is built, in a literal, an `input!`, a module's +`Variables` or `Operation::variable`: an `Int` must fit in 32 bits, a `Float` +must be finite (JSON has no NaN or infinity, and `null` would clear the +field), and a non-null `JSON` must not be `null` at its top (`null` inside it +is fine). An integer literal out of range, alone, negated, in parentheses or +in a list `[…]`, is a compile error at the literal; `Some(…)`, `vec![…]` and +any other form are checked at run time. A value known at run time makes `execute` fail before anything is sent, with +`Error::InvalidValue`, which says where and why, never the value: +`` invalid value at `$input.lineItems[2].quantity`: Int out of 32-bit range ``. + +### Named + +`graphql! { pub mod name = "…"; … }` names the types, for functions and +sharing. One block holds several modules. `Variables` runs as it is, and each +input object the variables hold is a type of the module: + +```rust,ignore +graphql! { + pub mod metafields_set = "mutation MetafieldsSet($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { metafields { id key } userErrors { field message code } } + }"; + pub mod shop_name = "query ShopName { shop { name } }"; } -#[derive(Deserialize)] -struct Shop { - name: String, +fn color_metafields(rows: &[Row]) -> Vec { + rows.iter() + .map(|row| input!(MetafieldsSetInput { ownerId: &row.product_id, key: "color", value: &row.color })) + .collect() } -#[tokio::main] -async fn main() -> Result<(), shopify_api::ShopifyAPIError> { - let shopify = Shopify::new( - "my-shop", - ShopifyAuth::AccessToken("shpat_...".to_string()), - ShopifyConfig::default(), - )?; - - let data: ShopQuery = shopify - .graphql( - "query { shop { name } }", - &serde_json::json!({}), - ) - .await?; +let data = shopify.execute(metafields_set::Variables { metafields: color_metafields(&rows) }).await?; +let shop = shopify.execute(shop_name::operation()).await?; +``` - println!("{}", data.shop.name); - Ok(()) +### From a file + +```rust,ignore +graphql! { + pub mod order = file("graphql/order.graphql"); } ``` -## Client Credentials +### Through a framework + +A crate that reaches `shopify_api` through a crate re-exporting it, and does +not list it in its own `Cargo.toml`, gives the path with `crate =`; the schema +is still that crate's `graphql/admin.schema.json`: ```rust,ignore -use shopify_api::{Shopify, ShopifyAuth, ShopifyConfig}; +let op = my_framework::graphql!(crate = ::my_framework::shopify_api, "{ shop { name } }"); +my_framework::graphql! { crate = ::my_framework::shopify_api; pub mod shop = "{ shop { name } }"; } +let m = my_framework::input!(crate = ::my_framework::shopify_api, SEOInput { title: title }); +``` + +### Untyped + +For an operation built at run time, `shopify.graphql(query, variables)` +returns `data` as a `serde_json::Value`, `graphql_as::` reads it as your +type, and `graphql_raw` returns the whole answer, `errors` included. + +### Limits + +- A literal and an `input!` are checked against the schema of the crate + where they are written; values of `input!` from another crate have the same + type for the same GraphQL name. +- There is no `if`/`else` value form: a Rust expression returning an `Option`, + a `Maybe` or a value of `input!` covers it. +- rustc's own errors, outside those of the macros, show an input object as + `InputObject`, `N` a hash of its name. +- Enum fields of a module's `Variables` and `raw(…)` are strings nothing checks. +- Under `#![no_implicit_prelude]`, a literal or an `input!` that holds a + Rust expression does not compile: its messages need `#[diagnostic::…]`, + which that attribute hides. Constants, modules and variables of scalars do. + +The full reference of `graphql!`, with the mapping of every GraphQL type and +the rules of literals, is +[on docs.rs](https://docs.rs/shopify_api/latest/shopify_api/macro.graphql.html). + +## API versions + +Every operation is checked against a schema, and **sent to the version of that +schema**. No schema ships with the crate: the first build downloads the one of +the latest stable version into `graphql/admin.schema.json`, and later builds +keep it, whatever Shopify releases since: a build gives the same result +whatever the date. Commit the file, so that builds without network access +have it. A library that uses `graphql!` must ship it: as a dependency, a +crate never downloads its schema, and `cargo package` fails without it. +`schema = "…"` in `[package.metadata.shopify_api]` names another schema file +for that package, relative to its `Cargo.toml`: a relative path with `/` and portable names (no `:`, `\`, `<>"|?*` or control character, no name ending in `.` or a space, no device name such as `CON`). The details are in the +[`graphql!` docs](https://docs.rs/shopify_api/latest/shopify_api/macro.graphql.html#schema-and-api-version). + +To choose the version, pin it in your `Cargo.toml` (`graphql!` downloads its +schema when the file holds another one): -let shopify = Shopify::new( - "my-shop", - ShopifyAuth::client_credentials("client_id", "client_secret"), - ShopifyConfig::default(), -)?; +```toml +[package.metadata.shopify_api] +api-version = "2026-07" ``` -The crate acquires and refreshes 24-hour client-credentials tokens automatically. Add a `TokenStore` in `ShopifyConfig` when your app needs to persist refreshed token data. +Your operations are then checked against 2026-07, and the client sends them to +the 2026-07 endpoint: nothing else to change. `ShopifyBuilder::api_version` +pins every request to one version instead. -## Dynamic GraphQL Schema +The `shopify-api` command (`cargo install shopify_api --features cli`) +refreshes the file (`shopify-api schema download`, or `--shop` for the schema +a token sees), and `shopify-api check graphql/*.graphql` checks `.graphql` +files the same way, for CI or for operations used by other tools. -Public Shopify schema: +## Tokens -```rust,no_run -# async fn example() -> Result<(), shopify_api::ShopifyAPIError> { -let schema = shopify_api::download_public_admin_schema("2026-04").await?; -# Ok(()) -# } +```rust,ignore +use shopify_api::{Auth, Shopify, TokenData}; + +// A custom app's Admin API token, or an offline token stored at installation. +let shopify = Shopify::new("my-shop", Auth::access_token("shpat_…"))?; + +// The client credentials grant: tokens of 24 hours for a store of the +// organization that owns the app, asked for and renewed by the client. +let shopify = Shopify::new("my-shop", Auth::client_credentials(client_id, client_secret))?; + +// An expiring offline token, renewed with its refresh token and saved. +let shopify = Shopify::builder("my-shop") + .auth(Auth::expiring_token(client_id, client_secret, stored_token)) + .token_store(MyDatabase) + .build()?; ``` -```bash -cargo install shopify_api --features cli -shopify-api schema download \ - --public \ - --api-version 2026-04 \ - --out graphql.schema.json +Clones of a client share its token: one renewal serves them all, however many +requests wait for it. + +When Shopify refuses a token, `Error::Auth` says how, without a message to +parse: `error.token_endpoint_status()` (`Some(400)`), `error.oauth_code()` +(`Some(OAuthErrorCode::InvalidClient)`, `None` when the body has no code) and +`error.is_held_auth_failure()` (the failure of a renewal another request ran). +A `4xx` other than `408` and `429` with a code will not pass by itself; a +`5xx`, `408`, `429` or no code may. + +## Rate limits and retries + +A request Shopify throttles is sent again when the bucket holds its cost again, +computed from `extensions.cost`. A `429` waits for its `Retry-After` (seconds or an HTTP date), even past +`max_delay` (which caps only the backoff the client computes); a `Retry-After` +longer than `max_retry_after` (five minutes by default) is not waited for, and +ends in `Error::Throttled` with that wait in `retry_after`. A query +is also retried after a `5xx` or a network failure, with exponential backoff; +a mutation is not, since it may have run. + +```rust,ignore +use std::time::Duration; +use shopify_api::RetryPolicy; + +let shopify = Shopify::builder("my-shop") + .access_token(token) + .retry(RetryPolicy::new(6).with_max_delay(Duration::from_secs(10))) + .build()?; + +let response = shopify.execute_response(operation).await?; +println!("{:?}", response.cost()); // requested and actual cost, what is left ``` -This uses Shopify's public schema proxy: +## Pagination -```txt -https://shopify.dev/admin-graphql-direct-proxy/2026-04 +```rust,ignore +use shopify_api::Page; + +let products = shopify + .paginate( + |after| graphql!( + "query($after: String) { products(first: 250, after: $after) { nodes { id title } pageInfo { hasNextPage endCursor } } }", + after = after, + ), + |data| Page::new(data.products.nodes, data.products.page_info.has_next_page, data.products.page_info.end_cursor), + ) + .await?; ``` -The proxy is a GraphQL endpoint for introspection requests, not a static `GET` file. +## Bulk operations -Runtime: +`graphql!(bulk(…))` checks a bulk query against the schema and Shopify's +bulk rules (one top-level connection, five connections at most, two levels +deep, `edges { node }`, an `id` on each parent…), and reads its results as +generated types: each nested connection is a `Vec` of its nodes, put back +under its parent as the file downloads, one product in memory at a time. -```rust,no_run -use shopify_api::{Shopify, ShopifyAuth, ShopifyConfig}; +```rust,ignore +use shopify_api::bulk::BulkWaitOptions; + +graphql! { + mod catalog = bulk("query($filter: String) { + products(query: $filter) { edges { node { + id title + variants { edges { node { sku } } } + } } } + }"); +} -# async fn example() -> Result<(), shopify_api::ShopifyAPIError> { -let shopify = Shopify::new( - "my-shop", - ShopifyAuth::AccessToken("shpat_...".to_string()), - ShopifyConfig::default(), -)?; -let schema = shopify.download_admin_schema().await?; -# Ok(()) -# } +let mut products = shopify + .bulk_query(catalog::Variables { filter: Some("status:active".into()) }, BulkWaitOptions::default()) + .await?; +while let Some(product) = products.next_item().await { + let product = product?; + println!("{}: {} variants", product.title, product.variants.len()); +} ``` -CLI: +Shopify takes no variables for a bulk query: they are written into its text +as GraphQL literals. A bulk mutation, `bulk("mutation …")`, runs over an +iterator of its `Variables` with `bulk_mutation`, which checks every line +before uploading them and reads a typed result per line. See the +[documentation of `graphql!`](https://docs.rs/shopify_api/latest/shopify_api/macro.graphql.html#bulk-operations) +for the rules, and what is not checked. -```bash -cargo install shopify_api --features cli -shopify-api schema download \ - --shop my-shop \ - --access-token "$SHOPIFY_ACCESS_TOKEN" \ - --out shop.graphql.schema.json -``` +The untyped methods run any text: + +```rust,ignore +use shopify_api::bulk::BulkWaitOptions; -The crate no longer ships built-in Shopify schema JSON files. Use the CLI output as the `schema_path` for `graphql_client`. +// Start, wait, download, read each line. +let rows: Vec = shopify + .bulk_query_rows("{ products { edges { node { id title } } } }", BulkWaitOptions::default()) + .await?; + +// Start only: one mutation per item, uploaded as JSONL first. +let operation = shopify.start_bulk_mutation_text( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }", + &inputs, +).await?; +``` -## Bulk Operations +One verb per meaning: `start_bulk_*` only starts an operation and returns +it; `bulk_query*` and `bulk_mutation` start, wait and read. `start_bulk_query` +takes a text (`GroupObjects(text)` for `groupObjects`) or a +`graphql!(bulk(…))` query; `start_bulk_mutation` takes typed lines, and +`start_bulk_mutation_text` a text and its variables. With +`wait_for_bulk_operation`, `bulk_operations`, `cancel_bulk_operation` and +`download_bulk_results`, each step is on its own. -```rust,no_run -use shopify_api::{BulkWaitOptions, Shopify, ShopifyAuth, ShopifyConfig}; +### Large exports: stream the rows -# async fn example() -> Result<(), shopify_api::ShopifyAPIError> { -let shopify = Shopify::new( - "my-shop", - ShopifyAuth::AccessToken("shpat_...".to_string()), - ShopifyConfig::default(), -)?; +`bulk_query_rows` holds every row in a `Vec`. For an export of gigabytes, +`bulk_query_stream` reads the file line by line as it downloads: memory +follows the lines being read (the longest of the last few dozen), not the file. -let payload = shopify - .run_bulk_query("{ products { edges { node { id title } } } }") +```rust,ignore +let mut products = shopify + .bulk_query_stream::("{ products { edges { node { id title } } } }", BulkWaitOptions::default()) .await?; +while let Some(product) = products.next_row().await { + let product = product?; // a line that does not read: skip it, or stop + save(product).await?; +} +``` + +`BulkRows` is also a `futures_core::Stream`. A line that does not read as +the type is an error and the stream goes on; a download that fails, or a +line longer than `max_line_length` (64 MiB by default), ends it. -let operation = payload.bulk_operation.unwrap(); -let operation = shopify - .wait_for_bulk(&operation.id, BulkWaitOptions::default()) +Nested connections write their objects on lines of their own, after their +parent. `bulk_query_grouped::` runs the query with +`groupObjects` and yields each product with its variants, one product in +memory at a time. Every object that has a nested connection must select +`id`, without an alias: Shopify refuses the query otherwise. + + +```rust,ignore +let mut products = shopify + .bulk_query_grouped::( + "{ products { edges { node { id title variants { edges { node { id sku } } } } } } }", + BulkWaitOptions::default(), + ) .await?; +while let Some(group) = products.next_group().await { + let (product, variants) = group?; +} +``` + +`download_bulk_results_stream` and `download_bulk_results_grouped` read the +results of an operation you ran yourself. For a bulk mutation over more +items than you want in memory, `start_bulk_mutation_text` takes an iterator: +each item is serialized as it is taken. + +Use the `Vec` methods when the results fit in memory, the streams otherwise. + +## Webhooks -if let Some(url) = operation.url { - let rows: Vec = Shopify::download_bulk_jsonl(&url).await?; - println!("{} rows", rows.len()); +Feature `webhooks`: + +```rust,ignore +use shopify_api::webhooks::{Webhook, WebhookSubscriptionSpec}; + +// In your HTTP handler, on the raw body. `headers`: an `&http::HeaderMap` +// (axum, actix, warp), or any (name, value) pairs. +let webhook = Webhook::verify(&headers, body, client_secret)?; +match webhook.topic() { + "orders/create" => { + let order: MyOrder = webhook.payload()?; + } + "app/uninstalled" | "shop/redact" | "customers/redact" => { + // The signature covers the body, not the headers: check the shop. + webhook.verify_payload_shop()?; + } + _ => {} } -# Ok(()) -# } + +// Make the shop's subscriptions exactly these. +shopify.sync_webhook_subscriptions(&[ + WebhookSubscriptionSpec::new("orders/create", "https://example.com/webhooks"), + WebhookSubscriptionSpec::new("app/uninstalled", "https://example.com/webhooks"), +]).await?; ``` -## Changelog +Only JSON webhooks verify, a body whose first byte is `{` (no whitespace or +byte order mark before it), and the subscriptions the crate creates or syncs +are JSON: the client secret also signs launch queries, app proxy requests and +session tokens, which an installer of the app can read and make look like XML, +or like JSON after some whitespace. + +## OAuth and embedded apps + +Feature `oauth`: + +```rust,ignore +use shopify_api::oauth::{RequestedToken, ShopifyApp}; + +// The clients it builds save the tokens they renew. +let app = ShopifyApp::new(client_id, client_secret).with_token_store(MyDatabase); + +// Embedded app: the session token of each request, exchanged for a token. +let session = app.verify_session_token(bearer)?; +let token = app.exchange_session_token(&session, RequestedToken::ExpiringOffline).await?; +let shopify = app.client(session.shop(), token)?; + +// Or, once the token is stored: verify the session, then load the shop's token. +let session = app.verify_session_token(bearer)?; +let shopify = app.client(session.shop(), my_database.offline_token(session.shop())?)?; + +// A checkout or customer account UI extension: the shop, and the customer if logged in. +let extension = app.verify_extension_session_token(bearer)?; +let customer = extension.customer(); // Some("gid://shopify/Customer/…") + +// Install link and callback, admin launches, app proxies. +let link = app.authorization_url(&shop, &request); +let callback = app.verify_query(query_string)?; +let token = app.exchange_code(&callback).await?; +let proxied = app.verify_app_proxy(query_string)?; +``` + +`verify_session_token` takes only the tokens of Shopify admin (`dest` and +`iss` exactly `https://{shop}.myshopify.com` and its `/admin`), which Shopify +gives a staff member: they may open the admin side of the app, such as the +stored offline token of the shop. The tokens of checkout and customer account +UI extensions are signed with the same secret, but any buyer of the shop gets +one, logged in or not: `verify_extension_session_token` verifies them, as an +`ExtensionSessionToken` that does not exchange for a token, so that one can +never pass for the other. + +## Testing your code + +Feature `testing`: a `MockTransport` records what the client sends and answers +what the test says, with no network. + +```rust,ignore +use shopify_api::testing::{MockTransport, client}; + +let mock = MockTransport::new(); +mock.push_data(serde_json::json!({ "shop": { "name": "Test shop" } })); +let shopify = client(&mock); + +assert_eq!(my_code_under_test(&shopify).await?, "Test shop"); +assert_eq!(mock.graphql_requests()[0].operation_name.as_deref(), Some("Shop")); +``` + +## Features + +| Feature | | +| --- | --- | +| `rustls` (default) | The default transport over rustls. | +| `native-tls` | The same over the platform's TLS. | +| `webhooks` | Webhook verification, parsing and subscriptions. | +| `oauth` | Install links, callbacks, token exchange, session tokens, app proxies. | +| `testing` | `MockTransport`, and the signing helpers of tests. | +| `cli` | The `shopify-api` command. | +| `full` | Every feature but `native-tls`: `webhooks`, `oauth`, `testing`, `cli`, over rustls. | + +Without `rustls` or `native-tls`, give the client your own `Transport`. + +## Upgrading from 0.10 + +See [MIGRATION.md](MIGRATION.md). + +## Development + +The toolchain and the tasks are in `mise.toml`: + +```bash +mise install +mise run check # what CI runs: fmt, clippy, tests, docs +mise run schema:test # download the schema the tests use again (version in crates/shopify_api/Cargo.toml) +mise run schema:internal # cut it down to the crate's own operations, graphql/internal.schema.json +mise tasks # every task +``` + +The tests never reach Shopify: they script it with `MockTransport`. +`mise run test:live` runs a few against a real development store: + +```bash +SHOPIFY_TEST_SHOP=my-dev-store SHOPIFY_TEST_ACCESS_TOKEN=shpat_… mise run test:live +# or SHOPIFY_TEST_CLIENT_ID and SHOPIFY_TEST_CLIENT_SECRET instead of the token +``` + +The token needs `read_products` and `write_products`. One of them runs a +typed bulk query, `products { variants { metafields } media }`, and compares +its items with the raw JSONL regrouped by `__parentId`: it confirms what +Shopify's guide does not show and the typed reader relies on, that the +`_shopifyApiTypename` alias is kept in the file and that `groupObjects` +writes each object right after its parent at the second level too. When +the store has no product with an image and a variant metafield, it creates +one, tagged `shopify-api-live-test`, and reuses it later. + +## License -See [CHANGELOG.md](CHANGELOG.md). +MIT diff --git a/crates/shopify_api/Cargo.toml b/crates/shopify_api/Cargo.toml new file mode 100644 index 0000000..94d5d94 --- /dev/null +++ b/crates/shopify_api/Cargo.toml @@ -0,0 +1,104 @@ +[package] +name = "shopify_api" +description = "Shopify Admin GraphQL client: operations checked against Shopify's schema at compile time, typed results, automatic tokens and throttling, bulk operations, webhooks and OAuth." +documentation = "https://docs.rs/shopify_api" +readme = "../../README.md" +keywords = ["shopify", "graphql", "api", "client", "ecommerce"] +categories = ["api-bindings", "web-programming::http-client"] +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +# What `cargo test` of the published crate needs, offline: the sources and +# their doctests, which read the Admin schema of `graphql/`. The tests and the +# examples stay in the repository: they need its other files and toolchain. +include = [ + "src/**", + "docs/**", + "graphql/admin.schema.json", + "graphql/internal.schema.json", + "graphql/operations/**", + "Cargo.toml", + "LICENSE.txt", +] + +# The version of the tests, the examples and `graphql/internal.schema.json`. +# To move to another: change it, `shopify-api schema download` in this +# directory, then `mise run schema:internal` and `mise run ui:bless`. +[package.metadata.shopify_api] +api-version = "2026-10" + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] + +[dependencies] +shopify_api_macros.workspace = true + +chrono.workspace = true +# `Stream`, which the bulk downloads implement: the trait the async ecosystem shares. +futures-core.workspace = true +reqwest = { workspace = true, optional = true } +serde.workspace = true +serde_json = { workspace = true, features = ["raw_value"] } +serde_urlencoded.workspace = true +# `rt`: a token renewal runs in its own task, so a caller that gives up does not cancel it. +tokio = { workspace = true, features = ["rt", "sync", "time"] } +tracing.workspace = true + +base64 = { workspace = true, optional = true } +hex = { workspace = true, optional = true } +hmac = { workspace = true, optional = true } +sha2 = { workspace = true, optional = true } + +clap = { workspace = true, optional = true } +shopify_api_graphql = { workspace = true, optional = true } + +[dev-dependencies] +graphql-parser.workspace = true +tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time", "test-util", "net", "io-util"] } +trybuild.workspace = true + +[features] +default = ["rustls"] +## The default transport, `ReqwestTransport`, with rustls. +rustls = ["dep:reqwest", "reqwest/rustls"] +## The default transport, `ReqwestTransport`, with the platform's TLS. +native-tls = ["dep:reqwest", "reqwest/native-tls"] +## Webhook verification and parsing, webhook subscriptions. +webhooks = ["dep:hmac", "dep:sha2", "dep:base64"] +## OAuth: install links, callbacks, token exchange, session tokens, app proxies. +oauth = ["dep:hmac", "dep:sha2", "dep:base64", "dep:hex"] +## `MockTransport`, to test code that calls Shopify without the network. +testing = [] +## The `shopify-api` command: downloads Admin schemas, checks `.graphql` files. +cli = ["dep:clap", "dep:shopify_api_graphql", "shopify_api_graphql/download", "rustls", "tokio/macros", "tokio/rt-multi-thread", "tokio/fs"] +full = ["webhooks", "oauth", "testing", "cli"] + +[[bin]] +name = "shopify-api" +path = "src/bin/shopify-api.rs" +required-features = ["cli"] + +[[example]] +name = "products" +required-features = ["rustls"] + +[[example]] +name = "bulk_export" +required-features = ["rustls"] + +[[example]] +name = "metafields" +required-features = ["rustls"] + +# With one feature set only: `mise run check` runs the tests of two at once, +# in two processes, and this test's cargo projects are in one directory. +[[test]] +name = "schema_override" +required-features = ["testing"] + +[lints] +workspace = true diff --git a/crates/shopify_api/LICENSE.txt b/crates/shopify_api/LICENSE.txt new file mode 120000 index 0000000..1ef648f --- /dev/null +++ b/crates/shopify_api/LICENSE.txt @@ -0,0 +1 @@ +../../LICENSE.txt \ No newline at end of file diff --git a/crates/shopify_api/docs/graphql.md b/crates/shopify_api/docs/graphql.md new file mode 100644 index 0000000..5b89c9a --- /dev/null +++ b/crates/shopify_api/docs/graphql.md @@ -0,0 +1,697 @@ + +The operation is checked while the crate compiles: a field, an argument, a +fragment, a directive or an enum value that does not exist, a missing required +argument or input field, a variable that is not declared, unused or of the +wrong type, the same response key selected with other arguments, are compile +errors on the operation, with a suggestion when a name is close to an +existing one: + +```text +error: Type `Order` has no field `nam` (did you mean `name`?) (line 1, column 58) + (checked against the Shopify Admin API 2026-10) + --> src/orders.rs:12:13 +``` + +What the schema deprecates is a compiler warning that gives Shopify's reason +(an error under `-D warnings`; silence it with `#[allow(deprecated)]`): + +```text +warning: use of deprecated constant `…::SHOPIFY_DEPRECATION`: `Product.bodyHtml` is deprecated + in the Shopify Admin API 2026-10: Use `descriptionHtml` instead. (line 1, column 38 of the operation) +``` + +# Inline operations + +```rust,no_run +use shopify_api::{Shopify, graphql}; + +async fn recent_order_names(shopify: &Shopify, limit: u32) -> shopify_api::Result> { + let data = shopify + .execute(graphql!( + "query RecentOrders($first: Int!) { orders(first: $first, reverse: true) { nodes { id name } } }", + first = limit, + )) + .await?; + + Ok(data.orders.nodes.into_iter().map(|order| order.name).collect()) +} +``` + +[`Shopify::execute`] returns the contents of Shopify's `data`: read +`data.orders`, not `data.data`. + +The operation is a string literal, with or without a leading `#graphql` +comment, or `file("path.graphql")`, relative to the crate's `Cargo.toml`. It +holds one query or mutation and the fragments it uses. Its name, when it has +one, is sent as `operationName`, which Shopify shows in its logs. + +Reading a field the operation does not select is a compile error too: +`no field `name` on type `DataOrdersNodes``. + +# Result types + +Each selection is a struct with a field per selected key, in snake case: +`lineItems` is `line_items`, an alias gives its own name, `__typename` is +`typename`, a Rust keyword is written raw (`r#type`). + +| GraphQL | Rust | +| --- | --- | +| `String`, `ID` | `String` | +| `Int` | `i64` | +| `Float` | `f64` | +| `Boolean` | `bool` | +| `JSON` | `serde_json::Value` | +| Shopify's other scalars: `DateTime`, `Date`, `Decimal`, `Money`, `URL`, `HTML`, `UnsignedInt64`, `BigInt`… | `String`, as Shopify sends them | +| Enum | `String` holding the value, such as `"PAID"` | +| Object, interface, union | A struct | +| `T` without `!` | `Option` | +| `[T]` | `Vec` | + +Enum values are strings so that a value Shopify adds later does not break +reading an answer; enum values written in the operation, such as +`sortKey: CREATED_AT`, are checked. + +A field selected in a fragment on another type, as `title` below, is an +`Option`, `None` for the other types; so is a field under `@include` or +`@skip`, and the subfields only such a place selects. The schema's other +directives, such as Shopify's `@idempotent(key:)` on a mutation, are checked +like arguments. A fragment on the type itself or on one of its interfaces adds plain +fields. + +```rust,no_run +# async fn run(shopify: shopify_api::Shopify, ids: Vec) -> shopify_api::Result<()> { +let data = shopify + .execute(shopify_api::graphql!( + "query($ids: [ID!]!) { + nodes(ids: $ids) { + __typename + id + ... on Product { title } + ... on Order { name } + } + }", + ids = &ids, + )) + .await?; + +// `nodes` is `[Node]!`: a list of nullable nodes. +for node in data.nodes.iter().flatten() { + println!("{} {} {:?} {:?}", node.typename, node.id, node.title, node.name); +} +# Ok(()) +# } +``` + +The types derive `Debug`, `Clone`, `PartialEq`, `Serialize` and +`Deserialize`; they serialize under the names of the GraphQL fields. + +The generated types, these and the `Variables` of a module, may derive more +traits in a 1.x release (`Default`, `Eq`, `Hash`…). Do not implement standard +or serde traits for them yourself: such an impl would conflict with the +derive then. Convert to your own types for traits of your own choosing. + +The types of an inline operation have no name you can write: let inference +carry them, convert them to your own types, or use a [module](#named-operations). + +# Variables + +Values follow the operation as `name = value`. A variable that is non-null +without a default needs one; the others can be left out, and are then not sent. + +A Rust value for a scalar variable is converted to the Rust type of the +variable, so the usual spellings work: + +| Variable | Accepted values | +| --- | --- | +| `String`, `ID`, string-encoded scalars | `String`, `&str`, `&String`, `Cow` | +| `Int` | Any integer type | +| `Float` | `f32`, `f64`, `i32`, `u32` | +| `Boolean` | `bool` | +| `JSON` | `Value`, `&Value` | +| Nullable | The bare value, or an `Option` of it: `None` sends `null` | +| List | A `Vec`, a slice, an array or a `&Vec` of accepted values | + +Another type is a compile error on the value: `` `&str` is not a value for a +GraphQL variable of Rust type `i64` `` (see [`IntoVariable`]). The value is +then checked, as for [input values](#values-shopify-would-not-read-as-written). + +An enum value is written bare, and checked: `sortKey = TITLE`. A string +known at run time goes through `raw(…)`, which nothing checks: +`sortKey = raw(key)`, an `Option` for a nullable variable. + +An input object is written as an object literal, checked field by field +against the schema, or given as a value built by [`input!`](crate::input!): + +```rust,no_run +use shopify_api::{Shopify, graphql}; + +struct Row { key: String, value: String } + +async fn promote(shopify: &Shopify, product_id: &str, name: &str, new_vendor: Option, rows: &[Row]) + -> shopify_api::Result<()> { + let data = shopify + .execute(graphql!( + "mutation($product: ProductUpdateInput!) { + productUpdate(product: $product) { userErrors { field message } } + }", + product = { + id: product_id, + title: format!("{name} (promo)"), + status: ACTIVE, + descriptionHtml: null, + vendor?: new_vendor, + seo: { title: name }, + metafields: [for row in rows if !row.value.is_empty() => { + namespace: "custom", key: &row.key, value: &row.value, type: "single_line_text_field", + }], + }, + )) + .await?; + for error in data.product_update.into_iter().flat_map(|payload| payload.user_errors) { + eprintln!("{:?}: {}", error.field, error.message); + } + Ok(()) +} +``` + +# Input values + +A value written for an input type reads by the GraphQL type expected where +it stands: + +| Form | Where | Sent | +| --- | --- | --- | +| `null` | A nullable type | `null` | +| `{ field: value, field?: option, … }` | An input object | The object, its fields in the order written | +| `[value, …]` | A list | The list; a single value is not taken for a list | +| `[for pattern in iterable => value]`, `[for … if condition => value]` | A list | One item per turn of the loop | +| `NAME` | An enum | The value, checked against the enum | +| `raw(string)` | An enum | The string, as is: any `Into` | +| Any other Rust expression | Anywhere | Its value, its type checked as below | + +In an object, the field names are the GraphQL ones, Rust keywords included +(`type: "single_line_text_field"`). A field that does not exist, a field +given twice, a required field left out (every one is named), `null` for a +non-null type, an unknown enum value (the valid ones are listed) and an +object or a list where the type wants another form are compile errors that +point at the token. A deprecated field or enum value is a warning that gives +Shopify's reason. + +A `@oneOf` input object, such as `ProductSetIdentifiers`, takes exactly one +of its fields, written `field: value`, with a value that is not `null`: +`{ handle: "shirt" }`. No field, two fields, `field: null` and `field?: …` +are compile errors at the token, which list the fields to choose from. In +the text of an operation the same holds, and a variable given to such a field +must be non-null (`$handle: String!`). + +A field is written one of four ways: + +| Field | Sends | +| --- | --- | +| `title: value` | The value | +| `title: null` | `null`: Shopify clears the field | +| `title?: option` | The value of `Some`; nothing for `None`, so Shopify keeps what it has | +| `title?: maybe` | A [`Maybe`]: `Value`, `Null` or nothing for `Absent` | + +An `Option` given to `title: …` does not compile: sending `null` for `None` +would clear the field. The error says to write `title?: …` or `title: null`. +A required field (non-null without a default) cannot take `?:`; a non-null +field with a default takes an `Option` there, not a [`Maybe`], whose `Null` it +refuses. On an enum field, `status?: raw(option)` takes an `Option` or a +`Maybe` of a string. A variable keeps its own rule: `name = option` sends +`null` for `None`. + +A Rust expression is checked by a trait written for its place, whose error +names the GraphQL type: `` `title` of `ProductUpdateInput` expects a `String`, +not `i32` ``. It takes what a variable takes (the table above), except for an +`Option` in a field. Where an input object is expected, it takes a value of +[`input!`](crate::input!) for that type, or a `Vec`, a slice or an array of +them for a list: `` `$metafields` expects a list of `MetafieldsSetInput`, built +with `input!(MetafieldsSetInput { … })` ``. An enum takes a bare value or +`raw(…)`, never another expression. + +What reads as what, when Rust could read it too: + +- `{` starts an object when the braces are empty or start with `name:` or + `name?:`, which no Rust block does: `first = { compute() }` stays a block. +- `[a, b]` is a list where a list is expected and a Rust array elsewhere; + `[x; 3]` is an array. A variable of a list of scalars given plain Rust + values, `ids = [a, b]`, is converted as before. +- `null` and `raw(…)` are those forms only as a whole value: a Rust variable + named `null` is written `(null)`, a function `raw` is called as + `self::raw(x)` or `(raw(x))`. +- A lone identifier is an enum value where an enum is expected, and a Rust + variable everywhere else. + +Nothing goes through a `serde_json::Value`: each literal is written straight +to the JSON sent, and a value of `input!` holds its JSON already. + +# Values Shopify would not read as written + +Every value is checked when it is built (a literal, an `input!`, the +`Variables` of a module, [`Operation::variable`]), for what JSON or GraphQL +would turn into something else: + +| Value | Refused when | Reason shown | +| --- | --- | --- | +| A `Float` | NaN or infinite: JSON writes it `null`, which clears the field | `not a finite Float` | +| An `Int`, of any integer type | Outside of 32 bits, GraphQL's `Int` | `Int out of 32-bit range` | +| A non-null `JSON` | `null` at its top; `null` inside it is sent | `null for a non-null JSON field` | +| Any value | Its `Serialize` fails | `could not serialize` | + +An integer literal out of range is a compile error at the literal, where +an `Int` is expected: `2_147_483_648_i64`, `-2147483649`, `0x8000_0000`, +`(3_000_000_000)`, in any base, with `_` and a suffix, negated, in +parentheses, alone or as an item of a list `[…]`. Only these forms are +checked when the crate compiles, since their meaning does not depend on what +a name resolves to. Any other value, `Some(…)`, `vec![…]`, `[x; n]`, a +computed one, or a literal its suffix's type cannot hold (under +`allow(overflowing_literals)`, `0xffff_ffff_i32` is `-1`), is checked when +it is built: it is kept as refused, and the +operation fails with [`Error::InvalidValue`] when it is sent, or when +[`Operation::body`] or [`Operation::variable_json`] reads it, before any +request. Its `Display` names the place in GraphQL terms and the reason, never +the value: + +```text +invalid value at `$product.metafields[2].value`: not a finite Float +``` + +A serializer's message, which may quote the value, is only in +[`Error::sensitive_detail`]. Shopify's string-encoded scalars, such as +`UnsignedInt64`, are strings, and not checked. An [`InputObject`] that is +refused also fails to serialize on its own, with the same message. + +# Named operations + +A module names the types of an operation: to share it, or to return its +data from a function. One `graphql!` holds any number of modules, each with +its attributes, visibility and source; `;` goes between them. + +```rust,no_run +use shopify_api::{Shopify, graphql, input}; + +graphql! { + /// Writes metafields and returns what Shopify refused. + pub mod metafields_set = "mutation MetafieldsSet($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { + metafields { id key } + userErrors { field message code } + } + }"; + pub(crate) mod shop_name = "query ShopName { shop { name } }"; +} + +struct Row { product_id: String, color: String } + +fn color_metafields(rows: &[Row]) -> Vec { + rows.iter() + .filter(|row| !row.color.is_empty()) + .map(|row| input!(MetafieldsSetInput { + ownerId: &row.product_id, + namespace: "custom", + key: "color", + value: &row.color, + type: "single_line_text_field", + })) + .collect() +} + +async fn set_colors(shopify: &Shopify, rows: &[Row]) -> shopify_api::Result> { + let data = shopify + .execute(metafields_set::Variables { metafields: color_metafields(rows) }) + .await?; + let payload = data.metafields_set.expect("a payload"); + Ok(payload.user_errors.into_iter().map(|error| error.message).collect()) +} +``` + +| Item | | +| --- | --- | +| `QUERY` | The text of the operation. | +| `NAME`, `KIND`, `API_VERSION` | Its name, query or mutation, and the version it was checked against. | +| `Data` and nested structs | The result. A nested struct is named after its path: `DataMetafieldsSetUserErrors`. | +| `Variables` | A field per variable, absent when there is none. [`Shopify::execute`] runs it: `Operation` implements `From`. | +| Input objects | `pub type MetafieldsSetInput = InputObject<…>` for each input object the variables may hold, the type every [`input!`](crate::input!)`(MetafieldsSetInput { … })` builds. | +| `operation(variables)` | The operation, for `execute`. Takes nothing when there are no variables. | + +In `Variables`, a variable that may be left out is an `Option`, not sent when +`None`. `Variables` implements `Default` when no variable is required, so that +`..Default::default()` never leaves out a required one, and `PartialEq` when it +holds no input object. A variable of an enum is a `String` there, which +nothing checks. + +Operations kept in files read the same, and editors that know GraphQL help +writing them: + +```rust,ignore +graphql! { + pub mod order = file("graphql/order.graphql"); + pub mod orders = file("graphql/orders.graphql"); +} +``` + +# Bulk operations + +`bulk("…")`, or `bulk(file("…"))`, declares a bulk operation: a query Shopify +runs over a whole catalog in the background, or a mutation it runs once per +line of variables. It is checked like any operation, then against Shopify's +rules for bulk operations, and its results are read as generated types. + +```rust,no_run +use shopify_api::bulk::BulkWaitOptions; +use shopify_api::{Shopify, graphql}; + +graphql! { + pub mod catalog = bulk("query($filter: String) { + products(query: $filter) { edges { node { + id title + variants { edges { node { sku } } } + } } } + }"); +} + +async fn export(shopify: &Shopify) -> shopify_api::Result<()> { + let mut products = shopify + .bulk_query( + catalog::Variables { filter: Some("status:active".into()) }, + BulkWaitOptions::default(), + ) + .await?; + while let Some(product) = products.next_item().await { + let product: catalog::Item = product?; + println!("{}: {} variants", product.title, product.variants.len()); + } + Ok(()) +} +``` + +## The rules of a bulk query + +These follow Shopify's guide for API 2026-10 +([bulk queries](https://shopify.dev/docs/api/usage/bulk-operations/queries)). +Where the guide is silent, what it does not show is refused: a query +`graphql!` accepts is one the guide describes. + +- One top-level field, which is a connection, not `node` or `nodes`. +- Five connections at most, the top-level one included, nested two levels + deep at most below it. +- Each connection selected as `edges { node { … } }` and nothing else: no + `nodes`, `cursor` or `pageInfo`, no alias or directive on them, and no + `first`, `last`, `after` or `before`, which Shopify ignores in a bulk query. +- The nodes of a connection implement `Node`. +- A nested connection is written right in the `node { … }` of its parent + connection: not in a fragment, nor under another field. +- A node with nested connections selects `id`, without an alias or a + directive, and no other field aliased `id`. Shopify refuses the query + without it, and the lines of the children are placed under their parent + by that `id`: `graphql!` asks you to add it rather than adding it itself. + Elsewhere, `id` may be the alias of any field. +- Two connections of one node that may return the same type, such as two + aliased `metafields(…)`, are refused: their lines could not be told apart. +- No alias starting with `__`, nor `_shopifyApiTypename`. +- A string the GraphQL parser of `graphql!` reads otherwise than the + GraphQL specification: the query is sent as the text it read. That is a + `\b` escape, which it reads as U+0010 (write `\u0008`), and a block string + with a lone carriage return or indented with other whitespace than spaces + and tabs (write a quoted string). Escapes `\u{…}` and surrogate pairs do not + parse at all. + +## The items of a bulk query + +The result type is `Item`, an object of the top-level connection, with the +fields it selects. A nested connection is a `Vec` of its nodes, +`product.variants: Vec`, not `{ edges: [{ node }] }`: Shopify +writes each node on a line of its own, and the reader puts it back under +its parent. Other nested objects stay as in any operation. A connection of +an interface or a union gives one struct, the fields of each fragment +optional, as in any operation. + +[`Shopify::bulk_query`] starts the query, with `groupObjects` when it has +nested connections (Shopify is slower with it, and more likely to time out, +so a flat export goes without), waits for it, +and returns [`BulkItems`](crate::bulk::BulkItems): `next_item().await`, one +item at a time, `collect().await` into a `Vec`, or a `Stream`. One item is +held at a time, with its nested objects: memory follows the largest item, +not the file. A line that does not read as its type, or a nested line that +has no place, ends the stream with an error. [`Shopify::start_bulk_query`] +and [`Shopify::download_bulk_items`] split the steps, for an operation you +wait for yourself. + +The text sent is not the text written. Where a node has several nested +connections, their nodes gain `_shopifyApiTypename: __typename`, which +tells their lines apart; the types do not show it, and a `__typename` you +select is left as you wrote it. `_shopifyApiTypename` is reserved: it cannot +be an alias in a bulk query, nor can an alias that starts with `__`. [`BulkQuery::text`](crate::bulk::BulkQuery::text) +gives the text sent. + +## Variables of a bulk query + +Shopify takes no variables for a bulk query. Declare them all the same and +give them as for any operation, literals and [`input!`](crate::input!) +included: when the query runs, each value is written into its text as a +GraphQL literal, and the variable definitions are left out. + +- A string as JSON escapes it, which GraphQL reads alike; a `$` in a string + stays a `$`. Numbers, booleans and `null` as they are. +- An enum value bare (`sortKey: TITLE`), in an input object and in a list + too. One that is not a GraphQL name, which `raw(…)` or a `String` field of + `Variables` may hold, fails with [`Error::InvalidValue`](crate::Error::InvalidValue) + (`NotAGraphqlName`) before anything is sent, as does an enum value + `true`, `false` or `null` (`ReservedEnumValue`), which would read as a + boolean or as `null`, and as do the values any operation refuses. +- An input object as `{field: value}`, a list as `[a, b]`. +- A variable without a value takes its default value, or is left out with + its argument or field, as GraphQL leaves out an argument whose variable + has no value; in a list, it is `null`. A `None` in an optional field of a + module's `Variables` is such a variable without a value, not a `null`: + `sorted::Variables { sort: None }` sends `products { … }`, or + `products(sortKey: TITLE)` if `$sort` defaults to `TITLE`. +- A `null` given as a value is written `null` and replaces the default: + `sort = null`, or `sort = raw(option)` with `None` in an inline `graphql!`, + sends `products(sortKey: null)`. So does a `None` in a list, and `null` or + a `Maybe::Null` in an input object. +- A variable that may hold a `JSON` value is refused at compile time. + +## Bulk mutations + +`bulk("mutation …")` is one mutation field, not `bulkOperationRunQuery` or +`bulkOperationRunMutation`, with one connection at most in what it selects +(Shopify's [rules](https://shopify.dev/docs/api/usage/bulk-operations/imports)). +Its `Variables`, or an inline `graphql!(bulk("mutation …"), …)`, are one line +of variables: [`Shopify::bulk_mutation`] takes an iterator of them. + +```rust,no_run +use shopify_api::bulk::BulkWaitOptions; +use shopify_api::{Shopify, graphql}; + +graphql! { + pub mod tag = bulk("mutation($id: ID!, $tags: [String!]!) { + tagsAdd(id: $id, tags: $tags) { userErrors { field message } } + }"); +} + +async fn tag_all(shopify: &Shopify, ids: &[String]) -> shopify_api::Result<()> { + let lines = ids.iter().map(|id| tag::Variables { id: id.clone(), tags: vec!["sale".into()] }); + let mut results = shopify.bulk_mutation(lines, BulkWaitOptions::default()).await?; + while let Some(result) = results.next_row().await { + let result = result?; + // `index`: the line of variables it ran with, from 0. + if let Some(payload) = result.data.and_then(|data| data.tags_add) { + for error in payload.user_errors { + println!("line {:?}: {}", result.index, error.message); + } + } + } + Ok(()) +} +``` + +Every line is checked and written before anything is sent: one value refused +fails the call. Shopify runs the lines in no set order; each result is a +[`BulkMutationResult`](crate::bulk::BulkMutationResult), the `data` of the +mutation, its `errors`, and the `index` of its line. + +## What is not checked + +- What Shopify refuses at run time and its guide does not list: a + connection its bulk queries cannot read, a field that times out, missing + access scopes. Those come back as the user errors of + `bulkOperationRunQuery`, or as a failed operation. +- Shopify may accept more than `graphql!` does (`nodes`, `first`, a + connection in a fragment): the untyped methods of [`bulk`](crate::bulk) + send any text. +- The order of the lines: the reader relies on the order `groupObjects` + writes, each child after its parent and before the next top-level object. + A file of another order is an error, not a misplaced child. Shopify's + guide shows it for one level; a live test of the repository + (`a_typed_bulk_query_regroups_two_levels_and_sibling_connections`, run by + `mise run test:live`) checks two levels, sibling connections, and that the + `_shopifyApiTypename` alias is kept in the file. + +# Schema and API version + +No schema ships with `shopify_api`. Each crate that uses `graphql!` keeps the +schema of its Admin API version in `graphql/admin.schema.json`, next to its +`Cargo.toml`, and every operation of the crate is checked against it. Commit +the file: builds without network access (CI sandboxes, docs.rs) need it, and +so does a published crate. + +The version is the one your `Cargo.toml` pins, and `schema` names another +file than `graphql/admin.schema.json`, relative to that `Cargo.toml`: + +```toml +[package.metadata.shopify_api] +api-version = "2026-07" +schema = "schemas/admin-2026-07.json" # optional +``` + +The file `schema` names must be inside the package, so that `cargo package` +ships it: an absolute path, or one that climbs above `Cargo.toml` with `..`, +is a compile error. It is a relative path with `/` and portable names: no +`:`, `\`, `<>"|?*` or control character, no name ending in `.` or a space, +and no device name such as `CON`, which Windows would read as another file +or a device. A symbolic link inside the package may point elsewhere: +`cargo package` ships the content of the file it links to. + +Both keys belong to the package whose `Cargo.toml` holds them: a dependency +is always checked against the file its own `Cargo.toml` names, whatever yours +says. The file `schema` names follows the same rules as the default one: the +version is the pinned one, else the one of the file; it is downloaded only +where the default one would be; one in an older format is downloaded again, +or is a compile error. Editing either key compiles the crate again. + +Without a pin, the version is the one of the schema file: it does not change +when Shopify releases a new one, and a build gives the same result whatever +the date. With no file either, the first build takes the latest stable +version (the one before, on the first day of a quarter when Shopify has not +published it yet). `shopify-api schema download` moves an unpinned crate to +the latest version; pinning one is clearer. + +Which file a crate is checked against depends on its `Cargo.toml` only. What +happens when that file is missing, holds another version than the pinned +one, or is in a format an older `shopify_api` wrote, depends on two more +things: + +- whether cargo was asked to build the package: one of the workspace you + build, test or run, rather than a dependency of it; +- whether the package is your own source (the packages of the workspace, and + path dependencies inside it or outside), rather than a copy of a + dependency: a crate from crates.io or another registry, a git dependency, + a vendored crate, or the copy `cargo package` verifies. `graphql!` takes a + package for a copy when a `Cargo.toml.orig` sits next to its `Cargo.toml` + (cargo writes one into every packaged crate), when it has a + `.cargo-checksum.json` (vendored), when its directory or one above it + holds a `.cargo-ok` (cargo writes one at the root of every extracted + registry source and git checkout), or when it is under `$CARGO_HOME` + (`~/.cargo` by default), with or without symbolic links resolved. + +When both hold, `graphql!` downloads the file from Shopify's public endpoint. +It tries once per build: without network access, every operation fails at +once with the reason, and `graphql!` never checks against another version +than the one the operations go to. + +Otherwise it never downloads nor writes the file: it uses the one the crate +ships. When that file is missing, or does not fit, the build fails, names the +file, and names the directory where to run `shopify-api schema download`. +That includes a local library built only as a dependency of the package cargo +was asked to build (build it alone once, or download its schema), and the +verification of `cargo package`: a library that forgot to ship its schema +fails there, before it is published. A package taken for a copy by mistake +(below an unrelated `.cargo-ok`, say) fails the same way: never with another +schema. + +The `shopify-api` command (`cargo install shopify_api --features cli`) +downloads the file on demand, where `schema` says: `shopify-api schema +download`, or `shopify-api schema download --shop my-shop` for the schema a +shop's token sees. + +| The schema file of a crate (`schema`, else `graphql/admin.schema.json`) | Your own package, cargo was asked to build it | Your own package, built as a dependency | Packaged, vendored or checked out | +| --- | --- | --- | --- | +| Present, no pin | The file, never downloaded again. | The file. | The file. | +| Present, of the pinned version | The file. | The file. | The file. | +| Present, of another version or an older format | Downloaded again. | Compile error. | Compile error. | +| Missing | Downloaded: the pinned version, else the latest. | Compile error. | Compile error. | + +An operation goes to the version of the schema it was checked against: a +crate whose schema is 2026-07 calls the 2026-07 endpoint, with nothing to +configure. A client created with [`ShopifyBuilder::api_version`] sends +everything to that version instead, and logs a warning for an operation +checked against another. + +`execute` fails when `data` does not fit the operation, with the path of the +first mismatch: `` Shopify's answer does not match the operation at `orders.nodes[0]`: missing field `name` ``. +That happens when a shop runs another version than the schema, or when a test +scripts an answer that leaves out a non-null field. + +# Through a crate that re-exports `shopify_api` + +The generated code reaches `shopify_api` through `::shopify_api`. A crate +that uses `graphql!` and `input!` through a framework that re-exports them, +without `shopify_api` in its own `Cargo.toml`, names the path with `crate =`, +before anything else: + +```rust,ignore +use my_framework::{graphql, input}; + +// Inline, `,` after the path. +let operation = graphql!(crate = ::my_framework::shopify_api, "query($first: Int!) { products(first: $first) { nodes { id } } }", first = 10); +let bulk = graphql!(crate = ::my_framework::shopify_api, bulk("{ orders { edges { node { id } } } }")); + +// Modules, `;` after the path: it applies to every module of the block. +graphql! { + crate = ::my_framework::shopify_api; + pub mod products = "query($first: Int!) { products(first: $first) { nodes { id } } }"; + pub mod shop = "{ shop { name } }"; +} + +let metafield = input!(crate = ::my_framework::shopify_api, MetafieldsSetInput { + ownerId: product_id, namespace: "custom", key: "color", type: "single_line_text_field", value: color, +}); +``` + +The path is absolute, `::my_framework::shopify_api` or +`crate::path::to::shopify_api`: the generated code sits in modules of its +own, where a relative path or a name brought in by `use` does not resolve. It +cannot start with `$crate`, since serde's derive reads it as text: a +framework's `macro_rules!` wrapper writes `::my_framework::shopify_api`. +`extern crate my_framework as shopify_api;` at the root of the crate works +too, without `crate =`. + +The schema and the API version are those of the crate that writes the +operation, as always: its `graphql/admin.schema.json` and its +`[package.metadata.shopify_api]`, downloaded on the same terms, whether or not +it depends on `shopify_api` itself. + +# Limits + +- Subscriptions are refused, and one inline `graphql!` takes one operation. +- A block string whose lines are indented with different Unicode whitespace, + such as U+00A0 on one and U+2003 on another, is refused: the GraphQL parser + of `graphql!` cannot read it. Indent with spaces or tabs. +- A bulk operation follows the rules above: see [what is not checked](#what-is-not-checked). +- An error in the operation points at the whole operation; the line and + column in its message locate the mistake inside it. An error in a value + points at the value. +- A literal or an `input!` is checked against the schema of the crate where + it is written. Values of `input!` from another crate have the same Rust + type, checked against that crate's schema. +- rustc's own errors, outside the messages of `graphql!` and `input!`, name an + input object `InputObject`, `N` being a hash of its GraphQL name: when a + `Vec` mixes two input types, for one. +- A `Maybe::Null` alone has no type to infer: write `field: null`, or + `Maybe::::Null`. +- A value is a literal, a list built by `for`, or a Rust expression: there is + no `if`/`else` form; an expression that returns an `Option`, a `Maybe` or a + value of `input!` covers it. +- Enum values are checked where they are written; the `String` fields of + `Variables` and `raw(…)` are not. +- The generated code refers to `::shopify_api`: the dependency cannot be renamed. +- Names that start with `__shopify_api_` or `__SHOPIFY_API_` are reserved + to the generated code. Its bindings are hygienic, but a constant of such a + name in scope makes a pattern of the generated code refer to it: the code + then fails to compile (E0308 or E0530). It never changes meaning. +- Under `#![no_implicit_prelude]`, a literal or an `input!` that holds a Rust + expression does not compile: its messages are `#[diagnostic::on_unimplemented]`, + whose `diagnostic` namespace that attribute hides. Literals of constants, + modules and variables of scalars compile there. diff --git a/crates/shopify_api/docs/input.md b/crates/shopify_api/docs/input.md new file mode 100644 index 0000000..a935a53 --- /dev/null +++ b/crates/shopify_api/docs/input.md @@ -0,0 +1,69 @@ +The value is an [`InputObject`]: opaque, holding the JSON it is sent as, and +of one Rust type per GraphQL input object, whatever the module or the crate +of the `input!`. Values of several `input!` of one type go in one `Vec`, which +a variable of an inline [`graphql!`] or the `Variables` of a module takes as +it is: + +```rust,no_run +use shopify_api::{Shopify, graphql, input}; + +struct Row { product_id: String, color: String, digest: Option } + +async fn set_colors(shopify: &Shopify, rows: &[Row]) -> shopify_api::Result<()> { + let mut metafields = Vec::new(); + for row in rows { + if row.color.is_empty() { + continue; + } + metafields.push(input!(MetafieldsSetInput { + ownerId: &row.product_id, + namespace: "custom", + key: "color", + value: &row.color, + type: "single_line_text_field", + compareDigest?: row.digest.as_deref(), + })); + } + shopify + .execute(graphql!( + "mutation($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { userErrors { field message } } + }", + metafields = metafields, + )) + .await?; + Ok(()) +} +``` + +`TypeName` is an input object of the crate's schema; another name is a +compile error, with the closest input object. The fields follow the rules of +the [literals of `graphql!`](crate::graphql!#input-values): GraphQL names, every +required field, `?:` for a field that may be left out, enum values bare or +`raw(…)`, nested objects and lists, `[for … => …]`. A `@oneOf` input object +takes exactly one field, not `null`: `input!(ProductSetIdentifiers { handle: "shirt" })`. + +A value of another input type is refused where one is expected, with a +message that names the place and the GraphQL type it expects: + +```text +error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })` +``` + +The type given may show only as `InputObject`, `N` a hash of its name. + +A value that Shopify would not read as written, a `Float` that is not +finite, an `Int` beyond 32 bits, `null` for a non-null `JSON`, is kept as +refused: the operation that holds it fails with +[`Error::InvalidValue`](crate::Error::InvalidValue) before it is sent (see +[`graphql!`](crate::graphql!#values-shopify-would-not-read-as-written)). +`input!` needs no `?`. + +The fields are checked against the schema of the crate where `input!` is +written. A value built in another crate, against another schema or version, +has the same Rust type as long as the GraphQL name is the same. + +Through a framework that re-exports `shopify_api`, without it in the crate's +own `Cargo.toml`, the path comes first: +`input!(crate = ::my_framework::shopify_api, MetafieldsSetInput { … })` (see +[`graphql!`](crate::graphql!#through-a-crate-that-re-exports-shopify_api)). diff --git a/crates/shopify_api/examples/bulk_export.rs b/crates/shopify_api/examples/bulk_export.rs new file mode 100644 index 0000000..29b5c87 --- /dev/null +++ b/crates/shopify_api/examples/bulk_export.rs @@ -0,0 +1,62 @@ +//! Exports every variant of a shop with a bulk operation, outside the rate limit. +//! +//! ```bash +//! SHOPIFY_SHOP=my-shop SHOPIFY_CLIENT_ID=… SHOPIFY_CLIENT_SECRET=… cargo run -p shopify_api --example bulk_export +//! ``` + +use serde::Deserialize; +use shopify_api::bulk::BulkWaitOptions; +use shopify_api::{Auth, Shopify, graphql}; + +// Checked against the schema like any other operation; run as a bulk query. +graphql! { + mod variants = "{ + productVariants { + edges { node { id sku price inventoryQuantity product { title } } } + } + }"; +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct Variant { + id: String, + sku: Option, + price: String, + inventory_quantity: Option, + product: Product, +} + +#[derive(Debug, Deserialize)] +struct Product { + title: String, +} + +#[tokio::main] +async fn main() -> shopify_api::Result<()> { + let shop = std::env::var("SHOPIFY_SHOP").expect("SHOPIFY_SHOP"); + let client_id = std::env::var("SHOPIFY_CLIENT_ID").expect("SHOPIFY_CLIENT_ID"); + let client_secret = std::env::var("SHOPIFY_CLIENT_SECRET").expect("SHOPIFY_CLIENT_SECRET"); + // The client credentials grant: a store of the organization that owns the app. + let shopify = Shopify::new(shop, Auth::client_credentials(client_id, client_secret))?; + + // Read as the file downloads: an export of any size, in little memory. + let mut rows = shopify + .bulk_query_stream::(variants::QUERY, BulkWaitOptions::default()) + .await?; + let mut count = 0; + while let Some(variant) = rows.next_row().await { + let variant = variant?; + println!( + "{} {:<12} {:>8} {:>5?} {}", + variant.id, + variant.sku.as_deref().unwrap_or("-"), + variant.price, + variant.inventory_quantity, + variant.product.title + ); + count += 1; + } + println!("{count} variants"); + Ok(()) +} diff --git a/crates/shopify_api/examples/metafields.rs b/crates/shopify_api/examples/metafields.rs new file mode 100644 index 0000000..8b292c0 --- /dev/null +++ b/crates/shopify_api/examples/metafields.rs @@ -0,0 +1,95 @@ +//! Sets a `custom.color` metafield on the products listed on the command +//! line, then archives those without a color. +//! +//! ```bash +//! SHOPIFY_SHOP=my-shop SHOPIFY_ACCESS_TOKEN=shpat_… cargo run -p shopify_api --example metafields -- \ +//! gid://shopify/Product/1=blue gid://shopify/Product/2= +//! ``` + +use shopify_api::{Auth, Shopify, graphql, input}; + +graphql! { + /// Writes metafields and returns what Shopify refused. + mod metafields_set = "mutation MetafieldsSet($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { + metafields { id key value } + userErrors { field message } + } + }"; + mod shop_name = "query ShopName { shop { name } }"; +} + +struct Row { + product_id: String, + color: String, +} + +fn color_metafields(rows: &[Row]) -> Vec { + let mut metafields = Vec::new(); + for row in rows { + if row.color.is_empty() { + continue; + } + metafields.push(input!(MetafieldsSetInput { + ownerId: &row.product_id, + namespace: "custom", + key: "color", + value: &row.color, + type: "single_line_text_field", + })); + } + metafields +} + +#[tokio::main] +async fn main() -> shopify_api::Result<()> { + let shop = std::env::var("SHOPIFY_SHOP").expect("SHOPIFY_SHOP"); + let token = std::env::var("SHOPIFY_ACCESS_TOKEN").expect("SHOPIFY_ACCESS_TOKEN"); + let shopify = Shopify::new(shop, Auth::access_token(token))?; + let rows: Vec = std::env::args() + .skip(1) + .filter_map(|argument| { + let (product_id, color) = argument.split_once('=')?; + Some(Row { + product_id: product_id.to_string(), + color: color.to_string(), + }) + }) + .collect(); + + let shop = shopify.execute(shop_name::operation()).await?; + println!("{}", shop.shop.name); + + let data = shopify + .execute(metafields_set::Variables { + metafields: color_metafields(&rows), + }) + .await?; + if let Some(payload) = data.metafields_set { + for metafield in payload.metafields.into_iter().flatten() { + println!("{} = {}", metafield.key, metafield.value); + } + for error in payload.user_errors { + eprintln!("{:?}: {}", error.field, error.message); + } + } + + for row in rows.iter().filter(|row| row.color.is_empty()) { + let data = shopify + .execute(graphql!( + "mutation($product: ProductUpdateInput!) { + productUpdate(product: $product) { userErrors { field message } } + }", + product = { id: &row.product_id, status: ARCHIVED }, + )) + .await?; + for error in data + .product_update + .into_iter() + .flat_map(|payload| payload.user_errors) + { + eprintln!("{}: {:?}: {}", row.product_id, error.field, error.message); + } + } + Ok(()) +} diff --git a/crates/shopify_api/examples/products.rs b/crates/shopify_api/examples/products.rs new file mode 100644 index 0000000..142a8c9 --- /dev/null +++ b/crates/shopify_api/examples/products.rs @@ -0,0 +1,47 @@ +//! Lists the products of a shop, page after page. +//! +//! ```bash +//! SHOPIFY_SHOP=my-shop SHOPIFY_ACCESS_TOKEN=shpat_… cargo run -p shopify_api --example products +//! ``` + +use shopify_api::{Auth, Page, Shopify, graphql}; + +#[tokio::main] +async fn main() -> shopify_api::Result<()> { + let shop = std::env::var("SHOPIFY_SHOP").expect("SHOPIFY_SHOP"); + let token = std::env::var("SHOPIFY_ACCESS_TOKEN").expect("SHOPIFY_ACCESS_TOKEN"); + let shopify = Shopify::new(shop, Auth::access_token(token))?; + + let products = shopify + .paginate( + |after| { + graphql!( + "query Products($after: String) { + products(first: 100, after: $after, sortKey: TITLE) { + nodes { id title status totalInventory } + pageInfo { hasNextPage endCursor } + } + }", + after = after, + ) + }, + |data| { + let page_info = data.products.page_info; + Page::new( + data.products.nodes, + page_info.has_next_page, + page_info.end_cursor, + ) + }, + ) + .await?; + + for product in &products { + println!( + "{:<10} {:>6?} {}", + product.status, product.total_inventory, product.title + ); + } + println!("{} products", products.len()); + Ok(()) +} diff --git a/crates/shopify_api/graphql/admin.schema.json b/crates/shopify_api/graphql/admin.schema.json new file mode 100644 index 0000000..4300f96 --- /dev/null +++ b/crates/shopify_api/graphql/admin.schema.json @@ -0,0 +1,3711 @@ +{"format":2,"apiVersion":"2026-10","query":"QueryRoot","mutation":"Mutation", +"directives":{"idempotent":{"l":["FIELD"],"a":{"key":"String!"}},"include":{"l":["FIELD","FRAGMENT_SPREAD","INLINE_FRAGMENT"],"a":{"if":"Boolean!"}},"skip":{"l":["FIELD","FRAGMENT_SPREAD","INLINE_FRAGMENT"],"a":{"if":"Boolean!"}}},"types":{ +"ARN":"s", +"AbandonedCheckout":{"o":{"f":{"abandonedCheckoutUrl":"URL!","billingAddress":"MailingAddress","completedAt":"DateTime","createdAt":"DateTime!","customAttributes":"[Attribute!]!","customer":"Customer","defaultCursor":"String!","discountCodes":"[String!]!","id":"ID!","lineItems":["AbandonedCheckoutLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"lineItemsQuantity":"Int!","name":"String!","note":"String!","shippingAddress":"MailingAddress","subtotalPriceSet":"MoneyBag!","taxLines":"[TaxLine!]!","taxesIncluded":"Boolean!","totalDiscountSet":"MoneyBag!","totalDutiesSet":"MoneyBag","totalLineItemsPriceSet":"MoneyBag!","totalPriceSet":"MoneyBag!","totalTaxSet":"MoneyBag","updatedAt":"DateTime!"},"t":["Navigable","Node"],"d":{"lineItemsQuantity":"Use [AbandonedCheckoutLineItem.quantity](https://shopify.dev/api/admin-graphql/unstable/objects/AbandonedCheckoutLineItem#field-quantity) instead."}}}, +"AbandonedCheckoutConnection":{"o":{"f":{"edges":"[AbandonedCheckoutEdge!]!","nodes":"[AbandonedCheckout!]!","pageInfo":"PageInfo!"}}}, +"AbandonedCheckoutEdge":{"o":{"f":{"cursor":"String!","node":"AbandonedCheckout!"}}}, +"AbandonedCheckoutLineItem":{"o":{"f":{"components":"[AbandonedCheckoutLineItemComponent!]","customAttributes":"[Attribute!]!","discountAllocations":["DiscountAllocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"discountedTotalPriceSet":"MoneyBag!","discountedTotalPriceWithCodeDiscount":"MoneyBag!","discountedUnitPriceSet":"MoneyBag!","discountedUnitPriceWithCodeDiscount":"MoneyBag!","id":"ID!","image":"Image","originalTotalPriceSet":"MoneyBag!","originalUnitPriceSet":"MoneyBag!","parentRelationship":"AbandonedCheckoutLineItemParentRelationship","product":"Product","quantity":"Int!","sku":"String","title":"String","variant":"ProductVariant","variantTitle":"String"},"t":["Node"]}}, +"AbandonedCheckoutLineItemComponent":{"o":{"f":{"id":"ID!","image":"Image","quantity":"Int!","title":"String!","variantTitle":"String"}}}, +"AbandonedCheckoutLineItemConnection":{"o":{"f":{"edges":"[AbandonedCheckoutLineItemEdge!]!","nodes":"[AbandonedCheckoutLineItem!]!","pageInfo":"PageInfo!"}}}, +"AbandonedCheckoutLineItemEdge":{"o":{"f":{"cursor":"String!","node":"AbandonedCheckoutLineItem!"}}}, +"AbandonedCheckoutLineItemParentRelationship":{"o":{"f":{"parent":"AbandonedCheckoutLineItem!"}}}, +"AbandonedCheckoutSortKeys":{"e":["CHECKOUT_ID","CREATED_AT","CUSTOMER_NAME","ID","RELEVANCE","TOTAL_PRICE"]}, +"Abandonment":{"o":{"f":{"abandonedCheckoutPayload":"AbandonedCheckout","abandonmentType":"AbandonmentAbandonmentType!","app":"App!","cartUrl":"URL","createdAt":"DateTime!","customer":"Customer!","customerHasNoDraftOrderSinceAbandonment":"Boolean!","customerHasNoOrderSinceAbandonment":"Boolean!","daysSinceLastAbandonmentEmail":"Int!","emailSentAt":"DateTime","emailState":"AbandonmentEmailState","hoursSinceLastAbandonedCheckout":"Float","id":"ID!","inventoryAvailable":"Boolean!","isFromCustomStorefront":"Boolean!","isFromOnlineStore":"Boolean!","isFromShopApp":"Boolean!","isFromShopPay":"Boolean!","isMostSignificantAbandonment":"Boolean!","lastBrowseAbandonmentDate":"DateTime!","lastCartAbandonmentDate":"DateTime!","lastCheckoutAbandonmentDate":"DateTime!","mostRecentStep":"AbandonmentAbandonmentType!","productsAddedToCart":["CustomerVisitProductInfoConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productsViewed":["CustomerVisitProductInfoConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"visitStartedAt":"DateTime"},"t":["Node"]}}, +"AbandonmentAbandonmentType":{"e":["BROWSE","CART","CHECKOUT"]}, +"AbandonmentDeliveryState":{"e":["NOT_SENT","SENT","SCHEDULED"]}, +"AbandonmentEmailState":{"e":["NOT_SENT","SENT","SCHEDULED"]}, +"AbandonmentEmailStateUpdatePayload":{"o":{"f":{"abandonment":"Abandonment","userErrors":"[AbandonmentEmailStateUpdateUserError!]!"}}}, +"AbandonmentEmailStateUpdateUserError":{"o":{"f":{"code":"AbandonmentEmailStateUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AbandonmentEmailStateUpdateUserErrorCode":{"e":["ABANDONMENT_NOT_FOUND"]}, +"AbandonmentUpdateActivitiesDeliveryStatusesPayload":{"o":{"f":{"abandonment":"Abandonment","userErrors":"[AbandonmentUpdateActivitiesDeliveryStatusesUserError!]!"}}}, +"AbandonmentUpdateActivitiesDeliveryStatusesUserError":{"o":{"f":{"code":"AbandonmentUpdateActivitiesDeliveryStatusesUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AbandonmentUpdateActivitiesDeliveryStatusesUserErrorCode":{"e":["ABANDONMENT_NOT_FOUND","MARKETING_ACTIVITY_NOT_FOUND","DELIVERY_STATUS_INFO_NOT_FOUND"]}, +"AccessScope":{"o":{"f":{"description":"String!","handle":"String!"}}}, +"AccountType":{"e":["REGULAR","RESTRICTED","INVITED","REQUESTED","COLLABORATOR","COLLABORATOR_TEAM_MEMBER","SAML","INVITED_STORE_OWNER"]}, +"AddAllProductsOperation":{"o":{"f":{"id":"ID!","processedRowCount":"Int","rowCount":"RowCount","status":"ResourceOperationStatus!"},"t":["Node","ResourceOperation"]}}, +"AdditionalFee":{"o":{"f":{"id":"ID!","name":"String!","price":"MoneyBag!","taxLines":"[TaxLine!]!"},"t":["Node"]}}, +"AdditionalFeeSale":{"o":{"f":{"actionType":"SaleActionType!","additionalFee":"SaleAdditionalFee!","id":"ID!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"AdjustmentSale":{"o":{"f":{"actionType":"SaleActionType!","id":"ID!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"AdjustmentsSortKeys":{"e":["ID","TIME"]}, +"AllDiscountItems":{"o":{"f":{"allItems":"Boolean!"}}}, +"AnalyticsAnnotation":{"o":{"f":{"createdAt":"DateTime","createdByApp":"App","description":"String","endedAt":"DateTime","id":"ID!","source":"AnalyticsAnnotationSource!","startedAt":"DateTime!","title":"String","type":"String!","updatedAt":"DateTime"},"t":["Node"]}}, +"AnalyticsAnnotationConnection":{"o":{"f":{"edges":"[AnalyticsAnnotationEdge!]!","nodes":"[AnalyticsAnnotation!]!","pageInfo":"PageInfo!"}}}, +"AnalyticsAnnotationCreateInput":{"i":{"description":"String","endedAt":"DateTime","startedAt":"DateTime!","title":"String!","type":"String!"}}, +"AnalyticsAnnotationCreatePayload":{"o":{"f":{"analyticsAnnotation":"AnalyticsAnnotation","userErrors":"[AnalyticsAnnotationCreateUserError!]!"}}}, +"AnalyticsAnnotationCreateUserError":{"o":{"f":{"code":"AnalyticsAnnotationCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AnalyticsAnnotationCreateUserErrorCode":{"e":["LIMIT_REACHED","SHOPIFY_EMPLOYEE_IMPERSONATING","INVALID"]}, +"AnalyticsAnnotationDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[AnalyticsAnnotationDeleteUserError!]!"}}}, +"AnalyticsAnnotationDeleteUserError":{"o":{"f":{"code":"AnalyticsAnnotationDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AnalyticsAnnotationDeleteUserErrorCode":{"e":["NOT_FOUND","SHOPIFY_EMPLOYEE_IMPERSONATING","INVALID"]}, +"AnalyticsAnnotationEdge":{"o":{"f":{"cursor":"String!","node":"AnalyticsAnnotation!"}}}, +"AnalyticsAnnotationSortKeys":{"e":["CREATED_AT","ENDED_AT","ID","STARTED_AT","UPDATED_AT"]}, +"AnalyticsAnnotationSource":{"e":["SHOPIFY","STAFF","APP"]}, +"AnalyticsAnnotationUpdateInput":{"i":{"description":"String","endedAt":"DateTime","startedAt":"DateTime","title":"String","type":"String"}}, +"AnalyticsAnnotationUpdatePayload":{"o":{"f":{"analyticsAnnotation":"AnalyticsAnnotation","userErrors":"[AnalyticsAnnotationUpdateUserError!]!"}}}, +"AnalyticsAnnotationUpdateUserError":{"o":{"f":{"code":"AnalyticsAnnotationUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AnalyticsAnnotationUpdateUserErrorCode":{"e":["NOT_FOUND","SHOPIFY_EMPLOYEE_IMPERSONATING","INVALID"]}, +"AnalyticsTarget":{"o":{"f":{"createdAt":"DateTime!","currencyCode":"CurrencyCode!","endDate":"Date!","expectedValue":"Decimal!","filters":"String","id":"ID!","metric":"String!","name":"String!","presentmentExpectedValue":["MoneyV2",{"currencyCode":"CurrencyCode!"}],"shopifyqlQuery":"String","startDate":"Date!","updatedAt":"DateTime!"},"t":["Node"]}}, +"AnalyticsTargetConnection":{"o":{"f":{"edges":"[AnalyticsTargetEdge!]!","nodes":"[AnalyticsTarget!]!","pageInfo":"PageInfo!"}}}, +"AnalyticsTargetCreateInput":{"i":{"endDate":"Date!","expectedValue":"Decimal!","filters":"String","metric":"String!","name":"String!","startDate":"Date!"}}, +"AnalyticsTargetCreatePayload":{"o":{"f":{"analyticsTarget":"AnalyticsTarget","userErrors":"[AnalyticsTargetCreateUserError!]!"}}}, +"AnalyticsTargetCreateUserError":{"o":{"f":{"code":"AnalyticsTargetCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AnalyticsTargetCreateUserErrorCode":{"e":["SHOPIFY_EMPLOYEE_IMPERSONATING","INVALID_METRIC","INVALID","TAKEN"]}, +"AnalyticsTargetEdge":{"o":{"f":{"cursor":"String!","node":"AnalyticsTarget!"}}}, +"AnalyticsTargetSortKeys":{"e":["CREATED_AT","END_DATE","EXPECTED_VALUE","ID","METRIC","NAME","START_DATE"]}, +"AnalyticsTargetUpdateInput":{"i":{"endDate":"Date","expectedValue":"Decimal","filters":"String","metric":"String","name":"String","startDate":"Date"}}, +"AnalyticsTargetUpdatePayload":{"o":{"f":{"analyticsTarget":"AnalyticsTarget","userErrors":"[AnalyticsTargetUpdateUserError!]!"}}}, +"AnalyticsTargetUpdateUserError":{"o":{"f":{"code":"AnalyticsTargetUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AnalyticsTargetUpdateUserErrorCode":{"e":["NOT_FOUND","SHOPIFY_EMPLOYEE_IMPERSONATING","INVALID_METRIC","INVALID","TAKEN"]}, +"AnalyticsTargetsDeletePayload":{"o":{"f":{"deletedIds":"[ID!]","userErrors":"[AnalyticsTargetsDeleteUserError!]!"}}}, +"AnalyticsTargetsDeleteUserError":{"o":{"f":{"code":"AnalyticsTargetsDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AnalyticsTargetsDeleteUserErrorCode":{"e":["NOT_FOUND","SHOPIFY_EMPLOYEE_IMPERSONATING","INVALID"]}, +"AndroidApplication":{"o":{"f":{"appLinksEnabled":"Boolean!","applicationId":"String","id":"ID!","sha256CertFingerprints":"[String!]!"}}}, +"ApiVersion":{"o":{"f":{"displayName":"String!","handle":"String!","supported":"Boolean!"}}}, +"App":{"o":{"f":{"apiKey":"String!","appStoreAppUrl":"URL","appStoreDeveloperUrl":"URL","availableAccessScopes":"[AccessScope!]!","banner":"Image!","channels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"description":"String","developerName":"String","developerType":"AppDeveloperType!","developerUrl":"URL!","embedded":"Boolean!","failedRequirements":"[FailedRequirement!]!","features":"[String!]!","feedback":"AppFeedback","handle":"String","icon":"Image!","id":"ID!","installUrl":"URL","installation":"AppInstallation","isPostPurchaseAppInUse":"Boolean!","launchUrl":"URL!","navigationItems":"[NavigationItem!]!","optionalAccessScopes":"[AccessScope!]!","previouslyInstalled":"Boolean!","pricingDetails":"String","pricingDetailsSummary":"String!","privacyPolicyUrl":"URL","publicCategory":"AppPublicCategory!","published":"Boolean!","requestedAccessScopes":"[AccessScope!]!","screenshots":"[Image!]!","shopifyDeveloped":"Boolean!","title":"String!","uninstallMessage":"String!","uninstallUrl":"URL","webhookApiVersion":"String!"},"t":["Node"],"d":{"developerUrl":"Use `appStoreDeveloperUrl` instead.","launchUrl":"Use AppInstallation.launchUrl instead","navigationItems":"Use AppInstallation.navigationItems instead","uninstallUrl":"Use AppInstallation.uninstallUrl instead"}}}, +"AppCatalog":{"o":{"f":{"apps":["AppConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"channels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"id":"ID!","operations":"[ResourceOperation!]!","priceList":"PriceList","publication":"Publication","status":"CatalogStatus!","title":"String!"},"t":["Catalog","Node"]}}, +"AppConnection":{"o":{"f":{"edges":"[AppEdge!]!","nodes":"[App!]!","pageInfo":"PageInfo!"}}}, +"AppCredit":{"o":{"f":{"amount":"MoneyV2!","createdAt":"DateTime!","description":"String!","id":"ID!","test":"Boolean!"},"t":["Node"]}}, +"AppCreditConnection":{"o":{"f":{"edges":"[AppCreditEdge!]!","nodes":"[AppCredit!]!","pageInfo":"PageInfo!"}}}, +"AppCreditEdge":{"o":{"f":{"cursor":"String!","node":"AppCredit!"}}}, +"AppDeveloperType":{"e":["SHOPIFY","PARTNER","MERCHANT","UNKNOWN"]}, +"AppDiscountType":{"o":{"f":{"app":"App!","appBridge":"FunctionsAppBridge!","appKey":"String!","description":"String","discountClass":"DiscountClass!","discountClasses":"[DiscountClass!]!","functionId":"String!","targetType":"DiscountApplicationTargetType!","title":"String!"},"d":{"discountClass":"Use `discountClasses` instead.","targetType":"Use `discountClasses` instead."}}}, +"AppDiscountTypeConnection":{"o":{"f":{"edges":"[AppDiscountTypeEdge!]!","nodes":"[AppDiscountType!]!","pageInfo":"PageInfo!"}}}, +"AppDiscountTypeEdge":{"o":{"f":{"cursor":"String!","node":"AppDiscountType!"}}}, +"AppEdge":{"o":{"f":{"cursor":"String!","node":"App!"}}}, +"AppFeedback":{"o":{"f":{"app":"App!","channel":"Channel","feedbackGeneratedAt":"DateTime!","link":"Link","messages":"[UserError!]!","state":"ResourceFeedbackState!"}}}, +"AppInstallation":{"o":{"f":{"accessScopes":"[AccessScope!]!","activeSubscriptions":"[AppSubscription!]!","allSubscriptions":["AppSubscriptionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"AppSubscriptionSortKeys="}],"app":"App!","channel":"Channel","credits":["AppCreditConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"AppTransactionSortKeys="}],"id":"ID!","launchUrl":"URL!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"oneTimePurchases":["AppPurchaseOneTimeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"AppTransactionSortKeys="}],"publication":"Publication","revenueAttributionRecords":["AppRevenueAttributionRecordConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"AppRevenueAttributionRecordSortKeys="}],"subscriptions":"[AppSubscription!]!","uninstallUrl":"URL"},"t":["HasMetafields","Node"],"d":{"channel":"Use the root-level `channels` query instead.","publication":"Use the root-level `publications` query instead.","subscriptions":"Use `activeSubscriptions` instead."}}}, +"AppInstallationCategory":{"e":["CHANNEL","POS_EMBEDDED"]}, +"AppInstallationConnection":{"o":{"f":{"edges":"[AppInstallationEdge!]!","nodes":"[AppInstallation!]!","pageInfo":"PageInfo!"}}}, +"AppInstallationEdge":{"o":{"f":{"cursor":"String!","node":"AppInstallation!"}}}, +"AppInstallationPrivacy":{"e":["PUBLIC","PRIVATE"]}, +"AppInstallationSortKeys":{"e":["APP_TITLE","ID","INSTALLED_AT"]}, +"AppPlanInput":{"i":{"appRecurringPricingDetails":"AppRecurringPricingInput","appUsagePricingDetails":"AppUsagePricingInput"}}, +"AppPlanV2":{"o":{"f":{"pricingDetails":"AppPricingDetails!"}}}, +"AppPricingDetails":{"u":["AppRecurringPricing","AppUsagePricing"]}, +"AppPricingInterval":{"e":["ANNUAL","EVERY_30_DAYS"]}, +"AppPublicCategory":{"e":["PRIVATE","PUBLIC","CUSTOM","OTHER"]}, +"AppPurchase":{"n":{"f":{"createdAt":"DateTime!","name":"String!","price":"MoneyV2!","status":"AppPurchaseStatus!","test":"Boolean!"},"t":["AppPurchaseOneTime"]}}, +"AppPurchaseOneTime":{"o":{"f":{"createdAt":"DateTime!","id":"ID!","name":"String!","price":"MoneyV2!","status":"AppPurchaseStatus!","test":"Boolean!"},"t":["AppPurchase","Node"]}}, +"AppPurchaseOneTimeConnection":{"o":{"f":{"edges":"[AppPurchaseOneTimeEdge!]!","nodes":"[AppPurchaseOneTime!]!","pageInfo":"PageInfo!"}}}, +"AppPurchaseOneTimeCreatePayload":{"o":{"f":{"appPurchaseOneTime":"AppPurchaseOneTime","confirmationUrl":"URL","userErrors":"[UserError!]!"}}}, +"AppPurchaseOneTimeEdge":{"o":{"f":{"cursor":"String!","node":"AppPurchaseOneTime!"}}}, +"AppPurchaseStatus":{"e":{"v":["ACCEPTED","ACTIVE","DECLINED","EXPIRED","PENDING"],"d":{"ACCEPTED":"When a merchant accepts an app purchase, the status immediately changes from `pending` to `active`."}}}, +"AppRecurringPricing":{"o":{"f":{"discount":"AppSubscriptionDiscount","interval":"AppPricingInterval!","planHandle":"String","price":"MoneyV2!"}}}, +"AppRecurringPricingInput":{"i":{"discount":"AppSubscriptionDiscountInput","interval":"AppPricingInterval=","price":"MoneyInput!"}}, +"AppRevenueAttributionRecord":{"o":{"f":{"amount":"MoneyV2!","capturedAt":"DateTime!","createdAt":"DateTime!","id":"ID!","idempotencyKey":"String!","test":"Boolean!","type":"AppRevenueAttributionType!"},"t":["Node"]}}, +"AppRevenueAttributionRecordConnection":{"o":{"f":{"edges":"[AppRevenueAttributionRecordEdge!]!","nodes":"[AppRevenueAttributionRecord!]!","pageInfo":"PageInfo!"}}}, +"AppRevenueAttributionRecordEdge":{"o":{"f":{"cursor":"String!","node":"AppRevenueAttributionRecord!"}}}, +"AppRevenueAttributionRecordSortKeys":{"e":["CREATED_AT","ID"]}, +"AppRevenueAttributionType":{"e":["APPLICATION_PURCHASE","APPLICATION_SUBSCRIPTION","APPLICATION_USAGE","OTHER"]}, +"AppRevokeAccessScopesAppRevokeScopeError":{"o":{"f":{"code":"AppRevokeAccessScopesAppRevokeScopeErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AppRevokeAccessScopesAppRevokeScopeErrorCode":{"e":["MISSING_SOURCE_APP","APPLICATION_CANNOT_BE_FOUND","UNKNOWN_SCOPES","CANNOT_REVOKE_REQUIRED_SCOPES","CANNOT_REVOKE_IMPLIED_SCOPES","CANNOT_REVOKE_UNDECLARED_SCOPES","APP_NOT_INSTALLED"]}, +"AppRevokeAccessScopesPayload":{"o":{"f":{"revoked":"[AccessScope!]","userErrors":"[AppRevokeAccessScopesAppRevokeScopeError!]!"}}}, +"AppSubscription":{"o":{"f":{"createdAt":"DateTime!","currentPeriodEnd":"DateTime","id":"ID!","lineItems":"[AppSubscriptionLineItem!]!","name":"String!","returnUrl":"URL!","status":"AppSubscriptionStatus!","test":"Boolean!","trialDays":"Int!"},"t":["Node"]}}, +"AppSubscriptionCancelPayload":{"o":{"f":{"appSubscription":"AppSubscription","userErrors":"[UserError!]!"}}}, +"AppSubscriptionConnection":{"o":{"f":{"edges":"[AppSubscriptionEdge!]!","nodes":"[AppSubscription!]!","pageInfo":"PageInfo!"}}}, +"AppSubscriptionCreatePayload":{"o":{"f":{"appSubscription":"AppSubscription","confirmationUrl":"URL","userErrors":"[UserError!]!"}}}, +"AppSubscriptionDiscount":{"o":{"f":{"durationLimitInIntervals":"Int","priceAfterDiscount":"MoneyV2!","remainingDurationInIntervals":"Int","value":"AppSubscriptionDiscountValue!"}}}, +"AppSubscriptionDiscountAmount":{"o":{"f":{"amount":"MoneyV2!"}}}, +"AppSubscriptionDiscountInput":{"i":{"durationLimitInIntervals":"Int","value":"AppSubscriptionDiscountValueInput"}}, +"AppSubscriptionDiscountPercentage":{"o":{"f":{"percentage":"Float!"}}}, +"AppSubscriptionDiscountValue":{"u":["AppSubscriptionDiscountAmount","AppSubscriptionDiscountPercentage"]}, +"AppSubscriptionDiscountValueInput":{"i":{"amount":"Decimal","percentage":"Float"}}, +"AppSubscriptionEdge":{"o":{"f":{"cursor":"String!","node":"AppSubscription!"}}}, +"AppSubscriptionLineItem":{"o":{"f":{"id":"ID!","plan":"AppPlanV2!","usageRecords":["AppUsageRecordConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"AppUsageRecordSortKeys="}]}}}, +"AppSubscriptionLineItemInput":{"i":{"plan":"AppPlanInput!"}}, +"AppSubscriptionLineItemUpdatePayload":{"o":{"f":{"appSubscription":"AppSubscription","confirmationUrl":"URL","userErrors":"[UserError!]!"}}}, +"AppSubscriptionReplacementBehavior":{"e":["APPLY_IMMEDIATELY","APPLY_ON_NEXT_BILLING_CYCLE","STANDARD"]}, +"AppSubscriptionSortKeys":{"e":["CREATED_AT","ID"]}, +"AppSubscriptionStatus":{"e":{"v":["PENDING","ACCEPTED","ACTIVE","DECLINED","EXPIRED","FROZEN","CANCELLED"],"d":{"ACCEPTED":"When a merchant approves an app subscription, the status immediately transitions from `pending` to `active`."}}}, +"AppSubscriptionTrialExtendPayload":{"o":{"f":{"appSubscription":"AppSubscription","userErrors":"[AppSubscriptionTrialExtendUserError!]!"}}}, +"AppSubscriptionTrialExtendUserError":{"o":{"f":{"code":"AppSubscriptionTrialExtendUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AppSubscriptionTrialExtendUserErrorCode":{"e":["SUBSCRIPTION_NOT_FOUND","TRIAL_NOT_ACTIVE","SUBSCRIPTION_NOT_ACTIVE"]}, +"AppTransactionSortKeys":{"e":["CREATED_AT","ID"]}, +"AppUninstallAppUninstallError":{"o":{"f":{"code":"AppUninstallAppUninstallErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"AppUninstallAppUninstallErrorCode":{"e":["APP_NOT_FOUND","APP_NOT_INSTALLED","USER_PERMISSIONS_INSUFFICIENT","APP_UNINSTALL_ERROR"]}, +"AppUninstallPayload":{"o":{"f":{"app":"App","userErrors":"[AppUninstallAppUninstallError!]!"}}}, +"AppUsagePricing":{"o":{"f":{"balanceUsed":"MoneyV2!","cappedAmount":"MoneyV2!","interval":"AppPricingInterval!","terms":"String!"}}}, +"AppUsagePricingInput":{"i":{"cappedAmount":"MoneyInput!","terms":"String!"}}, +"AppUsageRecord":{"o":{"f":{"createdAt":"DateTime!","description":"String!","id":"ID!","idempotencyKey":"String","price":"MoneyV2!","subscriptionLineItem":"AppSubscriptionLineItem!"},"t":["Node"]}}, +"AppUsageRecordConnection":{"o":{"f":{"edges":"[AppUsageRecordEdge!]!","nodes":"[AppUsageRecord!]!","pageInfo":"PageInfo!"}}}, +"AppUsageRecordCreatePayload":{"o":{"f":{"appUsageRecord":"AppUsageRecord","userErrors":"[UserError!]!"}}}, +"AppUsageRecordEdge":{"o":{"f":{"cursor":"String!","node":"AppUsageRecord!"}}}, +"AppUsageRecordSortKeys":{"e":["CREATED_AT","ID"]}, +"AppleApplication":{"o":{"f":{"appClipApplicationId":"String","appClipsEnabled":"Boolean!","appId":"String","id":"ID!","sharedWebCredentialsEnabled":"Boolean!","universalLinksEnabled":"Boolean!"}}}, +"Article":{"o":{"f":{"author":"ArticleAuthor","blog":"Blog!","body":"HTML!","comments":["CommentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"commentsCount":["Count",{"limit":"Int=","query":"String"}],"createdAt":"DateTime!","defaultCursor":"String!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"handle":"String!","id":"ID!","image":"Image","isPublished":"Boolean!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"publishedAt":"DateTime","summary":"HTML","tags":"[String!]!","templateSuffix":"String","title":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"updatedAt":"DateTime"},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","Navigable","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"ArticleAuthor":{"o":{"f":{"name":"String!"}}}, +"ArticleAuthorConnection":{"o":{"f":{"edges":"[ArticleAuthorEdge!]!","nodes":"[ArticleAuthor!]!","pageInfo":"PageInfo!"}}}, +"ArticleAuthorEdge":{"o":{"f":{"cursor":"String!","node":"ArticleAuthor!"}}}, +"ArticleBlogInput":{"i":{"title":"String!"}}, +"ArticleConnection":{"o":{"f":{"edges":"[ArticleEdge!]!","nodes":"[Article!]!","pageInfo":"PageInfo!"}}}, +"ArticleCreateInput":{"i":{"author":"AuthorInput!","blogId":"ID","body":"HTML","handle":"String","image":"ArticleImageInput","isPublished":"Boolean","metafields":"[MetafieldInput!]","publishDate":"DateTime","summary":"HTML","tags":"[String!]","templateSuffix":"String","title":"String!"}}, +"ArticleCreatePayload":{"o":{"f":{"article":"Article","userErrors":"[ArticleCreateUserError!]!"}}}, +"ArticleCreateUserError":{"o":{"f":{"code":"ArticleCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ArticleCreateUserErrorCode":{"e":["AMBIGUOUS_AUTHOR","AMBIGUOUS_BLOG","AUTHOR_FIELD_REQUIRED","AUTHOR_MUST_EXIST","INVALID_PUBLISH_DATE","BLOG_REFERENCE_REQUIRED","UPLOAD_FAILED","BLANK","NOT_FOUND","TOO_LONG","TOO_SHORT","TAKEN","INVALID","INVALID_VALUE","INVALID_TYPE"]}, +"ArticleDeletePayload":{"o":{"f":{"deletedArticleId":"ID","userErrors":"[ArticleDeleteUserError!]!"}}}, +"ArticleDeleteUserError":{"o":{"f":{"code":"ArticleDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ArticleDeleteUserErrorCode":{"e":["NOT_FOUND"]}, +"ArticleEdge":{"o":{"f":{"cursor":"String!","node":"Article!"}}}, +"ArticleImageInput":{"i":{"altText":"String","url":"String"}}, +"ArticleSortKeys":{"e":["AUTHOR","BLOG_TITLE","ID","PUBLISHED_AT","TITLE","UPDATED_AT"]}, +"ArticleTagSort":{"e":["ALPHABETICAL","POPULAR"]}, +"ArticleUpdateInput":{"i":{"author":"AuthorInput","blogId":"ID","body":"HTML","handle":"String","image":"ArticleImageInput","isPublished":"Boolean","metafields":"[MetafieldInput!]","publishDate":"DateTime","redirectNewHandle":"Boolean=","summary":"HTML","tags":"[String!]","templateSuffix":"String","title":"String"}}, +"ArticleUpdatePayload":{"o":{"f":{"article":"Article","userErrors":"[ArticleUpdateUserError!]!"}}}, +"ArticleUpdateUserError":{"o":{"f":{"code":"ArticleUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ArticleUpdateUserErrorCode":{"e":["AMBIGUOUS_AUTHOR","AMBIGUOUS_BLOG","AUTHOR_MUST_EXIST","INVALID_PUBLISH_DATE","UPLOAD_FAILED","BLANK","NOT_FOUND","TOO_LONG","TAKEN","INVALID","INVALID_VALUE","INVALID_TYPE"]}, +"Attribute":{"o":{"f":{"key":"String!","value":"String"}}}, +"AttributeInput":{"i":{"key":"String!","value":"String!"}}, +"Audience":{"e":["CUSTOMERVIEW","MERCHANTVIEW"]}, +"AuditTrailAdjustment":{"o":{"f":{"label":"String!","price":"MoneyV2!","type":"AuditTrailAdjustmentType!","value":"Decimal!"}}}, +"AuditTrailAdjustmentType":{"e":["ADDITION","MULTIPLICATION","REPLACEMENT"]}, +"AuthorInput":{"i":{"name":"String","userId":"ID"}}, +"AutomaticDiscountApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","index":"Int!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","title":"String!","value":"PricingValue!"},"t":["DiscountApplication"]}}, +"AutomaticDiscountSortKeys":{"e":["CREATED_AT","ID"]}, +"AvailableChannelDefinitionsByChannel":{"o":{"f":{"channelDefinitions":"[ChannelDefinition!]!","channelName":"String!"},"d":{"channelDefinitions":"Use [`QueryRoot.orderAttributionDefinitions`](https://shopify.dev/docs/api/admin-graphql/latest/queries/orderAttributionDefinitions) and select `id`, `handle`, `displayName`, and `icon` instead.","channelName":"Use [`OrderAttributionDefinition.displayName`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttributionDefinition#field-OrderAttributionDefinition.fields.displayName) instead."}}}, +"B2BType":{"o":{"f":{"enabled":"Boolean!"}}}, +"BackupRegionUpdateInput":{"i":{"countryCode":"CountryCode!"}}, +"BackupRegionUpdatePayload":{"o":{"f":{"backupRegion":"MarketRegion","userErrors":"[MarketUserError!]!"}}}, +"BadgeType":{"e":["DEFAULT","SUCCESS","ATTENTION","WARNING","INFO","CRITICAL"]}, +"BalanceTransactionSortKeys":{"e":["AMOUNT","FEE","ID","NET","ORDER_NAME","PAYMENT_METHOD_NAME","PAYOUT_DATE","PAYOUT_STATUS","PROCESSED_AT","TRANSACTION_TYPE"]}, +"BankAccount":{"o":{"f":{"accountHolderType":"BankAccountHolderType!","accountType":"BankAccountType!","bankName":"String!","billingAddress":"CustomerPaymentInstrumentBillingAddress","lastDigits":"String!"}}}, +"BankAccountHolderType":{"e":["COMPANY","INDIVIDUAL"]}, +"BankAccountType":{"e":["CHECKING","SAVINGS"]}, +"BankingFinanceAppAccess":{"e":["READ_ACCESS","MOVE_MONEY","MONEY_MOVEMENT_RESTRICTED","MONEY_MOVEMENT_BLOCKED_MFA"]}, +"BarcodeInput":{"i":{"type":"BarcodeType","value":"String!"}}, +"BarcodeType":{"e":["UPC","EAN","ISBN","GTIN","ASIN","NS_PID"]}, +"BasePaymentDetails":{"n":{"f":{"paymentMethodName":"String"},"t":["CardPaymentDetails","LocalPaymentMethodsPaymentDetails","PaypalWalletPaymentDetails","ShopPayInstallmentsPaymentDetails"]}}, +"BasicEvent":{"o":{"f":{"action":"String!","additionalContent":"JSON","additionalData":"JSON","appTitle":"String","arguments":"JSON","attributeToApp":"Boolean!","attributeToUser":"Boolean!","author":"String","createdAt":"DateTime!","criticalAlert":"Boolean!","hasAdditionalContent":"Boolean!","id":"ID!","message":"FormattedString!","secondaryMessage":"FormattedString","subject":"HasEvents","subjectId":"ID!","subjectType":"EventSubjectType!"},"t":["Event","Node"]}}, +"BigInt":"s", +"BillingAttemptUserError":{"o":{"f":{"code":"BillingAttemptUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BillingAttemptUserErrorCode":{"e":["INVALID","BLANK","CONTRACT_NOT_FOUND","ORIGIN_TIME_BEFORE_CONTRACT_CREATION","UPCOMING_CYCLE_LIMIT_EXCEEDED","CYCLE_INDEX_OUT_OF_RANGE","CYCLE_START_DATE_OUT_OF_RANGE","ORIGIN_TIME_OUT_OF_RANGE","BILLING_CYCLE_CHARGE_BEFORE_EXPECTED_DATE","BILLING_CYCLE_SKIPPED","CONTRACT_UNDER_REVIEW","CONTRACT_TERMINATED","CONTRACT_PAUSED","THROTTLED","PROCESSING_FAILED"]}, +"Blog":{"o":{"f":{"articles":["ArticleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"articlesCount":["Count",{"limit":"Int="}],"commentPolicy":"CommentPolicy!","createdAt":"DateTime!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"feed":"BlogFeed","handle":"String!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"tags":"[String!]!","templateSuffix":"String","title":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"updatedAt":"DateTime"},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"BlogConnection":{"o":{"f":{"edges":"[BlogEdge!]!","nodes":"[Blog!]!","pageInfo":"PageInfo!"}}}, +"BlogCreateInput":{"i":{"commentPolicy":"CommentPolicy","handle":"String","metafields":"[MetafieldInput!]","templateSuffix":"String","title":"String!"}}, +"BlogCreatePayload":{"o":{"f":{"blog":"Blog","userErrors":"[BlogCreateUserError!]!"}}}, +"BlogCreateUserError":{"o":{"f":{"code":"BlogCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BlogCreateUserErrorCode":{"e":["BLANK","INVALID","TOO_LONG","INCLUSION","INVALID_VALUE","INVALID_TYPE"]}, +"BlogDeletePayload":{"o":{"f":{"deletedBlogId":"ID","userErrors":"[BlogDeleteUserError!]!"}}}, +"BlogDeleteUserError":{"o":{"f":{"code":"BlogDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BlogDeleteUserErrorCode":{"e":["NOT_FOUND"]}, +"BlogEdge":{"o":{"f":{"cursor":"String!","node":"Blog!"}}}, +"BlogFeed":{"o":{"f":{"location":"URL!","path":"String!"}}}, +"BlogSortKeys":{"e":["HANDLE","ID","TITLE"]}, +"BlogUpdateInput":{"i":{"commentPolicy":"CommentPolicy","handle":"String","metafields":"[MetafieldInput!]","redirectArticles":"Boolean=","redirectNewHandle":"Boolean=","templateSuffix":"String","title":"String"}}, +"BlogUpdatePayload":{"o":{"f":{"blog":"Blog","userErrors":"[BlogUpdateUserError!]!"}}}, +"BlogUpdateUserError":{"o":{"f":{"code":"BlogUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BlogUpdateUserErrorCode":{"e":["NOT_FOUND","INVALID","BLANK","TOO_LONG","INCLUSION"]}, +"Boolean":"s", +"BulkMutationErrorCode":{"e":["OPERATION_IN_PROGRESS","INVALID_MUTATION","INVALID_STAGED_UPLOAD_FILE","NO_SUCH_FILE","INTERNAL_FILE_SERVER_ERROR","LIMIT_REACHED"]}, +"BulkMutationUserError":{"o":{"f":{"code":"BulkMutationErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BulkOperation":{"o":{"f":{"completedAt":"DateTime","createdAt":"DateTime!","errorCode":"BulkOperationErrorCode","fileSize":"UnsignedInt64","id":"ID!","objectCount":"UnsignedInt64!","partialDataUrl":"URL","query":"String!","rootObjectCount":"UnsignedInt64!","status":"BulkOperationStatus!","type":"BulkOperationType!","url":"URL"},"t":["Node"]}}, +"BulkOperationCancelPayload":{"o":{"f":{"bulkOperation":"BulkOperation","userErrors":"[UserError!]!"}}}, +"BulkOperationConnection":{"o":{"f":{"edges":"[BulkOperationEdge!]!","nodes":"[BulkOperation!]!","pageInfo":"PageInfo!"}}}, +"BulkOperationEdge":{"o":{"f":{"cursor":"String!","node":"BulkOperation!"}}}, +"BulkOperationErrorCode":{"e":["ACCESS_DENIED","INTERNAL_SERVER_ERROR","TIMEOUT"]}, +"BulkOperationRunMutationPayload":{"o":{"f":{"bulkOperation":"BulkOperation","userErrors":"[BulkMutationUserError!]!"}}}, +"BulkOperationRunQueryPayload":{"o":{"f":{"bulkOperation":"BulkOperation","userErrors":"[BulkOperationUserError!]!"}}}, +"BulkOperationStatus":{"e":["CANCELED","CANCELING","COMPLETED","CREATED","EXPIRED","FAILED","RUNNING"]}, +"BulkOperationType":{"e":["QUERY","MUTATION"]}, +"BulkOperationUserError":{"o":{"f":{"code":"BulkOperationUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BulkOperationUserErrorCode":{"e":["OPERATION_IN_PROGRESS","INVALID","LIMIT_REACHED"]}, +"BulkOperationsSortKeys":{"e":["COMPLETED_AT","CREATED_AT"]}, +"BulkProductResourceFeedbackCreatePayload":{"o":{"f":{"feedback":"[ProductResourceFeedback!]","userErrors":"[BulkProductResourceFeedbackCreateUserError!]!"}}}, +"BulkProductResourceFeedbackCreateUserError":{"o":{"f":{"code":"BulkProductResourceFeedbackCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BulkProductResourceFeedbackCreateUserErrorCode":{"e":["MAXIMUM_FEEDBACK_LIMIT_EXCEEDED","OUTDATED_FEEDBACK","PRODUCT_NOT_FOUND","NOT_FOUND","INVALID","BLANK","PRESENT","LESS_THAN_OR_EQUAL_TO"]}, +"BundlesDraftOrderBundleLineItemComponentInput":{"i":{"quantity":"Int!","uuid":"String","variantId":"ID"}}, +"BundlesFeature":{"o":{"f":{"eligibleForBundles":"Boolean!","ineligibilityReason":"String","sellsBundles":"Boolean!"}}}, +"BusinessCustomerErrorCode":{"e":["INTERNAL_ERROR","RESOURCE_NOT_FOUND","FAILED_TO_DELETE","REQUIRED","NO_INPUT","INVALID_INPUT","UNEXPECTED_TYPE","TOO_LONG","LIMIT_REACHED","INVALID","BLANK","TAKEN"]}, +"BusinessCustomerUserError":{"o":{"f":{"code":"BusinessCustomerErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"BusinessEntity":{"o":{"f":{"address":"BusinessEntityAddress!","archived":"Boolean!","companyName":"String","displayName":"String!","id":"ID!","legalEntityId":"BigInt","primary":"Boolean!","shopifyPaymentsAccount":"ShopifyPaymentsAccount"},"t":["Node"]}}, +"BusinessEntityAddress":{"o":{"f":{"address1":"String","address2":"String","city":"String","countryCode":"CountryCode!","province":"String","zip":"String"}}}, +"BuyerExperienceConfiguration":{"o":{"f":{"checkoutToDraft":"Boolean!","deposit":"DepositConfiguration","editableShippingAddress":"Boolean!","payNowOnly":"Boolean!","paymentTermsTemplate":"PaymentTermsTemplate"},"d":{"payNowOnly":"Please use `checkoutToDraft`(must be false) and `paymentTermsTemplate`(must be nil) to derive this instead."}}}, +"BuyerExperienceConfigurationInput":{"i":{"checkoutToDraft":"Boolean","deposit":"DepositInput","editableShippingAddress":"Boolean","paymentTermsTemplateId":"ID"}}, +"BuyerSignalInput":{"i":{"countryCode":"CountryCode!"}}, +"CalculateExchangeLineItemInput":{"i":{"appliedDiscount":"ExchangeLineItemAppliedDiscountInput","quantity":"Int!","variantId":"ID"}}, +"CalculateRequestedOrderEditInput":{"i":{"lineItems":"CalculateRequestedOrderEditLineItemsInput!","orderId":"ID!"}}, +"CalculateRequestedOrderEditLineItemRemovalInput":{"i":{"lineItemId":"ID!","quantity":"Int!"}}, +"CalculateRequestedOrderEditLineItemsInput":{"i":{"removals":"[CalculateRequestedOrderEditLineItemRemovalInput!]!"}}, +"CalculateReturnInput":{"i":{"exchangeLineItems":"[CalculateExchangeLineItemInput!]=","orderId":"ID!","returnLineItems":"[CalculateReturnLineItemInput!]=","returnShippingFee":"ReturnShippingFeeInput"}}, +"CalculateReturnLineItemInput":{"i":{"fulfillmentLineItemId":"ID!","quantity":"Int!","restockingFee":"RestockingFeeInput"}}, +"CalculatedAutomaticDiscountApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","appliedTo":"DiscountApplicationLevel!","description":"String","id":"ID!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","value":"PricingValue!"},"t":["CalculatedDiscountApplication"]}}, +"CalculatedDiscountAllocation":{"o":{"f":{"allocatedAmountSet":"MoneyBag!","discountApplication":"CalculatedDiscountApplication!"}}}, +"CalculatedDiscountApplication":{"n":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","appliedTo":"DiscountApplicationLevel!","description":"String","id":"ID!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","value":"PricingValue!"},"t":["CalculatedAutomaticDiscountApplication","CalculatedDiscountCodeApplication","CalculatedManualDiscountApplication","CalculatedScriptDiscountApplication"]}}, +"CalculatedDiscountApplicationConnection":{"o":{"f":{"edges":"[CalculatedDiscountApplicationEdge!]!","nodes":"[CalculatedDiscountApplication!]!","pageInfo":"PageInfo!"}}}, +"CalculatedDiscountApplicationEdge":{"o":{"f":{"cursor":"String!","node":"CalculatedDiscountApplication!"}}}, +"CalculatedDiscountCodeApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","appliedTo":"DiscountApplicationLevel!","code":"String!","description":"String","id":"ID!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","value":"PricingValue!"},"t":["CalculatedDiscountApplication"]}}, +"CalculatedDraftOrder":{"o":{"f":{"acceptAutomaticDiscounts":"Boolean","alerts":"[ResourceAlert!]!","allVariantPricesOverridden":"Boolean!","amountDueLaterSet":"MoneyBag!","amountDueNowSet":"MoneyBag!","anyVariantPricesOverridden":"Boolean!","appliedDiscount":"DraftOrderAppliedDiscount","availableShippingRates":"[ShippingRate!]!","billingAddressMatchesShippingAddress":"Boolean!","currencyCode":"CurrencyCode!","customer":"Customer","deposit":"DepositConfiguration","discountCodes":"[String!]!","lineItems":"[CalculatedDraftOrderLineItem!]!","lineItemsSubtotalPrice":"MoneyBag!","marketName":"String!","marketRegionCountryCode":"CountryCode!","phone":"String","platformDiscounts":"[DraftOrderPlatformDiscount!]!","presentmentCurrencyCode":"CurrencyCode!","purchasingEntity":"PurchasingEntity","shippingLine":"ShippingLine","subtotalPrice":"Money!","subtotalPriceSet":"MoneyBag!","taxLines":"[TaxLine!]!","taxesIncluded":"Boolean!","totalDiscountsSet":"MoneyBag!","totalLineItemsPriceSet":"MoneyBag!","totalPrice":"Money!","totalPriceSet":"MoneyBag!","totalQuantityOfLineItems":"Int!","totalShippingPrice":"Money!","totalShippingPriceSet":"MoneyBag!","totalTax":"Money!","totalTaxSet":"MoneyBag!","transformerFingerprint":"String","warnings":"[DraftOrderWarning!]!"},"d":{"marketName":"This field is now incompatible with Markets.","marketRegionCountryCode":"This field is now incompatible with Markets.","subtotalPrice":"Use `subtotalPriceSet` instead.","totalPrice":"Use `totalPriceSet` instead.","totalShippingPrice":"Use `totalShippingPriceSet` instead.","totalTax":"Use `totalTaxSet` instead."}}}, +"CalculatedDraftOrderLineItem":{"o":{"f":{"appliedDiscount":"DraftOrderAppliedDiscount","approximateDiscountedUnitPriceSet":"MoneyBag!","bundleComponents":"[CalculatedDraftOrderLineItem!]!","components":"[CalculatedDraftOrderLineItem!]!","custom":"Boolean!","customAttributes":"[Attribute!]!","customAttributesV2":"[TypedAttribute!]!","discountedTotal":"MoneyV2!","discountedTotalSet":"MoneyBag!","discountedUnitPrice":"MoneyV2!","discountedUnitPriceSet":"MoneyBag!","fulfillmentService":"FulfillmentService","image":"Image","isGiftCard":"Boolean!","name":"String!","originalTotal":"MoneyV2!","originalTotalSet":"MoneyBag!","originalUnitPrice":"MoneyV2!","originalUnitPriceSet":"MoneyBag!","originalUnitPriceWithCurrency":"MoneyV2","priceOverride":"MoneyV2","product":"Product","quantity":"Int!","requiresShipping":"Boolean!","sku":"String","taxable":"Boolean!","title":"String!","totalDiscount":"MoneyV2!","totalDiscountSet":"MoneyBag!","uuid":"String!","variant":"ProductVariant","variantTitle":"String","vendor":"String","weight":"Weight"},"d":{"bundleComponents":"Use `components` instead.","discountedUnitPrice":"Use `approximateDiscountedUnitPriceSet` instead.","discountedUnitPriceSet":"Use `approximateDiscountedUnitPriceSet` instead."}}}, +"CalculatedExchangeLineItem":{"o":{"f":{"calculatedDiscountAllocations":"[CalculatedDiscountAllocation!]!","discountedUnitPriceSet":"MoneyBag!","id":"ID","originalUnitPriceSet":"MoneyBag!","quantity":"Int!","subtotalSet":"MoneyBag!","totalTaxSet":"MoneyBag!","variant":"ProductVariant"}}}, +"CalculatedLineItem":{"o":{"f":{"calculatedDiscountAllocations":"[CalculatedDiscountAllocation!]!","customAttributes":"[Attribute!]!","discountAllocations":"[DiscountAllocation!]!","discountedUnitPriceSet":"MoneyBag!","editableQuantity":"Int!","editableQuantityBeforeChanges":"Int!","editableSubtotalSet":"MoneyBag!","hasStagedLineItemDiscount":"Boolean!","id":"ID!","image":"Image","originalUnitPriceSet":"MoneyBag!","quantity":"Int!","restockable":"Boolean!","restocking":"Boolean!","sku":"String","stagedChanges":"[OrderStagedChange!]!","title":"String!","uneditableSubtotalSet":"MoneyBag!","variant":"ProductVariant","variantTitle":"String"},"d":{"discountAllocations":"Use `calculatedDiscountAllocations` instead."}}}, +"CalculatedLineItemConnection":{"o":{"f":{"edges":"[CalculatedLineItemEdge!]!","nodes":"[CalculatedLineItem!]!","pageInfo":"PageInfo!"}}}, +"CalculatedLineItemEdge":{"o":{"f":{"cursor":"String!","node":"CalculatedLineItem!"}}}, +"CalculatedManualDiscountApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","appliedTo":"DiscountApplicationLevel!","description":"String","id":"ID!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","value":"PricingValue!"},"t":["CalculatedDiscountApplication"]}}, +"CalculatedOrder":{"o":{"f":{"addedDiscountApplications":["CalculatedDiscountApplicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"addedLineItems":["CalculatedLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"cartDiscountAmountSet":"MoneyBag","committed":"Boolean!","id":"ID!","lineItems":["CalculatedLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"notificationPreviewHtml":"HTML","notificationPreviewTitle":"String!","originalOrder":"Order!","shippingLines":"[CalculatedShippingLine!]!","stagedChanges":["OrderStagedChangeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"subtotalLineItemsQuantity":"Int!","subtotalPriceSet":"MoneyBag","taxLines":"[TaxLine!]!","totalOutstandingSet":"MoneyBag!","totalPriceSet":"MoneyBag!"},"t":["Node"],"d":{"committed":"CalculatedOrder for committed order edits is being deprecated, and this field will also be removed in a future version. See [changelog](https://shopify.dev/changelog/deprecation-notice-calculatedorder-for-committed-order-edits) for more details."}}}, +"CalculatedRequestedOrderEdit":{"o":{"f":{"financialSummary":"RequestedOrderEditFinancialSummary!","lineItems":"CalculatedRequestedOrderEditLineItems!"}}}, +"CalculatedRequestedOrderEditLineItem":{"o":{"f":{"lineItem":"LineItem!","quantity":"Int!","subtotalSet":"MoneyBag!","totalTaxSet":"MoneyBag!"}}}, +"CalculatedRequestedOrderEditLineItemConnection":{"o":{"f":{"edges":"[CalculatedRequestedOrderEditLineItemEdge!]!","nodes":"[CalculatedRequestedOrderEditLineItem!]!","pageInfo":"PageInfo!"}}}, +"CalculatedRequestedOrderEditLineItemEdge":{"o":{"f":{"cursor":"String!","node":"CalculatedRequestedOrderEditLineItem!"}}}, +"CalculatedRequestedOrderEditLineItems":{"o":{"f":{"removals":["CalculatedRequestedOrderEditLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"CalculatedRestockingFee":{"o":{"f":{"amountSet":"MoneyBag!","id":"ID!","percentage":"Float!"},"t":["CalculatedReturnFee"]}}, +"CalculatedReturn":{"o":{"f":{"exchangeLineItems":"[CalculatedExchangeLineItem!]!","id":"ID!","returnLineItems":"[CalculatedReturnLineItem!]!","returnShippingFee":"CalculatedReturnShippingFee"}}}, +"CalculatedReturnFee":{"n":{"f":{"amountSet":"MoneyBag!","id":"ID!"},"t":["CalculatedRestockingFee","CalculatedReturnShippingFee"]}}, +"CalculatedReturnLineItem":{"o":{"f":{"fulfillmentLineItem":"FulfillmentLineItem!","id":"ID","quantity":"Int!","restockingFee":"CalculatedRestockingFee","subtotalBeforeOrderDiscountsSet":"MoneyBag!","subtotalSet":"MoneyBag!","totalTaxSet":"MoneyBag!"}}}, +"CalculatedReturnShippingFee":{"o":{"f":{"amountSet":"MoneyBag!","id":"ID!","taxAmountSet":"MoneyBag!"},"t":["CalculatedReturnFee"]}}, +"CalculatedScriptDiscountApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","appliedTo":"DiscountApplicationLevel!","description":"String","id":"ID!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","value":"PricingValue!"},"t":["CalculatedDiscountApplication"]}}, +"CalculatedShippingLine":{"o":{"f":{"id":"ID","price":"MoneyBag!","stagedStatus":"CalculatedShippingLineStagedStatus!","title":"String!"}}}, +"CalculatedShippingLineStagedStatus":{"e":["NONE","ADDED","REMOVED"]}, +"CardPaymentDetails":{"o":{"f":{"avsResultCode":"String","bin":"String","company":"String","createdAt":"DateTime!","cvvResultCode":"String","expirationMonth":"Int","expirationYear":"Int","name":"String","number":"String","paymentMethodName":"String","wallet":"DigitalWallet"},"t":["BasePaymentDetails"]}}, +"CarrierServiceCreatePayload":{"o":{"f":{"carrierService":"DeliveryCarrierService","userErrors":"[CarrierServiceCreateUserError!]!"}}}, +"CarrierServiceCreateUserError":{"o":{"f":{"code":"CarrierServiceCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CarrierServiceCreateUserErrorCode":{"e":["CARRIER_SERVICE_CREATE_FAILED"]}, +"CarrierServiceDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[CarrierServiceDeleteUserError!]!"}}}, +"CarrierServiceDeleteUserError":{"o":{"f":{"code":"CarrierServiceDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CarrierServiceDeleteUserErrorCode":{"e":["CARRIER_SERVICE_DELETE_FAILED"]}, +"CarrierServiceSortKeys":{"e":["CREATED_AT","ID","UPDATED_AT"]}, +"CarrierServiceUpdatePayload":{"o":{"f":{"carrierService":"DeliveryCarrierService","userErrors":"[CarrierServiceUpdateUserError!]!"}}}, +"CarrierServiceUpdateUserError":{"o":{"f":{"code":"CarrierServiceUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CarrierServiceUpdateUserErrorCode":{"e":["CARRIER_SERVICE_UPDATE_FAILED"]}, +"CartTransform":{"o":{"f":{"blockOnFailure":"Boolean!","functionId":"String!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}]},"t":["HasMetafields","Node"]}}, +"CartTransformConnection":{"o":{"f":{"edges":"[CartTransformEdge!]!","nodes":"[CartTransform!]!","pageInfo":"PageInfo!"}}}, +"CartTransformCreatePayload":{"o":{"f":{"cartTransform":"CartTransform","userErrors":"[CartTransformCreateUserError!]!"}}}, +"CartTransformCreateUserError":{"o":{"f":{"code":"CartTransformCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CartTransformCreateUserErrorCode":{"e":["INPUT_INVALID","FUNCTION_NOT_FOUND","FUNCTION_ALREADY_REGISTERED","FUNCTION_DOES_NOT_IMPLEMENT","CUSTOM_APP_FUNCTION_NOT_ELIGIBLE","INVALID_METAFIELDS","MAXIMUM_CART_TRANSFORMS","MULTIPLE_FUNCTION_IDENTIFIERS","MISSING_FUNCTION_IDENTIFIER"]}, +"CartTransformDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[CartTransformDeleteUserError!]!"}}}, +"CartTransformDeleteUserError":{"o":{"f":{"code":"CartTransformDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CartTransformDeleteUserErrorCode":{"e":["NOT_FOUND","UNAUTHORIZED_APP_SCOPE"]}, +"CartTransformEdge":{"o":{"f":{"cursor":"String!","node":"CartTransform!"}}}, +"CartTransformEligibleOperations":{"o":{"f":{"expandOperation":"Boolean!","mergeOperation":"Boolean!","updateOperation":"Boolean!"}}}, +"CartTransformFeature":{"o":{"f":{"eligibleOperations":"CartTransformEligibleOperations!"}}}, +"CashActivitiesSortKeys":{"e":["ID","TIME"]}, +"CashActivity":{"n":{"f":{"cash":"MoneyV2!","paymentSession":"PointOfSaleDevicePaymentSession!","staffMember":"StaffMember!","time":"DateTime!"},"t":["CashAdjustmentActivity","CashCountActivity","CashTransactionActivity"]}}, +"CashActivityConnection":{"o":{"f":{"edges":"[CashActivityEdge!]!","nodes":"[CashActivity!]!","pageInfo":"PageInfo!"}}}, +"CashActivityEdge":{"o":{"f":{"cursor":"String!","node":"CashActivity!"}}}, +"CashAdjustmentActivity":{"o":{"f":{"cash":"MoneyV2!","giftCard":"GiftCard","note":"String","paymentSession":"PointOfSaleDevicePaymentSession!","reasonCode":"CashManagementReasonCode","staffMember":"StaffMember!","time":"DateTime!","type":"CashAdjustmentActivityType!"},"t":["CashActivity"]}}, +"CashAdjustmentActivityType":{"e":["ADJUSTMENT","CASH_PAYOUT","CLOSING_ADJUSTMENT"]}, +"CashCountActivity":{"o":{"f":{"cash":"MoneyV2!","cashCounted":"MoneyV2!","cashDiscrepancy":"MoneyV2!","cashExpected":"MoneyV2!","note":"String","paymentSession":"PointOfSaleDevicePaymentSession!","reasonCode":"CashManagementReasonCode","staffMember":"StaffMember!","time":"DateTime!","type":"CashCountActivityType!"},"t":["CashActivity"]}}, +"CashCountActivityType":{"e":["OPENING","CLOSING","MID_SESSION"]}, +"CashDrawer":{"o":{"f":{"balance":"MoneyV2!","cashActivities":["CashActivityConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CashActivitiesSortKeys=","staffMemberId":"ID"}],"id":"ID!","location":"Location!","name":"String!","netSales":["MoneyV2!",{"dateRange":"CashDrawerDateRangeInput!"}],"pointOfSaleDevices":["PointOfSaleDeviceConnection",{"after":"String","before":"String","first":"Int","last":"Int"}],"totalAdjustments":["MoneyV2!",{"dateRange":"CashDrawerDateRangeInput!"}],"totalDiscrepancies":["MoneyV2!",{"dateRange":"CashDrawerDateRangeInput!"}],"totalRefunds":["MoneyV2!",{"dateRange":"CashDrawerDateRangeInput!"}],"totalSales":["MoneyV2!",{"dateRange":"CashDrawerDateRangeInput!"}]},"t":["Node"]}}, +"CashDrawerConnection":{"o":{"f":{"edges":"[CashDrawerEdge!]!","nodes":"[CashDrawer!]!","pageInfo":"PageInfo!"}}}, +"CashDrawerCreatePayload":{"o":{"f":{"cashDrawer":"CashDrawer","userErrors":"[CashDrawerCreateUserError!]!"}}}, +"CashDrawerCreateUserError":{"o":{"f":{"code":"CashDrawerCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CashDrawerCreateUserErrorCode":{"e":["INTERNAL_ERROR","NOT_SAVED","CASH_DRAWER_ALREADY_EXISTS","LOCATION_NOT_FOUND","INVALID_NAME"]}, +"CashDrawerDateRangeInput":{"i":{"from":"DateTime!","to":"DateTime!"}}, +"CashDrawerEdge":{"o":{"f":{"cursor":"String!","node":"CashDrawer!"}}}, +"CashDrawerFindOrCreatePayload":{"o":{"f":{"cashDrawer":"CashDrawer","userErrors":"[CashDrawerFindOrCreateUserError!]!"}}}, +"CashDrawerFindOrCreateUserError":{"o":{"f":{"code":"CashDrawerFindOrCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CashDrawerFindOrCreateUserErrorCode":{"e":["INTERNAL_ERROR","NOT_SAVED","CASH_DRAWER_ASSIGNMENT_ALREADY_EXISTS","LOCATION_NOT_FOUND","POINT_OF_SALE_DEVICE_NOT_FOUND"]}, +"CashDrawerUpdateInput":{"i":{"name":"String!"}}, +"CashDrawerUpdatePayload":{"o":{"f":{"cashDrawer":"CashDrawer","userErrors":"[CashDrawerUpdateUserError!]!"}}}, +"CashDrawerUpdateUserError":{"o":{"f":{"code":"CashDrawerUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CashDrawerUpdateUserErrorCode":{"e":["INTERNAL_ERROR","NOT_SAVED","CASH_DRAWER_NOT_FOUND","CASH_DRAWER_ALREADY_EXISTS","INVALID_NAME"]}, +"CashManagementCustomReasonCode":{"o":{"f":{"code":"String!","id":"ID!"},"t":["Node"]}}, +"CashManagementDefaultReasonCode":{"o":{"f":{"code":"CashManagementDefaultReasonCodeEnum!","id":"ID!"},"t":["Node"]}}, +"CashManagementDefaultReasonCodeEnum":{"e":["CASH_PICKUP","CASH_COUNT","CHANGE_CORRECTION","PETTY_CASH","TIP_PAYOUT","CASH_PAYOUT","OTHER","AUTO_END_SESSION_LOGOUT","AUTO_END_SESSION_LOCATION_CHANGE","AUTO_START_SESSION_CHECKOUT"]}, +"CashManagementReasonCode":{"u":["CashManagementCustomReasonCode","CashManagementDefaultReasonCode","CashManagementSystemReasonCode"]}, +"CashManagementReasonCodeConnection":{"o":{"f":{"edges":"[CashManagementReasonCodeEdge!]!","nodes":"[CashManagementReasonCode!]!","pageInfo":"PageInfo!"}}}, +"CashManagementReasonCodeCreatePayload":{"o":{"f":{"reasonCode":"CashManagementCustomReasonCode","userErrors":"[CashManagementReasonCodeCreateUserError!]!"}}}, +"CashManagementReasonCodeCreateUserError":{"o":{"f":{"code":"CashManagementReasonCodeCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CashManagementReasonCodeCreateUserErrorCode":{"e":["CODE_ALREADY_EXISTS","NOT_SAVED","BLANK"]}, +"CashManagementReasonCodeDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[CashManagementReasonCodeDeleteUserError!]!"}}}, +"CashManagementReasonCodeDeleteUserError":{"o":{"f":{"code":"CashManagementReasonCodeDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CashManagementReasonCodeDeleteUserErrorCode":{"e":["NOT_FOUND","DATABASE_ERROR","NOT_DELETABLE"]}, +"CashManagementReasonCodeEdge":{"o":{"f":{"cursor":"String!","node":"CashManagementReasonCode!"}}}, +"CashManagementSummary":{"o":{"f":{"cashBalanceAtEnd":"MoneyV2!","cashBalanceAtStart":"MoneyV2!","netCash":"MoneyV2!","sessionsClosed":"Int!","sessionsOpened":"Int!","totalDiscrepancies":"MoneyV2!"}}}, +"CashManagementSystemReasonCode":{"o":{"f":{"code":"CashManagementSystemReasonCodeEnum!","id":"ID!"},"t":["Node"]}}, +"CashManagementSystemReasonCodeEnum":{"e":{"v":["FLOAT_SETUP","CASH_PAYOUT","OTHER","AUTO_END_SESSION_LOGOUT","AUTO_END_SESSION_LOCATION_CHANGE","AUTO_START_SESSION_CHECKOUT"],"d":{"OTHER":"Use CashManagementDefaultReasonCodeEnum.OTHER instead."}}}, +"CashRoundingAdjustment":{"o":{"f":{"paymentSet":"MoneyBag!","refundSet":"MoneyBag!"}}}, +"CashTrackingAdjustment":{"o":{"f":{"cash":"MoneyV2!","id":"ID!","note":"String","staffMember":"StaffMember!","time":"DateTime!"},"t":["Node"]}}, +"CashTrackingAdjustmentConnection":{"o":{"f":{"edges":"[CashTrackingAdjustmentEdge!]!","nodes":"[CashTrackingAdjustment!]!","pageInfo":"PageInfo!"}}}, +"CashTrackingAdjustmentEdge":{"o":{"f":{"cursor":"String!","node":"CashTrackingAdjustment!"}}}, +"CashTrackingSession":{"o":{"f":{"adjustments":["CashTrackingAdjustmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"AdjustmentsSortKeys="}],"cashTrackingEnabled":"Boolean!","cashTransactions":["OrderTransactionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CashTrackingSessionTransactionsSortKeys="}],"closingBalance":"MoneyV2","closingNote":"String","closingStaffMember":"StaffMember","closingTime":"DateTime","expectedBalance":"MoneyV2!","expectedClosingBalance":"MoneyV2","expectedOpeningBalance":"MoneyV2","id":"ID!","location":"Location","netCashSales":"MoneyV2!","openingBalance":"MoneyV2!","openingNote":"String","openingStaffMember":"StaffMember","openingTime":"DateTime!","registerName":"String!","totalAdjustments":"MoneyV2","totalCashRefunds":"MoneyV2!","totalCashSales":"MoneyV2!","totalDiscrepancy":"MoneyV2"},"t":["Node"]}}, +"CashTrackingSessionConnection":{"o":{"f":{"edges":"[CashTrackingSessionEdge!]!","nodes":"[CashTrackingSession!]!","pageInfo":"PageInfo!"}}}, +"CashTrackingSessionEdge":{"o":{"f":{"cursor":"String!","node":"CashTrackingSession!"}}}, +"CashTrackingSessionTransactionsSortKeys":{"e":["ID","PROCESSED_AT"]}, +"CashTrackingSessionsSortKeys":{"e":["CLOSING_TIME_ASC","CLOSING_TIME_DESC","ID","OPENING_TIME_ASC","OPENING_TIME_DESC","TOTAL_DISCREPANCY_ASC","TOTAL_DISCREPANCY_DESC"]}, +"CashTransactionActivity":{"o":{"f":{"cash":"MoneyV2!","orderTransaction":"OrderTransaction!","paymentSession":"PointOfSaleDevicePaymentSession!","staffMember":"StaffMember!","time":"DateTime!","type":"CashTransactionActivityType!"},"t":["CashActivity"]}}, +"CashTransactionActivityType":{"e":["SALE","REFUND","CHANGE"]}, +"Catalog":{"n":{"f":{"id":"ID!","operations":"[ResourceOperation!]!","priceList":"PriceList","publication":"Publication","status":"CatalogStatus!","title":"String!"},"t":["AppCatalog","CompanyLocationCatalog","MarketCatalog"]}}, +"CatalogConnection":{"o":{"f":{"edges":"[CatalogEdge!]!","nodes":"[Catalog!]!","pageInfo":"PageInfo!"}}}, +"CatalogContextInput":{"i":{"companyLocationIds":"[ID!]","marketIds":"[ID!]"}}, +"CatalogContextUpdatePayload":{"o":{"f":{"catalog":"Catalog","userErrors":"[CatalogUserError!]!"}}}, +"CatalogCreateInput":{"i":{"context":"CatalogContextInput!","priceListId":"ID","publicationId":"ID","status":"CatalogStatus!","title":"String!"}}, +"CatalogCreatePayload":{"o":{"f":{"catalog":"Catalog","userErrors":"[CatalogUserError!]!"}}}, +"CatalogCsvOperation":{"o":{"f":{"id":"ID!","processedRowCount":"Int","rowCount":"RowCount","status":"ResourceOperationStatus!"},"t":["Node","ResourceOperation"]}}, +"CatalogDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[CatalogUserError!]!"}}}, +"CatalogEdge":{"o":{"f":{"cursor":"String!","node":"Catalog!"}}}, +"CatalogSortKeys":{"e":["ID","RELEVANCE","TITLE","TYPE"]}, +"CatalogStatus":{"e":["ACTIVE","ARCHIVED","DRAFT"]}, +"CatalogType":{"e":["NONE","APP","COMPANY_LOCATION","MARKET"]}, +"CatalogUpdateInput":{"i":{"context":"CatalogContextInput","priceListId":"ID","publicationId":"ID","status":"CatalogStatus","title":"String"}}, +"CatalogUpdatePayload":{"o":{"f":{"catalog":"Catalog","userErrors":"[CatalogUserError!]!"}}}, +"CatalogUserError":{"o":{"f":{"code":"CatalogUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CatalogUserErrorCode":{"e":["APP_CATALOG_PRICE_LIST_ASSIGNMENT","B2B_CATALOG_LIMIT_REACHED","CATALOG_FAILED_TO_SAVE","CATALOG_NOT_FOUND","PRICE_LIST_NOT_ALLOWED_FOR_PRIMARY_MARKET","CATALOG_CONTEXT_DOES_NOT_SUPPORT_QUANTITY_RULES","CATALOG_CONTEXT_DOES_NOT_SUPPORT_QUANTITY_PRICE_BREAKS","CANNOT_ADD_MORE_THAN_ONE_MARKET","COMPANY_LOCATION_CATALOG_STATUS_PLAN","CONTEXT_ALREADY_ASSIGNED_TO_CATALOG","CONTEXT_CATALOG_LIMIT_REACHED","COMPANY_LOCATION_NOT_FOUND","CONTEXT_DRIVER_MISMATCH","COUNTRY_CATALOG_PRICE_LIST_ASSIGNMENT","COUNTRY_PRICE_LIST_ASSIGNMENT","INVALID_CATALOG_CONTEXT_TYPE","CATALOG_NOT_COMPATIBLE_WITH_CONDITION_TYPES","MARKET_CATALOG_STATUS","MARKET_NOT_FOUND","MARKET_AND_PRICE_LIST_CURRENCY_MISMATCH","MARKET_TAKEN","MANAGED_COUNTRY_BELONGS_TO_ANOTHER_CATALOG","MUST_PROVIDE_EXACTLY_ONE_CONTEXT_TYPE","PRICE_LIST_FAILED_TO_SAVE","PRICE_LIST_NOT_FOUND","PRICE_LIST_LOCKED","CATALOG_CONTEXT_LOCKED","PUBLICATION_NOT_FOUND","REQUIRES_CONTEXTS_TO_ADD_OR_REMOVE","UNSUPPORTED_CATALOG_ACTION","CANNOT_CREATE_APP_CATALOG","CANNOT_MODIFY_APP_CATALOG","CANNOT_DELETE_APP_CATALOG","CANNOT_CREATE_MARKET_CATALOG","CANNOT_MODIFY_MARKET_CATALOG","CANNOT_DELETE_MARKET_CATALOG","UNPERMITTED_ENTITLEMENTS_DIRECT_CATALOG_ASSIGNMENT","UNPERMITTED_ENTITLEMENTS_MARKET_CATALOGS","INVALID","TAKEN","TOO_LONG","TOO_SHORT","BLANK","INVALID_CONTEXT_CHANGE"]}, +"Channel":{"o":{"f":{"accountId":"String","accountName":"String","activeRegions":"[CountryCode!]!","app":"App!","collectionPublicationsV3":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collections":["CollectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"handle":"String!","hasCollection":["Boolean!",{"id":"ID!"}],"id":"ID!","markets":["MarketConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"marketsCount":"Count","name":"String!","navigationItems":"[NavigationItem!]!","overviewPath":"URL","productPublications":["ProductPublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productPublicationsV3":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productsCount":["Count",{"limit":"Int=","query":"String"}],"resourceFeedback":"AppFeedback","specificationHandle":"String","supportsFuturePublishing":"Boolean!"},"t":["Node"],"d":{"navigationItems":"Use [AppInstallation.navigationItems](\n https://shopify.dev/api/admin-graphql/current/objects/AppInstallation#field-appinstallation-navigationitems) instead.","overviewPath":"Use [AppInstallation.launchUrl](\n https://shopify.dev/api/admin-graphql/current/objects/AppInstallation#field-appinstallation-launchurl) instead.","productPublications":"Use `productPublicationsV3` instead."}}}, +"ChannelConnection":{"o":{"f":{"edges":"[ChannelEdge!]!","nodes":"[Channel!]!","pageInfo":"PageInfo!"}}}, +"ChannelCreateInput":{"i":{"accountId":"String!","accountName":"String!","handle":"String","specificationHandle":"String!"}}, +"ChannelCreatePayload":{"o":{"f":{"channel":"Channel","userErrors":"[ChannelCreateUserError!]!"}}}, +"ChannelCreateUserError":{"o":{"f":{"code":"ChannelCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ChannelCreateUserErrorCode":{"e":["INVALID","NOT_FOUND"]}, +"ChannelDefinition":{"o":{"f":{"channelName":"String!","handle":"String!","id":"ID!","isMarketplace":"Boolean!","subChannelName":"String!","svgIcon":"String"},"t":["Node"],"d":{"channelName":"Use [`OrderAttributionDefinition.displayName`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttributionDefinition#field-OrderAttributionDefinition.fields.displayName) instead.","handle":"Use [`OrderAttributionDefinition.handle`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttributionDefinition#field-OrderAttributionDefinition.fields.handle) instead.","id":"Use [`OrderAttributionDefinition.id`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttributionDefinition#field-OrderAttributionDefinition.fields.id) instead.","isMarketplace":"Use [`OrderAttributionDefinition.handle`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttributionDefinition#field-OrderAttributionDefinition.fields.handle) instead.","subChannelName":"Use [`OrderAttributionDefinition.displayName`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttributionDefinition#field-OrderAttributionDefinition.fields.displayName) instead.","svgIcon":"Use [`OrderAttributionDefinition.icon`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttributionDefinition#field-OrderAttributionDefinition.fields.icon) instead."}}}, +"ChannelDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[ChannelDeleteUserError!]!"}}}, +"ChannelDeleteUserError":{"o":{"f":{"code":"ChannelDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ChannelDeleteUserErrorCode":{"e":["INVALID","NOT_FOUND"]}, +"ChannelEdge":{"o":{"f":{"cursor":"String!","node":"Channel!"}}}, +"ChannelFullSyncPayload":{"o":{"f":{"fullSyncTraceInfo":"[FullSyncTraceInfo!]","userErrors":"[ChannelFullSyncUserError!]!"}}}, +"ChannelFullSyncUserError":{"o":{"f":{"code":"ChannelFullSyncUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ChannelFullSyncUserErrorCode":{"e":["INVALID","NOT_FOUND"]}, +"ChannelInformation":{"o":{"f":{"app":"App!","channelDefinition":"ChannelDefinition","channelId":"ID!","displayName":"String","id":"ID!"},"t":["Node"],"d":{"app":"Use [`Order.attribution`](https://shopify.dev/docs/api/admin-graphql/latest/objects/Order#field-Order.fields.attribution) for order attribution, or [`Order.app`](https://shopify.dev/docs/api/admin-graphql/latest/objects/Order#field-Order.fields.app) and [`Order.publication`](https://shopify.dev/docs/api/admin-graphql/latest/objects/Order#field-Order.fields.publication) for app and sales channel details.","channelDefinition":"Use [`QueryRoot.orderAttributionDefinitions`](https://shopify.dev/docs/api/admin-graphql/latest/queries/orderAttributionDefinitions) and select `id`, `handle`, `displayName`, and `icon` instead.","channelId":"Use [`Order.attribution.handle`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttribution#field-OrderAttribution.fields.handle) instead.","displayName":"Use [`Order.attribution.displayName`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttribution#field-OrderAttribution.fields.displayName) instead.","id":"Use [`Order.attribution.handle`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttribution#field-OrderAttribution.fields.handle) instead."}}}, +"ChannelUpdateInput":{"i":{"accountId":"String","accountName":"String","handle":"String","specificationHandle":"String"}}, +"ChannelUpdatePayload":{"o":{"f":{"channel":"Channel","userErrors":"[ChannelUpdateUserError!]!"}}}, +"ChannelUpdateUserError":{"o":{"f":{"code":"ChannelUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ChannelUpdateUserErrorCode":{"e":["INVALID","NOT_FOUND"]}, +"ChannelsCondition":{"o":{"f":{"applicationLevel":"MarketConditionApplicationType","channels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"channelsCount":"Count"}}}, +"CheckoutAndAccountsConfiguration":{"o":{"f":{"branding":"CheckoutAndAccountsConfigurationBranding","createdAt":"DateTime!","editedAt":"DateTime!","id":"ID!","isPublished":"Boolean!","name":"String!","overrides":"[CheckoutAndAccountsConfigurationOverride!]!","updatedAt":"DateTime!"},"t":["CheckoutAndAccountsConfigurationInterface","Node"]}}, +"CheckoutAndAccountsConfigurationBranding":{"o":{"f":{"components":"CheckoutAndAccountsConfigurationBrandingComponents","designTokens":"CheckoutAndAccountsConfigurationBrandingDesignTokens","surfaces":"CheckoutAndAccountsConfigurationBrandingSurfaces"}}}, +"CheckoutAndAccountsConfigurationBrandingBackground":{"e":["BASE","SUBDUED"]}, +"CheckoutAndAccountsConfigurationBrandingBaseColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","text":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingBaseColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","text":"String"}}, +"CheckoutAndAccountsConfigurationBrandingBorder":{"e":["NONE","BLOCK_END","FULL"]}, +"CheckoutAndAccountsConfigurationBrandingBorderStyle":{"e":["BASE","DASHED","DOTTED"]}, +"CheckoutAndAccountsConfigurationBrandingBorderWidth":{"e":["BASE","LARGE","LARGE_100","LARGE_200"]}, +"CheckoutAndAccountsConfigurationBrandingButton":{"o":{"f":{"blockPadding":"CheckoutAndAccountsConfigurationBrandingSpacing","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","inlinePadding":"CheckoutAndAccountsConfigurationBrandingSpacing","typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyle"}}}, +"CheckoutAndAccountsConfigurationBrandingButtonInput":{"i":{"blockPadding":"CheckoutAndAccountsConfigurationBrandingSpacing","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","inlinePadding":"CheckoutAndAccountsConfigurationBrandingSpacing","typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyleInput"}}, +"CheckoutAndAccountsConfigurationBrandingBuyerJourney":{"o":{"f":{"visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}}, +"CheckoutAndAccountsConfigurationBrandingBuyerJourneyInput":{"i":{"visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}, +"CheckoutAndAccountsConfigurationBrandingCartLink":{"o":{"f":{"visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}}, +"CheckoutAndAccountsConfigurationBrandingCartLinkContentType":{"e":["ICON","IMAGE","TEXT"]}, +"CheckoutAndAccountsConfigurationBrandingCartLinkInput":{"i":{"visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}, +"CheckoutAndAccountsConfigurationBrandingCheckbox":{"o":{"f":{"cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius"}}}, +"CheckoutAndAccountsConfigurationBrandingCheckboxInput":{"i":{"cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius"}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutComponents":{"o":{"f":{"buyerJourney":"CheckoutAndAccountsConfigurationBrandingBuyerJourney","cartLink":"CheckoutAndAccountsConfigurationBrandingCartLink","content":"CheckoutAndAccountsConfigurationBrandingContent","expressCheckout":"CheckoutAndAccountsConfigurationBrandingExpressCheckout","footer":"CheckoutAndAccountsConfigurationBrandingCheckoutFooter","header":"CheckoutAndAccountsConfigurationBrandingCheckoutHeader","main":"CheckoutAndAccountsConfigurationBrandingMain","orderSummary":"CheckoutAndAccountsConfigurationBrandingOrderSummary"}}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutComponentsInput":{"i":{"buyerJourney":"CheckoutAndAccountsConfigurationBrandingBuyerJourneyInput","cartLink":"CheckoutAndAccountsConfigurationBrandingCartLinkInput","content":"CheckoutAndAccountsConfigurationBrandingContentInput","expressCheckout":"CheckoutAndAccountsConfigurationBrandingExpressCheckoutInput","footer":"CheckoutAndAccountsConfigurationBrandingCheckoutFooterInput","header":"CheckoutAndAccountsConfigurationBrandingCheckoutHeaderInput","main":"CheckoutAndAccountsConfigurationBrandingMainInput","orderSummary":"CheckoutAndAccountsConfigurationBrandingOrderSummaryInput"}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutFooter":{"o":{"f":{"alignment":"CheckoutAndAccountsConfigurationBrandingFooterAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","colors":"CheckoutAndAccountsConfigurationBrandingColors","content":"CheckoutAndAccountsConfigurationBrandingFooterContent","divided":"Boolean","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","position":"CheckoutAndAccountsConfigurationBrandingFooterPosition"}}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutFooterInput":{"i":{"alignment":"CheckoutAndAccountsConfigurationBrandingFooterAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","content":"CheckoutAndAccountsConfigurationBrandingFooterContentInput","divided":"Boolean","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","position":"CheckoutAndAccountsConfigurationBrandingFooterPosition"}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutHeader":{"o":{"f":{"alignment":"CheckoutAndAccountsConfigurationBrandingHeaderAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","cartLink":"CheckoutAndAccountsConfigurationBrandingHeaderCartLink","colors":"CheckoutAndAccountsConfigurationBrandingColors","divided":"Boolean","logo":"CheckoutAndAccountsConfigurationBrandingLogo","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","position":"CheckoutAndAccountsConfigurationBrandingHeaderPosition"}}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutHeaderInput":{"i":{"alignment":"CheckoutAndAccountsConfigurationBrandingHeaderAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","cartLink":"CheckoutAndAccountsConfigurationBrandingHeaderCartLinkInput","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","divided":"Boolean","logo":"CheckoutAndAccountsConfigurationBrandingLogoInput","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","position":"CheckoutAndAccountsConfigurationBrandingHeaderPosition"}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutSurface":{"o":{"f":{"components":"CheckoutAndAccountsConfigurationBrandingCheckoutComponents"}}}, +"CheckoutAndAccountsConfigurationBrandingCheckoutSurfaceInput":{"i":{"components":"CheckoutAndAccountsConfigurationBrandingCheckoutComponentsInput"}}, +"CheckoutAndAccountsConfigurationBrandingChoiceList":{"o":{"f":{"group":"CheckoutAndAccountsConfigurationBrandingChoiceListGroup"}}}, +"CheckoutAndAccountsConfigurationBrandingChoiceListGroup":{"o":{"f":{"spacing":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}}, +"CheckoutAndAccountsConfigurationBrandingChoiceListGroupInput":{"i":{"spacing":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}, +"CheckoutAndAccountsConfigurationBrandingChoiceListInput":{"i":{"group":"CheckoutAndAccountsConfigurationBrandingChoiceListGroupInput"}}, +"CheckoutAndAccountsConfigurationBrandingColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","text":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","text":"String"}}, +"CheckoutAndAccountsConfigurationBrandingColors":{"o":{"f":{"base":"CheckoutAndAccountsConfigurationBrandingBaseColorRoles","control":"CheckoutAndAccountsConfigurationBrandingControlColorRoles","primaryButton":"CheckoutAndAccountsConfigurationBrandingPrimaryButtonColorRoles","secondaryButton":"CheckoutAndAccountsConfigurationBrandingSecondaryButtonColorRoles"}}}, +"CheckoutAndAccountsConfigurationBrandingColorsInput":{"i":{"base":"CheckoutAndAccountsConfigurationBrandingBaseColorRolesInput","control":"CheckoutAndAccountsConfigurationBrandingControlColorRolesInput","primaryButton":"CheckoutAndAccountsConfigurationBrandingPrimaryButtonColorRolesInput","secondaryButton":"CheckoutAndAccountsConfigurationBrandingSecondaryButtonColorRolesInput"}}, +"CheckoutAndAccountsConfigurationBrandingComponents":{"o":{"f":{"checkbox":"CheckoutAndAccountsConfigurationBrandingCheckbox","choiceList":"CheckoutAndAccountsConfigurationBrandingChoiceList","control":"CheckoutAndAccountsConfigurationBrandingControl","divider":"CheckoutAndAccountsConfigurationBrandingDividerStyle","favicon":"CheckoutAndAccountsConfigurationBrandingImageValue","footer":"CheckoutAndAccountsConfigurationBrandingFooter","header":"CheckoutAndAccountsConfigurationBrandingHeader","headingLevel1":"CheckoutAndAccountsConfigurationBrandingHeadingLevel","headingLevel2":"CheckoutAndAccountsConfigurationBrandingHeadingLevel","headingLevel3":"CheckoutAndAccountsConfigurationBrandingHeadingLevel","main":"CheckoutAndAccountsConfigurationBrandingMain","merchandiseThumbnail":"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnail","primaryButton":"CheckoutAndAccountsConfigurationBrandingButton","secondaryButton":"CheckoutAndAccountsConfigurationBrandingButton","select":"CheckoutAndAccountsConfigurationBrandingSelect","shared":"CheckoutAndAccountsConfigurationBrandingShared","textField":"CheckoutAndAccountsConfigurationBrandingTextField"}}}, +"CheckoutAndAccountsConfigurationBrandingComponentsInput":{"i":{"checkbox":"CheckoutAndAccountsConfigurationBrandingCheckboxInput","choiceList":"CheckoutAndAccountsConfigurationBrandingChoiceListInput","control":"CheckoutAndAccountsConfigurationBrandingControlInput","divider":"CheckoutAndAccountsConfigurationBrandingDividerStyleInput","favicon":"CheckoutAndAccountsConfigurationBrandingImageInput","footer":"CheckoutAndAccountsConfigurationBrandingFooterInput","header":"CheckoutAndAccountsConfigurationBrandingHeaderInput","headingLevel1":"CheckoutAndAccountsConfigurationBrandingHeadingLevelInput","headingLevel2":"CheckoutAndAccountsConfigurationBrandingHeadingLevelInput","headingLevel3":"CheckoutAndAccountsConfigurationBrandingHeadingLevelInput","main":"CheckoutAndAccountsConfigurationBrandingMainInput","merchandiseThumbnail":"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailInput","primaryButton":"CheckoutAndAccountsConfigurationBrandingButtonInput","secondaryButton":"CheckoutAndAccountsConfigurationBrandingButtonInput","select":"CheckoutAndAccountsConfigurationBrandingSelectInput","shared":"CheckoutAndAccountsConfigurationBrandingSharedInput","textField":"CheckoutAndAccountsConfigurationBrandingTextFieldInput"}}, +"CheckoutAndAccountsConfigurationBrandingContainerDivider":{"o":{"f":{"borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}}, +"CheckoutAndAccountsConfigurationBrandingContainerDividerInput":{"i":{"borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}, +"CheckoutAndAccountsConfigurationBrandingContent":{"o":{"f":{"divider":"CheckoutAndAccountsConfigurationBrandingContainerDivider"}}}, +"CheckoutAndAccountsConfigurationBrandingContentInput":{"i":{"divider":"CheckoutAndAccountsConfigurationBrandingContainerDividerInput"}}, +"CheckoutAndAccountsConfigurationBrandingControl":{"o":{"f":{"border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","labelPosition":"CheckoutAndAccountsConfigurationBrandingLabelPosition"}}}, +"CheckoutAndAccountsConfigurationBrandingControlColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","selected":"CheckoutAndAccountsConfigurationBrandingColorRoles","text":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingControlColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","selected":"CheckoutAndAccountsConfigurationBrandingColorRolesInput","text":"String"}}, +"CheckoutAndAccountsConfigurationBrandingControlInput":{"i":{"border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","labelPosition":"CheckoutAndAccountsConfigurationBrandingLabelPosition"}}, +"CheckoutAndAccountsConfigurationBrandingCornerRadius":{"e":["NONE","SMALL","BASE","LARGE"]}, +"CheckoutAndAccountsConfigurationBrandingCornerRadiusVariables":{"o":{"f":{"base":"Int","large":"Int","small":"Int"}}}, +"CheckoutAndAccountsConfigurationBrandingCornerRadiusVariablesInput":{"i":{"base":"Int","large":"Int","small":"Int"}}, +"CheckoutAndAccountsConfigurationBrandingCustomFont":{"o":{"f":{"genericFileId":"ID","sources":"String","weight":"Int"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomFontGroup":{"o":{"f":{"base":"CheckoutAndAccountsConfigurationBrandingCustomFont","bold":"CheckoutAndAccountsConfigurationBrandingCustomFont","loadingStrategy":"CheckoutAndAccountsConfigurationBrandingFontLoadingStrategy","name":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomFontGroupInput":{"i":{"base":"CheckoutAndAccountsConfigurationBrandingCustomFontInput!","bold":"CheckoutAndAccountsConfigurationBrandingCustomFontInput!","loadingStrategy":"CheckoutAndAccountsConfigurationBrandingFontLoadingStrategy"}}, +"CheckoutAndAccountsConfigurationBrandingCustomFontInput":{"i":{"genericFileId":"ID!","weight":"Int!"}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsComponents":{"o":{"f":{"footer":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsFooter","header":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsHeader","main":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMain"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsComponentsInput":{"i":{"footer":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsFooterInput","header":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsHeaderInput","main":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMainInput"}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsFooter":{"o":{"f":{"alignment":"CheckoutAndAccountsConfigurationBrandingFooterAlignment","colors":"CheckoutAndAccountsConfigurationBrandingColors","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsFooterInput":{"i":{"alignment":"CheckoutAndAccountsConfigurationBrandingFooterAlignment","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsHeader":{"o":{"f":{"alignment":"CheckoutAndAccountsConfigurationBrandingHeaderAlignment","colors":"CheckoutAndAccountsConfigurationBrandingColors","logo":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsLogo","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsHeaderInput":{"i":{"alignment":"CheckoutAndAccountsConfigurationBrandingHeaderAlignment","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","logo":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsLogoInput","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsLogo":{"o":{"f":{"image":"CheckoutAndAccountsConfigurationBrandingImageValue","maxWidth":"Int"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsLogoInput":{"i":{"image":"CheckoutAndAccountsConfigurationBrandingImageInput","maxWidth":"Int"}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMain":{"o":{"f":{"colors":"CheckoutAndAccountsConfigurationBrandingColors","section":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMainSection"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMainInput":{"i":{"colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","section":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMainSectionInput"}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMainSection":{"o":{"f":{"background":"CheckoutAndAccountsConfigurationBrandingBackground","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","colors":"CheckoutAndAccountsConfigurationBrandingColors","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","shadow":"CheckoutAndAccountsConfigurationBrandingShadow"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsMainSectionInput":{"i":{"background":"CheckoutAndAccountsConfigurationBrandingBackground","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","shadow":"CheckoutAndAccountsConfigurationBrandingShadow"}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsSurface":{"o":{"f":{"components":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsComponents"}}}, +"CheckoutAndAccountsConfigurationBrandingCustomerAccountsSurfaceInput":{"i":{"components":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsComponentsInput"}}, +"CheckoutAndAccountsConfigurationBrandingDesignTokenColors":{"o":{"f":{"palette":"CheckoutAndAccountsConfigurationBrandingPalette"}}}, +"CheckoutAndAccountsConfigurationBrandingDesignTokens":{"o":{"f":{"colors":"CheckoutAndAccountsConfigurationBrandingDesignTokenColors","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadiusVariables","typography":"CheckoutAndAccountsConfigurationBrandingTypography"}}}, +"CheckoutAndAccountsConfigurationBrandingDesignTokensColorsInput":{"i":{"palette":"CheckoutAndAccountsConfigurationBrandingPaletteInput"}}, +"CheckoutAndAccountsConfigurationBrandingDesignTokensInput":{"i":{"colors":"CheckoutAndAccountsConfigurationBrandingDesignTokensColorsInput","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadiusVariablesInput","typography":"CheckoutAndAccountsConfigurationBrandingTypographyInput"}}, +"CheckoutAndAccountsConfigurationBrandingDividerStyle":{"o":{"f":{"borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth"}}}, +"CheckoutAndAccountsConfigurationBrandingDividerStyleInput":{"i":{"borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth"}}, +"CheckoutAndAccountsConfigurationBrandingExpressCheckout":{"o":{"f":{"button":"CheckoutAndAccountsConfigurationBrandingExpressCheckoutButton"}}}, +"CheckoutAndAccountsConfigurationBrandingExpressCheckoutButton":{"o":{"f":{"cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius"}}}, +"CheckoutAndAccountsConfigurationBrandingExpressCheckoutButtonInput":{"i":{"cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius"}}, +"CheckoutAndAccountsConfigurationBrandingExpressCheckoutInput":{"i":{"button":"CheckoutAndAccountsConfigurationBrandingExpressCheckoutButtonInput"}}, +"CheckoutAndAccountsConfigurationBrandingFontGroup":{"u":["CheckoutAndAccountsConfigurationBrandingCustomFontGroup","CheckoutAndAccountsConfigurationBrandingShopifyFontGroup"]}, +"CheckoutAndAccountsConfigurationBrandingFontGroupInput":{"i":{"f":{"customFontGroup":"CheckoutAndAccountsConfigurationBrandingCustomFontGroupInput","shopifyFontGroup":"CheckoutAndAccountsConfigurationBrandingShopifyFontGroupInput"},"o":true}}, +"CheckoutAndAccountsConfigurationBrandingFontLoadingStrategy":{"e":["AUTO","BLOCK","SWAP","FALLBACK","OPTIONAL"]}, +"CheckoutAndAccountsConfigurationBrandingFontSize":{"o":{"f":{"base":"Float","ratio":"Float"}}}, +"CheckoutAndAccountsConfigurationBrandingFontSizeInput":{"i":{"base":"Float","ratio":"Float"}}, +"CheckoutAndAccountsConfigurationBrandingFooter":{"o":{"f":{"alignment":"CheckoutAndAccountsConfigurationBrandingFooterAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","colors":"CheckoutAndAccountsConfigurationBrandingColors","content":"CheckoutAndAccountsConfigurationBrandingFooterContent","divided":"Boolean","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}}, +"CheckoutAndAccountsConfigurationBrandingFooterAlignment":{"e":["START","CENTER","END"]}, +"CheckoutAndAccountsConfigurationBrandingFooterContent":{"o":{"f":{"visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}}, +"CheckoutAndAccountsConfigurationBrandingFooterContentInput":{"i":{"visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}, +"CheckoutAndAccountsConfigurationBrandingFooterInput":{"i":{"alignment":"CheckoutAndAccountsConfigurationBrandingFooterAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","content":"CheckoutAndAccountsConfigurationBrandingFooterContentInput","divided":"Boolean","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}, +"CheckoutAndAccountsConfigurationBrandingFooterPosition":{"e":["END","INLINE"]}, +"CheckoutAndAccountsConfigurationBrandingHeader":{"o":{"f":{"alignment":"CheckoutAndAccountsConfigurationBrandingHeaderAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","colors":"CheckoutAndAccountsConfigurationBrandingColors","divided":"Boolean","logo":"CheckoutAndAccountsConfigurationBrandingLogo","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}}, +"CheckoutAndAccountsConfigurationBrandingHeaderAlignment":{"e":["START","CENTER","END"]}, +"CheckoutAndAccountsConfigurationBrandingHeaderCartLink":{"o":{"f":{"contentType":"CheckoutAndAccountsConfigurationBrandingCartLinkContentType","image":"CheckoutAndAccountsConfigurationBrandingImageValue"}}}, +"CheckoutAndAccountsConfigurationBrandingHeaderCartLinkInput":{"i":{"contentType":"CheckoutAndAccountsConfigurationBrandingCartLinkContentType","image":"CheckoutAndAccountsConfigurationBrandingImageInput"}}, +"CheckoutAndAccountsConfigurationBrandingHeaderInput":{"i":{"alignment":"CheckoutAndAccountsConfigurationBrandingHeaderAlignment","background":"CheckoutAndAccountsConfigurationBrandingBackground","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","divided":"Boolean","logo":"CheckoutAndAccountsConfigurationBrandingLogoInput","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}, +"CheckoutAndAccountsConfigurationBrandingHeaderPosition":{"e":["INLINE","INLINE_SECONDARY","START"]}, +"CheckoutAndAccountsConfigurationBrandingHeadingLevel":{"o":{"f":{"typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyle"}}}, +"CheckoutAndAccountsConfigurationBrandingHeadingLevelInput":{"i":{"typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyleInput"}}, +"CheckoutAndAccountsConfigurationBrandingImage":{"o":{"f":{"image":"Image"}}}, +"CheckoutAndAccountsConfigurationBrandingImageInput":{"i":{"f":{"mediaImageId":"ID"},"o":true}}, +"CheckoutAndAccountsConfigurationBrandingImageValue":{"u":["CheckoutAndAccountsConfigurationBrandingImage"]}, +"CheckoutAndAccountsConfigurationBrandingInput":{"i":{"components":"CheckoutAndAccountsConfigurationBrandingComponentsInput","designTokens":"CheckoutAndAccountsConfigurationBrandingDesignTokensInput","surfaces":"CheckoutAndAccountsConfigurationBrandingSurfacesInput"}}, +"CheckoutAndAccountsConfigurationBrandingLabelPosition":{"e":["INSIDE","OUTSIDE"]}, +"CheckoutAndAccountsConfigurationBrandingLogo":{"o":{"f":{"image":"CheckoutAndAccountsConfigurationBrandingImageValue","maxWidth":"Int","visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}}, +"CheckoutAndAccountsConfigurationBrandingLogoInput":{"i":{"image":"CheckoutAndAccountsConfigurationBrandingImageInput","maxWidth":"Int","visibility":"CheckoutAndAccountsConfigurationBrandingVisibility"}}, +"CheckoutAndAccountsConfigurationBrandingMain":{"o":{"f":{"colors":"CheckoutAndAccountsConfigurationBrandingColors","divider":"CheckoutAndAccountsConfigurationBrandingContainerDivider","section":"CheckoutAndAccountsConfigurationBrandingMainSection"}}}, +"CheckoutAndAccountsConfigurationBrandingMainInput":{"i":{"colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","divider":"CheckoutAndAccountsConfigurationBrandingContainerDividerInput","section":"CheckoutAndAccountsConfigurationBrandingMainSectionInput"}}, +"CheckoutAndAccountsConfigurationBrandingMainSection":{"o":{"f":{"background":"CheckoutAndAccountsConfigurationBrandingBackground","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","colors":"CheckoutAndAccountsConfigurationBrandingColors","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","shadow":"CheckoutAndAccountsConfigurationBrandingShadow"}}}, +"CheckoutAndAccountsConfigurationBrandingMainSectionInput":{"i":{"background":"CheckoutAndAccountsConfigurationBrandingBackground","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","shadow":"CheckoutAndAccountsConfigurationBrandingShadow"}}, +"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnail":{"o":{"f":{"badge":"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailBadge","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","fit":"CheckoutAndAccountsConfigurationBrandingObjectFit"}}}, +"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailBadge":{"o":{"f":{"background":"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailBadgeBackground"}}}, +"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailBadgeBackground":{"e":["ACCENT","BASE"]}, +"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailBadgeInput":{"i":{"background":"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailBadgeBackground"}}, +"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailInput":{"i":{"aspectRatio":"Float","badge":"CheckoutAndAccountsConfigurationBrandingMerchandiseThumbnailBadgeInput","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","fit":"CheckoutAndAccountsConfigurationBrandingObjectFit"}}, +"CheckoutAndAccountsConfigurationBrandingObjectFit":{"e":["CONTAIN","COVER"]}, +"CheckoutAndAccountsConfigurationBrandingOrderSummary":{"o":{"f":{"backgroundImage":"CheckoutAndAccountsConfigurationBrandingImageValue","colors":"CheckoutAndAccountsConfigurationBrandingColors","divider":"CheckoutAndAccountsConfigurationBrandingContainerDivider","section":"CheckoutAndAccountsConfigurationBrandingOrderSummarySection"}}}, +"CheckoutAndAccountsConfigurationBrandingOrderSummaryInput":{"i":{"backgroundImage":"CheckoutAndAccountsConfigurationBrandingImageInput","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","divider":"CheckoutAndAccountsConfigurationBrandingContainerDividerInput","section":"CheckoutAndAccountsConfigurationBrandingOrderSummarySectionInput"}}, +"CheckoutAndAccountsConfigurationBrandingOrderSummarySection":{"o":{"f":{"background":"CheckoutAndAccountsConfigurationBrandingBackground","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","colors":"CheckoutAndAccountsConfigurationBrandingColors","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","shadow":"CheckoutAndAccountsConfigurationBrandingShadow"}}}, +"CheckoutAndAccountsConfigurationBrandingOrderSummarySectionInput":{"i":{"background":"CheckoutAndAccountsConfigurationBrandingBackground","border":"CheckoutAndAccountsConfigurationBrandingSimpleBorder","borderStyle":"CheckoutAndAccountsConfigurationBrandingBorderStyle","borderWidth":"CheckoutAndAccountsConfigurationBrandingBorderWidth","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","cornerRadius":"CheckoutAndAccountsConfigurationBrandingCornerRadius","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword","shadow":"CheckoutAndAccountsConfigurationBrandingShadow"}}, +"CheckoutAndAccountsConfigurationBrandingPalette":{"o":{"f":{"color1":"String","color10":"String","color11":"String","color12":"String","color13":"String","color14":"String","color15":"String","color16":"String","color17":"String","color18":"String","color19":"String","color2":"String","color20":"String","color3":"String","color4":"String","color5":"String","color6":"String","color7":"String","color8":"String","color9":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingPaletteInput":{"i":{"color1":"String","color10":"String","color11":"String","color12":"String","color13":"String","color14":"String","color15":"String","color16":"String","color17":"String","color18":"String","color19":"String","color2":"String","color20":"String","color3":"String","color4":"String","color5":"String","color6":"String","color7":"String","color8":"String","color9":"String"}}, +"CheckoutAndAccountsConfigurationBrandingPrimaryButtonColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","hover":"CheckoutAndAccountsConfigurationBrandingColorRoles","icon":"String","text":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingPrimaryButtonColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","hover":"CheckoutAndAccountsConfigurationBrandingColorRolesInput","icon":"String","text":"String"}}, +"CheckoutAndAccountsConfigurationBrandingSecondaryButtonColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","hover":"CheckoutAndAccountsConfigurationBrandingColorRoles","icon":"String","text":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingSecondaryButtonColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","hover":"CheckoutAndAccountsConfigurationBrandingColorRolesInput","icon":"String","text":"String"}}, +"CheckoutAndAccountsConfigurationBrandingSelect":{"o":{"f":{"border":"CheckoutAndAccountsConfigurationBrandingBorder","typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyle"}}}, +"CheckoutAndAccountsConfigurationBrandingSelectInput":{"i":{"border":"CheckoutAndAccountsConfigurationBrandingBorder","typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyleInput"}}, +"CheckoutAndAccountsConfigurationBrandingShadow":{"e":["SMALL_200","SMALL_100","BASE","LARGE_100","LARGE_200"]}, +"CheckoutAndAccountsConfigurationBrandingShared":{"o":{"f":{"colors":"CheckoutAndAccountsConfigurationBrandingSharedColors","cornerRadius":"CheckoutAndAccountsConfigurationBrandingSharedCornerRadius","typography":"CheckoutAndAccountsConfigurationBrandingSharedTypographyStyle"}}}, +"CheckoutAndAccountsConfigurationBrandingSharedColors":{"o":{"f":{"accent":"String","button":"String","control":"String","critical":"String","decorative":"String","info":"String","success":"String","warning":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingSharedColorsInput":{"i":{"accent":"String","button":"String","control":"String","critical":"String","decorative":"String","info":"String","success":"String","warning":"String"}}, +"CheckoutAndAccountsConfigurationBrandingSharedCornerRadius":{"e":["NONE"]}, +"CheckoutAndAccountsConfigurationBrandingSharedInput":{"i":{"colors":"CheckoutAndAccountsConfigurationBrandingSharedColorsInput","cornerRadius":"CheckoutAndAccountsConfigurationBrandingSharedCornerRadius","typography":"CheckoutAndAccountsConfigurationBrandingSharedTypographyStyleInput"}}, +"CheckoutAndAccountsConfigurationBrandingSharedTypographyStyle":{"o":{"f":{"kerning":"CheckoutAndAccountsConfigurationBrandingTypographyKerning","letterCase":"CheckoutAndAccountsConfigurationBrandingTypographyLetterCase"}}}, +"CheckoutAndAccountsConfigurationBrandingSharedTypographyStyleInput":{"i":{"kerning":"CheckoutAndAccountsConfigurationBrandingTypographyKerning","letterCase":"CheckoutAndAccountsConfigurationBrandingTypographyLetterCase"}}, +"CheckoutAndAccountsConfigurationBrandingShopifyFont":{"o":{"f":{"sources":"String","weight":"Int"}}}, +"CheckoutAndAccountsConfigurationBrandingShopifyFontGroup":{"o":{"f":{"base":"CheckoutAndAccountsConfigurationBrandingShopifyFont","bold":"CheckoutAndAccountsConfigurationBrandingShopifyFont","loadingStrategy":"CheckoutAndAccountsConfigurationBrandingFontLoadingStrategy","name":"String"}}}, +"CheckoutAndAccountsConfigurationBrandingShopifyFontGroupInput":{"i":{"baseFontHandle":"String!","boldFontHandle":"String!","loadingStrategy":"CheckoutAndAccountsConfigurationBrandingFontLoadingStrategy"}}, +"CheckoutAndAccountsConfigurationBrandingSignInComponents":{"o":{"f":{"header":"CheckoutAndAccountsConfigurationBrandingSignInHeader","main":"CheckoutAndAccountsConfigurationBrandingSignInMain"}}}, +"CheckoutAndAccountsConfigurationBrandingSignInComponentsInput":{"i":{"header":"CheckoutAndAccountsConfigurationBrandingSignInHeaderInput","main":"CheckoutAndAccountsConfigurationBrandingSignInMainInput"}}, +"CheckoutAndAccountsConfigurationBrandingSignInHeader":{"o":{"f":{"logo":"CheckoutAndAccountsConfigurationBrandingSignInLogo","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}}, +"CheckoutAndAccountsConfigurationBrandingSignInHeaderInput":{"i":{"logo":"CheckoutAndAccountsConfigurationBrandingSignInLogoInput","padding":"CheckoutAndAccountsConfigurationBrandingSpacingKeyword"}}, +"CheckoutAndAccountsConfigurationBrandingSignInLogo":{"o":{"f":{"image":"CheckoutAndAccountsConfigurationBrandingImageValue","maxWidth":"Int"}}}, +"CheckoutAndAccountsConfigurationBrandingSignInLogoInput":{"i":{"image":"CheckoutAndAccountsConfigurationBrandingImageInput","maxWidth":"Int"}}, +"CheckoutAndAccountsConfigurationBrandingSignInMain":{"o":{"f":{"backgroundImage":"CheckoutAndAccountsConfigurationBrandingImageValue","colors":"CheckoutAndAccountsConfigurationBrandingColors","section":"CheckoutAndAccountsConfigurationBrandingMainSection"}}}, +"CheckoutAndAccountsConfigurationBrandingSignInMainInput":{"i":{"backgroundImage":"CheckoutAndAccountsConfigurationBrandingImageInput","colors":"CheckoutAndAccountsConfigurationBrandingColorsInput","section":"CheckoutAndAccountsConfigurationBrandingMainSectionInput"}}, +"CheckoutAndAccountsConfigurationBrandingSignInSurface":{"o":{"f":{"components":"CheckoutAndAccountsConfigurationBrandingSignInComponents"}}}, +"CheckoutAndAccountsConfigurationBrandingSignInSurfaceInput":{"i":{"components":"CheckoutAndAccountsConfigurationBrandingSignInComponentsInput"}}, +"CheckoutAndAccountsConfigurationBrandingSimpleBorder":{"e":["NONE","FULL"]}, +"CheckoutAndAccountsConfigurationBrandingSpacing":{"e":["NONE","EXTRA_TIGHT","TIGHT","BASE","LOOSE","EXTRA_LOOSE"]}, +"CheckoutAndAccountsConfigurationBrandingSpacingKeyword":{"e":["NONE","BASE","SMALL","SMALL_100","SMALL_200","SMALL_300","SMALL_400","SMALL_500","LARGE","LARGE_100","LARGE_200","LARGE_300","LARGE_400","LARGE_500"]}, +"CheckoutAndAccountsConfigurationBrandingSurfaces":{"o":{"f":{"checkout":"CheckoutAndAccountsConfigurationBrandingCheckoutSurface","customerAccounts":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsSurface","signIn":"CheckoutAndAccountsConfigurationBrandingSignInSurface"}}}, +"CheckoutAndAccountsConfigurationBrandingSurfacesInput":{"i":{"checkout":"CheckoutAndAccountsConfigurationBrandingCheckoutSurfaceInput","customerAccounts":"CheckoutAndAccountsConfigurationBrandingCustomerAccountsSurfaceInput","signIn":"CheckoutAndAccountsConfigurationBrandingSignInSurfaceInput"}}, +"CheckoutAndAccountsConfigurationBrandingTextField":{"o":{"f":{"border":"CheckoutAndAccountsConfigurationBrandingBorder","typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyle"}}}, +"CheckoutAndAccountsConfigurationBrandingTextFieldInput":{"i":{"border":"CheckoutAndAccountsConfigurationBrandingBorder","typography":"CheckoutAndAccountsConfigurationBrandingTypographyStyleInput"}}, +"CheckoutAndAccountsConfigurationBrandingTypography":{"o":{"f":{"primary":"CheckoutAndAccountsConfigurationBrandingFontGroup","secondary":"CheckoutAndAccountsConfigurationBrandingFontGroup","size":"CheckoutAndAccountsConfigurationBrandingFontSize"}}}, +"CheckoutAndAccountsConfigurationBrandingTypographyFont":{"e":["PRIMARY","SECONDARY"]}, +"CheckoutAndAccountsConfigurationBrandingTypographyInput":{"i":{"primary":"CheckoutAndAccountsConfigurationBrandingFontGroupInput","secondary":"CheckoutAndAccountsConfigurationBrandingFontGroupInput","size":"CheckoutAndAccountsConfigurationBrandingFontSizeInput"}}, +"CheckoutAndAccountsConfigurationBrandingTypographyKerning":{"e":["BASE","LOOSE","EXTRA_LOOSE"]}, +"CheckoutAndAccountsConfigurationBrandingTypographyLetterCase":{"e":["LOWER","NONE","TITLE","UPPER"]}, +"CheckoutAndAccountsConfigurationBrandingTypographySize":{"e":["EXTRA_SMALL","SMALL","BASE","MEDIUM","LARGE","EXTRA_LARGE","EXTRA_EXTRA_LARGE"]}, +"CheckoutAndAccountsConfigurationBrandingTypographyStyle":{"o":{"f":{"font":"CheckoutAndAccountsConfigurationBrandingTypographyFont","kerning":"CheckoutAndAccountsConfigurationBrandingTypographyKerning","letterCase":"CheckoutAndAccountsConfigurationBrandingTypographyLetterCase","size":"CheckoutAndAccountsConfigurationBrandingTypographySize","weight":"CheckoutAndAccountsConfigurationBrandingTypographyWeight"}}}, +"CheckoutAndAccountsConfigurationBrandingTypographyStyleInput":{"i":{"font":"CheckoutAndAccountsConfigurationBrandingTypographyFont","kerning":"CheckoutAndAccountsConfigurationBrandingTypographyKerning","letterCase":"CheckoutAndAccountsConfigurationBrandingTypographyLetterCase","size":"CheckoutAndAccountsConfigurationBrandingTypographySize","weight":"CheckoutAndAccountsConfigurationBrandingTypographyWeight"}}, +"CheckoutAndAccountsConfigurationBrandingTypographyWeight":{"e":["BASE","BOLD"]}, +"CheckoutAndAccountsConfigurationBrandingVisibility":{"e":["HIDDEN","VISIBLE"]}, +"CheckoutAndAccountsConfigurationConnection":{"o":{"f":{"edges":"[CheckoutAndAccountsConfigurationEdge!]!","nodes":"[CheckoutAndAccountsConfiguration!]!","pageInfo":"PageInfo!"}}}, +"CheckoutAndAccountsConfigurationEdge":{"o":{"f":{"cursor":"String!","node":"CheckoutAndAccountsConfiguration!"}}}, +"CheckoutAndAccountsConfigurationInput":{"i":{"branding":"CheckoutAndAccountsConfigurationBrandingInput","overrides":"[CheckoutAndAccountsConfigurationOverrideInput!]"}}, +"CheckoutAndAccountsConfigurationInterface":{"n":{"f":{"branding":"CheckoutAndAccountsConfigurationBranding","createdAt":"DateTime!","editedAt":"DateTime!","name":"String!","updatedAt":"DateTime!"},"t":["CheckoutAndAccountsConfiguration","CheckoutAndAccountsConfigurationOverride"]}}, +"CheckoutAndAccountsConfigurationOverride":{"o":{"f":{"branding":"CheckoutAndAccountsConfigurationBranding","createdAt":"DateTime!","editedAt":"DateTime!","id":"ID!","name":"String!","updatedAt":"DateTime!"},"t":["CheckoutAndAccountsConfigurationInterface","Node"]}}, +"CheckoutAndAccountsConfigurationOverrideInput":{"i":{"branding":"CheckoutAndAccountsConfigurationBrandingInput","id":"ID"}}, +"CheckoutAndAccountsConfigurationUpdatePayload":{"o":{"f":{"configuration":"CheckoutAndAccountsConfiguration","userErrors":"[CheckoutAndAccountsConfigurationUserError!]!"}}}, +"CheckoutAndAccountsConfigurationUserError":{"o":{"f":{"code":"CheckoutAndAccountsConfigurationUserErrorCode","field":"[String!]","message":"String!","reason":"String!"},"t":["DisplayableError"]}}, +"CheckoutAndAccountsConfigurationUserErrorCode":{"e":["INVALID","BLANK","INTERNAL_SERVER_ERROR","MISSING","NOT_FOUND","TRANSIENT"]}, +"CheckoutAndAccountsConfigurationsGraphQLSortKeys":{"e":["CREATED_AT","EDITED_AT","ID","IS_PUBLISHED"]}, +"CheckoutBranding":{"o":{"f":{"customizations":"CheckoutBrandingCustomizations","designSystem":"CheckoutBrandingDesignSystem"}}}, +"CheckoutBrandingBackground":{"e":["BASE","SUBDUED","TRANSPARENT"]}, +"CheckoutBrandingBackgroundStyle":{"e":["SOLID","NONE"]}, +"CheckoutBrandingBorder":{"e":["NONE","BLOCK_END","FULL"]}, +"CheckoutBrandingBorderStyle":{"e":["BASE","DASHED","DOTTED"]}, +"CheckoutBrandingBorderWidth":{"e":["BASE","LARGE_100","LARGE_200","LARGE"]}, +"CheckoutBrandingButton":{"o":{"f":{"background":"CheckoutBrandingBackgroundStyle","blockPadding":"CheckoutBrandingSpacing","border":"CheckoutBrandingSimpleBorder","cornerRadius":"CheckoutBrandingCornerRadius","inlinePadding":"CheckoutBrandingSpacing","typography":"CheckoutBrandingTypographyStyle"}}}, +"CheckoutBrandingButtonColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","hover":"CheckoutBrandingColorRoles","icon":"String","text":"String"}}}, +"CheckoutBrandingButtonColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","hover":"CheckoutBrandingColorRolesInput","icon":"String","text":"String"}}, +"CheckoutBrandingButtonInput":{"i":{"background":"CheckoutBrandingBackgroundStyle","blockPadding":"CheckoutBrandingSpacing","border":"CheckoutBrandingSimpleBorder","cornerRadius":"CheckoutBrandingCornerRadius","inlinePadding":"CheckoutBrandingSpacing","typography":"CheckoutBrandingTypographyStyleInput"}}, +"CheckoutBrandingBuyerJourney":{"o":{"f":{"visibility":"CheckoutBrandingVisibility"}}}, +"CheckoutBrandingBuyerJourneyInput":{"i":{"visibility":"CheckoutBrandingVisibility"}}, +"CheckoutBrandingCartLink":{"o":{"f":{"visibility":"CheckoutBrandingVisibility"}}}, +"CheckoutBrandingCartLinkContentType":{"e":["ICON","IMAGE","TEXT"]}, +"CheckoutBrandingCartLinkInput":{"i":{"visibility":"CheckoutBrandingVisibility"}}, +"CheckoutBrandingCheckbox":{"o":{"f":{"cornerRadius":"CheckoutBrandingCornerRadius"}}}, +"CheckoutBrandingCheckboxInput":{"i":{"cornerRadius":"CheckoutBrandingCornerRadius"}}, +"CheckoutBrandingChoiceList":{"o":{"f":{"group":"CheckoutBrandingChoiceListGroup"}}}, +"CheckoutBrandingChoiceListGroup":{"o":{"f":{"spacing":"CheckoutBrandingSpacingKeyword"}}}, +"CheckoutBrandingChoiceListGroupInput":{"i":{"spacing":"CheckoutBrandingSpacingKeyword"}}, +"CheckoutBrandingChoiceListInput":{"i":{"group":"CheckoutBrandingChoiceListGroupInput"}}, +"CheckoutBrandingColorGlobal":{"o":{"f":{"accent":"String","brand":"String","critical":"String","decorative":"String","info":"String","success":"String","warning":"String"}}}, +"CheckoutBrandingColorGlobalInput":{"i":{"accent":"String","brand":"String","critical":"String","decorative":"String","info":"String","success":"String","warning":"String"}}, +"CheckoutBrandingColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","text":"String"}}}, +"CheckoutBrandingColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","text":"String"}}, +"CheckoutBrandingColorScheme":{"o":{"f":{"base":"CheckoutBrandingColorRoles","control":"CheckoutBrandingControlColorRoles","primaryButton":"CheckoutBrandingButtonColorRoles","secondaryButton":"CheckoutBrandingButtonColorRoles"}}}, +"CheckoutBrandingColorSchemeInput":{"i":{"base":"CheckoutBrandingColorRolesInput","control":"CheckoutBrandingControlColorRolesInput","primaryButton":"CheckoutBrandingButtonColorRolesInput","secondaryButton":"CheckoutBrandingButtonColorRolesInput"}}, +"CheckoutBrandingColorSchemeSelection":{"e":["TRANSPARENT","COLOR_SCHEME1","COLOR_SCHEME2","COLOR_SCHEME3","COLOR_SCHEME4","COLOR_SCHEME5","COLOR_SCHEME6"]}, +"CheckoutBrandingColorSchemes":{"o":{"f":{"scheme1":"CheckoutBrandingColorScheme","scheme2":"CheckoutBrandingColorScheme","scheme3":"CheckoutBrandingColorScheme","scheme4":"CheckoutBrandingColorScheme","scheme5":"CheckoutBrandingColorScheme","scheme6":"CheckoutBrandingColorScheme"}}}, +"CheckoutBrandingColorSchemesInput":{"i":{"scheme1":"CheckoutBrandingColorSchemeInput","scheme2":"CheckoutBrandingColorSchemeInput","scheme3":"CheckoutBrandingColorSchemeInput","scheme4":"CheckoutBrandingColorSchemeInput","scheme5":"CheckoutBrandingColorSchemeInput","scheme6":"CheckoutBrandingColorSchemeInput"}}, +"CheckoutBrandingColorSelection":{"e":["TRANSPARENT"]}, +"CheckoutBrandingColors":{"o":{"f":{"global":"CheckoutBrandingColorGlobal","schemes":"CheckoutBrandingColorSchemes"}}}, +"CheckoutBrandingColorsInput":{"i":{"global":"CheckoutBrandingColorGlobalInput","schemes":"CheckoutBrandingColorSchemesInput"}}, +"CheckoutBrandingContainerDivider":{"o":{"f":{"borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth","visibility":"CheckoutBrandingVisibility"}}}, +"CheckoutBrandingContainerDividerInput":{"i":{"borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth","visibility":"CheckoutBrandingVisibility"}}, +"CheckoutBrandingContent":{"o":{"f":{"divider":"CheckoutBrandingContainerDivider"}}}, +"CheckoutBrandingContentInput":{"i":{"divider":"CheckoutBrandingContainerDividerInput"}}, +"CheckoutBrandingControl":{"o":{"f":{"border":"CheckoutBrandingSimpleBorder","color":"CheckoutBrandingColorSelection","cornerRadius":"CheckoutBrandingCornerRadius","labelPosition":"CheckoutBrandingLabelPosition"}}}, +"CheckoutBrandingControlColorRoles":{"o":{"f":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","selected":"CheckoutBrandingColorRoles","text":"String"}}}, +"CheckoutBrandingControlColorRolesInput":{"i":{"accent":"String","background":"String","border":"String","decorative":"String","icon":"String","selected":"CheckoutBrandingColorRolesInput","text":"String"}}, +"CheckoutBrandingControlInput":{"i":{"border":"CheckoutBrandingSimpleBorder","color":"CheckoutBrandingColorSelection","cornerRadius":"CheckoutBrandingCornerRadius","labelPosition":"CheckoutBrandingLabelPosition"}}, +"CheckoutBrandingCornerRadius":{"e":["NONE","SMALL","BASE","LARGE"]}, +"CheckoutBrandingCornerRadiusVariables":{"o":{"f":{"base":"Int","large":"Int","small":"Int"}}}, +"CheckoutBrandingCornerRadiusVariablesInput":{"i":{"base":"Int","large":"Int","small":"Int"}}, +"CheckoutBrandingCustomFont":{"o":{"f":{"genericFileId":"ID","sources":"String","weight":"Int"},"t":["CheckoutBrandingFont"]}}, +"CheckoutBrandingCustomFontGroupInput":{"i":{"base":"CheckoutBrandingCustomFontInput!","bold":"CheckoutBrandingCustomFontInput!","loadingStrategy":"CheckoutBrandingFontLoadingStrategy"}}, +"CheckoutBrandingCustomFontInput":{"i":{"genericFileId":"ID!","weight":"Int!"}}, +"CheckoutBrandingCustomizations":{"o":{"f":{"buyerJourney":"CheckoutBrandingBuyerJourney","cartLink":"CheckoutBrandingCartLink","checkbox":"CheckoutBrandingCheckbox","choiceList":"CheckoutBrandingChoiceList","content":"CheckoutBrandingContent","control":"CheckoutBrandingControl","divider":"CheckoutBrandingDividerStyle","expressCheckout":"CheckoutBrandingExpressCheckout","favicon":"CheckoutBrandingImage","footer":"CheckoutBrandingFooter","global":"CheckoutBrandingGlobal","header":"CheckoutBrandingHeader","headingLevel1":"CheckoutBrandingHeadingLevel","headingLevel2":"CheckoutBrandingHeadingLevel","headingLevel3":"CheckoutBrandingHeadingLevel","main":"CheckoutBrandingMain","merchandiseThumbnail":"CheckoutBrandingMerchandiseThumbnail","orderSummary":"CheckoutBrandingOrderSummary","primaryButton":"CheckoutBrandingButton","secondaryButton":"CheckoutBrandingButton","select":"CheckoutBrandingSelect","textField":"CheckoutBrandingTextField"}}}, +"CheckoutBrandingCustomizationsInput":{"i":{"buyerJourney":"CheckoutBrandingBuyerJourneyInput","cartLink":"CheckoutBrandingCartLinkInput","checkbox":"CheckoutBrandingCheckboxInput","choiceList":"CheckoutBrandingChoiceListInput","content":"CheckoutBrandingContentInput","control":"CheckoutBrandingControlInput","divider":"CheckoutBrandingDividerStyleInput","expressCheckout":"CheckoutBrandingExpressCheckoutInput","favicon":"CheckoutBrandingImageInput","footer":"CheckoutBrandingFooterInput","global":"CheckoutBrandingGlobalInput","header":"CheckoutBrandingHeaderInput","headingLevel1":"CheckoutBrandingHeadingLevelInput","headingLevel2":"CheckoutBrandingHeadingLevelInput","headingLevel3":"CheckoutBrandingHeadingLevelInput","main":"CheckoutBrandingMainInput","merchandiseThumbnail":"CheckoutBrandingMerchandiseThumbnailInput","orderSummary":"CheckoutBrandingOrderSummaryInput","primaryButton":"CheckoutBrandingButtonInput","secondaryButton":"CheckoutBrandingButtonInput","select":"CheckoutBrandingSelectInput","textField":"CheckoutBrandingTextFieldInput"}}, +"CheckoutBrandingDesignSystem":{"o":{"f":{"colors":"CheckoutBrandingColors","cornerRadius":"CheckoutBrandingCornerRadiusVariables","typography":"CheckoutBrandingTypography"}}}, +"CheckoutBrandingDesignSystemInput":{"i":{"colors":"CheckoutBrandingColorsInput","cornerRadius":"CheckoutBrandingCornerRadiusVariablesInput","typography":"CheckoutBrandingTypographyInput"}}, +"CheckoutBrandingDividerStyle":{"o":{"f":{"borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth"}}}, +"CheckoutBrandingDividerStyleInput":{"i":{"borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth"}}, +"CheckoutBrandingExpressCheckout":{"o":{"f":{"button":"CheckoutBrandingExpressCheckoutButton"}}}, +"CheckoutBrandingExpressCheckoutButton":{"o":{"f":{"cornerRadius":"CheckoutBrandingCornerRadius"}}}, +"CheckoutBrandingExpressCheckoutButtonInput":{"i":{"cornerRadius":"CheckoutBrandingCornerRadius"}}, +"CheckoutBrandingExpressCheckoutInput":{"i":{"button":"CheckoutBrandingExpressCheckoutButtonInput"}}, +"CheckoutBrandingFont":{"n":{"f":{"sources":"String","weight":"Int"},"t":["CheckoutBrandingCustomFont","CheckoutBrandingShopifyFont"]}}, +"CheckoutBrandingFontGroup":{"o":{"f":{"base":"CheckoutBrandingFont","bold":"CheckoutBrandingFont","loadingStrategy":"CheckoutBrandingFontLoadingStrategy","name":"String"}}}, +"CheckoutBrandingFontGroupInput":{"i":{"customFontGroup":"CheckoutBrandingCustomFontGroupInput","shopifyFontGroup":"CheckoutBrandingShopifyFontGroupInput"}}, +"CheckoutBrandingFontLoadingStrategy":{"e":["AUTO","BLOCK","SWAP","FALLBACK","OPTIONAL"]}, +"CheckoutBrandingFontSize":{"o":{"f":{"base":"Float","ratio":"Float"}}}, +"CheckoutBrandingFontSizeInput":{"i":{"base":"Float","ratio":"Float"}}, +"CheckoutBrandingFooter":{"o":{"f":{"alignment":"CheckoutBrandingFooterAlignment","colorScheme":"CheckoutBrandingColorSchemeSelection","content":"CheckoutBrandingFooterContent","divided":"Boolean","padding":"CheckoutBrandingSpacingKeyword","position":"CheckoutBrandingFooterPosition"}}}, +"CheckoutBrandingFooterAlignment":{"e":["START","CENTER","END"]}, +"CheckoutBrandingFooterContent":{"o":{"f":{"visibility":"CheckoutBrandingVisibility"}}}, +"CheckoutBrandingFooterContentInput":{"i":{"visibility":"CheckoutBrandingVisibility"}}, +"CheckoutBrandingFooterInput":{"i":{"alignment":"CheckoutBrandingFooterAlignment","colorScheme":"CheckoutBrandingColorSchemeSelection","content":"CheckoutBrandingFooterContentInput","divided":"Boolean","padding":"CheckoutBrandingSpacingKeyword","position":"CheckoutBrandingFooterPosition"}}, +"CheckoutBrandingFooterPosition":{"e":["END","INLINE"]}, +"CheckoutBrandingGlobal":{"o":{"f":{"cornerRadius":"CheckoutBrandingGlobalCornerRadius","typography":"CheckoutBrandingTypographyStyleGlobal"}}}, +"CheckoutBrandingGlobalCornerRadius":{"e":["NONE"]}, +"CheckoutBrandingGlobalInput":{"i":{"cornerRadius":"CheckoutBrandingGlobalCornerRadius","typography":"CheckoutBrandingTypographyStyleGlobalInput"}}, +"CheckoutBrandingHeader":{"o":{"f":{"alignment":"CheckoutBrandingHeaderAlignment","banner":"CheckoutBrandingImage","cartLink":"CheckoutBrandingHeaderCartLink","colorScheme":"CheckoutBrandingColorSchemeSelection","divided":"Boolean","logo":"CheckoutBrandingLogo","padding":"CheckoutBrandingSpacingKeyword","position":"CheckoutBrandingHeaderPosition"}}}, +"CheckoutBrandingHeaderAlignment":{"e":["START","CENTER","END"]}, +"CheckoutBrandingHeaderCartLink":{"o":{"f":{"contentType":"CheckoutBrandingCartLinkContentType","image":"Image"}}}, +"CheckoutBrandingHeaderCartLinkInput":{"i":{"contentType":"CheckoutBrandingCartLinkContentType","image":"CheckoutBrandingImageInput"}}, +"CheckoutBrandingHeaderInput":{"i":{"alignment":"CheckoutBrandingHeaderAlignment","banner":"CheckoutBrandingImageInput","cartLink":"CheckoutBrandingHeaderCartLinkInput","colorScheme":"CheckoutBrandingColorSchemeSelection","divided":"Boolean","logo":"CheckoutBrandingLogoInput","padding":"CheckoutBrandingSpacingKeyword","position":"CheckoutBrandingHeaderPosition"}}, +"CheckoutBrandingHeaderPosition":{"e":["INLINE","INLINE_SECONDARY","START"]}, +"CheckoutBrandingHeadingLevel":{"o":{"f":{"typography":"CheckoutBrandingTypographyStyle"}}}, +"CheckoutBrandingHeadingLevelInput":{"i":{"typography":"CheckoutBrandingTypographyStyleInput"}}, +"CheckoutBrandingImage":{"o":{"f":{"image":"Image"}}}, +"CheckoutBrandingImageInput":{"i":{"mediaImageId":"ID"}}, +"CheckoutBrandingInput":{"i":{"customizations":"CheckoutBrandingCustomizationsInput","designSystem":"CheckoutBrandingDesignSystemInput"}}, +"CheckoutBrandingLabelPosition":{"e":["INSIDE","OUTSIDE"]}, +"CheckoutBrandingLogo":{"o":{"f":{"image":"Image","maxWidth":"Int","visibility":"CheckoutBrandingVisibility"}}}, +"CheckoutBrandingLogoInput":{"i":{"image":"CheckoutBrandingImageInput","maxWidth":"Int","visibility":"CheckoutBrandingVisibility"}}, +"CheckoutBrandingMain":{"o":{"f":{"backgroundImage":"CheckoutBrandingImage","colorScheme":"CheckoutBrandingColorSchemeSelection","divider":"CheckoutBrandingContainerDivider","section":"CheckoutBrandingMainSection"}}}, +"CheckoutBrandingMainInput":{"i":{"backgroundImage":"CheckoutBrandingImageInput","colorScheme":"CheckoutBrandingColorSchemeSelection","divider":"CheckoutBrandingContainerDividerInput","section":"CheckoutBrandingMainSectionInput"}}, +"CheckoutBrandingMainSection":{"o":{"f":{"background":"CheckoutBrandingBackground","border":"CheckoutBrandingSimpleBorder","borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth","colorScheme":"CheckoutBrandingColorSchemeSelection","cornerRadius":"CheckoutBrandingCornerRadius","padding":"CheckoutBrandingSpacingKeyword","shadow":"CheckoutBrandingShadow"}}}, +"CheckoutBrandingMainSectionInput":{"i":{"background":"CheckoutBrandingBackground","border":"CheckoutBrandingSimpleBorder","borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth","colorScheme":"CheckoutBrandingColorSchemeSelection","cornerRadius":"CheckoutBrandingCornerRadius","padding":"CheckoutBrandingSpacingKeyword","shadow":"CheckoutBrandingShadow"}}, +"CheckoutBrandingMerchandiseThumbnail":{"o":{"f":{"badge":"CheckoutBrandingMerchandiseThumbnailBadge","border":"CheckoutBrandingSimpleBorder","cornerRadius":"CheckoutBrandingCornerRadius","fit":"CheckoutBrandingObjectFit"}}}, +"CheckoutBrandingMerchandiseThumbnailBadge":{"o":{"f":{"background":"CheckoutBrandingMerchandiseThumbnailBadgeBackground"}}}, +"CheckoutBrandingMerchandiseThumbnailBadgeBackground":{"e":["ACCENT","BASE"]}, +"CheckoutBrandingMerchandiseThumbnailBadgeInput":{"i":{"background":"CheckoutBrandingMerchandiseThumbnailBadgeBackground"}}, +"CheckoutBrandingMerchandiseThumbnailInput":{"i":{"badge":"CheckoutBrandingMerchandiseThumbnailBadgeInput","border":"CheckoutBrandingSimpleBorder","cornerRadius":"CheckoutBrandingCornerRadius","fit":"CheckoutBrandingObjectFit"}}, +"CheckoutBrandingObjectFit":{"e":["CONTAIN","COVER"]}, +"CheckoutBrandingOrderSummary":{"o":{"f":{"backgroundImage":"CheckoutBrandingImage","colorScheme":"CheckoutBrandingColorSchemeSelection","divider":"CheckoutBrandingContainerDivider","section":"CheckoutBrandingOrderSummarySection"}}}, +"CheckoutBrandingOrderSummaryInput":{"i":{"backgroundImage":"CheckoutBrandingImageInput","colorScheme":"CheckoutBrandingColorSchemeSelection","divider":"CheckoutBrandingContainerDividerInput","section":"CheckoutBrandingOrderSummarySectionInput"}}, +"CheckoutBrandingOrderSummarySection":{"o":{"f":{"background":"CheckoutBrandingBackground","border":"CheckoutBrandingSimpleBorder","borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth","colorScheme":"CheckoutBrandingColorSchemeSelection","cornerRadius":"CheckoutBrandingCornerRadius","padding":"CheckoutBrandingSpacingKeyword","shadow":"CheckoutBrandingShadow"}}}, +"CheckoutBrandingOrderSummarySectionInput":{"i":{"background":"CheckoutBrandingBackground","border":"CheckoutBrandingSimpleBorder","borderStyle":"CheckoutBrandingBorderStyle","borderWidth":"CheckoutBrandingBorderWidth","colorScheme":"CheckoutBrandingColorSchemeSelection","cornerRadius":"CheckoutBrandingCornerRadius","padding":"CheckoutBrandingSpacingKeyword","shadow":"CheckoutBrandingShadow"}}, +"CheckoutBrandingSelect":{"o":{"f":{"border":"CheckoutBrandingBorder","typography":"CheckoutBrandingTypographyStyle"}}}, +"CheckoutBrandingSelectInput":{"i":{"border":"CheckoutBrandingBorder","typography":"CheckoutBrandingTypographyStyleInput"}}, +"CheckoutBrandingShadow":{"e":["SMALL_200","SMALL_100","BASE","LARGE_100","LARGE_200"]}, +"CheckoutBrandingShopifyFont":{"o":{"f":{"sources":"String","weight":"Int"},"t":["CheckoutBrandingFont"]}}, +"CheckoutBrandingShopifyFontGroupInput":{"i":{"baseWeight":"Int","boldWeight":"Int","loadingStrategy":"CheckoutBrandingFontLoadingStrategy","name":"String!"}}, +"CheckoutBrandingSimpleBorder":{"e":["NONE","FULL"]}, +"CheckoutBrandingSpacing":{"e":["NONE","EXTRA_TIGHT","TIGHT","BASE","LOOSE","EXTRA_LOOSE"]}, +"CheckoutBrandingSpacingKeyword":{"e":["NONE","BASE","SMALL","SMALL_100","SMALL_200","SMALL_300","SMALL_400","SMALL_500","LARGE","LARGE_100","LARGE_200","LARGE_300","LARGE_400","LARGE_500"]}, +"CheckoutBrandingTextField":{"o":{"f":{"border":"CheckoutBrandingBorder","typography":"CheckoutBrandingTypographyStyle"}}}, +"CheckoutBrandingTextFieldInput":{"i":{"border":"CheckoutBrandingBorder","typography":"CheckoutBrandingTypographyStyleInput"}}, +"CheckoutBrandingTypography":{"o":{"f":{"primary":"CheckoutBrandingFontGroup","secondary":"CheckoutBrandingFontGroup","size":"CheckoutBrandingFontSize"}}}, +"CheckoutBrandingTypographyFont":{"e":["PRIMARY","SECONDARY"]}, +"CheckoutBrandingTypographyInput":{"i":{"primary":"CheckoutBrandingFontGroupInput","secondary":"CheckoutBrandingFontGroupInput","size":"CheckoutBrandingFontSizeInput"}}, +"CheckoutBrandingTypographyKerning":{"e":["BASE","LOOSE","EXTRA_LOOSE"]}, +"CheckoutBrandingTypographyLetterCase":{"e":["LOWER","NONE","TITLE","UPPER"]}, +"CheckoutBrandingTypographySize":{"e":["EXTRA_SMALL","SMALL","BASE","MEDIUM","LARGE","EXTRA_LARGE","EXTRA_EXTRA_LARGE"]}, +"CheckoutBrandingTypographyStyle":{"o":{"f":{"font":"CheckoutBrandingTypographyFont","kerning":"CheckoutBrandingTypographyKerning","letterCase":"CheckoutBrandingTypographyLetterCase","size":"CheckoutBrandingTypographySize","weight":"CheckoutBrandingTypographyWeight"}}}, +"CheckoutBrandingTypographyStyleGlobal":{"o":{"f":{"kerning":"CheckoutBrandingTypographyKerning","letterCase":"CheckoutBrandingTypographyLetterCase"}}}, +"CheckoutBrandingTypographyStyleGlobalInput":{"i":{"kerning":"CheckoutBrandingTypographyKerning","letterCase":"CheckoutBrandingTypographyLetterCase"}}, +"CheckoutBrandingTypographyStyleInput":{"i":{"font":"CheckoutBrandingTypographyFont","kerning":"CheckoutBrandingTypographyKerning","letterCase":"CheckoutBrandingTypographyLetterCase","size":"CheckoutBrandingTypographySize","weight":"CheckoutBrandingTypographyWeight"}}, +"CheckoutBrandingTypographyWeight":{"e":["BASE","BOLD"]}, +"CheckoutBrandingUpsertPayload":{"o":{"f":{"checkoutBranding":"CheckoutBranding","userErrors":"[CheckoutBrandingUpsertUserError!]!"}}}, +"CheckoutBrandingUpsertUserError":{"o":{"f":{"code":"CheckoutBrandingUpsertUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CheckoutBrandingUpsertUserErrorCode":{"e":["INTERNAL_ERROR"]}, +"CheckoutBrandingVisibility":{"e":["HIDDEN","VISIBLE"]}, +"CheckoutProfile":{"o":{"f":{"createdAt":"DateTime!","editedAt":"DateTime!","id":"ID!","isPublished":"Boolean!","name":"String!","typOspPagesActive":"Boolean!","updatedAt":"DateTime!"},"t":["Node"]}}, +"CheckoutProfileConnection":{"o":{"f":{"edges":"[CheckoutProfileEdge!]!","nodes":"[CheckoutProfile!]!","pageInfo":"PageInfo!"}}}, +"CheckoutProfileEdge":{"o":{"f":{"cursor":"String!","node":"CheckoutProfile!"}}}, +"CheckoutProfileSortKeys":{"e":["CREATED_AT","EDITED_AT","ID","IS_PUBLISHED","UPDATED_AT"]}, +"ChildProductRelationInput":{"i":{"childProductId":"ID!","selectedParentOptionValues":"[SelectedVariantOptionInput!]!"}}, +"CodeDiscountSortKeys":{"e":["CREATED_AT","ENDS_AT","ID","RELEVANCE","STARTS_AT","TITLE","UPDATED_AT"]}, +"Collection":{"o":{"f":{"activeOperations":"CollectionOperations!","availablePublicationsCount":"Count","createdAt":"DateTime!","description":["String!",{"truncateAt":"Int"}],"descriptionHtml":"HTML!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"feedback":"ResourceFeedback","handle":"String!","hasProduct":["Boolean!",{"id":"ID!"}],"id":"ID!","image":["Image",{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","scale":"Int="}],"legacyResourceId":"UnsignedInt64!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"ProductCollectionSortKeys="}],"productsCount":"Count","publicationCount":["Int!",{"onlyPublished":"Boolean="}],"publications":["CollectionPublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"publishedOnChannel":["Boolean!",{"channelId":"ID!"}],"publishedOnCurrentChannel":"Boolean!","publishedOnCurrentPublication":"Boolean!","publishedOnPublication":["Boolean!",{"publicationId":"ID!"}],"resourcePublications":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"resourcePublicationsCount":["Count",{"onlyPublished":"Boolean="}],"resourcePublicationsV2":["ResourcePublicationV2Connection!",{"after":"String","before":"String","catalogType":"CatalogType","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"ruleSet":"CollectionRuleSet","seo":"SEO!","sortOrder":"CollectionSortOrder!","sources":"[CollectionSource!]!","storefrontId":"StorefrontID!","subCollectionEligibility":"CollectionSubCollectionEligibility!","templateSuffix":"String","title":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"unpublishedChannels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"unpublishedPublications":["PublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"updatedAt":"DateTime!"},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","Node","Publishable"],"d":{"image(crop)":"Use `Image.url(transform: { crop:})` instead.","image(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","image(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","image(scale)":"Use `Image.url(transform: { scale:})` instead.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","publicationCount":"Use `resourcePublicationsCount` instead.","publications":"Use `resourcePublications` instead.","publishedOnChannel":"Use `publishedOnPublication` instead.","publishedOnCurrentChannel":"Use `publishedOnCurrentPublication` instead.","publishedOnCurrentPublication":"Use `publishedOnPublication` instead.","ruleSet":"Use `sources` instead.","storefrontId":"Use `id` instead.","unpublishedChannels":"Use `unpublishedPublications` instead."}}}, +"CollectionAddProductsPayload":{"o":{"f":{"collection":"Collection","userErrors":"[UserError!]!"}}}, +"CollectionAddProductsV2Payload":{"o":{"f":{"job":"Job","userErrors":"[CollectionAddProductsV2UserError!]!"}}}, +"CollectionAddProductsV2UserError":{"o":{"f":{"code":"CollectionAddProductsV2UserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CollectionAddProductsV2UserErrorCode":{"e":["CANT_ADD_TO_SMART_COLLECTION","COLLECTION_DOES_NOT_EXIST"]}, +"CollectionConditionBasicMetafieldDefinition":{"o":{"f":{"description":"String","id":"ID!","key":"String!","name":"String!","namespace":"String!","ownerType":"MetafieldOwnerType!","type":"MetafieldDefinitionType!","validations":"[MetafieldDefinitionValidation!]!"},"t":["CollectionConditionMetafieldDefinitionInterface"]}}, +"CollectionConditionMatchType":{"e":["ANY","ALL"]}, +"CollectionConditionMetafieldDefinitionInterface":{"n":{"f":{"description":"String","id":"ID!","key":"String!","name":"String!","namespace":"String!","ownerType":"MetafieldOwnerType!","type":"MetafieldDefinitionType!","validations":"[MetafieldDefinitionValidation!]!"},"t":["CollectionConditionBasicMetafieldDefinition","CollectionConditionMetaobjectMetafieldDefinition"]}}, +"CollectionConditionMetaobjectMetafieldDefinition":{"o":{"f":{"description":"String","id":"ID!","key":"String!","metaobjectDefinition":"MetaobjectDefinition!","name":"String!","namespace":"String!","ownerType":"MetafieldOwnerType!","type":"MetafieldDefinitionType!","validations":"[MetafieldDefinitionValidation!]!"},"t":["CollectionConditionMetafieldDefinitionInterface"]}}, +"CollectionConditionsSource":{"o":{"f":{"app":"App","description":"String","exclusion":"CollectionSourceExclusion","id":"ID!","inclusion":"CollectionSourceInclusion!","products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"shareable":"Boolean!","targetType":"CollectionSourceTargetType!","title":"String!"},"t":["CollectionSource","Node"]}}, +"CollectionConditionsSourceConnection":{"o":{"f":{"edges":"[CollectionConditionsSourceEdge!]!","nodes":"[CollectionConditionsSource!]!","pageInfo":"PageInfo!"}}}, +"CollectionConditionsSourceCreatePayload":{"o":{"f":{"source":"CollectionConditionsSource","userErrors":"[UserError!]!"}}}, +"CollectionConditionsSourceDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[UserError!]!"}}}, +"CollectionConditionsSourceEdge":{"o":{"f":{"cursor":"String!","node":"CollectionConditionsSource!"}}}, +"CollectionConditionsSourceSortKeys":{"e":["ID","TITLE"]}, +"CollectionConditionsSourceUpdatePayload":{"o":{"f":{"source":"CollectionConditionsSource","userErrors":"[UserError!]!"}}}, +"CollectionConditionsSourcesByApp":{"o":{"f":{"app":"App!","sources":["CollectionConditionsSourceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"CollectionConditionsSourceSortKeys="}]}}}, +"CollectionConditionsSourcesByAppConnection":{"o":{"f":{"edges":"[CollectionConditionsSourcesByAppEdge!]!","nodes":"[CollectionConditionsSourcesByApp!]!","pageInfo":"PageInfo!"}}}, +"CollectionConditionsSourcesByAppEdge":{"o":{"f":{"cursor":"String!","node":"CollectionConditionsSourcesByApp!"}}}, +"CollectionConnection":{"o":{"f":{"edges":"[CollectionEdge!]!","nodes":"[Collection!]!","pageInfo":"PageInfo!"}}}, +"CollectionCreateConditionsSourceInput":{"i":{"description":"String","exclusion":"CollectionCreateSourceExclusionInput","inclusion":"CollectionCreateSourceInclusionInput","targetType":"CollectionSourceTargetType=","title":"String!"}}, +"CollectionCreateInput":{"i":{"descriptionHtml":"String","handle":"String","image":"ImageInput","metafields":"[MetafieldInput!]","seo":"SEOInput","sortOrder":"CollectionSortOrder","sources":"[CollectionCreateSourceTargetInput!]","templateSuffix":"String","title":"String!"}}, +"CollectionCreatePayload":{"o":{"f":{"collection":"Collection","userErrors":"[UserError!]!"}}}, +"CollectionCreateSourceExclusionInput":{"i":{"conditions":"[CollectionSourceExclusionConditionInput!]=","matchType":"CollectionConditionMatchType","selections":"[CollectionExclusionProductSelectionInput!]="}}, +"CollectionCreateSourceInclusionInput":{"i":{"conditions":"[CollectionSourceInclusionConditionInput!]=","matchType":"CollectionConditionMatchType","selections":"[CollectionInclusionProductSelectionInput!]="}}, +"CollectionCreateSourceTargetInput":{"i":{"f":{"shareableSource":"CollectionShareableSourceInput","source":"CollectionCreateConditionsSourceInput","subCollections":"CollectionCreateSubCollectionsSourceInput"},"o":true}}, +"CollectionCreateSubCollectionsSourceInput":{"i":{"collectionIds":"[ID!]!","description":"String","title":"String!"}}, +"CollectionDeleteInput":{"i":{"id":"ID!"}}, +"CollectionDeletePayload":{"o":{"f":{"deletedCollectionId":"ID","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"CollectionDuplicateInput":{"i":{"collectionId":"ID!","copyPublications":"Boolean=","newTitle":"String!"}}, +"CollectionDuplicateOperation":{"o":{"f":{"collectionRole":"CollectionDuplicateOperationRole!","job":"Job!"}}}, +"CollectionDuplicateOperationRole":{"e":["SOURCE","TARGET"]}, +"CollectionDuplicatePayload":{"o":{"f":{"collection":"Collection","job":"Job","userErrors":"[CollectionDuplicateUserError!]!"}}}, +"CollectionDuplicateUserError":{"o":{"f":{"code":"CollectionDuplicateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CollectionDuplicateUserErrorCode":{"e":["COLLECTION_NOT_FOUND","BLANK","TOO_LONG","TAKEN","INVALID","TOO_MANY_SUB_COLLECTION_INCLUSION_COLLECTIONS","TOO_MANY_SUB_COLLECTION_EXCLUSION_COLLECTIONS","TOO_MANY_CONDITION_BACKED_SOURCES"]}, +"CollectionEdge":{"o":{"f":{"cursor":"String!","node":"Collection!"}}}, +"CollectionExclusionProductSelection":{"o":{"f":{"product":"Product!"}}}, +"CollectionExclusionProductSelectionConnection":{"o":{"f":{"edges":"[CollectionExclusionProductSelectionEdge!]!","nodes":"[CollectionExclusionProductSelection!]!","pageInfo":"PageInfo!"}}}, +"CollectionExclusionProductSelectionEdge":{"o":{"f":{"cursor":"String!","node":"CollectionExclusionProductSelection!"}}}, +"CollectionExclusionProductSelectionInput":{"i":{"productId":"ID!"}}, +"CollectionIdentifierInput":{"i":{"f":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"},"o":true}}, +"CollectionInclusionProductSelection":{"o":{"f":{"product":"Product!","variantIds":"[ID!]"}}}, +"CollectionInclusionProductSelectionConnection":{"o":{"f":{"edges":"[CollectionInclusionProductSelectionEdge!]!","nodes":"[CollectionInclusionProductSelection!]!","pageInfo":"PageInfo!"}}}, +"CollectionInclusionProductSelectionEdge":{"o":{"f":{"cursor":"String!","node":"CollectionInclusionProductSelection!"}}}, +"CollectionInclusionProductSelectionInput":{"i":{"productId":"ID!","variantIds":"[ID!]"}}, +"CollectionInput":{"i":{"f":{"descriptionHtml":"String","handle":"String","id":"ID","image":"ImageInput","metafields":"[MetafieldInput!]","products":"[ID!]","publications":"[CollectionPublicationInput!]","redirectNewHandle":"Boolean=","ruleSet":"CollectionRuleSetInput","seo":"SEOInput","sortOrder":"CollectionSortOrder","templateSuffix":"String","title":"String"},"d":{"publications":"Use PublishablePublish instead."}}}, +"CollectionOperations":{"o":{"f":{"duplicate":"[CollectionDuplicateOperation!]!"}}}, +"CollectionPublication":{"o":{"f":{"channel":"Channel!","collection":"Collection!","isPublished":"Boolean!","publication":"Publication!","publishDate":"DateTime!"},"d":{"channel":"Use `publication` instead."}}}, +"CollectionPublicationConnection":{"o":{"f":{"edges":"[CollectionPublicationEdge!]!","nodes":"[CollectionPublication!]!","pageInfo":"PageInfo!"}}}, +"CollectionPublicationEdge":{"o":{"f":{"cursor":"String!","node":"CollectionPublication!"}}}, +"CollectionPublicationInput":{"i":{"f":{"channelHandle":"String","channelId":"ID","publicationId":"ID"},"d":{"channelHandle":"Use publicationId instead.","channelId":"Use publicationId instead."}}}, +"CollectionPublishInput":{"i":{"collectionPublications":"[CollectionPublicationInput!]!","id":"ID!"}}, +"CollectionPublishPayload":{"o":{"f":{"collection":"Collection","collectionPublications":"[CollectionPublication!]","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"CollectionRemoveProductsPayload":{"o":{"f":{"job":"Job","userErrors":"[UserError!]!"}}}, +"CollectionReorderProductsPayload":{"o":{"f":{"job":"Job","userErrors":"[CollectionReorderProductsUserError!]!"}}}, +"CollectionReorderProductsUserError":{"o":{"f":{"code":"CollectionReorderProductsUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CollectionReorderProductsUserErrorCode":{"e":["TOO_MANY_ATTEMPTS_TO_REORDER_PRODUCTS","COLLECTION_NOT_FOUND","MANUALLY_SORTED_COLLECTION","INVALID_MOVE"]}, +"CollectionRule":{"o":{"f":{"column":"CollectionRuleColumn!","condition":"String!","conditionObject":"CollectionRuleConditionObject","relation":"CollectionRuleRelation!"}}}, +"CollectionRuleCategoryCondition":{"o":{"f":{"value":"TaxonomyCategory!"}}}, +"CollectionRuleColumn":{"e":["TAG","TITLE","TYPE","PRODUCT_TAXONOMY_NODE_ID","PRODUCT_CATEGORY_ID","PRODUCT_CATEGORY_ID_WITH_DESCENDANTS","VENDOR","VARIANT_PRICE","IS_PRICE_REDUCED","VARIANT_COMPARE_AT_PRICE","VARIANT_WEIGHT","VARIANT_INVENTORY","VARIANT_TITLE","PRODUCT_METAFIELD_DEFINITION","VARIANT_METAFIELD_DEFINITION"]}, +"CollectionRuleConditionObject":{"u":["CollectionRuleCategoryCondition","CollectionRuleMetafieldCondition","CollectionRuleProductCategoryCondition","CollectionRuleTextCondition"]}, +"CollectionRuleConditions":{"o":{"f":{"allowedRelations":"[CollectionRuleRelation!]!","defaultRelation":"CollectionRuleRelation!","ruleObject":"CollectionRuleConditionsRuleObject","ruleType":"CollectionRuleColumn!"}}}, +"CollectionRuleConditionsRuleObject":{"u":["CollectionRuleMetafieldCondition"]}, +"CollectionRuleInput":{"i":{"column":"CollectionRuleColumn!","condition":"String!","conditionObjectId":"ID","relation":"CollectionRuleRelation!"}}, +"CollectionRuleMetafieldCondition":{"o":{"f":{"metafieldDefinition":"MetafieldDefinition!"}}}, +"CollectionRuleProductCategoryCondition":{"o":{"f":{"value":"ProductTaxonomyNode!"}}}, +"CollectionRuleRelation":{"e":["CONTAINS","ENDS_WITH","EQUALS","GREATER_THAN","IS_NOT_SET","IS_SET","LESS_THAN","NOT_CONTAINS","NOT_EQUALS","STARTS_WITH"]}, +"CollectionRuleSet":{"o":{"f":{"appliedDisjunctively":"Boolean!","rules":"[CollectionRule!]!"}}}, +"CollectionRuleSetInput":{"i":{"appliedDisjunctively":"Boolean!","rules":"[CollectionRuleInput!]"}}, +"CollectionRuleTextCondition":{"o":{"f":{"value":"String!"}}}, +"CollectionShareableSourceInput":{"i":{"sourceId":"ID!"}}, +"CollectionSortKeys":{"e":["ID","RELEVANCE","TITLE","UPDATED_AT"]}, +"CollectionSortOrder":{"e":["ALPHA_ASC","ALPHA_DESC","BEST_SELLING","MOST_RELEVANT","CREATED","CREATED_DESC","MANUAL","PRICE_ASC","PRICE_DESC"]}, +"CollectionSource":{"n":{"f":{"app":"App","description":"String","id":"ID!","title":"String!"},"t":["CollectionConditionsSource","CollectionSubCollectionsSource"]}}, +"CollectionSourceExclusion":{"o":{"f":{"conditions":"[CollectionSourceExclusionCondition!]!","matchType":"CollectionConditionMatchType","selections":["CollectionExclusionProductSelectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"CollectionSourceExclusionCondition":{"n":{"f":{"id":"ID!"},"t":["CollectionSourceExclusionConditionCollection","CollectionSourceExclusionConditionProductCategory","CollectionSourceExclusionConditionProductTag","CollectionSourceExclusionConditionProductType","CollectionSourceExclusionConditionProductVendor","CollectionSourceExclusionConditionUnknown"]}}, +"CollectionSourceExclusionConditionCollection":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","values":"[Collection!]!"},"t":["CollectionSourceExclusionCondition"]}}, +"CollectionSourceExclusionConditionCollectionInput":{"i":{"values":"[ID!]!"}}, +"CollectionSourceExclusionConditionInput":{"i":{"f":{"collection":"CollectionSourceExclusionConditionCollectionInput","productCategory":"CollectionSourceExclusionConditionProductCategoryInput","productTag":"CollectionSourceExclusionConditionProductTagInput","productType":"CollectionSourceExclusionConditionProductTypeInput","productVendor":"CollectionSourceExclusionConditionProductVendorInput"},"o":true}}, +"CollectionSourceExclusionConditionProductCategory":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductCategoryRelation!","values":"[CollectionSourceExclusionConditionProductCategoryValue!]!"},"t":["CollectionSourceExclusionCondition"]}}, +"CollectionSourceExclusionConditionProductCategoryInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductCategoryRelation!","values":"[CollectionSourceExclusionConditionProductCategoryValueInput!]!"}}, +"CollectionSourceExclusionConditionProductCategoryRelation":{"e":["EQUALS"]}, +"CollectionSourceExclusionConditionProductCategoryValue":{"o":{"f":{"category":"TaxonomyCategory!","includeDescendants":"Boolean!"}}}, +"CollectionSourceExclusionConditionProductCategoryValueInput":{"i":{"categoryId":"ID!","includeDescendants":"Boolean="}}, +"CollectionSourceExclusionConditionProductTag":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductTagRelation!","values":"[String!]!"},"t":["CollectionSourceExclusionCondition"]}}, +"CollectionSourceExclusionConditionProductTagInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductTagRelation!","values":"[String!]!"}}, +"CollectionSourceExclusionConditionProductTagRelation":{"e":["TAGGED_WITH"]}, +"CollectionSourceExclusionConditionProductType":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductTypeRelation!","values":"[String!]!"},"t":["CollectionSourceExclusionCondition"]}}, +"CollectionSourceExclusionConditionProductTypeInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductTypeRelation!","values":"[String!]!"}}, +"CollectionSourceExclusionConditionProductTypeRelation":{"e":["EQUALS","CONTAINS"]}, +"CollectionSourceExclusionConditionProductVendor":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductVendorRelation!","values":"[String!]!"},"t":["CollectionSourceExclusionCondition"]}}, +"CollectionSourceExclusionConditionProductVendorInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceExclusionConditionProductVendorRelation!","values":"[String!]!"}}, +"CollectionSourceExclusionConditionProductVendorRelation":{"e":["EQUALS","CONTAINS"]}, +"CollectionSourceExclusionConditionUnknown":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType","relation":"String","values":"[String!]"},"t":["CollectionSourceExclusionCondition"]}}, +"CollectionSourceExclusionConditionUpdateCollectionInput":{"i":{"values":"[ID!]!"}}, +"CollectionSourceExclusionConditionUpdateInput":{"i":{"f":{"collection":"CollectionSourceExclusionConditionUpdateCollectionInput","productCategory":"CollectionSourceExclusionConditionUpdateProductCategoryInput","productTag":"CollectionSourceExclusionConditionUpdateProductTagInput","productType":"CollectionSourceExclusionConditionUpdateProductTypeInput","productVendor":"CollectionSourceExclusionConditionUpdateProductVendorInput"},"o":true}}, +"CollectionSourceExclusionConditionUpdateProductCategoryInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceExclusionConditionProductCategoryRelation","values":"[CollectionSourceExclusionConditionProductCategoryValueInput!]"}}, +"CollectionSourceExclusionConditionUpdateProductTagInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceExclusionConditionProductTagRelation","values":"[String!]"}}, +"CollectionSourceExclusionConditionUpdateProductTypeInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceExclusionConditionProductTypeRelation","values":"[String!]"}}, +"CollectionSourceExclusionConditionUpdateProductVendorInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceExclusionConditionProductVendorRelation","values":"[String!]"}}, +"CollectionSourceInclusion":{"o":{"f":{"conditions":"[CollectionSourceInclusionCondition!]!","matchType":"CollectionConditionMatchType","selections":["CollectionInclusionProductSelectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"CollectionSourceInclusionCondition":{"n":{"f":{"id":"ID!"},"t":["CollectionSourceInclusionConditionMetafieldBoolean","CollectionSourceInclusionConditionMetafieldDecimal","CollectionSourceInclusionConditionMetafieldInt","CollectionSourceInclusionConditionMetafieldInteger","CollectionSourceInclusionConditionMetafieldMetaobject","CollectionSourceInclusionConditionMetafieldMetaobjectList","CollectionSourceInclusionConditionMetafieldString","CollectionSourceInclusionConditionMetafieldStringList","CollectionSourceInclusionConditionProductCategory","CollectionSourceInclusionConditionProductStatus","CollectionSourceInclusionConditionProductTag","CollectionSourceInclusionConditionProductTitle","CollectionSourceInclusionConditionProductType","CollectionSourceInclusionConditionProductVendor","CollectionSourceInclusionConditionUnknown","CollectionSourceInclusionConditionVariantCompareAtPrice","CollectionSourceInclusionConditionVariantInventory","CollectionSourceInclusionConditionVariantPrice","CollectionSourceInclusionConditionVariantTitle","CollectionSourceInclusionConditionVariantWeight"]}}, +"CollectionSourceInclusionConditionInput":{"i":{"f":{"metafieldBoolean":"CollectionSourceInclusionConditionMetafieldBooleanInput","metafieldDecimal":"CollectionSourceInclusionConditionMetafieldDecimalInput","metafieldInt":"CollectionSourceInclusionConditionMetafieldIntInput","metafieldInteger":"CollectionSourceInclusionConditionMetafieldIntegerInput","metafieldMetaobject":"CollectionSourceInclusionConditionMetafieldMetaobjectInput","metafieldMetaobjectList":"CollectionSourceInclusionConditionMetafieldMetaobjectListInput","metafieldString":"CollectionSourceInclusionConditionMetafieldStringInput","metafieldStringList":"CollectionSourceInclusionConditionMetafieldStringListInput","productCategory":"CollectionSourceInclusionConditionProductCategoryInput","productStatus":"CollectionSourceInclusionConditionProductStatusInput","productTag":"CollectionSourceInclusionConditionProductTagInput","productTitle":"CollectionSourceInclusionConditionProductTitleInput","productType":"CollectionSourceInclusionConditionProductTypeInput","productVendor":"CollectionSourceInclusionConditionProductVendorInput","variantCompareAtPrice":"CollectionSourceInclusionConditionVariantCompareAtPriceInput","variantInventory":"CollectionSourceInclusionConditionVariantInventoryInput","variantPrice":"CollectionSourceInclusionConditionVariantPriceInput","variantTitle":"CollectionSourceInclusionConditionVariantTitleInput","variantWeight":"CollectionSourceInclusionConditionVariantWeightInput"},"d":{"metafieldInteger":"Use `metafieldInt` instead. Integer metafields support values beyond the range of GraphQL's 32-bit `Int`. Removed as of the 2027-01 release."},"o":true}}, +"CollectionSourceInclusionConditionMetafield":{"n":{"f":{"definition":"MetafieldDefinition!","id":"ID!"},"t":["CollectionSourceInclusionConditionMetafieldBoolean","CollectionSourceInclusionConditionMetafieldDecimal","CollectionSourceInclusionConditionMetafieldInt","CollectionSourceInclusionConditionMetafieldInteger","CollectionSourceInclusionConditionMetafieldMetaobject","CollectionSourceInclusionConditionMetafieldMetaobjectList","CollectionSourceInclusionConditionMetafieldString","CollectionSourceInclusionConditionMetafieldStringList"]}}, +"CollectionSourceInclusionConditionMetafieldBoolean":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","relation":"CollectionSourceInclusionConditionMetafieldBooleanRelation!","value":"Boolean!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"]}}, +"CollectionSourceInclusionConditionMetafieldBooleanInput":{"i":{"definitionId":"ID!","relation":"CollectionSourceInclusionConditionMetafieldBooleanRelation!","value":"Boolean!"}}, +"CollectionSourceInclusionConditionMetafieldBooleanRelation":{"e":["EQUALS"]}, +"CollectionSourceInclusionConditionMetafieldDecimal":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","relation":"CollectionSourceInclusionConditionMetafieldDecimalRelation!","value":"Decimal!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"]}}, +"CollectionSourceInclusionConditionMetafieldDecimalInput":{"i":{"definitionId":"ID!","relation":"CollectionSourceInclusionConditionMetafieldDecimalRelation!","value":"Decimal!"}}, +"CollectionSourceInclusionConditionMetafieldDecimalRelation":{"e":["EQUALS","GREATER_THAN","LESS_THAN"]}, +"CollectionSourceInclusionConditionMetafieldInt":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","relation":"CollectionSourceInclusionConditionMetafieldIntRelation!","value":"String!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"]}}, +"CollectionSourceInclusionConditionMetafieldIntInput":{"i":{"definitionId":"ID!","relation":"CollectionSourceInclusionConditionMetafieldIntRelation!","value":"String!"}}, +"CollectionSourceInclusionConditionMetafieldIntRelation":{"e":["EQUALS","GREATER_THAN","LESS_THAN"]}, +"CollectionSourceInclusionConditionMetafieldInteger":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","relation":"CollectionSourceInclusionConditionMetafieldIntegerRelation!","value":"Int!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"],"d":{"relation":"Use `CollectionSourceInclusionConditionMetafieldInt.relation` instead. That type replaces this one entirely and supports integer metafield values beyond the range of GraphQL's 32-bit `Int`.","value":"Use `CollectionSourceInclusionConditionMetafieldInt.value` instead. That type replaces this one entirely and supports integer metafield values beyond the range of GraphQL's 32-bit `Int`."}}}, +"CollectionSourceInclusionConditionMetafieldIntegerInput":{"i":{"definitionId":"ID!","relation":"CollectionSourceInclusionConditionMetafieldIntegerRelation!","value":"Int!"}}, +"CollectionSourceInclusionConditionMetafieldIntegerRelation":{"e":["EQUALS","GREATER_THAN","LESS_THAN"]}, +"CollectionSourceInclusionConditionMetafieldMetaobject":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","relation":"CollectionSourceInclusionConditionMetafieldMetaobjectRelation!","value":"Metaobject!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"]}}, +"CollectionSourceInclusionConditionMetafieldMetaobjectInput":{"i":{"definitionId":"ID!","relation":"CollectionSourceInclusionConditionMetafieldMetaobjectRelation!","value":"ID!"}}, +"CollectionSourceInclusionConditionMetafieldMetaobjectList":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionMetafieldMetaobjectListRelation!","values":"[Metaobject!]!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"]}}, +"CollectionSourceInclusionConditionMetafieldMetaobjectListInput":{"i":{"definitionId":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionMetafieldMetaobjectListRelation!","values":"[ID!]!"}}, +"CollectionSourceInclusionConditionMetafieldMetaobjectListRelation":{"e":["INCLUDES"]}, +"CollectionSourceInclusionConditionMetafieldMetaobjectRelation":{"e":["EQUALS"]}, +"CollectionSourceInclusionConditionMetafieldString":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionMetafieldStringRelation!","values":"[String!]!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"]}}, +"CollectionSourceInclusionConditionMetafieldStringInput":{"i":{"definitionId":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionMetafieldStringRelation!","values":"[String!]!"}}, +"CollectionSourceInclusionConditionMetafieldStringList":{"o":{"f":{"definition":"MetafieldDefinition!","id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionMetafieldStringListRelation!","values":"[String!]!"},"t":["CollectionSourceInclusionCondition","CollectionSourceInclusionConditionMetafield"]}}, +"CollectionSourceInclusionConditionMetafieldStringListInput":{"i":{"definitionId":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionMetafieldStringListRelation!","values":"[String!]!"}}, +"CollectionSourceInclusionConditionMetafieldStringListRelation":{"e":["INCLUDES"]}, +"CollectionSourceInclusionConditionMetafieldStringRelation":{"e":["EQUALS"]}, +"CollectionSourceInclusionConditionProductCategory":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductCategoryRelation!","values":"[CollectionSourceInclusionConditionProductCategoryValue!]!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionProductCategoryInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductCategoryRelation!","values":"[CollectionSourceInclusionConditionProductCategoryValueInput!]!"}}, +"CollectionSourceInclusionConditionProductCategoryRelation":{"e":["EQUALS","NOT_EQUALS"]}, +"CollectionSourceInclusionConditionProductCategoryValue":{"o":{"f":{"category":"TaxonomyCategory!","includeDescendants":"Boolean!"}}}, +"CollectionSourceInclusionConditionProductCategoryValueInput":{"i":{"categoryId":"ID!","includeDescendants":"Boolean!"}}, +"CollectionSourceInclusionConditionProductStatus":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductStatusRelation!","values":"[ProductStatus!]!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionProductStatusInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductStatusRelation!","values":"[ProductStatus!]!"}}, +"CollectionSourceInclusionConditionProductStatusRelation":{"e":["EQUALS","NOT_EQUALS"]}, +"CollectionSourceInclusionConditionProductTag":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductTagRelation!","values":"[String!]!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionProductTagInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductTagRelation!","values":"[String!]!"}}, +"CollectionSourceInclusionConditionProductTagRelation":{"e":["TAGGED_WITH","NOT_TAGGED_WITH"]}, +"CollectionSourceInclusionConditionProductTitle":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductTitleRelation!","values":"[String!]!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionProductTitleInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductTitleRelation!","values":"[String!]!"}}, +"CollectionSourceInclusionConditionProductTitleRelation":{"e":["EQUALS","NOT_EQUALS","CONTAINS","DOES_NOT_CONTAIN","STARTS_WITH","ENDS_WITH"]}, +"CollectionSourceInclusionConditionProductType":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductTypeRelation!","values":"[String!]!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionProductTypeInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductTypeRelation!","values":"[String!]!"}}, +"CollectionSourceInclusionConditionProductTypeRelation":{"e":["EQUALS","NOT_EQUALS","STARTS_WITH","ENDS_WITH","CONTAINS","DOES_NOT_CONTAIN"]}, +"CollectionSourceInclusionConditionProductVendor":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductVendorRelation!","values":"[String!]!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionProductVendorInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionProductVendorRelation!","values":"[String!]!"}}, +"CollectionSourceInclusionConditionProductVendorRelation":{"e":["EQUALS","NOT_EQUALS","STARTS_WITH","ENDS_WITH","CONTAINS","DOES_NOT_CONTAIN"]}, +"CollectionSourceInclusionConditionUnknown":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType","relation":"String","values":"[String!]"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionUpdateInput":{"i":{"f":{"metafieldBoolean":"CollectionSourceInclusionConditionUpdateMetafieldBooleanInput","metafieldDecimal":"CollectionSourceInclusionConditionUpdateMetafieldDecimalInput","metafieldInt":"CollectionSourceInclusionConditionUpdateMetafieldIntInput","metafieldInteger":"CollectionSourceInclusionConditionUpdateMetafieldIntegerInput","metafieldMetaobject":"CollectionSourceInclusionConditionUpdateMetafieldMetaobjectInput","metafieldMetaobjectList":"CollectionSourceInclusionConditionUpdateMetafieldMetaobjectListInput","metafieldString":"CollectionSourceInclusionConditionUpdateMetafieldStringInput","metafieldStringList":"CollectionSourceInclusionConditionUpdateMetafieldStringListInput","productCategory":"CollectionSourceInclusionConditionUpdateProductCategoryInput","productStatus":"CollectionSourceInclusionConditionUpdateProductStatusInput","productTag":"CollectionSourceInclusionConditionUpdateProductTagInput","productTitle":"CollectionSourceInclusionConditionUpdateProductTitleInput","productType":"CollectionSourceInclusionConditionUpdateProductTypeInput","productVendor":"CollectionSourceInclusionConditionUpdateProductVendorInput","variantCompareAtPrice":"CollectionSourceInclusionConditionUpdateVariantCompareAtPriceInput","variantInventory":"CollectionSourceInclusionConditionUpdateVariantInventoryInput","variantPrice":"CollectionSourceInclusionConditionUpdateVariantPriceInput","variantTitle":"CollectionSourceInclusionConditionUpdateVariantTitleInput","variantWeight":"CollectionSourceInclusionConditionUpdateVariantWeightInput"},"d":{"metafieldInteger":"Use `metafieldInt` instead. Integer metafields support values beyond the range of GraphQL's 32-bit `Int`. Removed as of the 2027-01 release."},"o":true}}, +"CollectionSourceInclusionConditionUpdateMetafieldBooleanInput":{"i":{"definitionId":"ID","relation":"CollectionSourceInclusionConditionMetafieldBooleanRelation","value":"Boolean"}}, +"CollectionSourceInclusionConditionUpdateMetafieldDecimalInput":{"i":{"definitionId":"ID","relation":"CollectionSourceInclusionConditionMetafieldDecimalRelation","value":"Decimal"}}, +"CollectionSourceInclusionConditionUpdateMetafieldIntInput":{"i":{"definitionId":"ID","relation":"CollectionSourceInclusionConditionMetafieldIntRelation","value":"String"}}, +"CollectionSourceInclusionConditionUpdateMetafieldIntegerInput":{"i":{"definitionId":"ID","relation":"CollectionSourceInclusionConditionMetafieldIntegerRelation","value":"Int"}}, +"CollectionSourceInclusionConditionUpdateMetafieldMetaobjectInput":{"i":{"definitionId":"ID","relation":"CollectionSourceInclusionConditionMetafieldMetaobjectRelation","value":"ID"}}, +"CollectionSourceInclusionConditionUpdateMetafieldMetaobjectListInput":{"i":{"definitionId":"ID","matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionMetafieldMetaobjectListRelation","values":"[ID!]"}}, +"CollectionSourceInclusionConditionUpdateMetafieldStringInput":{"i":{"definitionId":"ID","matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionMetafieldStringRelation","values":"[String!]"}}, +"CollectionSourceInclusionConditionUpdateMetafieldStringListInput":{"i":{"definitionId":"ID","matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionMetafieldStringListRelation","values":"[String!]"}}, +"CollectionSourceInclusionConditionUpdateProductCategoryInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionProductCategoryRelation","values":"[CollectionSourceInclusionConditionProductCategoryValueInput!]"}}, +"CollectionSourceInclusionConditionUpdateProductStatusInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionProductStatusRelation","values":"[ProductStatus!]"}}, +"CollectionSourceInclusionConditionUpdateProductTagInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionProductTagRelation","values":"[String!]"}}, +"CollectionSourceInclusionConditionUpdateProductTitleInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionProductTitleRelation","values":"[String!]"}}, +"CollectionSourceInclusionConditionUpdateProductTypeInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionProductTypeRelation","values":"[String!]"}}, +"CollectionSourceInclusionConditionUpdateProductVendorInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionProductVendorRelation","values":"[String!]"}}, +"CollectionSourceInclusionConditionUpdateVariantCompareAtPriceInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantCompareAtPriceRelation","value":"MoneyInput"}}, +"CollectionSourceInclusionConditionUpdateVariantInventoryInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantInventoryRelation","value":"Int"}}, +"CollectionSourceInclusionConditionUpdateVariantPriceInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantPriceRelation","value":"MoneyInput"}}, +"CollectionSourceInclusionConditionUpdateVariantTitleInput":{"i":{"matchType":"CollectionConditionMatchType","relation":"CollectionSourceInclusionConditionVariantTitleRelation","values":"[String!]"}}, +"CollectionSourceInclusionConditionUpdateVariantWeightInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantWeightRelation","value":"WeightInput"}}, +"CollectionSourceInclusionConditionVariantCompareAtPrice":{"o":{"f":{"id":"ID!","relation":"CollectionSourceInclusionConditionVariantCompareAtPriceRelation!","value":"MoneyV2"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionVariantCompareAtPriceInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantCompareAtPriceRelation!","value":"MoneyInput"}}, +"CollectionSourceInclusionConditionVariantCompareAtPriceRelation":{"e":["EQUALS","NOT_EQUALS","GREATER_THAN","LESS_THAN","IS_SET","IS_NOT_SET"]}, +"CollectionSourceInclusionConditionVariantInventory":{"o":{"f":{"id":"ID!","relation":"CollectionSourceInclusionConditionVariantInventoryRelation!","value":"Int!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionVariantInventoryInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantInventoryRelation!","value":"Int!"}}, +"CollectionSourceInclusionConditionVariantInventoryRelation":{"e":["EQUALS","GREATER_THAN","LESS_THAN"]}, +"CollectionSourceInclusionConditionVariantPrice":{"o":{"f":{"id":"ID!","relation":"CollectionSourceInclusionConditionVariantPriceRelation!","value":"MoneyV2!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionVariantPriceInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantPriceRelation!","value":"MoneyInput!"}}, +"CollectionSourceInclusionConditionVariantPriceRelation":{"e":["EQUALS","NOT_EQUALS","GREATER_THAN","LESS_THAN"]}, +"CollectionSourceInclusionConditionVariantTitle":{"o":{"f":{"id":"ID!","matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionVariantTitleRelation!","values":"[String!]!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionVariantTitleInput":{"i":{"matchType":"CollectionConditionMatchType!","relation":"CollectionSourceInclusionConditionVariantTitleRelation!","values":"[String!]!"}}, +"CollectionSourceInclusionConditionVariantTitleRelation":{"e":["EQUALS","NOT_EQUALS","STARTS_WITH","ENDS_WITH","CONTAINS","DOES_NOT_CONTAIN"]}, +"CollectionSourceInclusionConditionVariantWeight":{"o":{"f":{"id":"ID!","relation":"CollectionSourceInclusionConditionVariantWeightRelation!","value":"Weight!"},"t":["CollectionSourceInclusionCondition"]}}, +"CollectionSourceInclusionConditionVariantWeightInput":{"i":{"relation":"CollectionSourceInclusionConditionVariantWeightRelation!","value":"WeightInput!"}}, +"CollectionSourceInclusionConditionVariantWeightRelation":{"e":["EQUALS","NOT_EQUALS","GREATER_THAN","LESS_THAN"]}, +"CollectionSourceTargetType":{"e":["PRODUCTS","VARIANTS"]}, +"CollectionSubCollectionEligibility":{"o":{"f":{"exclusion":"CollectionSubCollectionEligibilityState!","inclusion":"CollectionSubCollectionEligibilityState!"}}}, +"CollectionSubCollectionEligibilityState":{"o":{"f":{"eligible":"Boolean!","ineligibleReason":"SubCollectionIneligibleReason"}}}, +"CollectionSubCollectionsSource":{"o":{"f":{"app":"App","collections":"[Collection!]!","description":"String","id":"ID!","title":"String!"},"t":["CollectionSource","Node"]}}, +"CollectionUnpublishInput":{"i":{"collectionPublications":"[CollectionPublicationInput!]!","id":"ID!"}}, +"CollectionUnpublishPayload":{"o":{"f":{"collection":"Collection","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"CollectionUpdateConditionsSourceInput":{"i":{"description":"String","exclusion":"CollectionUpdateSourceExclusionInput","id":"ID!","inclusion":"CollectionUpdateSourceInclusionInput","title":"String"}}, +"CollectionUpdateInput":{"i":{"descriptionHtml":"String","handle":"String","id":"ID","image":"ImageInput","metafields":"[MetafieldInput!]","redirectNewHandle":"Boolean=","seo":"SEOInput","sortOrder":"CollectionSortOrder","sourcesToCreate":"[CollectionCreateSourceTargetInput!]","sourcesToDelete":"[ID!]","sourcesToUpdate":"[CollectionUpdateSourceTargetInput!]","templateSuffix":"String","title":"String"}}, +"CollectionUpdatePayload":{"o":{"f":{"collection":"Collection","job":"Job","userErrors":"[UserError!]!"}}}, +"CollectionUpdateSourceExclusionConditionInput":{"i":{"condition":"CollectionSourceExclusionConditionUpdateInput!","id":"ID!"}}, +"CollectionUpdateSourceExclusionInput":{"i":{"conditionsToCreate":"[CollectionSourceExclusionConditionInput!]","conditionsToDelete":"[ID!]","conditionsToUpdate":"[CollectionUpdateSourceExclusionConditionInput!]","matchType":"CollectionConditionMatchType","selectionsToAdd":"[CollectionExclusionProductSelectionInput!]","selectionsToRemove":"[CollectionExclusionProductSelectionInput!]"}}, +"CollectionUpdateSourceInclusionConditionInput":{"i":{"condition":"CollectionSourceInclusionConditionUpdateInput!","id":"ID!"}}, +"CollectionUpdateSourceInclusionInput":{"i":{"conditionsToCreate":"[CollectionSourceInclusionConditionInput!]","conditionsToDelete":"[ID!]","conditionsToUpdate":"[CollectionUpdateSourceInclusionConditionInput!]","matchType":"CollectionConditionMatchType","selectionsToAdd":"[CollectionInclusionProductSelectionInput!]","selectionsToRemove":"[CollectionInclusionProductSelectionInput!]"}}, +"CollectionUpdateSourceTargetInput":{"i":{"f":{"condition":"CollectionUpdateConditionsSourceInput","subCollections":"CollectionUpdateSubCollectionsSourceInput"},"o":true}}, +"CollectionUpdateSubCollectionsSourceInput":{"i":{"collectionIds":"[ID!]","description":"String","id":"ID!","title":"String"}}, +"Color":"s", +"ColumnDataType":{"e":["UNSPECIFIED","MONEY","PERCENT","INTEGER","FLOAT","DECIMAL","STRING","BOOLEAN","TIMESTAMP","MINUTE_TIMESTAMP","HOUR_TIMESTAMP","DAY_TIMESTAMP","WEEK_TIMESTAMP","MONTH_TIMESTAMP","QUARTER_TIMESTAMP","YEAR_TIMESTAMP","DAY_OF_WEEK","HOUR_OF_DAY","IDENTITY","MONTH_OF_YEAR","WEEK_OF_YEAR","SECOND_TIMESTAMP","ARRAY","MILLISECOND_DURATION","SECOND_DURATION","MINUTE_DURATION","HOUR_DURATION","DAY_DURATION","CUMULATIVE","GEO_COORDINATE","ENTITY","COLOR","STRING_IDENTITY","RATING","UNITLESS_SCALAR","MULTIPLIER"]}, +"CombinedListing":{"o":{"f":{"combinedListingChildren":["CombinedListingChildConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"parentProduct":"Product!"}}}, +"CombinedListingChild":{"o":{"f":{"parentVariant":"ProductVariant!","product":"Product!"}}}, +"CombinedListingChildConnection":{"o":{"f":{"edges":"[CombinedListingChildEdge!]!","nodes":"[CombinedListingChild!]!","pageInfo":"PageInfo!"}}}, +"CombinedListingChildEdge":{"o":{"f":{"cursor":"String!","node":"CombinedListingChild!"}}}, +"CombinedListingUpdatePayload":{"o":{"f":{"product":"Product","userErrors":"[CombinedListingUpdateUserError!]!"}}}, +"CombinedListingUpdateUserError":{"o":{"f":{"code":"CombinedListingUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CombinedListingUpdateUserErrorCode":{"e":["CANNOT_HAVE_DUPLICATED_PRODUCTS","CANNOT_HAVE_PARENT_AS_CHILD","CANNOT_HAVE_REPEATED_OPTION_VALUES","CANNOT_HAVE_REPEATED_OPTIONS","CANT_ADD_OPTIONS_VALUES_IF_ALREADY_EXISTS","COMBINED_LISTINGS_NOT_ENABLED","EDIT_AND_REMOVE_ON_SAME_PRODUCTS","FAILED_TO_ADD_PRODUCTS","FAILED_TO_REMOVE_PRODUCTS","FAILED_TO_UPDATE_PRODUCTS","LINKED_METAFIELD_CANNOT_BE_CHANGED","LINKED_METAFIELD_VALUE_MISSING","LINKED_METAFIELDS_CANNOT_BE_REPEATED","LINKED_OPTIONS_NOT_SUPPORTED_FOR_SHOP","MISSING_OPTION_VALUES","MUST_HAVE_SELECTED_OPTION_VALUES","OPTION_NAME_CANNOT_BE_BLANK","OPTION_NAME_CONTAINS_INVALID_CHARACTERS","OPTION_NOT_FOUND","OPTIONS_MUST_BE_EQUAL_TO_THE_OTHER_COMPONENTS","OPTION_VALUES_CANNOT_BE_BLANK","OPTION_VALUES_CANNOT_BE_EMPTY","OPTION_VALUES_MUST_BE_COMPLETE","PARENT_PRODUCT_CANNOT_BE_COMBINED_LISTING_CHILD","PARENT_PRODUCT_MUST_BE_A_COMBINED_LISTING","PARENT_PRODUCT_MUST_HAVE_CATEGORY","PARENT_PRODUCT_NOT_FOUND","PRODUCT_IS_ALREADY_A_CHILD","PRODUCT_MEMBERSHIP_NOT_FOUND","PRODUCT_NOT_FOUND","TITLE_TOO_LONG","TOO_MANY_VARIANTS","TOO_MANY_PRODUCTS","UNEXPECTED_ERROR"]}, +"CombinedListingsRole":{"e":["PARENT","CHILD"]}, +"Comment":{"o":{"f":{"article":"Article","author":"CommentAuthor!","body":"String!","bodyHtml":"HTML!","createdAt":"DateTime!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"id":"ID!","ip":"String","isPublished":"Boolean!","publishedAt":"DateTime","status":"CommentStatus!","updatedAt":"DateTime","userAgent":"String"},"t":["HasEvents","Node"]}}, +"CommentApprovePayload":{"o":{"f":{"comment":"Comment","userErrors":"[CommentApproveUserError!]!"}}}, +"CommentApproveUserError":{"o":{"f":{"code":"CommentApproveUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CommentApproveUserErrorCode":{"e":["NOT_FOUND"]}, +"CommentAuthor":{"o":{"f":{"email":"String!","name":"String!"}}}, +"CommentConnection":{"o":{"f":{"edges":"[CommentEdge!]!","nodes":"[Comment!]!","pageInfo":"PageInfo!"}}}, +"CommentDeletePayload":{"o":{"f":{"deletedCommentId":"ID","userErrors":"[CommentDeleteUserError!]!"}}}, +"CommentDeleteUserError":{"o":{"f":{"code":"CommentDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CommentDeleteUserErrorCode":{"e":["NOT_FOUND"]}, +"CommentEdge":{"o":{"f":{"cursor":"String!","node":"Comment!"}}}, +"CommentEvent":{"o":{"f":{"action":"String!","appTitle":"String","attachments":"[CommentEventAttachment!]!","attributeToApp":"Boolean!","attributeToUser":"Boolean!","author":"StaffMember!","canDelete":"Boolean!","canEdit":"Boolean!","createdAt":"DateTime!","criticalAlert":"Boolean!","edited":"Boolean!","embed":"CommentEventEmbed","id":"ID!","message":"FormattedString!","rawMessage":"String!","subject":"CommentEventSubject"},"t":["Event","Node"]}}, +"CommentEventAttachment":{"o":{"f":{"fileExtension":"String","id":"ID!","image":["Image",{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","scale":"Int="}],"name":"String!","size":"Int!","url":"URL!"},"d":{"image(crop)":"Use `Image.url(transform: { crop:})` instead.","image(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","image(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","image(scale)":"Use `Image.url(transform: { scale:})` instead."}}}, +"CommentEventEmbed":{"u":["Customer","DraftOrder","InventoryTransfer","Order","Product","ProductVariant"]}, +"CommentEventSubject":{"n":{"f":{"hasTimelineComment":"Boolean!","id":"ID!"},"t":["Company","CompanyLocation","Customer","DraftOrder","InventoryTransfer","Order"]}}, +"CommentNotSpamPayload":{"o":{"f":{"comment":"Comment","userErrors":"[CommentNotSpamUserError!]!"}}}, +"CommentNotSpamUserError":{"o":{"f":{"code":"CommentNotSpamUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CommentNotSpamUserErrorCode":{"e":["NOT_FOUND"]}, +"CommentPolicy":{"e":["AUTO_PUBLISHED","CLOSED","MODERATED"]}, +"CommentSortKeys":{"e":["CREATED_AT","ID"]}, +"CommentSpamPayload":{"o":{"f":{"comment":"Comment","userErrors":"[CommentSpamUserError!]!"}}}, +"CommentSpamUserError":{"o":{"f":{"code":"CommentSpamUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CommentSpamUserErrorCode":{"e":["NOT_FOUND"]}, +"CommentStatus":{"e":["SPAM","REMOVED","PUBLISHED","UNAPPROVED","PENDING"]}, +"CompaniesDeletePayload":{"o":{"f":{"deletedCompanyIds":"[ID!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"Company":{"o":{"f":{"contactCount":"Int!","contactRoles":["CompanyContactRoleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"CompanyContactRoleSortKeys="}],"contacts":["CompanyContactConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanyContactSortKeys="}],"contactsCount":"Count","createdAt":"DateTime!","customerSince":"DateTime!","defaultCursor":"String!","defaultRole":"CompanyContactRole","draftOrders":["DraftOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"DraftOrderSortKeys="}],"events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"externalId":"String","hasTimelineComment":"Boolean!","id":"ID!","lifetimeDuration":"String!","locations":["CompanyLocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanyLocationSortKeys="}],"locationsCount":"Count","mainContact":"CompanyContact","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","note":"String","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"OrderSortKeys="}],"ordersCount":"Count","totalSpent":"MoneyV2!","updatedAt":"DateTime!"},"t":["CommentEventSubject","HasEvents","HasMetafieldDefinitions","HasMetafields","Navigable","Node"],"d":{"contactCount":"Use `contactsCount` instead.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"CompanyAddress":{"o":{"f":{"address1":"String!","address2":"String","city":"String","companyName":"String!","country":"String","countryCode":"CountryCode!","createdAt":"DateTime!","firstName":"String","formattedAddress":["[String!]!",{"withCompanyName":"Boolean=","withName":"Boolean="}],"formattedArea":"String","id":"ID!","lastName":"String","phone":"String","province":"String","recipient":"String","updatedAt":"DateTime!","zip":"String","zoneCode":"String"},"t":["Node"]}}, +"CompanyAddressDeletePayload":{"o":{"f":{"deletedAddressId":"ID","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyAddressInput":{"i":{"address1":"String","address2":"String","city":"String","countryCode":"CountryCode","firstName":"String","lastName":"String","phone":"String","recipient":"String","zip":"String","zoneCode":"String"}}, +"CompanyAddressType":{"e":["BILLING","SHIPPING"]}, +"CompanyAssignCustomerAsContactPayload":{"o":{"f":{"companyContact":"CompanyContact","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyAssignMainContactPayload":{"o":{"f":{"company":"Company","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyConnection":{"o":{"f":{"edges":"[CompanyEdge!]!","nodes":"[Company!]!","pageInfo":"PageInfo!"}}}, +"CompanyContact":{"o":{"f":{"company":"Company!","createdAt":"DateTime!","customer":"Customer!","draftOrders":["DraftOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"DraftOrderSortKeys="}],"id":"ID!","isMainContact":"Boolean!","lifetimeDuration":"String!","locale":"String","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"OrderSortKeys="}],"roleAssignments":["CompanyContactRoleAssignmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanyContactRoleAssignmentSortKeys="}],"title":"String","updatedAt":"DateTime!"},"t":["Node"]}}, +"CompanyContactAssignRolePayload":{"o":{"f":{"companyContactRoleAssignment":"CompanyContactRoleAssignment","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactAssignRolesPayload":{"o":{"f":{"roleAssignments":"[CompanyContactRoleAssignment!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactConnection":{"o":{"f":{"edges":"[CompanyContactEdge!]!","nodes":"[CompanyContact!]!","pageInfo":"PageInfo!"}}}, +"CompanyContactCreatePayload":{"o":{"f":{"companyContact":"CompanyContact","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactDeletePayload":{"o":{"f":{"deletedCompanyContactId":"ID","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactEdge":{"o":{"f":{"cursor":"String!","node":"CompanyContact!"}}}, +"CompanyContactInput":{"i":{"email":"String","firstName":"String","lastName":"String","locale":"String","phone":"String","title":"String"}}, +"CompanyContactRemoveFromCompanyPayload":{"o":{"f":{"removedCompanyContactId":"ID","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactRevokeRolePayload":{"o":{"f":{"revokedCompanyContactRoleAssignmentId":"ID","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactRevokeRolesPayload":{"o":{"f":{"revokedRoleAssignmentIds":"[ID!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactRole":{"o":{"f":{"id":"ID!","name":"String!","note":"String"},"t":["Node"]}}, +"CompanyContactRoleAssign":{"i":{"companyContactRoleId":"ID!","companyLocationId":"ID!"}}, +"CompanyContactRoleAssignment":{"o":{"f":{"company":"Company!","companyContact":"CompanyContact!","companyLocation":"CompanyLocation!","createdAt":"DateTime!","id":"ID!","role":"CompanyContactRole!","updatedAt":"DateTime!"},"t":["Node"]}}, +"CompanyContactRoleAssignmentConnection":{"o":{"f":{"edges":"[CompanyContactRoleAssignmentEdge!]!","nodes":"[CompanyContactRoleAssignment!]!","pageInfo":"PageInfo!"}}}, +"CompanyContactRoleAssignmentEdge":{"o":{"f":{"cursor":"String!","node":"CompanyContactRoleAssignment!"}}}, +"CompanyContactRoleAssignmentSortKeys":{"e":["CREATED_AT","ID","LOCATION_NAME","UPDATED_AT"]}, +"CompanyContactRoleConnection":{"o":{"f":{"edges":"[CompanyContactRoleEdge!]!","nodes":"[CompanyContactRole!]!","pageInfo":"PageInfo!"}}}, +"CompanyContactRoleEdge":{"o":{"f":{"cursor":"String!","node":"CompanyContactRole!"}}}, +"CompanyContactRoleSortKeys":{"e":["CREATED_AT","ID","UPDATED_AT"]}, +"CompanyContactSendWelcomeEmailPayload":{"o":{"f":{"companyContact":"CompanyContact","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactSortKeys":{"e":["COMPANY_ID","CREATED_AT","EMAIL","ID","NAME","NAME_EMAIL","RELEVANCE","TITLE","UPDATED_AT"]}, +"CompanyContactUpdatePayload":{"o":{"f":{"companyContact":"CompanyContact","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyContactsDeletePayload":{"o":{"f":{"deletedCompanyContactIds":"[ID!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyCreateInput":{"i":{"company":"CompanyInput!","companyContact":"CompanyContactInput","companyLocation":"CompanyLocationInput"}}, +"CompanyCreatePayload":{"o":{"f":{"company":"Company","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyDeletePayload":{"o":{"f":{"deletedCompanyId":"ID","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyEdge":{"o":{"f":{"cursor":"String!","node":"Company!"}}}, +"CompanyInput":{"i":{"customerSince":"DateTime","externalId":"String","name":"String","note":"String"}}, +"CompanyLocation":{"o":{"f":{"billingAddress":"CompanyAddress","buyerExperienceConfiguration":"BuyerExperienceConfiguration","catalogs":["CatalogConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"catalogsCount":["Count",{"limit":"Int="}],"company":"Company!","createdAt":"DateTime!","currency":"CurrencyCode!","defaultCursor":"String!","draftOrders":["DraftOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"DraftOrderSortKeys="}],"events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"externalId":"String","hasTimelineComment":"Boolean!","id":"ID!","inCatalog":["Boolean!",{"catalogId":"ID!"}],"locale":"String","market":"Market!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","note":"String","orderCount":"Int!","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"OrderSortKeys="}],"ordersCount":"Count","phone":"String","roleAssignments":["CompanyContactRoleAssignmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanyContactRoleAssignmentSortKeys="}],"shippingAddress":"CompanyAddress","staffMemberAssignments":["CompanyLocationStaffMemberAssignmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanyLocationStaffMemberAssignmentSortKeys="}],"storeCreditAccounts":["StoreCreditAccountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String"}],"taxExemptions":"[TaxExemption!]!","taxRegistrationId":"String","taxSettings":"CompanyLocationTaxSettings!","totalSpent":"MoneyV2!","updatedAt":"DateTime!"},"t":["CommentEventSubject","HasEvents","HasMetafieldDefinitions","HasMetafields","HasStoreCreditAccounts","Navigable","Node"],"d":{"market":"This `market` field will be removed in a future version of the API.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","orderCount":"Use `ordersCount` instead.","taxExemptions":"Use `taxSettings` instead.","taxRegistrationId":"Use `taxSettings` instead."}}}, +"CompanyLocationAssignAddressPayload":{"o":{"f":{"addresses":"[CompanyAddress!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationAssignRolesPayload":{"o":{"f":{"roleAssignments":"[CompanyContactRoleAssignment!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationAssignStaffMembersPayload":{"o":{"f":{"companyLocationStaffMemberAssignments":"[CompanyLocationStaffMemberAssignment!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationAssignTaxExemptionsPayload":{"o":{"f":{"companyLocation":"CompanyLocation","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationCatalog":{"o":{"f":{"companyLocations":["CompanyLocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanyLocationSortKeys="}],"companyLocationsCount":"Count","id":"ID!","operations":"[ResourceOperation!]!","priceList":"PriceList","publication":"Publication","status":"CatalogStatus!","title":"String!"},"t":["Catalog","Node"]}}, +"CompanyLocationConnection":{"o":{"f":{"edges":"[CompanyLocationEdge!]!","nodes":"[CompanyLocation!]!","pageInfo":"PageInfo!"}}}, +"CompanyLocationCreatePayload":{"o":{"f":{"companyLocation":"CompanyLocation","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationCreateTaxRegistrationPayload":{"o":{"f":{"companyLocation":"CompanyLocation","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationDeletePayload":{"o":{"f":{"deletedCompanyLocationId":"ID","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationEdge":{"o":{"f":{"cursor":"String!","node":"CompanyLocation!"}}}, +"CompanyLocationInput":{"i":{"billingAddress":"CompanyAddressInput","billingSameAsShipping":"Boolean","buyerExperienceConfiguration":"BuyerExperienceConfigurationInput","externalId":"String","locale":"String","name":"String","note":"String","phone":"String","shippingAddress":"CompanyAddressInput","taxExempt":"Boolean","taxExemptions":"[TaxExemption!]","taxRegistrationId":"String"}}, +"CompanyLocationRemoveStaffMembersPayload":{"o":{"f":{"deletedCompanyLocationStaffMemberAssignmentIds":"[ID!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationRevokeRolesPayload":{"o":{"f":{"revokedRoleAssignmentIds":"[ID!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationRevokeTaxExemptionsPayload":{"o":{"f":{"companyLocation":"CompanyLocation","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationRevokeTaxRegistrationPayload":{"o":{"f":{"companyLocation":"CompanyLocation","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationRoleAssign":{"i":{"companyContactId":"ID!","companyContactRoleId":"ID!"}}, +"CompanyLocationSortKeys":{"e":["COMPANY_AND_LOCATION_NAME","COMPANY_ID","CREATED_AT","ID","NAME","RELEVANCE","UPDATED_AT"]}, +"CompanyLocationStaffMemberAssignment":{"o":{"f":{"companyLocation":"CompanyLocation!","id":"ID!","staffMember":"StaffMember!"},"t":["Node"]}}, +"CompanyLocationStaffMemberAssignmentConnection":{"o":{"f":{"edges":"[CompanyLocationStaffMemberAssignmentEdge!]!","nodes":"[CompanyLocationStaffMemberAssignment!]!","pageInfo":"PageInfo!"}}}, +"CompanyLocationStaffMemberAssignmentEdge":{"o":{"f":{"cursor":"String!","node":"CompanyLocationStaffMemberAssignment!"}}}, +"CompanyLocationStaffMemberAssignmentSortKeys":{"e":["CREATED_AT","ID","UPDATED_AT"]}, +"CompanyLocationTaxSettings":{"o":{"f":{"taxExempt":"Boolean!","taxExemptions":"[TaxExemption!]!","taxRegistrationId":"String"}}}, +"CompanyLocationTaxSettingsUpdatePayload":{"o":{"f":{"companyLocation":"CompanyLocation","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationUpdateInput":{"i":{"buyerExperienceConfiguration":"BuyerExperienceConfigurationInput","externalId":"String","locale":"String","name":"String","note":"String","phone":"String"}}, +"CompanyLocationUpdatePayload":{"o":{"f":{"companyLocation":"CompanyLocation","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyLocationsCondition":{"o":{"f":{"applicationLevel":"MarketConditionApplicationType","companyLocations":["CompanyLocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"CompanyLocationsDeletePayload":{"o":{"f":{"deletedCompanyLocationIds":"[ID!]","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanyRevokeMainContactPayload":{"o":{"f":{"company":"Company","userErrors":"[BusinessCustomerUserError!]!"}}}, +"CompanySortKeys":{"e":["CREATED_AT","ID","NAME","ORDER_COUNT","SINCE_DATE","TOTAL_SPENT","UPDATED_AT"]}, +"CompanyUpdatePayload":{"o":{"f":{"company":"Company","userErrors":"[BusinessCustomerUserError!]!"}}}, +"ComponentizedProductsBundleConsolidatedOption":{"o":{"f":{"name":"String!","selections":"[ComponentizedProductsBundleConsolidatedOptionSelection!]!"}}}, +"ComponentizedProductsBundleConsolidatedOptionSelection":{"o":{"f":{"components":"[ComponentizedProductsBundleConsolidatedOptionSelectionComponent!]!","value":"String!"}}}, +"ComponentizedProductsBundleConsolidatedOptionSelectionComponent":{"o":{"f":{"optionId":"ID!","value":"String!"}}}, +"ConsentPolicy":{"o":{"f":{"consentRequired":"Boolean","countryCode":"PrivacyCountryCode","dataSaleOptOutRequired":"Boolean","id":"ID!","regionCode":"String","shopId":"ID!"},"t":["Node"]}}, +"ConsentPolicyError":{"o":{"f":{"code":"ConsentPolicyErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ConsentPolicyErrorCode":{"e":["COUNTRY_CODE_REQUIRED","REGION_CODE_REQUIRED","REGION_CODE_MUST_MATCH_COUNTRY_CODE","SHOPIFY_COOKIE_BANNER_NOT_DISABLED","UNSUPORTED_CONSENT_POLICY"]}, +"ConsentPolicyInput":{"i":{"consentRequired":"Boolean","countryCode":"PrivacyCountryCode","dataSaleOptOutRequired":"Boolean","regionCode":"String"}}, +"ConsentPolicyRegion":{"o":{"f":{"countryCode":"PrivacyCountryCode","regionCode":"String"}}}, +"ConsentPolicyUpdatePayload":{"o":{"f":{"updatedPolicies":"[ConsentPolicy!]","userErrors":"[ConsentPolicyError!]!"}}}, +"ContextualPricingContext":{"i":{"companyLocationId":"ID","country":"CountryCode","locationId":"ID"}}, +"ContextualPublicationContext":{"i":{"companyLocationId":"ID","country":"CountryCode","locationId":"ID"}}, +"CookieBanner":{"o":{"f":{"autoManaged":"Boolean!","enabled":"Boolean!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}]},"t":["HasPublishedTranslations"]}}, +"Count":{"o":{"f":{"count":"Int!","precision":"CountPrecision!"}}}, +"CountPrecision":{"e":["EXACT","AT_LEAST"]}, +"CountriesInShippingZones":{"o":{"f":{"countryCodes":"[CountryCode!]!","includeRestOfWorld":"Boolean!"}}}, +"CountryCode":{"e":["AF","AX","AL","DZ","AD","AO","AI","AG","AR","AM","AW","AC","AU","AT","AZ","BS","BH","BD","BB","BY","BE","BZ","BJ","BM","BT","BO","BA","BW","BV","BR","IO","BN","BG","BF","BI","KH","CA","CV","BQ","KY","CF","TD","CL","CN","CX","CC","CO","KM","CG","CD","CK","CR","HR","CU","CW","CY","CZ","CI","DK","DJ","DM","DO","EC","EG","SV","GQ","ER","EE","SZ","ET","FK","FO","FJ","FI","FR","GF","PF","TF","GA","GM","GE","DE","GH","GI","GR","GL","GD","GP","GT","GG","GN","GW","GY","HT","HM","VA","HN","HK","HU","IS","IN","ID","IR","IQ","IE","IM","IL","IT","JM","JP","JE","JO","KZ","KE","KI","KP","XK","KW","KG","LA","LV","LB","LS","LR","LY","LI","LT","LU","MO","MG","MW","MY","MV","ML","MT","MQ","MR","MU","YT","MX","MD","MC","MN","ME","MS","MA","MZ","MM","NA","NR","NP","NL","AN","NC","NZ","NI","NE","NG","NU","NF","MK","NO","OM","PK","PS","PA","PG","PY","PE","PH","PN","PL","PT","QA","CM","RE","RO","RU","RW","BL","SH","KN","LC","MF","PM","WS","SM","ST","SA","SN","RS","SC","SL","SG","SX","SK","SI","SB","SO","ZA","GS","KR","SS","ES","LK","VC","SD","SR","SJ","SE","CH","SY","TW","TJ","TZ","TH","TL","TG","TK","TO","TT","TA","TN","TR","TM","TC","TV","UG","UA","AE","GB","US","UM","UY","UZ","VU","VE","VN","VG","WF","EH","YE","ZM","ZW","ZZ"]}, +"CountryHarmonizedSystemCode":{"o":{"f":{"countryCode":"CountryCode!","harmonizedSystemCode":"String!"}}}, +"CountryHarmonizedSystemCodeConnection":{"o":{"f":{"edges":"[CountryHarmonizedSystemCodeEdge!]!","nodes":"[CountryHarmonizedSystemCode!]!","pageInfo":"PageInfo!"}}}, +"CountryHarmonizedSystemCodeEdge":{"o":{"f":{"cursor":"String!","node":"CountryHarmonizedSystemCode!"}}}, +"CountryHarmonizedSystemCodeInput":{"i":{"countryCode":"CountryCode","harmonizedSystemCode":"String!"}}, +"CreateMediaInput":{"i":{"alt":"String","mediaContentType":"MediaContentType!","originalSource":"String!"}}, +"CropRegion":{"e":["CENTER","TOP","BOTTOM","LEFT","RIGHT"]}, +"CurrencyCode":{"e":{"v":["USD","EUR","GBP","CAD","AFN","ALL","DZD","AOA","ARS","AMD","AWG","AUD","BBD","AZN","BDT","BSD","BHD","BIF","BYN","BZD","BMD","BTN","BAM","BRL","BOB","BWP","BND","BGN","MMK","KHR","CVE","XCG","KYD","XAF","CLP","CNY","COP","KMF","CDF","CRC","HRK","CZK","DKK","DJF","DOP","XCD","EGP","ERN","ETB","FKP","XPF","FJD","GIP","GMD","GHS","GTQ","GYD","GEL","GNF","HTG","HNL","HKD","HUF","ISK","INR","IDR","ILS","IRR","IQD","JMD","JPY","JEP","JOD","KZT","KES","KID","KWD","KGS","LAK","LVL","LBP","LSL","LRD","LYD","LTL","MGA","MKD","MOP","MWK","MVR","MRU","MXN","MYR","MUR","MDL","MAD","MNT","MZN","NAD","NPR","ANG","NZD","NIO","NGN","NOK","OMR","PAB","PKR","PGK","PYG","PEN","PHP","PLN","QAR","RON","RUB","RWF","WST","SHP","SAR","RSD","SCR","SLL","SGD","SDG","SOS","SYP","ZAR","KRW","SSP","SBD","LKR","SRD","SZL","SEK","CHF","TWD","THB","TJS","TZS","TOP","TTD","TND","TRY","TMT","UGX","UAH","AED","UYU","UZS","VUV","VES","VND","XOF","YER","ZMW","USDC","BYR","STD","STN","VED","VEF","XXX"],"d":{"ANG":"Use `XCG` instead.","BYR":"Use `BYN` instead.","STD":"Use `STN` instead.","VEF":"Use `VES` instead."}}}, +"CurrencyExchangeAdjustment":{"o":{"f":{"adjustment":"MoneyV2!","finalAmountSet":"MoneyV2!","id":"ID!","originalAmountSet":"MoneyV2!"},"t":["Node"]}}, +"CurrencyFormats":{"o":{"f":{"moneyFormat":"FormattedString!","moneyInEmailsFormat":"String!","moneyWithCurrencyFormat":"FormattedString!","moneyWithCurrencyInEmailsFormat":"String!"}}}, +"CurrencySetting":{"o":{"f":{"currencyCode":"CurrencyCode!","currencyName":"String!","enabled":"Boolean!","manualRate":"Decimal","rateUpdatedAt":"DateTime"}}}, +"CurrencySettingConnection":{"o":{"f":{"edges":"[CurrencySettingEdge!]!","nodes":"[CurrencySetting!]!","pageInfo":"PageInfo!"}}}, +"CurrencySettingEdge":{"o":{"f":{"cursor":"String!","node":"CurrencySetting!"}}}, +"CustomShippingPackageInput":{"i":{"default":"Boolean=","dimensions":"ObjectDimensionsInput","name":"String","type":"ShippingPackageType","weight":"WeightInput"}}, +"Customer":{"o":{"f":{"addresses":["[MailingAddress!]!",{"first":"Int"}],"addressesV2":["MailingAddressConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"amountSpent":"MoneyV2!","canDelete":"Boolean!","companyContactProfiles":"[CompanyContact!]!","createdAt":"DateTime!","dataSaleOptOut":"Boolean!","defaultAddress":"MailingAddress","defaultEmailAddress":"CustomerEmailAddress","defaultPhoneNumber":"CustomerPhoneNumber","displayName":"String!","email":"String","emailMarketingConsent":"CustomerEmailMarketingConsentState","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"firstName":"String","hasTimelineComment":"Boolean!","id":"ID!","identityProviderSubjects":"[IdentityProviderSubject!]!","image":["Image!",{"size":"Int"}],"lastName":"String","lastOrder":"Order","legacyResourceId":"UnsignedInt64!","lifetimeDuration":"String!","locale":"String!","market":"Market","mergeable":"CustomerMergeable!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"multipassIdentifier":"String","note":"String","numberOfOrders":"UnsignedInt64!","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"OrderSortKeys="}],"paymentMethods":["CustomerPaymentMethodConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","showRevoked":"Boolean="}],"phone":"String","productSubscriberStatus":"CustomerProductSubscriberStatus!","smsMarketingConsent":"CustomerSmsMarketingConsentState","state":"CustomerState!","statistics":"CustomerStatistics!","storeCreditAccounts":["StoreCreditAccountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String"}],"subscriptionContracts":["SubscriptionContractConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"tags":"[String!]!","taxExempt":"Boolean!","taxExemptions":"[TaxExemption!]!","taxSettings":"TaxSettings!","unsubscribeUrl":"URL!","updatedAt":"DateTime!","validEmailAddress":"Boolean!","verifiedEmail":"Boolean!"},"t":["CommentEventSubject","HasEvents","HasMetafieldDefinitions","HasMetafields","HasStoreCreditAccounts","LegacyInteroperability","Node"],"d":{"addresses":"Limited to 250 addresses. Use `addressesV2` for paginated access to all addresses.","email":"Use `defaultEmailAddress.emailAddress` instead.","emailMarketingConsent":"Use `defaultEmailAddress.marketingState`, `defaultEmailAddress.marketingOptInLevel`, `defaultEmailAddress.marketingUpdatedAt`, and `defaultEmailAddress.sourceLocation` instead.","hasTimelineComment":"To query for comments on the timeline, use the `events` connection and a 'query' argument containing `verb:comment`, or look for a 'CommentEvent' in the `__typename` of `events`.","image(size)":"Use `maxWidth` or `maxHeight` on `Image.transformedSrc` instead.","market":"This `market` field will be removed in a future version of the API.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","phone":"Use `defaultPhoneNumber.phoneNumber` instead.","smsMarketingConsent":"Use `defaultPhoneNumber.marketingState`, `defaultPhoneNumber.marketingOptInLevel`, `defaultPhoneNumber.marketingUpdatedAt`, `defaultPhoneNumber.marketingCollectedFrom`, and `defaultPhoneNumber.sourceLocation` instead.","unsubscribeUrl":"Use `defaultEmailAddress.marketingUnsubscribeUrl` instead.","validEmailAddress":"Use `defaultEmailAddress.validFormat` instead."}}}, +"CustomerAccountAppExtensionPage":{"o":{"f":{"appExtensionUuid":"String","defaultCursor":"String!","handle":"String!","id":"ID!","title":"String!"},"t":["CustomerAccountPage","Navigable","Node"]}}, +"CustomerAccountNativePage":{"o":{"f":{"defaultCursor":"String!","handle":"String!","id":"ID!","pageType":"CustomerAccountNativePagePageType!","title":"String!"},"t":["CustomerAccountPage","Navigable","Node"]}}, +"CustomerAccountNativePagePageType":{"e":["NATIVE_ORDERS","NATIVE_SETTINGS","NATIVE_PROFILE","UNKNOWN"]}, +"CustomerAccountPage":{"n":{"f":{"defaultCursor":"String!","handle":"String!","id":"ID!","title":"String!"},"t":["CustomerAccountAppExtensionPage","CustomerAccountNativePage"]}}, +"CustomerAccountPageConnection":{"o":{"f":{"edges":"[CustomerAccountPageEdge!]!","nodes":"[CustomerAccountPage!]!","pageInfo":"PageInfo!"}}}, +"CustomerAccountPageEdge":{"o":{"f":{"cursor":"String!","node":"CustomerAccountPage!"}}}, +"CustomerAccountsV2":{"o":{"f":{"customerAccountsVersion":"CustomerAccountsVersion!","loginLinksVisibleOnStorefrontAndCheckout":"Boolean!","loginRequiredAtCheckout":"Boolean!","url":"URL"}}}, +"CustomerAccountsVersion":{"e":["CLASSIC","NEW_CUSTOMER_ACCOUNTS"]}, +"CustomerAddTaxExemptionsPayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"CustomerAddressCreatePayload":{"o":{"f":{"address":"MailingAddress","userErrors":"[UserError!]!"}}}, +"CustomerAddressDeletePayload":{"o":{"f":{"deletedAddressId":"ID","userErrors":"[UserError!]!"}}}, +"CustomerAddressUpdatePayload":{"o":{"f":{"address":"MailingAddress","userErrors":"[UserError!]!"}}}, +"CustomerCancelDataErasureErrorCode":{"e":["DOES_NOT_EXIST","FAILED_TO_CANCEL","NOT_BEING_ERASED","UNAUTHORIZED_CANCELLATION"]}, +"CustomerCancelDataErasurePayload":{"o":{"f":{"customerId":"ID","userErrors":"[CustomerCancelDataErasureUserError!]!"}}}, +"CustomerCancelDataErasureUserError":{"o":{"f":{"code":"CustomerCancelDataErasureErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerConnection":{"o":{"f":{"edges":"[CustomerEdge!]!","nodes":"[Customer!]!","pageInfo":"PageInfo!"}}}, +"CustomerConsentCollectedFrom":{"e":["SHOPIFY","OTHER"]}, +"CustomerCreatePayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"CustomerCreditCard":{"o":{"f":{"billingAddress":"CustomerCreditCardBillingAddress","brand":"String!","expiresSoon":"Boolean!","expiryMonth":"Int!","expiryYear":"Int!","firstDigits":"String","isRevocable":"Boolean!","lastDigits":"String!","maskedNumber":"String!","name":"String!","source":"String","virtualLastDigits":"String"}}}, +"CustomerCreditCardBillingAddress":{"o":{"f":{"address1":"String","city":"String","country":"String","countryCode":"CountryCode","firstName":"String","lastName":"String","province":"String","provinceCode":"String","zip":"String"}}}, +"CustomerDeleteInput":{"i":{"id":"ID!"}}, +"CustomerDeletePayload":{"o":{"f":{"deletedCustomerId":"ID","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"CustomerEdge":{"o":{"f":{"cursor":"String!","node":"Customer!"}}}, +"CustomerEmailAddress":{"o":{"f":{"emailAddress":"String!","marketingOptInLevel":"CustomerMarketingOptInLevel","marketingState":"CustomerEmailAddressMarketingState!","marketingUnsubscribeUrl":"URL!","marketingUpdatedAt":"DateTime","openTrackingLevel":"CustomerEmailAddressOpenTrackingLevel!","openTrackingUrl":"URL!","sourceLocation":"Location","validFormat":"Boolean!"}}}, +"CustomerEmailAddressMarketingState":{"e":["INVALID","NOT_SUBSCRIBED","PENDING","SUBSCRIBED","UNSUBSCRIBED"]}, +"CustomerEmailAddressOpenTrackingLevel":{"e":["UNKNOWN","OPTED_IN","OPTED_OUT"]}, +"CustomerEmailMarketingConsentInput":{"i":{"consentUpdatedAt":"DateTime","marketingOptInLevel":"CustomerMarketingOptInLevel","marketingState":"CustomerEmailMarketingState!","sourceLocationId":"ID"}}, +"CustomerEmailMarketingConsentState":{"o":{"f":{"consentUpdatedAt":"DateTime","marketingOptInLevel":"CustomerMarketingOptInLevel","marketingState":"CustomerEmailMarketingState!","sourceLocation":"Location"}}}, +"CustomerEmailMarketingConsentUpdateInput":{"i":{"customerId":"ID!","emailMarketingConsent":"CustomerEmailMarketingConsentInput!"}}, +"CustomerEmailMarketingConsentUpdatePayload":{"o":{"f":{"customer":"Customer","userErrors":"[CustomerEmailMarketingConsentUpdateUserError!]!"}}}, +"CustomerEmailMarketingConsentUpdateUserError":{"o":{"f":{"code":"CustomerEmailMarketingConsentUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerEmailMarketingConsentUpdateUserErrorCode":{"e":["INVALID","INCLUSION","INTERNAL_ERROR","MISSING_ARGUMENT"]}, +"CustomerEmailMarketingState":{"e":["NOT_SUBSCRIBED","PENDING","SUBSCRIBED","UNSUBSCRIBED","REDACTED","INVALID"]}, +"CustomerGenerateAccountActivationUrlPayload":{"o":{"f":{"accountActivationUrl":"URL","userErrors":"[UserError!]!"}}}, +"CustomerIdentifierInput":{"i":{"f":{"customId":"UniqueMetafieldValueInput","emailAddress":"String","id":"ID","phoneNumber":"String"},"o":true}}, +"CustomerInput":{"i":{"f":{"addresses":"[MailingAddressInput!]","email":"String","emailMarketingConsent":"CustomerEmailMarketingConsentInput","firstName":"String","id":"ID","lastName":"String","locale":"String","metafields":"[MetafieldInput!]","multipassIdentifier":"String","note":"String","phone":"String","smsMarketingConsent":"CustomerSmsMarketingConsentInput","tags":"[String!]","taxExempt":"Boolean","taxExemptions":"[TaxExemption!]","whatsAppMarketingConsent":"CustomerMarketingConsentInput"},"d":{"addresses":"Use the dedicated address mutations (`customerAddressCreate`, `customerAddressUpdate`, `customerAddressDelete`) instead."}}}, +"CustomerJourney":{"o":{"f":{"customerOrderIndex":"Int!","daysToConversion":"Int!","firstVisit":"CustomerVisit!","lastVisit":"CustomerVisit","moments":"[CustomerMoment!]!"}}}, +"CustomerJourneySummary":{"o":{"f":{"customerOrderIndex":"Int","daysToConversion":"Int","firstVisit":"CustomerVisit","lastVisit":"CustomerVisit","moments":["CustomerMomentConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"momentsCount":"Count","ready":"Boolean!"}}}, +"CustomerMarketingConsent":{"n":{"f":{"collectedFrom":"CustomerConsentCollectedFrom","optInLevel":"CustomerMarketingOptInLevel","sourceLocation":"Location","state":"CustomerMarketingConsentState!","updatedAt":"DateTime"},"t":["CustomerSmsMarketingConsent","CustomerWhatsAppMarketingConsent"]}}, +"CustomerMarketingConsentError":{"o":{"f":{"code":"CustomerMarketingConsentErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerMarketingConsentErrorCode":{"e":["INVALID","INCLUSION","INTERNAL_ERROR","MISSING_ARGUMENT"]}, +"CustomerMarketingConsentInput":{"i":{"optInLevel":"CustomerMarketingOptInLevel","sourceLocationId":"ID","state":"CustomerMarketingConsentState!","updatedAt":"DateTime"}}, +"CustomerMarketingConsentState":{"e":["NEVER_SUBSCRIBED","PENDING","SUBSCRIBED","UNSUBSCRIBED","REDACTED"]}, +"CustomerMarketingOptInLevel":{"e":["SINGLE_OPT_IN","CONFIRMED_OPT_IN","UNKNOWN"]}, +"CustomerMergeError":{"o":{"f":{"errorFields":"[CustomerMergeErrorFieldType!]!","message":"String!"}}}, +"CustomerMergeErrorCode":{"e":["INTERNAL_ERROR","INVALID_CUSTOMER","INVALID_CUSTOMER_ID","CUSTOMER_HAS_GIFT_CARDS","MISSING_OVERRIDE_ATTRIBUTE","OVERRIDE_ATTRIBUTE_INVALID"]}, +"CustomerMergeErrorFieldType":{"e":["DELETED_AT","REDACTED_AT","SUBSCRIPTIONS","MERGE_IN_PROGRESS","GIFT_CARDS","OVERRIDE_FIELDS","STORE_CREDIT","COMPANY_CONTACT","CUSTOMER_PAYMENT_METHODS","PENDING_DATA_REQUEST","MULTIPASS_IDENTIFIER"]}, +"CustomerMergeOverrideFields":{"i":{"customerIdOfDefaultAddressToKeep":"ID","customerIdOfEmailToKeep":"ID","customerIdOfFirstNameToKeep":"ID","customerIdOfLastNameToKeep":"ID","customerIdOfPhoneNumberToKeep":"ID","note":"String","tags":"[String!]"}}, +"CustomerMergePayload":{"o":{"f":{"job":"Job","resultingCustomerId":"ID","userErrors":"[CustomerMergeUserError!]!"}}}, +"CustomerMergePreview":{"o":{"f":{"alternateFields":"CustomerMergePreviewAlternateFields","blockingFields":"CustomerMergePreviewBlockingFields","customerMergeErrors":"[CustomerMergeError!]","defaultFields":"CustomerMergePreviewDefaultFields","resultingCustomerId":"ID"}}}, +"CustomerMergePreviewAlternateFields":{"o":{"f":{"defaultAddress":"MailingAddress","email":"CustomerEmailAddress","firstName":"String","lastName":"String","phoneNumber":"CustomerPhoneNumber"}}}, +"CustomerMergePreviewBlockingFields":{"o":{"f":{"note":"String","tags":"[String!]!"}}}, +"CustomerMergePreviewDefaultFields":{"o":{"f":{"addresses":["MailingAddressConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"defaultAddress":"MailingAddress","discountNodeCount":"UnsignedInt64!","discountNodes":["DiscountNodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"DiscountSortKeys="}],"displayName":"String!","draftOrderCount":"UnsignedInt64!","draftOrders":["DraftOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"DraftOrderSortKeys="}],"email":"CustomerEmailAddress","firstName":"String","giftCardCount":"UnsignedInt64!","giftCards":["GiftCardConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"GiftCardSortKeys="}],"lastName":"String","metafieldCount":"UnsignedInt64!","note":"String","orderCount":"UnsignedInt64!","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"OrderSortKeys="}],"phoneNumber":"CustomerPhoneNumber","tags":"[String!]!"}}}, +"CustomerMergeRequest":{"o":{"f":{"customerMergeErrors":"[CustomerMergeError!]!","jobId":"ID","resultingCustomerId":"ID!","status":"CustomerMergeRequestStatus!"}}}, +"CustomerMergeRequestStatus":{"e":["REQUESTED","IN_PROGRESS","COMPLETED","FAILED"]}, +"CustomerMergeUserError":{"o":{"f":{"code":"CustomerMergeErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerMergeable":{"o":{"f":{"errorFields":"[CustomerMergeErrorFieldType!]!","isMergeable":"Boolean!","mergeInProgress":"CustomerMergeRequest","reason":"String"}}}, +"CustomerMoment":{"n":{"f":{"occurredAt":"DateTime!"},"t":["CustomerVisit"]}}, +"CustomerMomentConnection":{"o":{"f":{"edges":"[CustomerMomentEdge!]!","nodes":"[CustomerMoment!]!","pageInfo":"PageInfo!"}}}, +"CustomerMomentEdge":{"o":{"f":{"cursor":"String!","node":"CustomerMoment!"}}}, +"CustomerPaymentInstrument":{"u":["BankAccount","CustomerCreditCard","CustomerPaypalBillingAgreement","CustomerShopPayAgreement"]}, +"CustomerPaymentInstrumentBillingAddress":{"o":{"f":{"address1":"String","city":"String","country":"String","countryCode":"CountryCode","name":"String","province":"String","provinceCode":"String","zip":"String"}}}, +"CustomerPaymentMethod":{"o":{"f":{"customer":"Customer","id":"ID!","instrument":"CustomerPaymentInstrument","mandates":["PaymentMandateResourceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"revokedAt":"DateTime","revokedReason":"CustomerPaymentMethodRevocationReason","subscriptionContracts":["SubscriptionContractConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["Node"]}}, +"CustomerPaymentMethodConnection":{"o":{"f":{"edges":"[CustomerPaymentMethodEdge!]!","nodes":"[CustomerPaymentMethod!]!","pageInfo":"PageInfo!"}}}, +"CustomerPaymentMethodCreateFromDuplicationDataPayload":{"o":{"f":{"customerPaymentMethod":"CustomerPaymentMethod","userErrors":"[CustomerPaymentMethodCreateFromDuplicationDataUserError!]!"}}}, +"CustomerPaymentMethodCreateFromDuplicationDataUserError":{"o":{"f":{"code":"CustomerPaymentMethodCreateFromDuplicationDataUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerPaymentMethodCreateFromDuplicationDataUserErrorCode":{"e":["TOO_MANY_REQUESTS","CUSTOMER_DOES_NOT_EXIST","INVALID_ENCRYPTED_DUPLICATION_DATA"]}, +"CustomerPaymentMethodCreditCardCreatePayload":{"o":{"f":{"customerPaymentMethod":"CustomerPaymentMethod","processing":"Boolean","userErrors":"[UserError!]!"}}}, +"CustomerPaymentMethodCreditCardUpdatePayload":{"o":{"f":{"customerPaymentMethod":"CustomerPaymentMethod","processing":"Boolean","userErrors":"[UserError!]!"}}}, +"CustomerPaymentMethodEdge":{"o":{"f":{"cursor":"String!","node":"CustomerPaymentMethod!"}}}, +"CustomerPaymentMethodGetDuplicationDataPayload":{"o":{"f":{"encryptedDuplicationData":"String","userErrors":"[CustomerPaymentMethodGetDuplicationDataUserError!]!"}}}, +"CustomerPaymentMethodGetDuplicationDataUserError":{"o":{"f":{"code":"CustomerPaymentMethodGetDuplicationDataUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerPaymentMethodGetDuplicationDataUserErrorCode":{"e":["PAYMENT_METHOD_DOES_NOT_EXIST","INVALID_INSTRUMENT","TOO_MANY_REQUESTS","CUSTOMER_DOES_NOT_EXIST","SAME_SHOP","INVALID_ORGANIZATION_SHOP"]}, +"CustomerPaymentMethodGetUpdateUrlPayload":{"o":{"f":{"updatePaymentMethodUrl":"URL","userErrors":"[CustomerPaymentMethodGetUpdateUrlUserError!]!"}}}, +"CustomerPaymentMethodGetUpdateUrlUserError":{"o":{"f":{"code":"CustomerPaymentMethodGetUpdateUrlUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerPaymentMethodGetUpdateUrlUserErrorCode":{"e":["PAYMENT_METHOD_DOES_NOT_EXIST","INVALID_INSTRUMENT","TOO_MANY_REQUESTS","CUSTOMER_DOES_NOT_EXIST"]}, +"CustomerPaymentMethodPaypalBillingAgreementCreatePayload":{"o":{"f":{"customerPaymentMethod":"CustomerPaymentMethod","userErrors":"[CustomerPaymentMethodUserError!]!"}}}, +"CustomerPaymentMethodPaypalBillingAgreementUpdatePayload":{"o":{"f":{"customerPaymentMethod":"CustomerPaymentMethod","userErrors":"[CustomerPaymentMethodUserError!]!"}}}, +"CustomerPaymentMethodRemoteCreatePayload":{"o":{"f":{"customerPaymentMethod":"CustomerPaymentMethod","userErrors":"[CustomerPaymentMethodRemoteUserError!]!"}}}, +"CustomerPaymentMethodRemoteInput":{"i":{"authorizeNetCustomerPaymentProfile":"RemoteAuthorizeNetCustomerPaymentProfileInput","braintreePaymentMethod":"RemoteBraintreePaymentMethodInput","stripePaymentMethod":"RemoteStripePaymentMethodInput"}}, +"CustomerPaymentMethodRemoteUserError":{"o":{"f":{"code":"CustomerPaymentMethodRemoteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerPaymentMethodRemoteUserErrorCode":{"e":["INVALID","PRESENT","TAKEN","EXACTLY_ONE_REMOTE_REFERENCE_REQUIRED","AUTHORIZE_NET_NOT_ENABLED_FOR_SUBSCRIPTIONS","BRAINTREE_NOT_ENABLED_FOR_SUBSCRIPTIONS"]}, +"CustomerPaymentMethodRevocationReason":{"e":["AUTHORIZE_NET_GATEWAY_NOT_ENABLED","AUTHORIZE_NET_RETURNED_NO_PAYMENT_METHOD","FAILED_TO_UPDATE_CREDIT_CARD","STRIPE_API_AUTHENTICATION_ERROR","STRIPE_API_INVALID_REQUEST_ERROR","STRIPE_GATEWAY_NOT_ENABLED","STRIPE_RETURNED_NO_PAYMENT_METHOD","STRIPE_PAYMENT_METHOD_NOT_CARD","BRAINTREE_API_AUTHENTICATION_ERROR","BRAINTREE_GATEWAY_NOT_ENABLED","BRAINTREE_RETURNED_NO_PAYMENT_METHOD","BRAINTREE_PAYMENT_METHOD_NOT_CARD","PAYMENT_METHOD_VERIFICATION_FAILED","THREE_D_SECURE_FLOW_IN_VERIFICATION_NOT_IMPLEMENTED","MANUALLY_REVOKED","FAILED_TO_RETRIEVE_BILLING_ADDRESS","MERGED","CUSTOMER_REDACTED","TOO_MANY_CONSECUTIVE_FAILURES","CVV_ATTEMPTS_LIMIT_EXCEEDED"]}, +"CustomerPaymentMethodRevokePayload":{"o":{"f":{"revokedCustomerPaymentMethodId":"ID","userErrors":"[UserError!]!"}}}, +"CustomerPaymentMethodSendUpdateEmailPayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"CustomerPaymentMethodUserError":{"o":{"f":{"code":"CustomerPaymentMethodUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerPaymentMethodUserErrorCode":{"e":["INVALID","PRESENT","TAKEN"]}, +"CustomerPaypalBillingAgreement":{"o":{"f":{"billingAddress":"CustomerPaymentInstrumentBillingAddress","inactive":"Boolean!","isRevocable":"Boolean!","paypalAccountEmail":"String"}}}, +"CustomerPhoneNumber":{"o":{"f":{"marketingCollectedFrom":"CustomerConsentCollectedFrom","marketingOptInLevel":"CustomerMarketingOptInLevel","marketingState":"CustomerSmsMarketingState!","marketingUpdatedAt":"DateTime","phoneNumber":"String!","smsMarketingConsent":"CustomerSmsMarketingConsent!","sourceLocation":"Location","whatsAppMarketingConsent":"CustomerWhatsAppMarketingConsent!"},"d":{"marketingCollectedFrom":"Use `smsMarketingConsent.collectedFrom` instead.","marketingOptInLevel":"Use `smsMarketingConsent.optInLevel` instead.","marketingState":"Use `smsMarketingConsent.state` instead.","marketingUpdatedAt":"Use `smsMarketingConsent.updatedAt` instead.","sourceLocation":"Use `smsMarketingConsent.sourceLocation` instead."}}}, +"CustomerPredictedSpendTier":{"e":["HIGH","MEDIUM","LOW"]}, +"CustomerProductSubscriberStatus":{"e":["ACTIVE","CANCELLED","EXPIRED","FAILED","NEVER_SUBSCRIBED","PAUSED"]}, +"CustomerRemoveTaxExemptionsPayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"CustomerReplaceTaxExemptionsPayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"CustomerRequestDataErasureErrorCode":{"e":["DOES_NOT_EXIST","FAILED_TO_REQUEST"]}, +"CustomerRequestDataErasurePayload":{"o":{"f":{"customerId":"ID","userErrors":"[CustomerRequestDataErasureUserError!]!"}}}, +"CustomerRequestDataErasureUserError":{"o":{"f":{"code":"CustomerRequestDataErasureErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerRfmGroup":{"e":["CHAMPIONS","LOYAL","ACTIVE","NEW","PROMISING","NEEDS_ATTENTION","ALMOST_LOST","PREVIOUSLY_LOYAL","AT_RISK","DORMANT","PROSPECTS"]}, +"CustomerSavedSearchSortKeys":{"e":["ID","NAME"]}, +"CustomerSegmentMember":{"o":{"f":{"amountSpent":"MoneyV2","defaultAddress":"MailingAddress","defaultEmailAddress":"CustomerEmailAddress","defaultPhoneNumber":"CustomerPhoneNumber","displayName":"String!","firstName":"String","id":"ID!","lastName":"String","lastOrderId":"ID","mergeable":"CustomerMergeable!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"note":"String","numberOfOrders":"UnsignedInt64"},"t":["HasMetafields"]}}, +"CustomerSegmentMemberConnection":{"o":{"f":{"edges":"[CustomerSegmentMemberEdge!]!","pageInfo":"PageInfo!","statistics":"SegmentStatistics!","totalCount":"Int!"}}}, +"CustomerSegmentMemberEdge":{"o":{"f":{"cursor":"String!","node":"CustomerSegmentMember!"}}}, +"CustomerSegmentMembersQuery":{"o":{"f":{"currentCount":"Int!","done":"Boolean!","id":"ID!"},"t":["JobResult","Node"]}}, +"CustomerSegmentMembersQueryCreatePayload":{"o":{"f":{"customerSegmentMembersQuery":"CustomerSegmentMembersQuery","userErrors":"[CustomerSegmentMembersQueryUserError!]!"}}}, +"CustomerSegmentMembersQueryInput":{"i":{"query":"String","reverse":"Boolean=","segmentId":"ID","sortKey":"String"}}, +"CustomerSegmentMembersQueryUserError":{"o":{"f":{"code":"CustomerSegmentMembersQueryUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerSegmentMembersQueryUserErrorCode":{"e":["INVALID"]}, +"CustomerSendAccountInviteEmailPayload":{"o":{"f":{"customer":"Customer","userErrors":"[CustomerSendAccountInviteEmailUserError!]!"}}}, +"CustomerSendAccountInviteEmailUserError":{"o":{"f":{"code":"CustomerSendAccountInviteEmailUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerSendAccountInviteEmailUserErrorCode":{"e":["INVALID"]}, +"CustomerSetIdentifiers":{"i":{"f":{"customId":"UniqueMetafieldValueInput","email":"String","id":"ID","phone":"String"},"o":true}}, +"CustomerSetInput":{"i":{"f":{"addresses":"[MailingAddressInput!]","email":"String","firstName":"String","id":"ID","lastName":"String","locale":"String","note":"String","phone":"String","tags":"[String!]","taxExempt":"Boolean","taxExemptions":"[TaxExemption!]"},"d":{"addresses":"Use the dedicated address mutations (`customerAddressCreate`, `customerAddressUpdate`, `customerAddressDelete`) instead.","id":"To update a customer use `identifier` argument instead."}}}, +"CustomerSetPayload":{"o":{"f":{"customer":"Customer","userErrors":"[CustomerSetUserError!]!"}}}, +"CustomerSetUserError":{"o":{"f":{"code":"CustomerSetUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerSetUserErrorCode":{"e":["INVALID","INCLUSION","TAKEN","TOO_LONG","TOO_SHORT","PRESENT","BLANK","ID_NOT_ALLOWED","MISSING_FIELD_REQUIRED","INPUT_MISMATCH","NOT_FOUND","METAFIELD_MISMATCH"]}, +"CustomerShopPayAgreement":{"o":{"f":{"billingAddress":"CustomerCreditCardBillingAddress","expiresSoon":"Boolean!","expiryMonth":"Int!","expiryYear":"Int!","inactive":"Boolean!","isRevocable":"Boolean!","lastDigits":"String!","maskedNumber":"String!","name":"String!"}}}, +"CustomerSmsMarketingConsent":{"o":{"f":{"collectedFrom":"CustomerConsentCollectedFrom","optInLevel":"CustomerMarketingOptInLevel","sourceLocation":"Location","state":"CustomerMarketingConsentState!","updatedAt":"DateTime"},"t":["CustomerMarketingConsent"]}}, +"CustomerSmsMarketingConsentError":{"o":{"f":{"code":"CustomerSmsMarketingConsentErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"CustomerSmsMarketingConsentErrorCode":{"e":["INVALID","INCLUSION","INTERNAL_ERROR","MISSING_ARGUMENT"]}, +"CustomerSmsMarketingConsentInput":{"i":{"consentUpdatedAt":"DateTime","marketingOptInLevel":"CustomerMarketingOptInLevel","marketingState":"CustomerSmsMarketingState!","sourceLocationId":"ID"}}, +"CustomerSmsMarketingConsentState":{"o":{"f":{"consentCollectedFrom":"CustomerConsentCollectedFrom","consentUpdatedAt":"DateTime","marketingOptInLevel":"CustomerMarketingOptInLevel!","marketingState":"CustomerSmsMarketingState!","sourceLocation":"Location"}}}, +"CustomerSmsMarketingConsentUpdateInput":{"i":{"customerId":"ID!","smsMarketingConsent":"CustomerSmsMarketingConsentInput!"}}, +"CustomerSmsMarketingConsentUpdatePayload":{"o":{"f":{"customer":"Customer","userErrors":"[CustomerSmsMarketingConsentError!]!"}}}, +"CustomerSmsMarketingState":{"e":["NOT_SUBSCRIBED","PENDING","SUBSCRIBED","UNSUBSCRIBED","REDACTED"]}, +"CustomerSortKeys":{"e":["CREATED_AT","ID","LOCATION","NAME","RELEVANCE","UPDATED_AT"]}, +"CustomerState":{"e":["DECLINED","DISABLED","ENABLED","INVITED"]}, +"CustomerStatistics":{"o":{"f":{"predictedSpendTier":"CustomerPredictedSpendTier","rfmGroup":"CustomerRfmGroup"}}}, +"CustomerUpdateDefaultAddressPayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"CustomerUpdatePayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"CustomerVisit":{"o":{"f":{"id":"ID!","landingPage":"URL","landingPageHtml":"HTML","marketingEvent":"MarketingEvent","occurredAt":"DateTime!","referralCode":"String","referralInfoHtml":"FormattedString!","referrerUrl":"URL","source":"String!","sourceDescription":"String","sourceType":"MarketingTactic","utmParameters":"UTMParameters"},"t":["CustomerMoment","Node"]}}, +"CustomerVisitProductInfo":{"o":{"f":{"product":"Product","quantity":"Int!","variant":"ProductVariant"}}}, +"CustomerVisitProductInfoConnection":{"o":{"f":{"edges":"[CustomerVisitProductInfoEdge!]!","nodes":"[CustomerVisitProductInfo!]!","pageInfo":"PageInfo!"}}}, +"CustomerVisitProductInfoEdge":{"o":{"f":{"cursor":"String!","node":"CustomerVisitProductInfo!"}}}, +"CustomerWhatsAppMarketingConsent":{"o":{"f":{"collectedFrom":"CustomerConsentCollectedFrom","optInLevel":"CustomerMarketingOptInLevel","sourceLocation":"Location","state":"CustomerMarketingConsentState!","updatedAt":"DateTime"},"t":["CustomerMarketingConsent"]}}, +"CustomerWhatsAppMarketingConsentUpdateInput":{"i":{"customerId":"ID!","whatsAppMarketingConsent":"CustomerMarketingConsentInput!"}}, +"CustomerWhatsAppMarketingConsentUpdatePayload":{"o":{"f":{"customerPhoneNumber":"CustomerPhoneNumber","userErrors":"[CustomerMarketingConsentError!]!"}}}, +"DataSaleOptOutPage":{"o":{"f":{"autoManaged":"Boolean!"}}}, +"DataSaleOptOutPayload":{"o":{"f":{"customerId":"ID","userErrors":"[DataSaleOptOutUserError!]!"}}}, +"DataSaleOptOutUserError":{"o":{"f":{"code":"DataSaleOptOutUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DataSaleOptOutUserErrorCode":{"e":["FAILED"]}, +"Date":"s", +"DateTime":"s", +"DayOfTheWeek":{"e":["MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"]}, +"Decimal":"s", +"DelegateAccessToken":{"o":{"f":{"accessScopes":"[String!]!","accessToken":"String!","createdAt":"DateTime!","expiresIn":"Int"}}}, +"DelegateAccessTokenCreatePayload":{"o":{"f":{"delegateAccessToken":"DelegateAccessToken","shop":"Shop!","userErrors":"[DelegateAccessTokenCreateUserError!]!"}}}, +"DelegateAccessTokenCreateUserError":{"o":{"f":{"code":"DelegateAccessTokenCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DelegateAccessTokenCreateUserErrorCode":{"e":["EMPTY_ACCESS_SCOPE","DELEGATE_ACCESS_TOKEN","NEGATIVE_EXPIRES_IN","EXPIRES_AFTER_PARENT","REFRESH_TOKEN","PERSISTENCE_FAILED","UNKNOWN_SCOPES"]}, +"DelegateAccessTokenDestroyPayload":{"o":{"f":{"shop":"Shop!","status":"Boolean","userErrors":"[DelegateAccessTokenDestroyUserError!]!"}}}, +"DelegateAccessTokenDestroyUserError":{"o":{"f":{"code":"DelegateAccessTokenDestroyUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DelegateAccessTokenDestroyUserErrorCode":{"e":["PERSISTENCE_FAILED","ACCESS_TOKEN_NOT_FOUND","CAN_ONLY_DELETE_DELEGATE_TOKENS","ACCESS_DENIED"]}, +"DelegateAccessTokenInput":{"i":{"delegateAccessScope":"[String!]!","expiresIn":"Int"}}, +"DeletionEvent":{"o":{"f":{"occurredAt":"DateTime!","subjectId":"ID!","subjectType":"DeletionEventSubjectType!"}}}, +"DeletionEventConnection":{"o":{"f":{"edges":"[DeletionEventEdge!]!","nodes":"[DeletionEvent!]!","pageInfo":"PageInfo!"}}}, +"DeletionEventEdge":{"o":{"f":{"cursor":"String!","node":"DeletionEvent!"}}}, +"DeletionEventSortKeys":{"e":["CREATED_AT","ID"]}, +"DeletionEventSubjectType":{"e":["COLLECTION","PRODUCT"]}, +"DeliveryAvailableService":{"o":{"f":{"countries":"DeliveryCountryCodesOrRestOfWorld!","name":"String!"}}}, +"DeliveryBrandedPromise":{"o":{"f":{"handle":"String!","name":"String!"}}}, +"DeliveryCarrierCalculatedOptionDefinition":{"o":{"f":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyV2","id":"ID!","includedCollections":["CollectionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"includedLocations":["LocationConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"isActive":"Boolean!","rateGroups":["DeliveryCarrierCalculatedRateGroupConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["DeliveryOptionDefinition"]}}, +"DeliveryCarrierCalculatedOptionDefinitionCreateInput":{"i":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyInput","isActive":"Boolean=","rateGroups":"[DeliveryCarrierCalculatedRateGroupCreateInput!]!"}}, +"DeliveryCarrierCalculatedOptionDefinitionUpdateInput":{"i":{"currency":"CurrencyCode","description":"String","freeDeliveryMinimumValue":"MoneyInput","id":"ID!","isActive":"Boolean","rateGroupsToCreate":"[DeliveryCarrierCalculatedRateGroupCreateInput!]","rateGroupsToDelete":"[ID!]","rateGroupsToUpdate":"[DeliveryCarrierCalculatedRateGroupUpdateInput!]"}}, +"DeliveryCarrierCalculatedRateGroup":{"o":{"f":{"absoluteAdjustment":"MoneyV2","autoIncludeNewServices":"Boolean!","carrierService":"DeliveryCarrierService!","conditions":"DeliveryRateGroupConditions!","id":"ID!","percentageAdjustment":"Int","serviceConfiguration":"[DeliveryCarrierCalculatedRateGroupService!]!"},"t":["DeliveryOptionDefinitionRateGroup"]}}, +"DeliveryCarrierCalculatedRateGroupConnection":{"o":{"f":{"edges":"[DeliveryCarrierCalculatedRateGroupEdge!]!","nodes":"[DeliveryCarrierCalculatedRateGroup!]!","pageInfo":"PageInfo!"}}}, +"DeliveryCarrierCalculatedRateGroupCreateInput":{"i":{"absoluteAdjustment":"MoneyInput","autoIncludeNewServices":"Boolean","carrierServiceId":"ID!","conditions":"DeliveryRateConditionsCreateInput","percentageAdjustment":"Int","serviceConfiguration":"[DeliveryCarrierCalculatedRateGroupServiceInput!]"}}, +"DeliveryCarrierCalculatedRateGroupEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryCarrierCalculatedRateGroup!"}}}, +"DeliveryCarrierCalculatedRateGroupService":{"o":{"f":{"name":"String!","status":"DeliveryCarrierCalculatedRateGroupServiceStatus!"}}}, +"DeliveryCarrierCalculatedRateGroupServiceInput":{"i":{"name":"String!","status":"DeliveryCarrierCalculatedRateGroupServiceStatus!"}}, +"DeliveryCarrierCalculatedRateGroupServiceStatus":{"e":["INCLUDED","EXCLUDED"]}, +"DeliveryCarrierCalculatedRateGroupUpdateInput":{"i":{"absoluteAdjustment":"MoneyInput","autoIncludeNewServices":"Boolean","carrierServiceId":"ID","conditions":"DeliveryRateConditionsUpdateInput","id":"ID!","percentageAdjustment":"Int","serviceConfiguration":"[DeliveryCarrierCalculatedRateGroupServiceInput!]"}}, +"DeliveryCarrierService":{"o":{"f":{"active":"Boolean!","availableServicesForCountries":["[DeliveryAvailableService!]!",{"countryCodes":"[CountryCode!]","origins":"[ID!]","restOfWorld":"Boolean!"}],"callbackUrl":"URL","createdAt":"DateTime!","formattedName":"String","icon":"Image!","id":"ID!","name":"String","supportsServiceDiscovery":"Boolean!"},"t":["Node"]}}, +"DeliveryCarrierServiceAndLocations":{"o":{"f":{"carrierService":"DeliveryCarrierService!","locations":"[Location!]!"}}}, +"DeliveryCarrierServiceConnection":{"o":{"f":{"edges":"[DeliveryCarrierServiceEdge!]!","nodes":"[DeliveryCarrierService!]!","pageInfo":"PageInfo!"}}}, +"DeliveryCarrierServiceCreateInput":{"i":{"active":"Boolean!","callbackUrl":"URL!","name":"String!","supportsServiceDiscovery":"Boolean!"}}, +"DeliveryCarrierServiceEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryCarrierService!"}}}, +"DeliveryCarrierServiceUpdateInput":{"i":{"active":"Boolean","callbackUrl":"URL","id":"ID!","name":"String","supportsServiceDiscovery":"Boolean"}}, +"DeliveryCondition":{"o":{"f":{"conditionCriteria":"DeliveryConditionCriteria!","field":"DeliveryConditionField!","id":"ID!","operator":"DeliveryConditionOperator!"},"t":["Node"]}}, +"DeliveryConditionCriteria":{"u":["MoneyV2","Weight"]}, +"DeliveryConditionField":{"e":["TOTAL_WEIGHT","TOTAL_PRICE"]}, +"DeliveryConditionOperator":{"e":["GREATER_THAN_OR_EQUAL_TO","LESS_THAN_OR_EQUAL_TO"]}, +"DeliveryCountry":{"o":{"f":{"code":"DeliveryCountryCodeOrRestOfWorld!","id":"ID!","name":"String!","provinces":"[DeliveryProvince!]!","translatedName":"String!"},"t":["Node"]}}, +"DeliveryCountryAndZone":{"o":{"f":{"country":"DeliveryCountry!","zone":"String!"}}}, +"DeliveryCountryCodeOrRestOfWorld":{"o":{"f":{"countryCode":"CountryCode","restOfWorld":"Boolean!"}}}, +"DeliveryCountryCodesOrRestOfWorld":{"o":{"f":{"countryCodes":"[CountryCode!]!","restOfWorld":"Boolean!"}}}, +"DeliveryCountryInput":{"i":{"code":"CountryCode","includeAllProvinces":"Boolean","provinces":"[DeliveryProvinceInput!]","restOfWorld":"Boolean"}}, +"DeliveryCustomization":{"o":{"f":{"enabled":"Boolean!","errorHistory":"FunctionsErrorHistory","functionId":"String!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"shopifyFunction":"ShopifyFunction!","title":"String!"},"t":["HasMetafieldDefinitions","HasMetafields","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"DeliveryCustomizationActivationPayload":{"o":{"f":{"ids":"[String!]","userErrors":"[DeliveryCustomizationError!]!"}}}, +"DeliveryCustomizationConnection":{"o":{"f":{"edges":"[DeliveryCustomizationEdge!]!","nodes":"[DeliveryCustomization!]!","pageInfo":"PageInfo!"}}}, +"DeliveryCustomizationCreatePayload":{"o":{"f":{"deliveryCustomization":"DeliveryCustomization","userErrors":"[DeliveryCustomizationError!]!"}}}, +"DeliveryCustomizationDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[DeliveryCustomizationError!]!"}}}, +"DeliveryCustomizationEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryCustomization!"}}}, +"DeliveryCustomizationError":{"o":{"f":{"code":"DeliveryCustomizationErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DeliveryCustomizationErrorCode":{"e":["INVALID","FUNCTION_NOT_FOUND","DELIVERY_CUSTOMIZATION_NOT_FOUND","DELIVERY_CUSTOMIZATION_FUNCTION_NOT_ELIGIBLE","UNAUTHORIZED_APP_SCOPE","MAXIMUM_ACTIVE_DELIVERY_CUSTOMIZATIONS","MAXIMUM_DELIVERY_CUSTOMIZATIONS","CUSTOM_APP_FUNCTION_NOT_ELIGIBLE","FUNCTION_DOES_NOT_IMPLEMENT","FUNCTION_PENDING_DELETION","FUNCTION_ID_CANNOT_BE_CHANGED","REQUIRED_INPUT_FIELD","INVALID_METAFIELDS","MISSING_FUNCTION_IDENTIFIER","MULTIPLE_FUNCTION_IDENTIFIERS"]}, +"DeliveryCustomizationInput":{"i":{"f":{"enabled":"Boolean","functionHandle":"String","functionId":"String","metafields":"[MetafieldInput!]=","title":"String"},"d":{"functionId":"Use `functionHandle` instead."}}}, +"DeliveryCustomizationUpdatePayload":{"o":{"f":{"deliveryCustomization":"DeliveryCustomization","userErrors":"[DeliveryCustomizationError!]!"}}}, +"DeliveryFlatRate":{"o":{"f":{"id":"ID!","price":"MoneyV2!","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"},"t":["DeliveryRate"]}}, +"DeliveryFlatRateCreateInput":{"i":{"price":"MoneyInput!","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"}}, +"DeliveryFlatRateGroup":{"o":{"f":{"conditions":"DeliveryRateGroupConditions!","id":"ID!","rate":"DeliveryFlatRate!"},"t":["DeliveryOptionDefinitionRateGroup"]}}, +"DeliveryFlatRateGroupConnection":{"o":{"f":{"edges":"[DeliveryFlatRateGroupEdge!]!","nodes":"[DeliveryFlatRateGroup!]!","pageInfo":"PageInfo!"}}}, +"DeliveryFlatRateGroupCreateInput":{"i":{"conditions":"DeliveryRateConditionsCreateInput","rate":"DeliveryFlatRateCreateInput!"}}, +"DeliveryFlatRateGroupEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryFlatRateGroup!"}}}, +"DeliveryFlatRateGroupUpdateInput":{"i":{"conditions":"DeliveryRateConditionsUpdateInput","id":"ID!","rate":"DeliveryFlatRateUpdateInput"}}, +"DeliveryFlatRateOptionDefinition":{"o":{"f":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyV2","id":"ID!","includedCollections":["CollectionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"includedLocations":["LocationConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"isActive":"Boolean!","name":"String!","rateGroups":["DeliveryFlatRateGroupConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["DeliveryOptionDefinition"]}}, +"DeliveryFlatRateOptionDefinitionCreateInput":{"i":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyInput","isActive":"Boolean=","name":"String!","rateGroups":"[DeliveryFlatRateGroupCreateInput!]"}}, +"DeliveryFlatRateOptionDefinitionUpdateInput":{"i":{"currency":"CurrencyCode","description":"String","freeDeliveryMinimumValue":"MoneyInput","id":"ID!","isActive":"Boolean","name":"String","rateGroupsToCreate":"[DeliveryFlatRateGroupCreateInput!]","rateGroupsToDelete":"[ID!]","rateGroupsToUpdate":"[DeliveryFlatRateGroupUpdateInput!]"}}, +"DeliveryFlatRateUpdateInput":{"i":{"price":"MoneyInput","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"}}, +"DeliveryLocalPickupSettings":{"o":{"f":{"instructions":"String!","pickupTime":"DeliveryLocalPickupTime!"}}}, +"DeliveryLocalPickupTime":{"e":{"v":["ONE_HOUR","TWO_HOURS","FOUR_HOURS","TWENTY_FOUR_HOURS","TWO_TO_FOUR_DAYS","FIVE_OR_MORE_DAYS","CUSTOM"],"d":{"CUSTOM":"Custom pickup time is no longer supported."}}}, +"DeliveryLocationGroup":{"o":{"f":{"id":"ID!","locations":["LocationConnection!",{"after":"String","before":"String","first":"Int","includeInactive":"Boolean=","includeLegacy":"Boolean=","last":"Int","query":"String","reverse":"Boolean=","sortKey":"LocationSortKeys="}],"locationsCount":"Count"},"t":["Node"]}}, +"DeliveryLocationGroupZone":{"o":{"f":{"methodDefinitionCounts":"DeliveryMethodDefinitionCounts!","methodDefinitions":["DeliveryMethodDefinitionConnection!",{"after":"String","before":"String","eligible":"Boolean","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"MethodDefinitionSortKeys=","type":"DeliveryMethodDefinitionType"}],"zone":"DeliveryZone!"}}}, +"DeliveryLocationGroupZoneConnection":{"o":{"f":{"edges":"[DeliveryLocationGroupZoneEdge!]!","nodes":"[DeliveryLocationGroupZone!]!","pageInfo":"PageInfo!"}}}, +"DeliveryLocationGroupZoneEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryLocationGroupZone!"}}}, +"DeliveryLocationGroupZoneInput":{"i":{"countries":"[DeliveryCountryInput!]","id":"ID","methodDefinitionsToCreate":"[DeliveryMethodDefinitionInput!]","methodDefinitionsToUpdate":"[DeliveryMethodDefinitionInput!]","name":"String"}}, +"DeliveryLocationLocalPickupEnableInput":{"i":{"instructions":"String","locationId":"ID!","pickupTime":"DeliveryLocalPickupTime!"}}, +"DeliveryLocationLocalPickupSettingsError":{"o":{"f":{"code":"DeliveryLocationLocalPickupSettingsErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DeliveryLocationLocalPickupSettingsErrorCode":{"e":["ACTIVE_LOCATION_NOT_FOUND","CUSTOM_PICKUP_TIME_NOT_ALLOWED","GENERIC_ERROR"]}, +"DeliveryMethod":{"o":{"f":{"additionalInformation":"DeliveryMethodAdditionalInformation","brandedPromise":"DeliveryBrandedPromise","id":"ID!","maxDeliveryDateTime":"DateTime","methodType":"DeliveryMethodType!","minDeliveryDateTime":"DateTime","presentedName":"String","serviceCode":"String","sourceReference":"String"},"t":["Node"]}}, +"DeliveryMethodAdditionalInformation":{"o":{"f":{"instructions":"String","phone":"String"}}}, +"DeliveryMethodDefinition":{"o":{"f":{"active":"Boolean!","description":"String","id":"ID!","methodConditions":"[DeliveryCondition!]!","name":"String!","rateProvider":"DeliveryRateProvider!"},"t":["Node"]}}, +"DeliveryMethodDefinitionConnection":{"o":{"f":{"edges":"[DeliveryMethodDefinitionEdge!]!","nodes":"[DeliveryMethodDefinition!]!","pageInfo":"PageInfo!"}}}, +"DeliveryMethodDefinitionCounts":{"o":{"f":{"participantDefinitionsCount":"Int!","rateDefinitionsCount":"Int!"}}}, +"DeliveryMethodDefinitionEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryMethodDefinition!"}}}, +"DeliveryMethodDefinitionInput":{"i":{"active":"Boolean","conditionsToUpdate":"[DeliveryUpdateConditionInput!]","description":"String","id":"ID","name":"String","participant":"DeliveryParticipantInput","priceConditionsToCreate":"[DeliveryPriceConditionInput!]","rateDefinition":"DeliveryRateDefinitionInput","weightConditionsToCreate":"[DeliveryWeightConditionInput!]"}}, +"DeliveryMethodDefinitionType":{"e":["MERCHANT","PARTICIPANT"]}, +"DeliveryMethodType":{"e":["SHIPPING","PICK_UP","NONE","RETAIL","LOCAL","PICKUP_POINT"]}, +"DeliveryOptionDefinition":{"n":{"f":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyV2","id":"ID!","includedCollections":["CollectionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"includedLocations":["LocationConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"isActive":"Boolean!"},"t":["DeliveryCarrierCalculatedOptionDefinition","DeliveryFlatRateOptionDefinition","DeliveryValueBasedOptionDefinition","DeliveryWeightBasedOptionDefinition"]}}, +"DeliveryOptionDefinitionConnection":{"o":{"f":{"edges":"[DeliveryOptionDefinitionEdge!]!","nodes":"[DeliveryOptionDefinition!]!","pageInfo":"PageInfo!"}}}, +"DeliveryOptionDefinitionCreateInput":{"i":{"f":{"carrierCalculated":"DeliveryCarrierCalculatedOptionDefinitionCreateInput","flatRate":"DeliveryFlatRateOptionDefinitionCreateInput","valueBased":"DeliveryValueBasedOptionDefinitionCreateInput","weightBased":"DeliveryWeightBasedOptionDefinitionCreateInput"},"o":true}}, +"DeliveryOptionDefinitionEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryOptionDefinition!"}}}, +"DeliveryOptionDefinitionRateGroup":{"n":{"f":{"conditions":"DeliveryRateGroupConditions!","id":"ID!"},"t":["DeliveryCarrierCalculatedRateGroup","DeliveryFlatRateGroup","DeliveryValueBasedRateGroup","DeliveryWeightBasedRateGroup"]}}, +"DeliveryOptionDefinitionUpdateInput":{"i":{"f":{"carrierCalculated":"DeliveryCarrierCalculatedOptionDefinitionUpdateInput","flatRate":"DeliveryFlatRateOptionDefinitionUpdateInput","valueBased":"DeliveryValueBasedOptionDefinitionUpdateInput","weightBased":"DeliveryWeightBasedOptionDefinitionUpdateInput"},"o":true}}, +"DeliveryParticipant":{"o":{"f":{"adaptToNewServicesFlag":"Boolean!","carrierService":"DeliveryCarrierService!","fixedFee":"MoneyV2","id":"ID!","participantServices":"[DeliveryParticipantService!]!","percentageOfRateFee":"Float!"},"t":["Node"]}}, +"DeliveryParticipantInput":{"i":{"adaptToNewServices":"Boolean","carrierServiceId":"ID","fixedFee":"MoneyInput","id":"ID","participantServices":"[DeliveryParticipantServiceInput!]","percentageOfRateFee":"Float"}}, +"DeliveryParticipantService":{"o":{"f":{"active":"Boolean!","name":"String!"}}}, +"DeliveryParticipantServiceInput":{"i":{"active":"Boolean!","name":"String!"}}, +"DeliveryPriceConditionInput":{"i":{"criteria":"MoneyInput","operator":"DeliveryConditionOperator"}}, +"DeliveryProductVariantsCount":{"o":{"f":{"capped":"Boolean!","count":"Int!"}}}, +"DeliveryProfile":{"o":{"f":{"activeMethodDefinitionsCount":"Int!","coversAllItems":"Boolean!","createdAt":"DateTime!","default":"Boolean!","id":"ID!","locationsWithoutRatesCount":"Int!","name":"String!","originLocationCount":"Int!","productVariantsCount":"Count","productVariantsCountV2":"DeliveryProductVariantsCount!","profileItems":["DeliveryProfileItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"ProfileItemSortKeys="}],"profileLocationGroups":["[DeliveryProfileLocationGroup!]!",{"locationGroupId":"ID"}],"sellingPlanGroups":["SellingPlanGroupConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"unassignedLocations":"[Location!]!","unassignedLocationsPaginated":["LocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"version":"Int!","zoneCountryCount":"Int!"},"t":["Node"],"d":{"productVariantsCountV2":"Use `productVariantsCount` instead.","profileItems(sortKey)":"Profile item sorting is no longer supported."}}}, +"DeliveryProfileConnection":{"o":{"f":{"edges":"[DeliveryProfileEdge!]!","nodes":"[DeliveryProfile!]!","pageInfo":"PageInfo!"}}}, +"DeliveryProfileCreatePayload":{"o":{"f":{"profile":"DeliveryProfile","userErrors":"[UserError!]!"}}}, +"DeliveryProfileEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryProfile!"}}}, +"DeliveryProfileInput":{"i":{"conditionsToDelete":"[ID!]","coversAllItems":"Boolean","locationGroupsToCreate":"[DeliveryProfileLocationGroupInput!]","locationGroupsToDelete":"[ID!]","locationGroupsToUpdate":"[DeliveryProfileLocationGroupInput!]","methodDefinitionsToDelete":"[ID!]","name":"String","profileLocationGroups":"[DeliveryProfileLocationGroupInput!]","sellingPlanGroupsToAssociate":"[ID!]","sellingPlanGroupsToDissociate":"[ID!]","variantsToAssociate":"[ID!]","variantsToDissociate":"[ID!]","zonesToDelete":"[ID!]"}}, +"DeliveryProfileItem":{"o":{"f":{"id":"ID!","product":"Product!","variants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"ProductVariantSortKeys="}]},"t":["Node"],"d":{"variants(sortKey)":"Profile item variant sorting is no longer supported."}}}, +"DeliveryProfileItemConnection":{"o":{"f":{"edges":"[DeliveryProfileItemEdge!]!","nodes":"[DeliveryProfileItem!]!","pageInfo":"PageInfo!"}}}, +"DeliveryProfileItemEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryProfileItem!"}}}, +"DeliveryProfileLocationGroup":{"o":{"f":{"countriesInAnyZone":"[DeliveryCountryAndZone!]!","locationGroup":"DeliveryLocationGroup!","locationGroupZones":["DeliveryLocationGroupZoneConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"DeliveryProfileLocationGroupInput":{"i":{"id":"ID","locations":"[ID!]","locationsToAdd":"[ID!]","locationsToRemove":"[ID!]","zonesToCreate":"[DeliveryLocationGroupZoneInput!]","zonesToUpdate":"[DeliveryLocationGroupZoneInput!]"}}, +"DeliveryProfileRemovePayload":{"o":{"f":{"job":"Job","userErrors":"[UserError!]!"}}}, +"DeliveryProfileUpdatePayload":{"o":{"f":{"profile":"DeliveryProfile","userErrors":"[UserError!]!"}}}, +"DeliveryPromiseParticipant":{"o":{"f":{"id":"ID!","owner":"DeliveryPromiseParticipantOwner","ownerType":"DeliveryPromiseParticipantOwnerType!"},"t":["Node"]}}, +"DeliveryPromiseParticipantConnection":{"o":{"f":{"edges":"[DeliveryPromiseParticipantEdge!]!","nodes":"[DeliveryPromiseParticipant!]!","pageInfo":"PageInfo!"}}}, +"DeliveryPromiseParticipantEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryPromiseParticipant!"}}}, +"DeliveryPromiseParticipantOwner":{"u":["ProductVariant"]}, +"DeliveryPromiseParticipantOwnerType":{"e":["PRODUCTVARIANT"]}, +"DeliveryPromiseParticipantsUpdatePayload":{"o":{"f":{"promiseParticipants":"[DeliveryPromiseParticipant!]","userErrors":"[UserError!]!"}}}, +"DeliveryPromiseProvider":{"o":{"f":{"active":"Boolean!","fulfillmentDelay":"Int","id":"ID!","location":"Location!","timeZone":"String!"},"t":["Node"]}}, +"DeliveryPromiseProviderUpsertPayload":{"o":{"f":{"deliveryPromiseProvider":"DeliveryPromiseProvider","userErrors":"[DeliveryPromiseProviderUpsertUserError!]!"}}}, +"DeliveryPromiseProviderUpsertUserError":{"o":{"f":{"code":"DeliveryPromiseProviderUpsertUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DeliveryPromiseProviderUpsertUserErrorCode":{"e":["NOT_FOUND","TOO_LONG","MUST_BELONG_TO_APP","INVALID_TIME_ZONE"]}, +"DeliveryPromiseSetting":{"o":{"f":{"deliveryDatesEnabled":"Boolean!","processingTime":"String"}}}, +"DeliveryProvince":{"o":{"f":{"code":"String!","id":"ID!","name":"String!","translatedName":"String!"},"t":["Node"]}}, +"DeliveryProvinceInput":{"i":{"code":"String!"}}, +"DeliveryRate":{"n":{"f":{"price":"MoneyV2!","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"},"t":["DeliveryFlatRate","DeliveryValueBasedRate","DeliveryWeightBasedRate"]}}, +"DeliveryRateConditionsCreateInput":{"i":{"collectionsToAdd":"[ID!]","originLocationsToAdd":"[ID!]"}}, +"DeliveryRateConditionsUpdateInput":{"i":{"collectionsToAdd":"[ID!]","collectionsToRemove":"[ID!]","originLocationsToAdd":"[ID!]","originLocationsToRemove":"[ID!]","resetToAllProducts":"Boolean"}}, +"DeliveryRateDefinition":{"o":{"f":{"id":"ID!","price":"MoneyV2!"},"t":["Node"]}}, +"DeliveryRateDefinitionInput":{"i":{"id":"ID","price":"MoneyInput!"}}, +"DeliveryRateGroupConditions":{"o":{"f":{"collections":["CollectionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collectionsCount":"Count","originLocations":["LocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"originLocationsCount":"Count!"}}}, +"DeliveryRateProvider":{"u":["DeliveryParticipant","DeliveryRateDefinition"]}, +"DeliverySettingUpdatePayload":{"o":{"f":{"userErrors":"[UserError!]!"}}}, +"DeliveryShippingOriginAssignPayload":{"o":{"f":{"userErrors":"[UserError!]!"}}}, +"DeliveryUpdateConditionInput":{"i":{"criteria":"Float","criteriaUnit":"String","field":"DeliveryConditionField","id":"ID!","operator":"DeliveryConditionOperator"}}, +"DeliveryValueBasedOptionDefinition":{"o":{"f":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyV2","id":"ID!","includedCollections":["CollectionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"includedLocations":["LocationConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"isActive":"Boolean!","name":"String!","rateGroups":["DeliveryValueBasedRateGroupConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["DeliveryOptionDefinition"]}}, +"DeliveryValueBasedOptionDefinitionCreateInput":{"i":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyInput","isActive":"Boolean=","name":"String!","rateGroups":"[DeliveryValueBasedRateGroupCreateInput!]!"}}, +"DeliveryValueBasedOptionDefinitionUpdateInput":{"i":{"currency":"CurrencyCode","description":"String","freeDeliveryMinimumValue":"MoneyInput","id":"ID!","isActive":"Boolean","name":"String","rateGroupsToCreate":"[DeliveryValueBasedRateGroupCreateInput!]","rateGroupsToDelete":"[ID!]","rateGroupsToUpdate":"[DeliveryValueBasedRateGroupUpdateInput!]"}}, +"DeliveryValueBasedRate":{"o":{"f":{"id":"ID!","maxValue":"MoneyV2","minValue":"MoneyV2!","price":"MoneyV2!","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"},"t":["DeliveryRate"]}}, +"DeliveryValueBasedRateConnection":{"o":{"f":{"edges":"[DeliveryValueBasedRateEdge!]!","nodes":"[DeliveryValueBasedRate!]!","pageInfo":"PageInfo!"}}}, +"DeliveryValueBasedRateCreateInput":{"i":{"maxValue":"MoneyInput","minValue":"MoneyInput!","price":"MoneyInput!","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"}}, +"DeliveryValueBasedRateEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryValueBasedRate!"}}}, +"DeliveryValueBasedRateGroup":{"o":{"f":{"conditions":"DeliveryRateGroupConditions!","id":"ID!","rates":["DeliveryValueBasedRateConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["DeliveryOptionDefinitionRateGroup"]}}, +"DeliveryValueBasedRateGroupConnection":{"o":{"f":{"edges":"[DeliveryValueBasedRateGroupEdge!]!","nodes":"[DeliveryValueBasedRateGroup!]!","pageInfo":"PageInfo!"}}}, +"DeliveryValueBasedRateGroupCreateInput":{"i":{"conditions":"DeliveryRateConditionsCreateInput!","rates":"[DeliveryValueBasedRateCreateInput!]!"}}, +"DeliveryValueBasedRateGroupEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryValueBasedRateGroup!"}}}, +"DeliveryValueBasedRateGroupUpdateInput":{"i":{"conditions":"DeliveryRateConditionsUpdateInput","id":"ID!","ratesToCreate":"[DeliveryValueBasedRateCreateInput!]","ratesToDelete":"[ID!]","ratesToUpdate":"[DeliveryValueBasedRateUpdateInput!]"}}, +"DeliveryValueBasedRateUpdateInput":{"i":{"id":"ID!","maxValue":"MoneyInput","minValue":"MoneyInput","price":"MoneyInput","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"}}, +"DeliveryWeightBasedOptionDefinition":{"o":{"f":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyV2","id":"ID!","includedCollections":["CollectionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"includedLocations":["LocationConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"isActive":"Boolean!","name":"String!","rateGroups":["DeliveryWeightBasedRateGroupConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["DeliveryOptionDefinition"]}}, +"DeliveryWeightBasedOptionDefinitionCreateInput":{"i":{"currency":"CurrencyCode!","description":"String","freeDeliveryMinimumValue":"MoneyInput","isActive":"Boolean=","name":"String!","rateGroups":"[DeliveryWeightBasedRateGroupCreateInput!]!"}}, +"DeliveryWeightBasedOptionDefinitionUpdateInput":{"i":{"currency":"CurrencyCode","description":"String","freeDeliveryMinimumValue":"MoneyInput","id":"ID!","isActive":"Boolean","name":"String","rateGroupsToCreate":"[DeliveryWeightBasedRateGroupCreateInput!]","rateGroupsToDelete":"[ID!]","rateGroupsToUpdate":"[DeliveryWeightBasedRateGroupUpdateInput!]"}}, +"DeliveryWeightBasedRate":{"o":{"f":{"id":"ID!","maxWeight":"Weight","minWeight":"Weight!","price":"MoneyV2!","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"},"t":["DeliveryRate"]}}, +"DeliveryWeightBasedRateConnection":{"o":{"f":{"edges":"[DeliveryWeightBasedRateEdge!]!","nodes":"[DeliveryWeightBasedRate!]!","pageInfo":"PageInfo!"}}}, +"DeliveryWeightBasedRateCreateInput":{"i":{"maxWeight":"WeightInput","minWeight":"WeightInput!","price":"MoneyInput!","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"}}, +"DeliveryWeightBasedRateEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryWeightBasedRate!"}}}, +"DeliveryWeightBasedRateGroup":{"o":{"f":{"conditions":"DeliveryRateGroupConditions!","id":"ID!","rates":["DeliveryWeightBasedRateConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["DeliveryOptionDefinitionRateGroup"]}}, +"DeliveryWeightBasedRateGroupConnection":{"o":{"f":{"edges":"[DeliveryWeightBasedRateGroupEdge!]!","nodes":"[DeliveryWeightBasedRateGroup!]!","pageInfo":"PageInfo!"}}}, +"DeliveryWeightBasedRateGroupCreateInput":{"i":{"conditions":"DeliveryRateConditionsCreateInput!","rates":"[DeliveryWeightBasedRateCreateInput!]!"}}, +"DeliveryWeightBasedRateGroupEdge":{"o":{"f":{"cursor":"String!","node":"DeliveryWeightBasedRateGroup!"}}}, +"DeliveryWeightBasedRateGroupUpdateInput":{"i":{"conditions":"DeliveryRateConditionsUpdateInput","id":"ID!","ratesToCreate":"[DeliveryWeightBasedRateCreateInput!]","ratesToDelete":"[ID!]","ratesToUpdate":"[DeliveryWeightBasedRateUpdateInput!]"}}, +"DeliveryWeightBasedRateUpdateInput":{"i":{"id":"ID!","maxWeight":"WeightInput","minWeight":"WeightInput","price":"MoneyInput","transitTimeMaxSeconds":"Int","transitTimeMinSeconds":"Int"}}, +"DeliveryWeightConditionInput":{"i":{"criteria":"WeightInput","operator":"DeliveryConditionOperator"}}, +"DeliveryZone":{"o":{"f":{"countries":"[DeliveryCountry!]!","id":"ID!","name":"String!"},"t":["Node"]}}, +"DepositConfiguration":{"u":["DepositPercentage"]}, +"DepositInput":{"i":{"percentage":"Float!"}}, +"DepositPercentage":{"o":{"f":{"percentage":"Float!"}}}, +"DigitalWallet":{"e":["APPLE_PAY","ANDROID_PAY","GOOGLE_PAY","SHOPIFY_PAY","FACEBOOK_PAY","AMAZON_PAY"]}, +"Discount":{"u":["DiscountAutomaticApp","DiscountAutomaticBasic","DiscountAutomaticBxgy","DiscountAutomaticFreeShipping","DiscountCodeApp","DiscountCodeBasic","DiscountCodeBxgy","DiscountCodeFreeShipping"]}, +"DiscountAllocation":{"o":{"f":{"allocatedAmount":"MoneyV2!","allocatedAmountSet":"MoneyBag!","discountApplication":"DiscountApplication!"},"d":{"allocatedAmount":"Use `allocatedAmountSet` instead."}}}, +"DiscountAllocationConnection":{"o":{"f":{"edges":"[DiscountAllocationEdge!]!","nodes":"[DiscountAllocation!]!","pageInfo":"PageInfo!"}}}, +"DiscountAllocationEdge":{"o":{"f":{"cursor":"String!","node":"DiscountAllocation!"}}}, +"DiscountAmount":{"o":{"f":{"amount":"MoneyV2!","appliesOnEachItem":"Boolean!"}}}, +"DiscountAmountInput":{"i":{"amount":"Decimal","appliesOnEachItem":"Boolean"}}, +"DiscountApplication":{"n":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","index":"Int!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","value":"PricingValue!"},"t":["AutomaticDiscountApplication","DiscountCodeApplication","ManualDiscountApplication","ScriptDiscountApplication"]}}, +"DiscountApplicationAllocationMethod":{"e":{"v":["ACROSS","EACH","ONE"],"d":{"ONE":"Use ACROSS instead."}}}, +"DiscountApplicationConnection":{"o":{"f":{"edges":"[DiscountApplicationEdge!]!","nodes":"[DiscountApplication!]!","pageInfo":"PageInfo!"}}}, +"DiscountApplicationEdge":{"o":{"f":{"cursor":"String!","node":"DiscountApplication!"}}}, +"DiscountApplicationLevel":{"e":["ORDER","LINE"]}, +"DiscountApplicationTargetSelection":{"e":["ALL","ENTITLED","EXPLICIT"]}, +"DiscountApplicationTargetType":{"e":["LINE_ITEM","SHIPPING_LINE"]}, +"DiscountAutomatic":{"u":["DiscountAutomaticApp","DiscountAutomaticBasic","DiscountAutomaticBxgy","DiscountAutomaticFreeShipping"]}, +"DiscountAutomaticActivatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticApp":{"o":{"f":{"appDiscountType":"AppDiscountType!","appliesOnOneTimePurchase":"Boolean!","appliesOnSubscription":"Boolean!","asyncUsageCount":"Int!","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","discountClass":"DiscountClass!","discountClasses":"[DiscountClass!]!","discountId":"ID!","endsAt":"DateTime","errorHistory":"FunctionsErrorHistory","recurringCycleLimit":"Int!","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"startsAt":"DateTime!","status":"DiscountStatus!","tags":"[String!]!","title":"String!","updatedAt":"DateTime!"},"t":["HasRollouts"],"d":{"discountClass":"Use `discountClasses` instead."}}}, +"DiscountAutomaticAppCreatePayload":{"o":{"f":{"automaticAppDiscount":"DiscountAutomaticApp","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticAppInput":{"i":{"f":{"appliesOnOneTimePurchase":"Boolean=","appliesOnSubscription":"Boolean=","combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","discountClasses":"[DiscountClass!]","endsAt":"DateTime","functionHandle":"String","functionId":"String","metafields":"[MetafieldInput!]=","recurringCycleLimit":"Int=","startsAt":"DateTime","tags":"[String!]","title":"String"},"d":{"functionId":"Use `functionHandle` instead."}}}, +"DiscountAutomaticAppUpdatePayload":{"o":{"f":{"automaticAppDiscount":"DiscountAutomaticApp","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticBasic":{"o":{"f":{"asyncUsageCount":"Int!","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","customerGets":"DiscountCustomerGets!","discountClass":"MerchandiseDiscountClass!","discountClasses":"[DiscountClass!]!","endsAt":"DateTime","minimumRequirement":"DiscountMinimumRequirement","recurringCycleLimit":"Int!","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"shortSummary":"String!","startsAt":"DateTime!","status":"DiscountStatus!","summary":"String!","tags":"[String!]!","title":"String!","updatedAt":"DateTime!","usageCount":"Int!"},"t":["HasRollouts"],"d":{"discountClass":"Use `discountClasses` instead.","usageCount":"Use `asyncUsageCount` instead."}}}, +"DiscountAutomaticBasicCreatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticBasicInput":{"i":{"combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","customerGets":"DiscountCustomerGetsInput","endsAt":"DateTime","minimumRequirement":"DiscountMinimumRequirementInput","recurringCycleLimit":"Int","startsAt":"DateTime","tags":"[String!]","title":"String"}}, +"DiscountAutomaticBasicUpdatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticBulkDeletePayload":{"o":{"f":{"job":"Job","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticBxgy":{"o":{"f":{"asyncUsageCount":"Int!","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","customerBuys":"DiscountCustomerBuys!","customerGets":"DiscountCustomerGets!","discountClass":"MerchandiseDiscountClass!","discountClasses":"[DiscountClass!]!","endsAt":"DateTime","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"id":"ID!","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"startsAt":"DateTime!","status":"DiscountStatus!","summary":"String!","tags":"[String!]!","title":"String!","updatedAt":"DateTime!","usageCount":"Int!","usesPerOrderLimit":"Int"},"t":["HasEvents","HasRollouts","Node"],"d":{"discountClass":"Use `discountClasses` instead.","id":"Use DiscountAutomaticNode.id instead.","usageCount":"Use `asyncUsageCount` instead."}}}, +"DiscountAutomaticBxgyCreatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticBxgyInput":{"i":{"combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","customerBuys":"DiscountCustomerBuysInput","customerGets":"DiscountCustomerGetsInput","endsAt":"DateTime","startsAt":"DateTime","tags":"[String!]","title":"String","usesPerOrderLimit":"UnsignedInt64"}}, +"DiscountAutomaticBxgyUpdatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticConnection":{"o":{"f":{"edges":"[DiscountAutomaticEdge!]!","nodes":"[DiscountAutomatic!]!","pageInfo":"PageInfo!"}}}, +"DiscountAutomaticDeactivatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticDeletePayload":{"o":{"f":{"deletedAutomaticDiscountId":"ID","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticEdge":{"o":{"f":{"cursor":"String!","node":"DiscountAutomatic!"}}}, +"DiscountAutomaticFreeShipping":{"o":{"f":{"appliesOnOneTimePurchase":"Boolean!","appliesOnSubscription":"Boolean!","asyncUsageCount":"Int!","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","destinationSelection":"DiscountShippingDestinationSelection!","discountClass":"ShippingDiscountClass!","discountClasses":"[DiscountClass!]!","endsAt":"DateTime","hasTimelineComment":"Boolean!","maximumShippingPrice":"MoneyV2","minimumRequirement":"DiscountMinimumRequirement","recurringCycleLimit":"Int!","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"shortSummary":"String!","startsAt":"DateTime!","status":"DiscountStatus!","summary":"String!","tags":"[String!]!","title":"String!","totalSales":"MoneyV2","updatedAt":"DateTime!"},"t":["HasRollouts"],"d":{"discountClass":"Use `discountClasses` instead."}}}, +"DiscountAutomaticFreeShippingCreatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticFreeShippingInput":{"i":{"appliesOnOneTimePurchase":"Boolean","appliesOnSubscription":"Boolean","combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","destination":"DiscountShippingDestinationSelectionInput","endsAt":"DateTime","maximumShippingPrice":"Decimal","minimumRequirement":"DiscountMinimumRequirementInput","recurringCycleLimit":"Int","startsAt":"DateTime","tags":"[String!]","title":"String"}}, +"DiscountAutomaticFreeShippingUpdatePayload":{"o":{"f":{"automaticDiscountNode":"DiscountAutomaticNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountAutomaticNode":{"o":{"f":{"automaticDiscount":"DiscountAutomatic!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}]},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"DiscountAutomaticNodeConnection":{"o":{"f":{"edges":"[DiscountAutomaticNodeEdge!]!","nodes":"[DiscountAutomaticNode!]!","pageInfo":"PageInfo!"}}}, +"DiscountAutomaticNodeEdge":{"o":{"f":{"cursor":"String!","node":"DiscountAutomaticNode!"}}}, +"DiscountBulkTagsAddPayload":{"o":{"f":{"job":"Job","userErrors":"[DiscountUserError!]!"}}}, +"DiscountBulkTagsRemovePayload":{"o":{"f":{"job":"Job","userErrors":"[DiscountUserError!]!"}}}, +"DiscountBuyerSelection":{"e":["ALL"]}, +"DiscountBuyerSelectionAll":{"o":{"f":{"all":"DiscountBuyerSelection!"}}}, +"DiscountClass":{"e":["PRODUCT","ORDER","SHIPPING"]}, +"DiscountCode":{"u":["DiscountCodeApp","DiscountCodeBasic","DiscountCodeBxgy","DiscountCodeFreeShipping"]}, +"DiscountCodeActivatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeApp":{"o":{"f":{"appDiscountType":"AppDiscountType!","appliesOnOneTimePurchase":"Boolean!","appliesOnSubscription":"Boolean!","appliesOncePerCustomer":"Boolean!","asyncUsageCount":"Int!","codes":["DiscountRedeemCodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"DiscountCodeSortKeys="}],"codesCount":"Count","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","customerSelection":"DiscountCustomerSelection!","discountClass":"DiscountClass!","discountClasses":"[DiscountClass!]!","discountId":"ID!","endsAt":"DateTime","errorHistory":"FunctionsErrorHistory","hasTimelineComment":"Boolean!","recurringCycleLimit":"Int","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"shareableUrls":"[DiscountShareableUrl!]!","startsAt":"DateTime!","status":"DiscountStatus!","tags":"[String!]!","title":"String!","totalSales":"MoneyV2","updatedAt":"DateTime!","usageLimit":"Int"},"t":["HasRollouts"],"d":{"customerSelection":"Use `context` instead.","discountClass":"Use `discountClasses` instead."}}}, +"DiscountCodeAppCreatePayload":{"o":{"f":{"codeAppDiscount":"DiscountCodeApp","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeAppInput":{"i":{"f":{"appliesOnOneTimePurchase":"Boolean=","appliesOnSubscription":"Boolean=","appliesOncePerCustomer":"Boolean","code":"String","combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","customerSelection":"DiscountCustomerSelectionInput","discountClasses":"[DiscountClass!]","endsAt":"DateTime","functionHandle":"String","functionId":"String","metafields":"[MetafieldInput!]=","recurringCycleLimit":"Int=","startsAt":"DateTime","tags":"[String!]","title":"String","usageLimit":"Int"},"d":{"customerSelection":"Use `context` instead.","functionId":"Use `functionHandle` instead."}}}, +"DiscountCodeAppUpdatePayload":{"o":{"f":{"codeAppDiscount":"DiscountCodeApp","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","code":"String!","index":"Int!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","value":"PricingValue!"},"t":["DiscountApplication"]}}, +"DiscountCodeBasic":{"o":{"f":{"appliesOncePerCustomer":"Boolean!","asyncUsageCount":"Int!","codes":["DiscountRedeemCodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"DiscountCodeSortKeys="}],"codesCount":"Count","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","customerGets":"DiscountCustomerGets!","customerSelection":"DiscountCustomerSelection!","discountClass":"MerchandiseDiscountClass!","discountClasses":"[DiscountClass!]!","endsAt":"DateTime","hasTimelineComment":"Boolean!","minimumRequirement":"DiscountMinimumRequirement","recurringCycleLimit":"Int","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"shareableUrls":"[DiscountShareableUrl!]!","shortSummary":"String!","startsAt":"DateTime!","status":"DiscountStatus!","summary":"String!","tags":"[String!]!","title":"String!","totalSales":"MoneyV2","updatedAt":"DateTime!","usageLimit":"Int"},"t":["HasRollouts"],"d":{"customerSelection":"Use `context` instead.","discountClass":"Use `discountClasses` instead."}}}, +"DiscountCodeBasicCreatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeBasicInput":{"i":{"f":{"appliesOncePerCustomer":"Boolean","code":"String","combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","customerGets":"DiscountCustomerGetsInput","customerSelection":"DiscountCustomerSelectionInput","endsAt":"DateTime","minimumRequirement":"DiscountMinimumRequirementInput","recurringCycleLimit":"Int","startsAt":"DateTime","tags":"[String!]","title":"String","usageLimit":"Int"},"d":{"customerSelection":"Use `context` instead."}}}, +"DiscountCodeBasicUpdatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeBulkActivatePayload":{"o":{"f":{"job":"Job","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeBulkDeactivatePayload":{"o":{"f":{"job":"Job","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeBulkDeletePayload":{"o":{"f":{"job":"Job","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeBxgy":{"o":{"f":{"appliesOncePerCustomer":"Boolean!","asyncUsageCount":"Int!","codes":["DiscountRedeemCodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"DiscountCodeSortKeys="}],"codesCount":"Count","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","customerBuys":"DiscountCustomerBuys!","customerGets":"DiscountCustomerGets!","customerSelection":"DiscountCustomerSelection!","discountClass":"MerchandiseDiscountClass!","discountClasses":"[DiscountClass!]!","endsAt":"DateTime","hasTimelineComment":"Boolean!","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"shareableUrls":"[DiscountShareableUrl!]!","startsAt":"DateTime!","status":"DiscountStatus!","summary":"String!","tags":"[String!]!","title":"String!","totalSales":"MoneyV2","updatedAt":"DateTime!","usageLimit":"Int","usesPerOrderLimit":"Int"},"t":["HasRollouts"],"d":{"customerSelection":"Use `context` instead.","discountClass":"Use `discountClasses` instead."}}}, +"DiscountCodeBxgyCreatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeBxgyInput":{"i":{"f":{"appliesOncePerCustomer":"Boolean","code":"String","combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","customerBuys":"DiscountCustomerBuysInput","customerGets":"DiscountCustomerGetsInput","customerSelection":"DiscountCustomerSelectionInput","endsAt":"DateTime","startsAt":"DateTime","tags":"[String!]","title":"String","usageLimit":"Int","usesPerOrderLimit":"Int"},"d":{"customerSelection":"Use `context` instead."}}}, +"DiscountCodeBxgyUpdatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeDeactivatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeDeletePayload":{"o":{"f":{"deletedCodeDiscountId":"ID","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeFreeShipping":{"o":{"f":{"appliesOnOneTimePurchase":"Boolean!","appliesOnSubscription":"Boolean!","appliesOncePerCustomer":"Boolean!","asyncUsageCount":"Int!","codes":["DiscountRedeemCodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"DiscountCodeSortKeys="}],"codesCount":"Count","combinesWith":"DiscountCombinesWith!","context":"DiscountContext!","createdAt":"DateTime!","customerSelection":"DiscountCustomerSelection!","destinationSelection":"DiscountShippingDestinationSelection!","discountClass":"ShippingDiscountClass!","discountClasses":"[DiscountClass!]!","endsAt":"DateTime","hasTimelineComment":"Boolean!","maximumShippingPrice":"MoneyV2","minimumRequirement":"DiscountMinimumRequirement","recurringCycleLimit":"Int","rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"shareableUrls":"[DiscountShareableUrl!]!","shortSummary":"String!","startsAt":"DateTime!","status":"DiscountStatus!","summary":"String!","tags":"[String!]!","title":"String!","totalSales":"MoneyV2","updatedAt":"DateTime!","usageLimit":"Int"},"t":["HasRollouts"],"d":{"customerSelection":"Use `context` instead.","discountClass":"Use `discountClasses` instead."}}}, +"DiscountCodeFreeShippingCreatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeFreeShippingInput":{"i":{"f":{"appliesOnOneTimePurchase":"Boolean","appliesOnSubscription":"Boolean","appliesOncePerCustomer":"Boolean","code":"String","combinesWith":"DiscountCombinesWithInput","context":"DiscountContextInput","customerSelection":"DiscountCustomerSelectionInput","destination":"DiscountShippingDestinationSelectionInput","endsAt":"DateTime","maximumShippingPrice":"Decimal","minimumRequirement":"DiscountMinimumRequirementInput","recurringCycleLimit":"Int","startsAt":"DateTime","tags":"[String!]","title":"String","usageLimit":"Int"},"d":{"customerSelection":"Use `context` instead."}}}, +"DiscountCodeFreeShippingUpdatePayload":{"o":{"f":{"codeDiscountNode":"DiscountCodeNode","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeNode":{"o":{"f":{"codeDiscount":"DiscountCode!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}]},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"DiscountCodeNodeConnection":{"o":{"f":{"edges":"[DiscountCodeNodeEdge!]!","nodes":"[DiscountCodeNode!]!","pageInfo":"PageInfo!"}}}, +"DiscountCodeNodeEdge":{"o":{"f":{"cursor":"String!","node":"DiscountCodeNode!"}}}, +"DiscountCodeRedeemCodeBulkDeletePayload":{"o":{"f":{"job":"Job","userErrors":"[DiscountUserError!]!"}}}, +"DiscountCodeSortKeys":{"e":["CODE","CREATED_AT","ID","RELEVANCE"]}, +"DiscountCollections":{"o":{"f":{"collections":["CollectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"DiscountCollectionsInput":{"i":{"add":"[ID!]","remove":"[ID!]"}}, +"DiscountCombinesWith":{"o":{"f":{"orderDiscounts":"Boolean!","productDiscounts":"Boolean!","productDiscountsWithTagsOnSameCartLine":"[String!]","shippingDiscounts":"Boolean!"}}}, +"DiscountCombinesWithInput":{"i":{"orderDiscounts":"Boolean=","productDiscounts":"Boolean=","productDiscountsWithTagsOnSameCartLine":"ProductDiscountsWithTagsOnSameCartLineInput","shippingDiscounts":"Boolean="}}, +"DiscountContext":{"u":["DiscountBuyerSelectionAll","DiscountContextUnknown","DiscountCustomerSegments","DiscountCustomers","DiscountMarkets"]}, +"DiscountContextInput":{"i":{"f":{"all":"DiscountBuyerSelection","customerSegments":"DiscountCustomerSegmentsInput","customers":"DiscountCustomersInput","markets":"DiscountMarketsInput"},"o":true}}, +"DiscountContextUnknown":{"o":{"f":{"contextType":"String!"}}}, +"DiscountCountries":{"o":{"f":{"countries":"[CountryCode!]!","includeRestOfWorld":"Boolean!"},"d":{"includeRestOfWorld":"This field is being retired. Discounts that set `includeRestOfWorld: true` will be converted to an explicit list of countries, and `countries` will then return every country where the discount applies."}}}, +"DiscountCountriesInput":{"i":{"f":{"add":"[CountryCode!]","includeRestOfWorld":"Boolean=","remove":"[CountryCode!]"},"d":{"includeRestOfWorld":"This field is being retired. Use `add` to specify each country where the discount should apply."}}}, +"DiscountCountryAll":{"o":{"f":{"allCountries":"Boolean!"}}}, +"DiscountCustomerAll":{"o":{"f":{"allCustomers":"Boolean!"}}}, +"DiscountCustomerBuys":{"o":{"f":{"isOneTimePurchase":"Boolean!","isSubscription":"Boolean!","items":"DiscountItems!","value":"DiscountCustomerBuysValue!"}}}, +"DiscountCustomerBuysInput":{"i":{"isOneTimePurchase":"Boolean=","isSubscription":"Boolean=","items":"DiscountItemsInput","value":"DiscountCustomerBuysValueInput"}}, +"DiscountCustomerBuysValue":{"u":["DiscountPurchaseAmount","DiscountQuantity"]}, +"DiscountCustomerBuysValueInput":{"i":{"amount":"Decimal","quantity":"UnsignedInt64"}}, +"DiscountCustomerGets":{"o":{"f":{"appliesOnOneTimePurchase":"Boolean!","appliesOnSubscription":"Boolean!","items":"DiscountItems!","value":"DiscountCustomerGetsValue!"}}}, +"DiscountCustomerGetsInput":{"i":{"appliesOnOneTimePurchase":"Boolean","appliesOnSubscription":"Boolean","items":"DiscountItemsInput","value":"DiscountCustomerGetsValueInput"}}, +"DiscountCustomerGetsValue":{"u":["DiscountAmount","DiscountOnQuantity","DiscountPercentage"]}, +"DiscountCustomerGetsValueInput":{"i":{"discountAmount":"DiscountAmountInput","discountOnQuantity":"DiscountOnQuantityInput","percentage":"Float"}}, +"DiscountCustomerSegments":{"o":{"f":{"segments":"[Segment!]!"}}}, +"DiscountCustomerSegmentsInput":{"i":{"add":"[ID!]","remove":"[ID!]"}}, +"DiscountCustomerSelection":{"u":["DiscountCustomerAll","DiscountCustomerSegments","DiscountCustomerSelectionUnknown","DiscountCustomers"]}, +"DiscountCustomerSelectionInput":{"i":{"all":"Boolean","customerSegments":"DiscountCustomerSegmentsInput","customers":"DiscountCustomersInput"}}, +"DiscountCustomerSelectionUnknown":{"o":{"f":{"customerSelectionType":"String!"}}}, +"DiscountCustomers":{"o":{"f":{"customers":"[Customer!]!"}}}, +"DiscountCustomersInput":{"i":{"add":"[ID!]","remove":"[ID!]"}}, +"DiscountEffect":{"u":["DiscountAmount","DiscountPercentage"]}, +"DiscountEffectInput":{"i":{"amount":"Decimal","percentage":"Float"}}, +"DiscountErrorCode":{"e":["BLANK","PRESENT","EQUAL_TO","GREATER_THAN","GREATER_THAN_OR_EQUAL_TO","INVALID","LESS_THAN_OR_EQUAL_TO","LESS_THAN","TAKEN","TOO_LONG","TOO_SHORT","INTERNAL_ERROR","TOO_MANY_ARGUMENTS","MISSING_ARGUMENT","ACTIVE_PERIOD_OVERLAP","END_DATE_BEFORE_START_DATE","EXCEEDED_MAX","MINIMUM_SUBTOTAL_AND_QUANTITY_RANGE_BOTH_PRESENT","VALUE_OUTSIDE_RANGE","CONFLICT","IMPLICIT_DUPLICATE","DUPLICATE","INCLUSION","INVALID_COMBINES_WITH_FOR_DISCOUNT_CLASS","INVALID_DISCOUNT_CLASS_FOR_PRICE_RULE","DISCOUNT_NOT_COMPATIBLE_WITH_CONDITION_TYPES","MAX_APP_DISCOUNTS","APPLIES_ON_NOTHING","RECURRING_CYCLE_LIMIT_NOT_A_VALID_INTEGER","MULTIPLE_RECURRING_CYCLE_LIMIT_FOR_NON_SUBSCRIPTION_ITEMS","MISSING_FUNCTION_IDENTIFIER","MULTIPLE_FUNCTION_IDENTIFIERS","INVALID_TAG_LENGTH","TOO_MANY_TAGS","TOO_MANY_PRODUCT_DISCOUNTS_WITH_TAGS_ON_SAME_CART_LINE","INVALID_PRODUCT_DISCOUNTS_WITH_TAGS_ON_SAME_CART_LINE_FOR_DISCOUNT_CLASS","INVALID_PRODUCT_DISCOUNTS_WITH_TAGS_ON_SAME_CART_LINE_WITHOUT_PRODUCT_DISCOUNTS","INVALID_PRODUCT_DISCOUNTS_FALSE_WITH_EXISTING_TAGS_ON_SAME_CART_LINE","PRODUCT_DISCOUNTS_WITH_TAGS_ON_SAME_CART_LINE_NOT_ENTITLED"]}, +"DiscountItems":{"u":["AllDiscountItems","DiscountCollections","DiscountProducts"]}, +"DiscountItemsInput":{"i":{"all":"Boolean","collections":"DiscountCollectionsInput","products":"DiscountProductsInput"}}, +"DiscountMarkets":{"o":{"f":{"markets":["MarketConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"marketsCount":"Int!"}}}, +"DiscountMarketsInput":{"i":{"add":"[ID!]","remove":"[ID!]"}}, +"DiscountMinimumQuantity":{"o":{"f":{"greaterThanOrEqualToQuantity":"UnsignedInt64!"}}}, +"DiscountMinimumQuantityInput":{"i":{"greaterThanOrEqualToQuantity":"UnsignedInt64"}}, +"DiscountMinimumRequirement":{"u":["DiscountMinimumQuantity","DiscountMinimumSubtotal"]}, +"DiscountMinimumRequirementInput":{"i":{"quantity":"DiscountMinimumQuantityInput","subtotal":"DiscountMinimumSubtotalInput"}}, +"DiscountMinimumSubtotal":{"o":{"f":{"greaterThanOrEqualToSubtotal":"MoneyV2!"}}}, +"DiscountMinimumSubtotalInput":{"i":{"greaterThanOrEqualToSubtotal":"Decimal"}}, +"DiscountNode":{"o":{"f":{"discount":"Discount!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}]},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"DiscountNodeConnection":{"o":{"f":{"edges":"[DiscountNodeEdge!]!","nodes":"[DiscountNode!]!","pageInfo":"PageInfo!"}}}, +"DiscountNodeEdge":{"o":{"f":{"cursor":"String!","node":"DiscountNode!"}}}, +"DiscountOnQuantity":{"o":{"f":{"effect":"DiscountEffect!","quantity":"DiscountQuantity!"}}}, +"DiscountOnQuantityInput":{"i":{"effect":"DiscountEffectInput","quantity":"UnsignedInt64"}}, +"DiscountPercentage":{"o":{"f":{"percentage":"Float!"}}}, +"DiscountProducts":{"o":{"f":{"productVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"DiscountProductsInput":{"i":{"productVariantsToAdd":"[ID!]","productVariantsToRemove":"[ID!]","productsToAdd":"[ID!]","productsToRemove":"[ID!]"}}, +"DiscountPurchaseAmount":{"o":{"f":{"amount":"Decimal!"}}}, +"DiscountQuantity":{"o":{"f":{"quantity":"UnsignedInt64!"}}}, +"DiscountRedeemCode":{"o":{"f":{"asyncUsageCount":"Int!","code":"String!","createdAt":"DateTime!","createdBy":"App","id":"ID!"}}}, +"DiscountRedeemCodeBulkAddPayload":{"o":{"f":{"bulkCreation":"DiscountRedeemCodeBulkCreation","userErrors":"[DiscountUserError!]!"}}}, +"DiscountRedeemCodeBulkCreation":{"o":{"f":{"codes":["DiscountRedeemCodeBulkCreationCodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"codesCount":"Int!","createdAt":"DateTime!","discountCode":"DiscountCodeNode","done":"Boolean!","failedCount":"Int!","id":"ID!","importedCount":"Int!"},"t":["Node"]}}, +"DiscountRedeemCodeBulkCreationCode":{"o":{"f":{"code":"String!","discountRedeemCode":"DiscountRedeemCode","errors":"[DiscountUserError!]!"}}}, +"DiscountRedeemCodeBulkCreationCodeConnection":{"o":{"f":{"edges":"[DiscountRedeemCodeBulkCreationCodeEdge!]!","nodes":"[DiscountRedeemCodeBulkCreationCode!]!","pageInfo":"PageInfo!"}}}, +"DiscountRedeemCodeBulkCreationCodeEdge":{"o":{"f":{"cursor":"String!","node":"DiscountRedeemCodeBulkCreationCode!"}}}, +"DiscountRedeemCodeConnection":{"o":{"f":{"edges":"[DiscountRedeemCodeEdge!]!","nodes":"[DiscountRedeemCode!]!","pageInfo":"PageInfo!"}}}, +"DiscountRedeemCodeEdge":{"o":{"f":{"cursor":"String!","node":"DiscountRedeemCode!"}}}, +"DiscountRedeemCodeInput":{"i":{"code":"String!"}}, +"DiscountShareableUrl":{"o":{"f":{"targetItemImage":"Image","targetType":"DiscountShareableUrlTargetType!","title":"String!","url":"URL!"}}}, +"DiscountShareableUrlTargetType":{"e":["HOME","PRODUCT","COLLECTION"]}, +"DiscountShippingDestinationSelection":{"u":["DiscountCountries","DiscountCountryAll"]}, +"DiscountShippingDestinationSelectionInput":{"i":{"all":"Boolean=","countries":"DiscountCountriesInput"}}, +"DiscountSortKeys":{"e":["CREATED_AT","ENDS_AT","ID","RELEVANCE","STARTS_AT","TITLE","UPDATED_AT"]}, +"DiscountStatus":{"e":["ACTIVE","EXPIRED","SCHEDULED"]}, +"DiscountTagSortKeys":{"e":["ID","TITLE"]}, +"DiscountTargetType":{"e":["LINE_ITEM","SHIPPING_LINE"]}, +"DiscountType":{"e":["MANUAL","CODE_DISCOUNT","AUTOMATIC_DISCOUNT"]}, +"DiscountUserError":{"o":{"f":{"code":"DiscountErrorCode","extraInfo":"String","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DisplayableError":{"n":{"f":{"field":"[String!]","message":"String!"},"t":["AbandonmentEmailStateUpdateUserError","AbandonmentUpdateActivitiesDeliveryStatusesUserError","AnalyticsAnnotationCreateUserError","AnalyticsAnnotationDeleteUserError","AnalyticsAnnotationUpdateUserError","AnalyticsTargetCreateUserError","AnalyticsTargetUpdateUserError","AnalyticsTargetsDeleteUserError","AppRevokeAccessScopesAppRevokeScopeError","AppSubscriptionTrialExtendUserError","AppUninstallAppUninstallError","ArticleCreateUserError","ArticleDeleteUserError","ArticleUpdateUserError","BillingAttemptUserError","BlogCreateUserError","BlogDeleteUserError","BlogUpdateUserError","BulkMutationUserError","BulkOperationUserError","BulkProductResourceFeedbackCreateUserError","BusinessCustomerUserError","CarrierServiceCreateUserError","CarrierServiceDeleteUserError","CarrierServiceUpdateUserError","CartTransformCreateUserError","CartTransformDeleteUserError","CashDrawerCreateUserError","CashDrawerFindOrCreateUserError","CashDrawerUpdateUserError","CashManagementReasonCodeCreateUserError","CashManagementReasonCodeDeleteUserError","CatalogUserError","ChannelCreateUserError","ChannelDeleteUserError","ChannelFullSyncUserError","ChannelUpdateUserError","CheckoutAndAccountsConfigurationUserError","CheckoutBrandingUpsertUserError","CollectionAddProductsV2UserError","CollectionDuplicateUserError","CollectionReorderProductsUserError","CombinedListingUpdateUserError","CommentApproveUserError","CommentDeleteUserError","CommentNotSpamUserError","CommentSpamUserError","ConsentPolicyError","CustomerCancelDataErasureUserError","CustomerEmailMarketingConsentUpdateUserError","CustomerMarketingConsentError","CustomerMergeUserError","CustomerPaymentMethodCreateFromDuplicationDataUserError","CustomerPaymentMethodGetDuplicationDataUserError","CustomerPaymentMethodGetUpdateUrlUserError","CustomerPaymentMethodRemoteUserError","CustomerPaymentMethodUserError","CustomerRequestDataErasureUserError","CustomerSegmentMembersQueryUserError","CustomerSendAccountInviteEmailUserError","CustomerSetUserError","CustomerSmsMarketingConsentError","DataSaleOptOutUserError","DelegateAccessTokenCreateUserError","DelegateAccessTokenDestroyUserError","DeliveryCustomizationError","DeliveryLocationLocalPickupSettingsError","DeliveryPromiseProviderUpsertUserError","DiscountUserError","DisputeEvidenceUpdateUserError","ErrorsServerPixelUserError","ErrorsWebPixelUserError","FilesUserError","FulfillmentConstraintRuleCreateUserError","FulfillmentConstraintRuleDeleteUserError","FulfillmentConstraintRuleUpdateUserError","FulfillmentOrderCancelError","FulfillmentOrderHoldUserError","FulfillmentOrderLineItemsPreparedForPickupUserError","FulfillmentOrderMergeUserError","FulfillmentOrderMoveFulfillmentOrderMoveUserError","FulfillmentOrderReleaseHoldUserError","FulfillmentOrderReportProgressUserError","FulfillmentOrderRescheduleUserError","FulfillmentOrderSplitUserError","FulfillmentOrdersRerouteUserError","FulfillmentOrdersSetFulfillmentDeadlineUserError","GiftCardDeactivateUserError","GiftCardProductSetUserError","GiftCardSendNotificationToCustomerUserError","GiftCardSendNotificationToRecipientUserError","GiftCardTransactionUserError","GiftCardUserError","InventoryAdjustQuantitiesUserError","InventoryBulkToggleActivationUserError","InventoryMoveQuantitiesUserError","InventorySetOnHandQuantitiesUserError","InventorySetQuantitiesUserError","InventoryShipmentAddItemsUserError","InventoryShipmentCreateInTransitUserError","InventoryShipmentCreateUserError","InventoryShipmentDeleteUserError","InventoryShipmentMarkInTransitUserError","InventoryShipmentReceiveUserError","InventoryShipmentRemoveItemsUserError","InventoryShipmentSetBarcodeUserError","InventoryShipmentSetTrackingUserError","InventoryShipmentUpdateItemQuantitiesUserError","InventoryTransferCancelUserError","InventoryTransferCreateAsReadyToShipUserError","InventoryTransferCreateUserError","InventoryTransferDeleteUserError","InventoryTransferDuplicateUserError","InventoryTransferEditUserError","InventoryTransferMarkAsReadyToShipUserError","InventoryTransferRemoveItemsUserError","InventoryTransferSetItemsUserError","LocationActivateUserError","LocationAddUserError","LocationDeactivateUserError","LocationDeleteUserError","LocationEditUserError","MarketCurrencySettingsUserError","MarketUserError","MarketingActivityUserError","MediaUserError","MenuCreateUserError","MenuDeleteUserError","MenuUpdateUserError","MetafieldDefinitionCreateUserError","MetafieldDefinitionDeleteUserError","MetafieldDefinitionPinUserError","MetafieldDefinitionUnpinUserError","MetafieldDefinitionUpdateUserError","MetafieldsSetUserError","MetaobjectUserError","MobilePlatformApplicationUserError","OnlineStoreThemeFilesUserErrors","OrderAttributionDefinitionDeleteUserError","OrderAttributionDefinitionUpsertUserError","OrderCancelUserError","OrderCreateMandatePaymentUserError","OrderCreateManualPaymentOrderCreateManualPaymentError","OrderCreateUserError","OrderCustomerRemoveUserError","OrderCustomerSetUserError","OrderDeleteUserError","OrderEditAddShippingLineUserError","OrderEditRemoveDiscountUserError","OrderEditRemoveShippingLineUserError","OrderEditUpdateDiscountUserError","OrderEditUpdateShippingLineUserError","OrderInvoiceSendUserError","OrderRiskAssessmentCreateUserError","PageCreateUserError","PageDeleteUserError","PageUpdateUserError","PaymentCustomizationError","PaymentReminderSendUserError","PaymentScheduleCaptureUserError","PaymentTermsCreateUserError","PaymentTermsDeleteUserError","PaymentTermsUpdateUserError","PointOfSaleDeviceAssignToCashDrawerUserError","PointOfSaleDevicePaymentSessionCloseUserError","PointOfSaleDevicePaymentSessionCountUserError","PointOfSaleDevicePaymentSessionOpenUserError","PreviewInstallUserError","PriceListFixedPricesByProductBulkUpdateUserError","PriceListPriceUserError","PriceListUserError","PrivacyFeaturesDisableUserError","ProductBundleMutationUserError","ProductChangeStatusUserError","ProductFeedCreateUserError","ProductFeedDeleteUserError","ProductFullSyncUserError","ProductOptionUpdateUserError","ProductOptionsCreateUserError","ProductOptionsDeleteUserError","ProductOptionsReorderUserError","ProductSetUserError","ProductVariantRelationshipBulkUpdateUserError","ProductVariantsBulkCreateUserError","ProductVariantsBulkDeleteUserError","ProductVariantsBulkReorderUserError","ProductVariantsBulkUpdateUserError","PubSubWebhookSubscriptionCreateUserError","PubSubWebhookSubscriptionUpdateUserError","PublicationUserError","QuantityPricingByVariantUserError","QuantityRuleUserError","RequestedOrderEditCreateUserError","RequestedOrderEditDeclineUserError","RequestedOrderEditResolveUserError","ReturnUserError","SellingPlanGroupUserError","ShippingLabelPurchaseError","ShippingLabelPurchaseUserError","ShopPolicyUserError","ShopResourceFeedbackCreateUserError","ShopifyPaymentsPayoutAlternateCurrencyCreateUserError","StandardMetafieldDefinitionEnableUserError","StoreCreditAccountCreditUserError","StoreCreditAccountDebitUserError","SubscriptionBillingCycleBulkUserError","SubscriptionBillingCycleContractEditCalculateUserError","SubscriptionBillingCycleSkipUserError","SubscriptionBillingCycleUnskipUserError","SubscriptionBillingCycleUserError","SubscriptionContractCalculationCommitUserError","SubscriptionContractCreateCalculateUserError","SubscriptionContractStatusUpdateUserError","SubscriptionContractUpdateCalculateUserError","SubscriptionContractUserError","SubscriptionDraftUserError","TaxAppConfigureUserError","TaxSummaryCreateUserError","ThemeCreateUserError","ThemeDeleteUserError","ThemeDuplicateUserError","ThemePublishUserError","ThemeUpdateUserError","TransactionVoidUserError","TranslationUserError","UrlRedirectBulkDeleteByIdsUserError","UrlRedirectBulkDeleteBySavedSearchUserError","UrlRedirectBulkDeleteBySearchUserError","UrlRedirectImportUserError","UrlRedirectUserError","UserError","ValidationUserError"]}}, +"DisputeEvidenceUpdatePayload":{"o":{"f":{"disputeEvidence":"ShopifyPaymentsDisputeEvidence","userErrors":"[DisputeEvidenceUpdateUserError!]!"}}}, +"DisputeEvidenceUpdateUserError":{"o":{"f":{"code":"DisputeEvidenceUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"DisputeEvidenceUpdateUserErrorCode":{"e":["DISPUTE_EVIDENCE_NOT_FOUND","EVIDENCE_ALREADY_ACCEPTED","EVIDENCE_PAST_DUE_DATE","EVIDENCE_UNDER_REVIEW","FILES_SIZE_EXCEEDED_LIMIT","FILE_NOT_FOUND","TOO_LARGE","INVALID"]}, +"DisputeStatus":{"e":{"v":["ACCEPTED","LOST","NEEDS_RESPONSE","PREVENTED","UNDER_REVIEW","WON","CHARGE_REFUNDED"],"d":{"CHARGE_REFUNDED":"CHARGE_REFUNDED is no longer supported."}}}, +"DisputeType":{"e":["CHARGEBACK","INQUIRY"]}, +"Distance":{"o":{"f":{"unit":"DistanceUnit!","value":"Float!"}}}, +"DistanceUnit":{"e":["KILOMETERS","MILES"]}, +"Domain":{"o":{"f":{"createdAt":"DateTime!","host":"String!","id":"ID!","localization":"DomainLocalization","marketWebPresence":"MarketWebPresence","sslEnabled":"Boolean!","url":"URL!"},"t":["Node"]}}, +"DomainLocalization":{"o":{"f":{"alternateLocales":"[String!]!","country":"String","defaultLocale":"String!"}}}, +"DraftOrder":{"o":{"f":{"acceptAutomaticDiscounts":"Boolean","allVariantPricesOverridden":"Boolean!","allowDiscountCodesInCheckout":"Boolean!","amountDueLaterSet":"MoneyBag!","amountDueNowSet":"MoneyBag!","anyVariantPricesOverridden":"Boolean!","appliedDiscount":"DraftOrderAppliedDiscount","billingAddress":"MailingAddress","billingAddressMatchesShippingAddress":"Boolean!","completedAt":"DateTime","createdAt":"DateTime!","currencyCode":"CurrencyCode!","customAttributes":"[Attribute!]!","customer":"Customer","defaultCursor":"String!","deposit":"DepositConfiguration","discountCodes":"[String!]!","email":"String","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"hasTimelineComment":"Boolean!","id":"ID!","invoiceEmailTemplateSubject":"String!","invoiceSentAt":"DateTime","invoiceUrl":"URL","legacyResourceId":"UnsignedInt64!","lineItems":["DraftOrderLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"lineItemsSubtotalPrice":"MoneyBag!","localizationExtensions":["LocalizationExtensionConnection!",{"after":"String","before":"String","countryCodes":"[CountryCode!]","first":"Int","last":"Int","purposes":"[LocalizationExtensionPurpose!]","reverse":"Boolean="}],"localizedFields":["LocalizedFieldConnection!",{"after":"String","before":"String","countryCodes":"[CountryCode!]","first":"Int","last":"Int","purposes":"[LocalizedFieldPurpose!]","reverse":"Boolean="}],"marketName":"String!","marketRegionCountryCode":"CountryCode!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","note2":"String","order":"Order","paymentTerms":"PaymentTerms","phone":"String","platformDiscounts":"[DraftOrderPlatformDiscount!]!","poNumber":"String","presentmentCurrencyCode":"CurrencyCode!","purchasingEntity":"PurchasingEntity","ready":"Boolean!","reserveInventoryUntil":"DateTime","shippingAddress":"MailingAddress","shippingLine":"ShippingLine","status":"DraftOrderStatus!","subtotalPrice":"Money!","subtotalPriceSet":"MoneyBag!","tags":"[String!]!","taxExempt":"Boolean!","taxLines":"[TaxLine!]!","taxesIncluded":"Boolean!","totalDiscountsSet":"MoneyBag!","totalLineItemsPriceSet":"MoneyBag!","totalPrice":"Money!","totalPriceSet":"MoneyBag!","totalQuantityOfLineItems":"Int!","totalShippingPrice":"Money!","totalShippingPriceSet":"MoneyBag!","totalTax":"Money!","totalTaxSet":"MoneyBag!","totalWeight":"UnsignedInt64!","transformerFingerprint":"String","updatedAt":"DateTime!","visibleToCustomer":"Boolean!","warnings":"[DraftOrderWarning!]!"},"t":["CommentEventSubject","HasEvents","HasLocalizationExtensions","HasLocalizedFields","HasMetafields","LegacyInteroperability","Navigable","Node"],"d":{"localizationExtensions":"This connection will be removed in a future version. Use `localizedFields` instead.","marketName":"This field is now incompatible with Markets.","marketRegionCountryCode":"This field is now incompatible with Markets.","subtotalPrice":"Use `subtotalPriceSet` instead.","totalPrice":"Use `totalPriceSet` instead.","totalShippingPrice":"Use `totalShippingPriceSet` instead.","totalTax":"Use `totalTaxSet` instead."}}}, +"DraftOrderAppliedDiscount":{"o":{"f":{"amount":"Money!","amountSet":"MoneyBag!","amountV2":"MoneyV2!","description":"String!","title":"String","value":"Float!","valueType":"DraftOrderAppliedDiscountType!"},"d":{"amount":"Use `amountSet` instead.","amountV2":"Use `amountSet` instead."}}}, +"DraftOrderAppliedDiscountInput":{"i":{"f":{"amount":"Money","amountWithCurrency":"MoneyInput","description":"String","title":"String","value":"Float!","valueType":"DraftOrderAppliedDiscountType!"},"d":{"amount":"Please use `amountWithCurrency` instead."}}}, +"DraftOrderAppliedDiscountType":{"e":["FIXED_AMOUNT","PERCENTAGE"]}, +"DraftOrderAvailableDeliveryOptions":{"o":{"f":{"availableLocalDeliveryRates":"[DraftOrderShippingRate!]!","availableLocalPickupOptions":"[PickupInStoreLocation!]!","availableShippingRates":"[DraftOrderShippingRate!]!","pageInfo":"PageInfo!"}}}, +"DraftOrderAvailableDeliveryOptionsInput":{"i":{"acceptAutomaticDiscounts":"Boolean","appliedDiscount":"DraftOrderAppliedDiscountInput","discountCodes":"[String!]","lineItems":"[DraftOrderLineItemInput!]","marketRegionCountryCode":"CountryCode","purchasingEntity":"PurchasingEntityInput","shippingAddress":"MailingAddressInput"}}, +"DraftOrderBulkAddTagsPayload":{"o":{"f":{"job":"Job","userErrors":"[UserError!]!"}}}, +"DraftOrderBulkDeletePayload":{"o":{"f":{"job":"Job","userErrors":"[UserError!]!"}}}, +"DraftOrderBulkRemoveTagsPayload":{"o":{"f":{"job":"Job","userErrors":"[UserError!]!"}}}, +"DraftOrderBundleAddedWarning":{"o":{"f":{"errorCode":"String!","field":"String!","message":"String!"},"t":["DraftOrderWarning"]}}, +"DraftOrderCalculatePayload":{"o":{"f":{"calculatedDraftOrder":"CalculatedDraftOrder","userErrors":"[UserError!]!"}}}, +"DraftOrderCompletePayload":{"o":{"f":{"draftOrder":"DraftOrder","userErrors":"[UserError!]!"}}}, +"DraftOrderConnection":{"o":{"f":{"edges":"[DraftOrderEdge!]!","nodes":"[DraftOrder!]!","pageInfo":"PageInfo!"}}}, +"DraftOrderCreateFromOrderPayload":{"o":{"f":{"draftOrder":"DraftOrder","userErrors":"[UserError!]!"}}}, +"DraftOrderCreatePayload":{"o":{"f":{"draftOrder":"DraftOrder","userErrors":"[UserError!]!"}}}, +"DraftOrderDeleteInput":{"i":{"id":"ID!"}}, +"DraftOrderDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[UserError!]!"}}}, +"DraftOrderDiscountNotAppliedWarning":{"o":{"f":{"discountCode":"String","discountTitle":"String","errorCode":"String!","field":"String!","message":"String!"},"t":["DraftOrderWarning"]}}, +"DraftOrderDuplicatePayload":{"o":{"f":{"draftOrder":"DraftOrder","userErrors":"[UserError!]!"}}}, +"DraftOrderEdge":{"o":{"f":{"cursor":"String!","node":"DraftOrder!"}}}, +"DraftOrderInput":{"i":{"f":{"acceptAutomaticDiscounts":"Boolean","allowDiscountCodesInCheckout":"Boolean","appliedDiscount":"DraftOrderAppliedDiscountInput","billingAddress":"MailingAddressInput","customAttributes":"[AttributeInput!]","customerId":"ID","deposit":"DepositInput","discountCodes":"[String!]","email":"String","lineItems":"[DraftOrderLineItemInput!]","localizationExtensions":"[LocalizationExtensionInput!]","localizedFields":"[LocalizedFieldInput!]","marketRegionCountryCode":"CountryCode","metafields":"[MetafieldInput!]","note":"String","paymentTerms":"PaymentTermsInput","phone":"String","poNumber":"String","presentmentCurrencyCode":"CurrencyCode","purchasingEntity":"PurchasingEntityInput","reserveInventoryUntil":"DateTime","sessionToken":"String","shippingAddress":"MailingAddressInput","shippingLine":"ShippingLineInput","sourceName":"String","tags":"[String!]","taxExempt":"Boolean","transformerFingerprint":"String","useCustomerDefaultAddress":"Boolean","visibleToCustomer":"Boolean"},"d":{"customerId":"Use `purchasingEntity` instead, which can be used for either a D2C or B2B customer.","localizationExtensions":"This field will be removed in a future version. Use `localizedFields` instead.","marketRegionCountryCode":"This field is now incompatible with Markets."}}}, +"DraftOrderInvoicePreviewPayload":{"o":{"f":{"previewHtml":"HTML","previewSubject":"HTML","userErrors":"[UserError!]!"}}}, +"DraftOrderInvoiceSendPayload":{"o":{"f":{"draftOrder":"DraftOrder","userErrors":"[UserError!]!"}}}, +"DraftOrderLineItem":{"o":{"f":{"appliedDiscount":"DraftOrderAppliedDiscount","approximateDiscountedUnitPriceSet":"MoneyBag!","bundleComponents":"[DraftOrderLineItem!]!","components":"[DraftOrderLineItem!]!","custom":"Boolean!","customAttributes":"[Attribute!]!","customAttributesV2":"[TypedAttribute!]!","discountedTotal":"Money!","discountedTotalSet":"MoneyBag!","discountedUnitPrice":"Money!","discountedUnitPriceSet":"MoneyBag!","fulfillmentService":"FulfillmentService","grams":"Int","id":"ID!","image":["Image",{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","scale":"Int="}],"isGiftCard":"Boolean!","name":"String!","originalTotal":"Money!","originalTotalSet":"MoneyBag!","originalUnitPrice":"Money!","originalUnitPriceSet":"MoneyBag!","originalUnitPriceWithCurrency":"MoneyV2","priceOverride":"MoneyV2","product":"Product","quantity":"Int!","requiresShipping":"Boolean!","sku":"String","taxLines":"[TaxLine!]!","taxable":"Boolean!","title":"String!","totalDiscount":"Money!","totalDiscountSet":"MoneyBag!","uuid":"String!","variant":"ProductVariant","variantTitle":"String","vendor":"String","weight":"Weight"},"t":["Node"],"d":{"bundleComponents":"Use `components` instead.","discountedTotal":"Use `discountedTotalSet` instead.","discountedUnitPrice":"Use `approximateDiscountedUnitPriceSet` instead.","discountedUnitPriceSet":"Use `approximateDiscountedUnitPriceSet` instead.","grams":"Use `weight` instead.","image(crop)":"Use `Image.url(transform: { crop:})` instead.","image(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","image(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","image(scale)":"Use `Image.url(transform: { scale:})` instead.","originalTotal":"Use `originalTotalSet` instead.","originalUnitPrice":"Use `originalUnitPriceWithCurrency` instead.","totalDiscount":"Use `totalDiscountSet` instead."}}}, +"DraftOrderLineItemComponentInput":{"i":{"quantity":"Int!","uuid":"String","variantId":"ID"}}, +"DraftOrderLineItemConnection":{"o":{"f":{"edges":"[DraftOrderLineItemEdge!]!","nodes":"[DraftOrderLineItem!]!","pageInfo":"PageInfo!"}}}, +"DraftOrderLineItemEdge":{"o":{"f":{"cursor":"String!","node":"DraftOrderLineItem!"}}}, +"DraftOrderLineItemInput":{"i":{"f":{"appliedDiscount":"DraftOrderAppliedDiscountInput","bundleComponents":"[BundlesDraftOrderBundleLineItemComponentInput!]","components":"[DraftOrderLineItemComponentInput!]","customAttributes":"[AttributeInput!]","generatePriceOverride":"Boolean","grams":"Int","originalUnitPrice":"Money","originalUnitPriceWithCurrency":"MoneyInput","priceOverride":"MoneyInput","quantity":"Int!","requiresShipping":"Boolean","sku":"String","taxable":"Boolean","title":"String","uuid":"String","variantId":"ID","weight":"WeightInput"},"d":{"bundleComponents":"Use `components` instead.","grams":"`weight` should be used instead, allowing different units to be used.","originalUnitPrice":"`originalUnitPriceWithCurrency` should be used instead, where currency can be specified."}}}, +"DraftOrderMarketRegionCountryCodeNotSupportedWarning":{"o":{"f":{"errorCode":"String!","field":"String!","message":"String!"},"t":["DraftOrderWarning"]}}, +"DraftOrderPlatformDiscount":{"o":{"f":{"allocations":"[DraftOrderPlatformDiscountAllocation!]!","automaticDiscount":"Boolean!","bxgyDiscount":"Boolean!","code":"String","discountClass":"DiscountClass!","discountClasses":"[DiscountClass!]!","discountNode":"DiscountNode","id":"ID","presentationLevel":"String!","shortSummary":"String!","summary":"String!","title":"String!","totalAmount":"MoneyV2!","totalAmountPriceSet":"MoneyBag!"},"d":{"discountClass":"Use `discountClasses` instead."}}}, +"DraftOrderPlatformDiscountAllocation":{"o":{"f":{"id":"ID","quantity":"Int","reductionAmount":"MoneyV2!","reductionAmountSet":"MoneyBag!","target":"DraftOrderPlatformDiscountAllocationTarget"}}}, +"DraftOrderPlatformDiscountAllocationTarget":{"u":["CalculatedDraftOrderLineItem","DraftOrderLineItem","ShippingLine"]}, +"DraftOrderShippingRate":{"o":{"f":{"code":"String!","handle":"String!","price":"MoneyV2!","source":"String!","title":"String!"}}}, +"DraftOrderSortKeys":{"e":["CUSTOMER_NAME","ID","NUMBER","RELEVANCE","STATUS","TOTAL_PRICE","UPDATED_AT"]}, +"DraftOrderStatus":{"e":["COMPLETED","INVOICE_SENT","OPEN"]}, +"DraftOrderTag":{"o":{"f":{"handle":"String!","id":"ID!","title":"String!"},"t":["Node"]}}, +"DraftOrderUpdatePayload":{"o":{"f":{"draftOrder":"DraftOrder","userErrors":"[UserError!]!"}}}, +"DraftOrderWarning":{"n":{"f":{"errorCode":"String!","field":"String!","message":"String!"},"t":["DraftOrderBundleAddedWarning","DraftOrderDiscountNotAppliedWarning","DraftOrderMarketRegionCountryCodeNotSupportedWarning"]}}, +"Duty":{"o":{"f":{"countryCodeOfOrigin":"CountryCode","harmonizedSystemCode":"String","id":"ID!","price":"MoneyBag!","taxLines":"[TaxLine!]!"},"t":["Node"]}}, +"DutySale":{"o":{"f":{"actionType":"SaleActionType!","duty":"Duty!","id":"ID!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"EditableProperty":{"o":{"f":{"locked":"Boolean!","reason":"FormattedString"}}}, +"EmailInput":{"i":{"bcc":"[String!]","body":"String","customMessage":"String","from":"String","subject":"String","to":"String"}}, +"EntitlementsType":{"o":{"f":{"b2b":"B2BType!","markets":"MarketsType!"}}}, +"ErrorsServerPixelUserError":{"o":{"f":{"code":"ErrorsServerPixelUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ErrorsServerPixelUserErrorCode":{"e":["NOT_FOUND","ALREADY_EXISTS","PUB_SUB_ERROR","NEEDS_CONFIGURATION_TO_CONNECT"]}, +"ErrorsWebPixelUserError":{"o":{"f":{"code":"ErrorsWebPixelUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ErrorsWebPixelUserErrorCode":{"e":{"v":["BLANK","TAKEN","NOT_FOUND","INVALID_SETTINGS","UNABLE_TO_DELETE","NO_EXTENSION","INVALID_CONFIGURATION_JSON","INVALID_SETTINGS_DEFINITION","UNEXPECTED_ERROR","INVALID_RUNTIME_CONTEXT"],"d":{"UNABLE_TO_DELETE":"`UNABLE_TO_DELETE` is deprecated. Use `UNEXPECTED_ERROR` instead."}}}, +"Event":{"n":{"f":{"action":"String!","appTitle":"String","attributeToApp":"Boolean!","attributeToUser":"Boolean!","createdAt":"DateTime!","criticalAlert":"Boolean!","id":"ID!","message":"FormattedString!"},"t":["BasicEvent","CommentEvent"]}}, +"EventBridgeServerPixelUpdatePayload":{"o":{"f":{"serverPixel":"ServerPixel","userErrors":"[ErrorsServerPixelUserError!]!"}}}, +"EventBridgeWebhookSubscriptionCreatePayload":{"o":{"f":{"userErrors":"[UserError!]!","webhookSubscription":"WebhookSubscription"}}}, +"EventBridgeWebhookSubscriptionInput":{"i":{"arn":"ARN","filter":"String","format":"WebhookSubscriptionFormat","includeFields":"[String!]","metafieldNamespaces":"[String!]","metafields":"[HasMetafieldsMetafieldIdentifierInput!]","name":"String"}}, +"EventBridgeWebhookSubscriptionUpdatePayload":{"o":{"f":{"userErrors":"[UserError!]!","webhookSubscription":"WebhookSubscription"}}}, +"EventConnection":{"o":{"f":{"edges":"[EventEdge!]!","nodes":"[Event!]!","pageInfo":"PageInfo!"}}}, +"EventEdge":{"o":{"f":{"cursor":"String!","node":"Event!"}}}, +"EventSortKeys":{"e":["CREATED_AT","ID"]}, +"EventSubjectType":{"e":["COMPANY_LOCATION","COMPANY","CUSTOMER","DRAFT_ORDER","INVENTORY_TRANSFER","COLLECTION","PRODUCT","PRODUCT_VARIANT","ARTICLE","BLOG","COMMENT","PAGE","DISCOUNT_AUTOMATIC_BXGY","DISCOUNT_AUTOMATIC_NODE","DISCOUNT_CODE_NODE","DISCOUNT_NODE","PRICE_RULE","ORDER","UNKNOWN"]}, +"ExchangeLineItem":{"o":{"f":{"id":"ID!","lineItem":"LineItem","lineItems":"[LineItem!]","processableQuantity":"Int!","processedQuantity":"Int!","productId":"ID","quantity":"Int!","title":"String","unprocessedQuantity":"Int!","variantId":"ID","variantSku":"String","variantTitle":"String"},"t":["Node"],"d":{"lineItem":"Use `lineItems` instead."}}}, +"ExchangeLineItemAppliedDiscountInput":{"i":{"description":"String","value":"ExchangeLineItemAppliedDiscountValueInput!"}}, +"ExchangeLineItemAppliedDiscountValueInput":{"i":{"f":{"amount":"MoneyInput","percentage":"Float"},"o":true}}, +"ExchangeLineItemConnection":{"o":{"f":{"edges":"[ExchangeLineItemEdge!]!","nodes":"[ExchangeLineItem!]!","pageInfo":"PageInfo!"}}}, +"ExchangeLineItemEdge":{"o":{"f":{"cursor":"String!","node":"ExchangeLineItem!"}}}, +"ExchangeLineItemInput":{"i":{"appliedDiscount":"ExchangeLineItemAppliedDiscountInput","giftCardCodes":"[String!]","quantity":"Int!","variantId":"ID"}}, +"ExchangeLineItemRemoveFromReturnInput":{"i":{"exchangeLineItemId":"ID!","quantity":"Int!"}}, +"ExchangeV2":{"o":{"f":{"additions":"ExchangeV2Additions!","completedAt":"DateTime","createdAt":"DateTime!","id":"ID!","location":"Location","mirrored":"Boolean!","note":"String","refunds":"[Refund!]!","returns":"ExchangeV2Returns!","staffMember":"StaffMember","totalAmountProcessedSet":"MoneyBag!","totalPriceSet":"MoneyBag!","transactions":"[OrderTransaction!]!"},"t":["Node"]}}, +"ExchangeV2Additions":{"o":{"f":{"lineItems":"[ExchangeV2LineItem!]!","subtotalPriceSet":"MoneyBag!","taxLines":"[TaxLine!]!","totalPriceSet":"MoneyBag!"}}}, +"ExchangeV2Connection":{"o":{"f":{"edges":"[ExchangeV2Edge!]!","nodes":"[ExchangeV2!]!","pageInfo":"PageInfo!"}}}, +"ExchangeV2Edge":{"o":{"f":{"cursor":"String!","node":"ExchangeV2!"}}}, +"ExchangeV2LineItem":{"o":{"f":{"customAttributes":"[Attribute!]!","discountedTotalSet":"MoneyBag!","discountedUnitPriceSet":"MoneyBag!","fulfillmentService":"FulfillmentService","giftCard":"Boolean!","giftCards":"[GiftCard!]!","isGiftCard":"Boolean!","lineItem":"LineItem","name":"String!","originalTotalSet":"MoneyBag!","originalUnitPriceSet":"MoneyBag!","quantity":"Int!","requiresShipping":"Boolean!","sku":"String","taxLines":"[TaxLine!]!","taxable":"Boolean!","title":"String!","variant":"ProductVariant","variantTitle":"String","vendor":"String"}}}, +"ExchangeV2Returns":{"o":{"f":{"lineItems":"[ExchangeV2LineItem!]!","orderDiscountAmountSet":"MoneyBag!","shippingRefundAmountSet":"MoneyBag!","subtotalPriceSet":"MoneyBag!","taxLines":"[TaxLine!]!","tipRefundAmountSet":"MoneyBag!","totalPriceSet":"MoneyBag!"}}}, +"ExternalVideo":{"o":{"f":{"alt":"String","createdAt":"DateTime!","embedUrl":"URL!","embeddedUrl":"URL!","fileErrors":"[FileError!]!","fileStatus":"FileStatus!","host":"MediaHost!","id":"ID!","mediaContentType":"MediaContentType!","mediaErrors":"[MediaError!]!","mediaWarnings":"[MediaWarning!]!","originUrl":"URL!","preview":"MediaPreviewImage","status":"MediaStatus!","updatedAt":"DateTime!"},"t":["File","Media","Node"],"d":{"embeddedUrl":"Use `originUrl` instead."}}}, +"FailedRequirement":{"o":{"f":{"action":"NavigationItem","message":"String!"}}}, +"Fee":{"n":{"f":{"id":"ID!"},"t":["RestockingFee","ReturnShippingFee"]}}, +"FeeSale":{"o":{"f":{"actionType":"SaleActionType!","fee":"Fee","id":"ID!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"File":{"n":{"f":{"alt":"String","createdAt":"DateTime!","fileErrors":"[FileError!]!","fileStatus":"FileStatus!","id":"ID!","preview":"MediaPreviewImage","updatedAt":"DateTime!"},"t":["ExternalVideo","GenericFile","MediaImage","Model3d","Video"]}}, +"FileAcknowledgeUpdateFailedPayload":{"o":{"f":{"files":"[File!]","userErrors":"[FilesUserError!]!"}}}, +"FileConnection":{"o":{"f":{"edges":"[FileEdge!]!","nodes":"[File!]!","pageInfo":"PageInfo!"}}}, +"FileContentType":{"e":["IMAGE","FILE","VIDEO","EXTERNAL_VIDEO","MODEL_3D"]}, +"FileCreateInput":{"i":{"alt":"String","contentType":"FileContentType","duplicateResolutionMode":"FileCreateInputDuplicateResolutionMode=","filename":"String","originalSource":"String!"}}, +"FileCreateInputDuplicateResolutionMode":{"e":["APPEND_UUID","RAISE_ERROR","REPLACE"]}, +"FileCreatePayload":{"o":{"f":{"files":"[File!]","userErrors":"[FilesUserError!]!"}}}, +"FileDeletePayload":{"o":{"f":{"deletedFileIds":"[ID!]","userErrors":"[FilesUserError!]!"}}}, +"FileEdge":{"o":{"f":{"cursor":"String!","node":"File!"}}}, +"FileError":{"o":{"f":{"code":"FileErrorCode!","details":"String","message":"String!"}}}, +"FileErrorCode":{"e":["UNKNOWN","INVALID_SIGNED_URL","IMAGE_DOWNLOAD_FAILURE","IMAGE_PROCESSING_FAILURE","MEDIA_TIMEOUT_ERROR","EXTERNAL_VIDEO_NOT_FOUND","EXTERNAL_VIDEO_UNLISTED","EXTERNAL_VIDEO_INVALID_ASPECT_RATIO","EXTERNAL_VIDEO_EMBED_DISABLED","EXTERNAL_VIDEO_EMBED_NOT_FOUND_OR_TRANSCODING","GENERIC_FILE_DOWNLOAD_FAILURE","GENERIC_FILE_INVALID_SIZE","VIDEO_METADATA_READ_ERROR","VIDEO_INVALID_FILETYPE_ERROR","VIDEO_MIN_WIDTH_ERROR","VIDEO_MAX_WIDTH_ERROR","VIDEO_MIN_HEIGHT_ERROR","VIDEO_MAX_HEIGHT_ERROR","VIDEO_MIN_DURATION_ERROR","VIDEO_MAX_DURATION_ERROR","VIDEO_VALIDATION_ERROR","MODEL3D_VALIDATION_ERROR","MODEL3D_THUMBNAIL_GENERATION_ERROR","MODEL3D_THUMBNAIL_REGENERATION_ERROR","MODEL3D_GLB_TO_USDZ_CONVERSION_ERROR","MODEL3D_GLB_OUTPUT_CREATION_ERROR","MODEL3D_PROCESSING_FAILURE","UNSUPPORTED_IMAGE_FILE_TYPE","INVALID_IMAGE_FILE_SIZE","INVALID_IMAGE_ASPECT_RATIO","INVALID_IMAGE_RESOLUTION","FILE_STORAGE_LIMIT_EXCEEDED","DUPLICATE_FILENAME_ERROR"]}, +"FileSetInput":{"i":{"alt":"String","contentType":"FileContentType","duplicateResolutionMode":"FileCreateInputDuplicateResolutionMode=","filename":"String","id":"ID","originalSource":"String"}}, +"FileSortKeys":{"e":["CREATED_AT","FILENAME","ID","ORIGINAL_UPLOAD_SIZE","RELEVANCE","UPDATED_AT"]}, +"FileStatus":{"e":["UPLOADED","PROCESSING","READY","FAILED"]}, +"FileUpdateInput":{"i":{"alt":"String","filename":"String","id":"ID!","originalSource":"String","previewImageSource":"String","referencesToAdd":"[ID!]","referencesToRemove":"[ID!]"}}, +"FileUpdatePayload":{"o":{"f":{"files":"[File!]","userErrors":"[FilesUserError!]!"}}}, +"FilesErrorCode":{"e":["INVALID","FILE_DOES_NOT_EXIST","FILE_LOCKED","UNSUPPORTED_MEDIA_TYPE_FOR_FILENAME_UPDATE","TOO_MANY_ARGUMENTS","BLANK_SEARCH","MISSING_ARGUMENTS","INVALID_QUERY","PRODUCT_SUSPENDED","INVALID_FILENAME_EXTENSION","INVALID_FILENAME","FILENAME_ALREADY_EXISTS","UNACCEPTABLE_UNVERIFIED_TRIAL_ASSET","UNACCEPTABLE_ASSET","UNACCEPTABLE_TRIAL_ASSET","ALT_VALUE_LIMIT_EXCEEDED","NON_READY_STATE","INVALID_FAILED_MEDIA_STATE","NON_IMAGE_MEDIA_PER_SHOP_LIMIT_EXCEEDED","MISMATCHED_FILENAME_AND_ORIGINAL_SOURCE","INVALID_DUPLICATE_MODE_FOR_TYPE","INVALID_IMAGE_SOURCE_URL","MISSING_FILENAME_FOR_DUPLICATE_MODE_REPLACE","PRODUCT_MEDIA_LIMIT_EXCEEDED","UNSUPPORTED_FILE_REFERENCE","REFERENCE_TARGET_DOES_NOT_EXIST","TOO_MANY_FILE_REFERENCE","INVALID_DUPLICATE_RESOLUTION_MODE","MEDIA_CANNOT_BE_MODIFIED"]}, +"FilesUserError":{"o":{"f":{"code":"FilesErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FilterOption":{"o":{"f":{"label":"String!","value":"String!"}}}, +"FinanceAppAccessPolicy":{"o":{"f":{"access":"[BankingFinanceAppAccess!]!"}}}, +"FinanceKycInformation":{"o":{"f":{"businessAddress":"ShopifyPaymentsAddressBasic","businessType":"ShopifyPaymentsBusinessType","industry":"ShopifyPaymentsMerchantCategoryCode","legalName":"String","shopOwner":"FinancialKycShopOwner!","taxIdentification":"ShopifyPaymentsTaxIdentification"}}}, +"FinancialKycShopOwner":{"o":{"f":{"email":"String!","firstName":"String","id":"ID!","lastName":"String","phone":"String"}}}, +"FinancialSummaryDiscountAllocation":{"o":{"f":{"approximateAllocatedAmountPerItem":"MoneyBag!","discountApplication":"FinancialSummaryDiscountApplication!"}}}, +"FinancialSummaryDiscountApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!"}}}, +"Float":"s", +"FlowGenerateSignaturePayload":{"o":{"f":{"payload":"String","signature":"String","targetUrl":"URL","userErrors":"[UserError!]!"}}}, +"FlowTriggerReceivePayload":{"o":{"f":{"userErrors":"[UserError!]!"}}}, +"FormattedString":"s", +"Fulfillment":{"o":{"f":{"createdAt":"DateTime!","deliveredAt":"DateTime","displayStatus":"FulfillmentDisplayStatus","estimatedDeliveryAt":"DateTime","events":["FulfillmentEventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"FulfillmentEventSortKeys="}],"fulfillmentLineItems":["FulfillmentLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"fulfillmentOrders":["FulfillmentOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"id":"ID!","inTransitAt":"DateTime","legacyResourceId":"UnsignedInt64!","location":"Location","name":"String!","order":"Order!","originAddress":"FulfillmentOriginAddress","requiresShipping":"Boolean!","service":"FulfillmentService","shippingLabel":"ShippingLabel","status":"FulfillmentStatus!","totalQuantity":"Int!","trackingInfo":["[FulfillmentTrackingInfo!]!",{"first":"Int"}],"updatedAt":"DateTime!"},"t":["LegacyInteroperability","Node"]}}, +"FulfillmentCancelPayload":{"o":{"f":{"fulfillment":"Fulfillment","userErrors":"[UserError!]!"}}}, +"FulfillmentConnection":{"o":{"f":{"edges":"[FulfillmentEdge!]!","nodes":"[Fulfillment!]!","pageInfo":"PageInfo!"}}}, +"FulfillmentConstraintRule":{"o":{"f":{"deliveryMethodTypes":"[DeliveryMethodType!]!","function":"ShopifyFunction!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}]},"t":["HasMetafields","Node"]}}, +"FulfillmentConstraintRuleCreatePayload":{"o":{"f":{"fulfillmentConstraintRule":"FulfillmentConstraintRule","userErrors":"[FulfillmentConstraintRuleCreateUserError!]!"}}}, +"FulfillmentConstraintRuleCreateUserError":{"o":{"f":{"code":"FulfillmentConstraintRuleCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentConstraintRuleCreateUserErrorCode":{"e":["INPUT_INVALID","FUNCTION_NOT_FOUND","FUNCTION_ALREADY_REGISTERED","FUNCTION_DOES_NOT_IMPLEMENT","CUSTOM_APP_FUNCTION_NOT_ELIGIBLE","FUNCTION_PENDING_DELETION","MULTIPLE_FUNCTION_IDENTIFIERS","MISSING_FUNCTION_IDENTIFIER","MAXIMUM_FULFILLMENT_CONSTRAINT_RULES_REACHED"]}, +"FulfillmentConstraintRuleDeletePayload":{"o":{"f":{"success":"Boolean","userErrors":"[FulfillmentConstraintRuleDeleteUserError!]!"}}}, +"FulfillmentConstraintRuleDeleteUserError":{"o":{"f":{"code":"FulfillmentConstraintRuleDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentConstraintRuleDeleteUserErrorCode":{"e":["NOT_FOUND","UNAUTHORIZED_APP_SCOPE"]}, +"FulfillmentConstraintRuleUpdatePayload":{"o":{"f":{"fulfillmentConstraintRule":"FulfillmentConstraintRule","userErrors":"[FulfillmentConstraintRuleUpdateUserError!]!"}}}, +"FulfillmentConstraintRuleUpdateUserError":{"o":{"f":{"code":"FulfillmentConstraintRuleUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentConstraintRuleUpdateUserErrorCode":{"e":["NOT_FOUND","UNAUTHORIZED_APP_SCOPE"]}, +"FulfillmentCreatePayload":{"o":{"f":{"fulfillment":"Fulfillment","userErrors":"[UserError!]!"}}}, +"FulfillmentCreateV2Payload":{"o":{"f":{"fulfillment":"Fulfillment","userErrors":"[UserError!]!"}}}, +"FulfillmentDisplayStatus":{"e":["ATTEMPTED_DELIVERY","CANCELED","CONFIRMED","DELAYED","DELIVERED","FAILURE","FULFILLED","CARRIER_PICKED_UP","IN_TRANSIT","LABEL_PRINTED","LABEL_PURCHASED","LABEL_VOIDED","MARKED_AS_FULFILLED","NOT_DELIVERED","OUT_FOR_DELIVERY","READY_FOR_PICKUP","PICKED_UP","SUBMITTED"]}, +"FulfillmentEdge":{"o":{"f":{"cursor":"String!","node":"Fulfillment!"}}}, +"FulfillmentEvent":{"o":{"f":{"address1":"String","city":"String","country":"String","createdAt":"DateTime!","estimatedDeliveryAt":"DateTime","happenedAt":"DateTime!","id":"ID!","latitude":"Float","longitude":"Float","message":"String","province":"String","status":"FulfillmentEventStatus!","zip":"String"},"t":["Node"]}}, +"FulfillmentEventConnection":{"o":{"f":{"edges":"[FulfillmentEventEdge!]!","nodes":"[FulfillmentEvent!]!","pageInfo":"PageInfo!"}}}, +"FulfillmentEventCreatePayload":{"o":{"f":{"fulfillmentEvent":"FulfillmentEvent","userErrors":"[UserError!]!"}}}, +"FulfillmentEventEdge":{"o":{"f":{"cursor":"String!","node":"FulfillmentEvent!"}}}, +"FulfillmentEventInput":{"i":{"address1":"String","city":"String","country":"String","estimatedDeliveryAt":"DateTime","fulfillmentId":"ID!","happenedAt":"DateTime","latitude":"Float","longitude":"Float","message":"String","province":"String","status":"FulfillmentEventStatus!","zip":"String"}}, +"FulfillmentEventSortKeys":{"e":["HAPPENED_AT","ID"]}, +"FulfillmentEventStatus":{"e":["LABEL_PURCHASED","LABEL_PRINTED","READY_FOR_PICKUP","CONFIRMED","IN_TRANSIT","OUT_FOR_DELIVERY","ATTEMPTED_DELIVERY","DELAYED","DELIVERED","FAILURE","CARRIER_PICKED_UP"]}, +"FulfillmentHold":{"o":{"f":{"displayReason":"String!","handle":"String","heldByApp":"App","heldByRequestingApp":"Boolean!","id":"ID!","reason":"FulfillmentHoldReason!","reasonNotes":"String"},"t":["Node"]}}, +"FulfillmentHoldReason":{"e":["AWAITING_PAYMENT","HIGH_RISK_OF_FRAUD","INCORRECT_ADDRESS","INVENTORY_OUT_OF_STOCK","UNKNOWN_DELIVERY_DATE","ONLINE_STORE_POST_PURCHASE_CROSS_SELL","AWAITING_RETURN_ITEMS","OTHER"]}, +"FulfillmentInput":{"i":{"lineItemsByFulfillmentOrder":"[FulfillmentOrderLineItemsInput!]!","notifyCustomer":"Boolean=","originAddress":"FulfillmentOriginAddressInput","trackingInfo":"FulfillmentTrackingInput"}}, +"FulfillmentLineItem":{"o":{"f":{"createdAt":"DateTime!","discountedTotal":"Money!","discountedTotalSet":"MoneyBag!","id":"ID!","lineItem":"LineItem!","originalTotal":"Money!","originalTotalSet":"MoneyBag!","quantity":"Int"},"t":["Node"],"d":{"discountedTotal":"Use `discountedTotalSet` instead.","originalTotal":"Use `originalTotalSet` instead."}}}, +"FulfillmentLineItemConnection":{"o":{"f":{"edges":"[FulfillmentLineItemEdge!]!","nodes":"[FulfillmentLineItem!]!","pageInfo":"PageInfo!"}}}, +"FulfillmentLineItemEdge":{"o":{"f":{"cursor":"String!","node":"FulfillmentLineItem!"}}}, +"FulfillmentOrder":{"o":{"f":{"assignedLocation":"FulfillmentOrderAssignedLocation!","channelId":"ID","createdAt":"DateTime!","deliveryMethod":"DeliveryMethod","destination":"FulfillmentOrderDestination","fulfillAt":"DateTime","fulfillBy":"DateTime","fulfillmentHolds":"[FulfillmentHold!]!","fulfillmentOrdersForMerge":["FulfillmentOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"fulfillments":["FulfillmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"id":"ID!","internationalDuties":"FulfillmentOrderInternationalDuties","lineItems":["FulfillmentOrderLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"locationsForMove":["FulfillmentOrderLocationForMoveConnection!",{"after":"String","before":"String","first":"Int","last":"Int","lineItemIds":"[ID!]=","locationIds":"[ID!]","query":"String","reverse":"Boolean="}],"merchantRequests":["FulfillmentOrderMerchantRequestConnection!",{"after":"String","before":"String","first":"Int","kind":"FulfillmentOrderMerchantRequestKind","last":"Int","reverse":"Boolean="}],"order":"Order!","orderId":"ID!","orderName":"String!","orderProcessedAt":"DateTime!","remainingLineItemsWeight":"Weight","requestStatus":"FulfillmentOrderRequestStatus!","status":"FulfillmentOrderStatus!","supportedActions":"[FulfillmentOrderSupportedAction!]!","updatedAt":"DateTime!"},"t":["Node"],"d":{"channelId":"Use [`order.attribution.handle`](https://shopify.dev/docs/api/admin-graphql/latest/objects/OrderAttribution#field-OrderAttribution.fields.handle) instead."}}}, +"FulfillmentOrderAcceptCancellationRequestPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderAcceptFulfillmentRequestPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderAction":{"e":["CREATE_FULFILLMENT","REQUEST_FULFILLMENT","CANCEL_FULFILLMENT_ORDER","MOVE","REQUEST_CANCELLATION","MARK_AS_OPEN","RELEASE_HOLD","HOLD","EXTERNAL","SPLIT","MERGE","REPORT_PROGRESS"]}, +"FulfillmentOrderAssignedLocation":{"o":{"f":{"address1":"String","address2":"String","city":"String","countryCode":"CountryCode!","location":"Location","name":"String!","phone":"String","province":"String","zip":"String"}}}, +"FulfillmentOrderAssignmentStatus":{"e":["CANCELLATION_REQUESTED","FULFILLMENT_REQUESTED","FULFILLMENT_ACCEPTED","FULFILLMENT_UNSUBMITTED"]}, +"FulfillmentOrderCancelError":{"o":{"f":{"code":"FulfillmentOrderCancelErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderCancelErrorCode":{"e":["FULFILLMENT_ORDER_HAS_MANUALLY_REPORTED_PROGRESS"]}, +"FulfillmentOrderCancelPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","replacementFulfillmentOrder":"FulfillmentOrder","userErrors":"[FulfillmentOrderCancelError!]!"}}}, +"FulfillmentOrderClosePayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderConnection":{"o":{"f":{"edges":"[FulfillmentOrderEdge!]!","nodes":"[FulfillmentOrder!]!","pageInfo":"PageInfo!"}}}, +"FulfillmentOrderDestination":{"o":{"f":{"address1":"String","address2":"String","city":"String","company":"String","countryCode":"CountryCode","email":"String","firstName":"String","id":"ID!","lastName":"String","location":"Location","phone":"String","province":"String","zip":"String"},"t":["Node"]}}, +"FulfillmentOrderEdge":{"o":{"f":{"cursor":"String!","node":"FulfillmentOrder!"}}}, +"FulfillmentOrderHoldInput":{"i":{"externalId":"String","fulfillmentOrderLineItems":"[FulfillmentOrderLineItemInput!]=","handle":"String=","notifyMerchant":"Boolean=","reason":"FulfillmentHoldReason!","reasonNotes":"String"}}, +"FulfillmentOrderHoldPayload":{"o":{"f":{"fulfillmentHold":"FulfillmentHold","fulfillmentOrder":"FulfillmentOrder","remainingFulfillmentOrder":"FulfillmentOrder","userErrors":"[FulfillmentOrderHoldUserError!]!"}}}, +"FulfillmentOrderHoldUserError":{"o":{"f":{"code":"FulfillmentOrderHoldUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderHoldUserErrorCode":{"e":["FULFILLMENT_ORDER_NOT_FOUND","TAKEN","GREATER_THAN_ZERO","FULFILLMENT_ORDER_HOLD_LIMIT_REACHED","DUPLICATE_FULFILLMENT_HOLD_HANDLE","INVALID_LINE_ITEM_QUANTITY","FULFILLMENT_ORDER_NOT_SPLITTABLE","DUPLICATED_FULFILLMENT_ORDER_LINE_ITEMS"]}, +"FulfillmentOrderInternationalDuties":{"o":{"f":{"incoterm":"String!"}}}, +"FulfillmentOrderLineItem":{"o":{"f":{"financialSummaries":"[FulfillmentOrderLineItemFinancialSummary!]!","id":"ID!","image":"Image","inventoryItemId":"ID","lineItem":"LineItem!","originalUnitPriceSet":"MoneyBag!","productTitle":"String!","remainingQuantity":"Int!","requiresShipping":"Boolean!","shippingLine":"ShippingLine","sku":"String","totalQuantity":"Int!","variant":"ProductVariant","variantTitle":"String","vendor":"String","warnings":"[FulfillmentOrderLineItemWarning!]!","weight":"Weight"},"t":["Node"],"d":{"originalUnitPriceSet":"Use `financialSummaries` instead."}}}, +"FulfillmentOrderLineItemConnection":{"o":{"f":{"edges":"[FulfillmentOrderLineItemEdge!]!","nodes":"[FulfillmentOrderLineItem!]!","pageInfo":"PageInfo!"}}}, +"FulfillmentOrderLineItemEdge":{"o":{"f":{"cursor":"String!","node":"FulfillmentOrderLineItem!"}}}, +"FulfillmentOrderLineItemFinancialSummary":{"o":{"f":{"approximateDiscountedUnitPriceSet":"MoneyBag!","discountAllocations":"[FinancialSummaryDiscountAllocation!]!","originalUnitPriceSet":"MoneyBag!","quantity":"Int!"}}}, +"FulfillmentOrderLineItemInput":{"i":{"id":"ID!","quantity":"Int!"}}, +"FulfillmentOrderLineItemWarning":{"o":{"f":{"description":"String","title":"String"}}}, +"FulfillmentOrderLineItemsInput":{"i":{"fulfillmentOrderId":"ID!","fulfillmentOrderLineItems":"[FulfillmentOrderLineItemInput!]"}}, +"FulfillmentOrderLineItemsPreparedForPickupInput":{"i":{"lineItemsByFulfillmentOrder":"[PreparedFulfillmentOrderLineItemsInput!]!"}}, +"FulfillmentOrderLineItemsPreparedForPickupPayload":{"o":{"f":{"userErrors":"[FulfillmentOrderLineItemsPreparedForPickupUserError!]!"}}}, +"FulfillmentOrderLineItemsPreparedForPickupUserError":{"o":{"f":{"code":"FulfillmentOrderLineItemsPreparedForPickupUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderLineItemsPreparedForPickupUserErrorCode":{"e":["NO_LINE_ITEMS_TO_PREPARE_FOR_FULFILLMENT_ORDER","FULFILLMENT_ORDER_INVALID","UNABLE_TO_PREPARE_QUANTITY"]}, +"FulfillmentOrderLocationForMove":{"o":{"f":{"availableLineItems":["FulfillmentOrderLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"availableLineItemsCount":"Count","location":"Location!","message":"String","movable":"Boolean!","unavailableLineItems":["FulfillmentOrderLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"unavailableLineItemsCount":"Count"}}}, +"FulfillmentOrderLocationForMoveConnection":{"o":{"f":{"edges":"[FulfillmentOrderLocationForMoveEdge!]!","nodes":"[FulfillmentOrderLocationForMove!]!","pageInfo":"PageInfo!"}}}, +"FulfillmentOrderLocationForMoveEdge":{"o":{"f":{"cursor":"String!","node":"FulfillmentOrderLocationForMove!"}}}, +"FulfillmentOrderMerchantRequest":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder!","id":"ID!","kind":"FulfillmentOrderMerchantRequestKind!","message":"String","requestOptions":"JSON","responseData":"JSON","sentAt":"DateTime!"},"t":["Node"]}}, +"FulfillmentOrderMerchantRequestConnection":{"o":{"f":{"edges":"[FulfillmentOrderMerchantRequestEdge!]!","nodes":"[FulfillmentOrderMerchantRequest!]!","pageInfo":"PageInfo!"}}}, +"FulfillmentOrderMerchantRequestEdge":{"o":{"f":{"cursor":"String!","node":"FulfillmentOrderMerchantRequest!"}}}, +"FulfillmentOrderMerchantRequestKind":{"e":["FULFILLMENT_REQUEST","CANCELLATION_REQUEST"]}, +"FulfillmentOrderMergeInput":{"i":{"mergeIntents":"[FulfillmentOrderMergeInputMergeIntent!]!"}}, +"FulfillmentOrderMergeInputMergeIntent":{"i":{"fulfillmentOrderId":"ID!","fulfillmentOrderLineItems":"[FulfillmentOrderLineItemInput!]"}}, +"FulfillmentOrderMergePayload":{"o":{"f":{"fulfillmentOrderMerges":"[FulfillmentOrderMergeResult!]","userErrors":"[FulfillmentOrderMergeUserError!]!"}}}, +"FulfillmentOrderMergeResult":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder!"}}}, +"FulfillmentOrderMergeUserError":{"o":{"f":{"code":"FulfillmentOrderMergeUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderMergeUserErrorCode":{"e":["FULFILLMENT_ORDER_NOT_FOUND","GREATER_THAN","INVALID_LINE_ITEM_QUANTITY"]}, +"FulfillmentOrderMoveFulfillmentOrderMoveUserError":{"o":{"f":{"code":"FulfillmentOrderMoveFulfillmentOrderMoveUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderMoveFulfillmentOrderMoveUserErrorCode":{"e":["CANNOT_MOVE_FULFILLMENT_ORDER_WITH_REPORTED_PROGRESS"]}, +"FulfillmentOrderMovePayload":{"o":{"f":{"movedFulfillmentOrder":"FulfillmentOrder","originalFulfillmentOrder":"FulfillmentOrder","remainingFulfillmentOrder":"FulfillmentOrder","userErrors":"[FulfillmentOrderMoveFulfillmentOrderMoveUserError!]!"}}}, +"FulfillmentOrderOpenPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderRejectCancellationRequestPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderRejectFulfillmentRequestPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderRejectionReason":{"e":["INCORRECT_ADDRESS","INVENTORY_OUT_OF_STOCK","INELIGIBLE_PRODUCT","UNDELIVERABLE_DESTINATION","INTERNATIONAL_SHIPPING_UNAVAILABLE","INCORRECT_PRODUCT_INFO","MISSING_CUSTOMS_INFO","INVALID_SKU","PAYMENT_DECLINED","PACKAGE_PREFERENCE_NOT_SET","INVALID_CONTACT_INFORMATION","ORDER_TOO_LARGE","MERCHANT_BLOCKED_OR_SUSPENDED","OTHER"]}, +"FulfillmentOrderReleaseHoldPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[FulfillmentOrderReleaseHoldUserError!]!"}}}, +"FulfillmentOrderReleaseHoldUserError":{"o":{"f":{"code":"FulfillmentOrderReleaseHoldUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderReleaseHoldUserErrorCode":{"e":["FULFILLMENT_ORDER_NOT_FOUND","INVALID_ACCESS"]}, +"FulfillmentOrderReportProgressInput":{"i":{"reasonNotes":"String"}}, +"FulfillmentOrderReportProgressPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[FulfillmentOrderReportProgressUserError!]!"}}}, +"FulfillmentOrderReportProgressUserError":{"o":{"f":{"code":"FulfillmentOrderReportProgressUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderReportProgressUserErrorCode":{"e":["FULFILLMENT_ORDER_NOT_FOUND","FULFILLMENT_ORDER_STATUS_INVALID","FULFILLMENT_ORDER_CONTAINS_PICKED_ITEMS","FULFILLMENT_ORDER_INVALID_DELIVERY_METHOD","FULFILLMENT_ORDER_INVALID_FULFILLMENT_SERVICE_OWNERSHIP","FULFILLMENT_ORDER_UNSUPPORTED_ACTION","MARKETPLACE_APP_NOT_ELIGIBLE"]}, +"FulfillmentOrderRequestStatus":{"e":["UNSUBMITTED","SUBMITTED","ACCEPTED","REJECTED","CANCELLATION_REQUESTED","CANCELLATION_ACCEPTED","CANCELLATION_REJECTED","CLOSED"]}, +"FulfillmentOrderReschedulePayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[FulfillmentOrderRescheduleUserError!]!"}}}, +"FulfillmentOrderRescheduleUserError":{"o":{"f":{"code":"FulfillmentOrderRescheduleUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderRescheduleUserErrorCode":{"e":["FULFILLMENT_ORDER_NOT_FOUND"]}, +"FulfillmentOrderSortKeys":{"e":["ID","UPDATED_AT"]}, +"FulfillmentOrderSplitInput":{"i":{"fulfillmentOrderId":"ID!","fulfillmentOrderLineItems":"[FulfillmentOrderLineItemInput!]!"}}, +"FulfillmentOrderSplitPayload":{"o":{"f":{"fulfillmentOrderSplits":"[FulfillmentOrderSplitResult!]","userErrors":"[FulfillmentOrderSplitUserError!]!"}}}, +"FulfillmentOrderSplitResult":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder!","remainingFulfillmentOrder":"FulfillmentOrder!","replacementFulfillmentOrder":"FulfillmentOrder"}}}, +"FulfillmentOrderSplitUserError":{"o":{"f":{"code":"FulfillmentOrderSplitUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrderSplitUserErrorCode":{"e":["FULFILLMENT_ORDER_NOT_FOUND","GREATER_THAN","INVALID_LINE_ITEM_QUANTITY","NO_LINE_ITEMS_PROVIDED_TO_SPLIT"]}, +"FulfillmentOrderStatus":{"e":["OPEN","IN_PROGRESS","CANCELLED","INCOMPLETE","CLOSED","SCHEDULED","ON_HOLD"]}, +"FulfillmentOrderSubmitCancellationRequestPayload":{"o":{"f":{"fulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderSubmitFulfillmentRequestPayload":{"o":{"f":{"originalFulfillmentOrder":"FulfillmentOrder","submittedFulfillmentOrder":"FulfillmentOrder","unsubmittedFulfillmentOrder":"FulfillmentOrder","userErrors":"[UserError!]!"}}}, +"FulfillmentOrderSupportedAction":{"o":{"f":{"action":"FulfillmentOrderAction!","externalUrl":"URL"}}}, +"FulfillmentOrdersReroutePayload":{"o":{"f":{"movedFulfillmentOrders":"[FulfillmentOrder!]","userErrors":"[FulfillmentOrdersRerouteUserError!]!"}}}, +"FulfillmentOrdersRerouteUserError":{"o":{"f":{"code":"FulfillmentOrdersRerouteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrdersRerouteUserErrorCode":{"e":["NO_FULFILLMENT_ORDER_IDS","FULFILLMENT_ORDER_NOT_FOUND","FULFILLMENT_ORDERS_NOT_FROM_THE_SAME_ORDER","FULFILLMENT_ORDERS_STATE_NOT_SUPPORTED","CANNOT_REASSIGN_LOCATION_FOR_FULFILLMENT_ORDERS","DELIVERY_METHOD_TYPE_NOT_SUPPORTED","SINGLE_LOCATION_SHOP_NOT_SUPPORTED","FULFILLMENT_ORDERS_MUST_BELONG_TO_SAME_LOCATION","CANNOT_MOVE_FULFILLMENT_ORDER_WITH_REPORTED_PROGRESS"]}, +"FulfillmentOrdersSetFulfillmentDeadlinePayload":{"o":{"f":{"success":"Boolean","userErrors":"[FulfillmentOrdersSetFulfillmentDeadlineUserError!]!"}}}, +"FulfillmentOrdersSetFulfillmentDeadlineUserError":{"o":{"f":{"code":"FulfillmentOrdersSetFulfillmentDeadlineUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"FulfillmentOrdersSetFulfillmentDeadlineUserErrorCode":{"e":["FULFILLMENT_ORDERS_NOT_FOUND"]}, +"FulfillmentOriginAddress":{"o":{"f":{"address1":"String","address2":"String","city":"String","countryCode":"String!","provinceCode":"String","zip":"String"}}}, +"FulfillmentOriginAddressInput":{"i":{"address1":"String","address2":"String","city":"String","countryCode":"String!","provinceCode":"String","zip":"String"}}, +"FulfillmentService":{"o":{"f":{"callbackUrl":"URL","createdAt":"DateTime!","fulfillmentOrdersOptIn":"Boolean!","handle":"String!","id":"ID!","inventoryManagement":"Boolean!","location":"Location","requiresShippingMethod":"Boolean!","serviceName":"String!","trackingSupport":"Boolean!","type":"FulfillmentServiceType!"},"d":{"fulfillmentOrdersOptIn":"Migration period ended. All correctly functioning fulfillment services have `fulfillmentOrdersOptIn` set to `true`."}}}, +"FulfillmentServiceCreatePayload":{"o":{"f":{"fulfillmentService":"FulfillmentService","userErrors":"[UserError!]!"}}}, +"FulfillmentServiceDeleteInventoryAction":{"e":["DELETE","KEEP","TRANSFER"]}, +"FulfillmentServiceDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[UserError!]!"}}}, +"FulfillmentServiceType":{"e":["GIFT_CARD","MANUAL","THIRD_PARTY"]}, +"FulfillmentServiceUpdatePayload":{"o":{"f":{"fulfillmentService":"FulfillmentService","userErrors":"[UserError!]!"}}}, +"FulfillmentStatus":{"e":{"v":["PENDING","OPEN","SUCCESS","CANCELLED","ERROR","FAILURE"],"d":{"OPEN":"This is a legacy status and is due to be deprecated.","PENDING":"This is a legacy status and is due to be deprecated."}}}, +"FulfillmentTrackingInfo":{"o":{"f":{"company":"String","number":"String","url":"URL"}}}, +"FulfillmentTrackingInfoUpdatePayload":{"o":{"f":{"fulfillment":"Fulfillment","userErrors":"[UserError!]!"}}}, +"FulfillmentTrackingInfoUpdateV2Payload":{"o":{"f":{"fulfillment":"Fulfillment","userErrors":"[UserError!]!"}}}, +"FulfillmentTrackingInput":{"i":{"company":"String","number":"String","numbers":"[String!]","url":"URL","urls":"[URL!]"}}, +"FulfillmentV2Input":{"i":{"lineItemsByFulfillmentOrder":"[FulfillmentOrderLineItemsInput!]!","notifyCustomer":"Boolean=","originAddress":"FulfillmentOriginAddressInput","trackingInfo":"FulfillmentTrackingInput"}}, +"FullSyncTraceInfo":{"o":{"f":{"country":"CountryCode!","language":"LanguageCode!","operationId":"ID"}}}, +"FunctionsAppBridge":{"o":{"f":{"createPath":"String!","detailsPath":"String!"}}}, +"FunctionsErrorHistory":{"o":{"f":{"errorsFirstOccurredAt":"DateTime!","firstOccurredAt":"DateTime!","hasBeenSharedSinceLastError":"Boolean!","hasSharedRecentErrors":"Boolean!"}}}, +"GenericFile":{"o":{"f":{"alt":"String","createdAt":"DateTime!","fileErrors":"[FileError!]!","fileStatus":"FileStatus!","id":"ID!","mimeType":"String","originalFileSize":"Int","preview":"MediaPreviewImage","updatedAt":"DateTime!","url":"URL"},"t":["File","Node"]}}, +"GiftCard":{"o":{"f":{"balance":"MoneyV2!","createdAt":"DateTime!","crossCurrencyRedemptionStrategy":"GiftCardCrossCurrencyRedemptionStrategy!","customer":"Customer","deactivatedAt":"DateTime","enabled":"Boolean!","expiresOn":"Date","id":"ID!","initialValue":"MoneyV2!","isRedeemable":"Boolean!","lastCharacters":"String!","lineItem":"LineItem","maskedCode":"String!","note":"String","order":"Order","recipientAttributes":"GiftCardRecipient","templateSuffix":"String","transactions":["GiftCardTransactionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"updatedAt":"DateTime!"},"t":["Node"]}}, +"GiftCardCashOutTransaction":{"o":{"f":{"amount":"MoneyV2!","giftCard":"GiftCard!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"note":"String","processedAt":"DateTime!"},"t":["GiftCardTransaction","HasMetafields","Node"]}}, +"GiftCardConfiguration":{"o":{"f":{"expirationConfiguration":"GiftCardExpirationConfiguration","issueLimit":"MoneyV2!","purchaseLimit":"MoneyV2!"}}}, +"GiftCardConfigurationExpirationUnit":{"e":["DAYS","MONTHS","YEARS"]}, +"GiftCardConnection":{"o":{"f":{"edges":"[GiftCardEdge!]!","nodes":"[GiftCard!]!","pageInfo":"PageInfo!"}}}, +"GiftCardCreateInput":{"i":{"f":{"code":"String","crossCurrencyRedemptionStrategy":"GiftCardCrossCurrencyRedemptionStrategy","customerId":"ID","expiresOn":"Date","initialAmount":"MoneyInput","initialValue":"Decimal","note":"String","recipientAttributes":"GiftCardRecipientInput","templateSuffix":"String"},"d":{"initialValue":"Use `initialAmount` instead."}}}, +"GiftCardCreatePayload":{"o":{"f":{"giftCard":"GiftCard","giftCardCode":"String","userErrors":"[GiftCardUserError!]!"}}}, +"GiftCardCreditInput":{"i":{"creditAmount":"MoneyInput!","note":"String","processedAt":"DateTime"}}, +"GiftCardCreditPayload":{"o":{"f":{"giftCardCreditTransaction":"GiftCardCreditTransaction","userErrors":"[GiftCardTransactionUserError!]!"}}}, +"GiftCardCreditTransaction":{"o":{"f":{"amount":"MoneyV2!","giftCard":"GiftCard!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"note":"String","processedAt":"DateTime!"},"t":["GiftCardTransaction","HasMetafields","Node"]}}, +"GiftCardCrossCurrencyRedemptionStrategy":{"e":["NONE","MARKET_FX","SPOT_FX"]}, +"GiftCardDeactivatePayload":{"o":{"f":{"giftCard":"GiftCard","userErrors":"[GiftCardDeactivateUserError!]!"}}}, +"GiftCardDeactivateUserError":{"o":{"f":{"code":"GiftCardDeactivateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"GiftCardDeactivateUserErrorCode":{"e":["GIFT_CARD_NOT_FOUND"]}, +"GiftCardDebitInput":{"i":{"debitAmount":"MoneyInput!","note":"String","processedAt":"DateTime"}}, +"GiftCardDebitPayload":{"o":{"f":{"giftCardDebitTransaction":"GiftCardDebitTransaction","userErrors":"[GiftCardTransactionUserError!]!"}}}, +"GiftCardDebitTransaction":{"o":{"f":{"amount":"MoneyV2!","giftCard":"GiftCard!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"note":"String","processedAt":"DateTime!"},"t":["GiftCardTransaction","HasMetafields","Node"]}}, +"GiftCardEdge":{"o":{"f":{"cursor":"String!","node":"GiftCard!"}}}, +"GiftCardErrorCode":{"e":["TOO_BIG","TOO_LONG","TOO_SHORT","TAKEN","INVALID","INTERNAL_ERROR","MISSING_ARGUMENT","GREATER_THAN","GIFT_CARD_LIMIT_EXCEEDED","CUSTOMER_NOT_FOUND","RECIPIENT_NOT_FOUND"]}, +"GiftCardExpirationConfiguration":{"o":{"f":{"expirationUnit":"GiftCardConfigurationExpirationUnit!","expirationValue":"Int!"}}}, +"GiftCardProductSetInput":{"i":{"collections":"[ID!]","crossCurrencyRedeemable":"Boolean","descriptionHtml":"String","files":"[FileSetInput!]","giftCardTemplateSuffix":"String","handle":"String","issuanceCurrency":"CurrencyCode","metafields":"[MetafieldInput!]","productOptions":"[OptionSetInput!]","productType":"String","redirectNewHandle":"Boolean","seo":"SEOInput","status":"ProductStatus","tags":"[String!]","templateSuffix":"String","title":"String","variants":"[GiftCardProductVariantSetInput!]","vendor":"String"}}, +"GiftCardProductSetPayload":{"o":{"f":{"product":"Product","productSetOperation":"ProductSetOperation","userErrors":"[GiftCardProductSetUserError!]!"}}}, +"GiftCardProductSetUserError":{"o":{"f":{"code":"GiftCardProductSetUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"GiftCardProductSetUserErrorCode":{"e":["ID_NOT_ALLOWED","MISSING_FIELD_REQUIRED","INPUT_MISMATCH","NOT_FOUND","METAFIELD_MISMATCH","GENERIC_ERROR","INVALID_METAFIELD","INVALID_VARIANT","PRODUCT_DOES_NOT_EXIST","PRODUCT_SUSPENDED","PRODUCT_VARIANT_DOES_NOT_EXIST","OPTION_DOES_NOT_EXIST","OPTION_VALUE_DOES_NOT_EXIST","OPTIONS_OVER_LIMIT","OPTION_VALUES_OVER_LIMIT","OPTION_VALUES_MISSING","DUPLICATED_OPTION_NAME","DUPLICATED_OPTION_VALUE","VARIANTS_OVER_LIMIT","PRODUCT_OPTIONS_INPUT_MISSING","VARIANTS_INPUT_MISSING","GIFT_CARDS_NOT_ACTIVATED","GIFT_CARD_ATTRIBUTE_CANNOT_BE_CHANGED","INVALID_PRODUCT","INVALID_INPUT","JOB_ERROR","CAPABILITY_VIOLATION","CANNOT_COMBINE_LINKED_AND_NONLINKED_OPTION_VALUES","INVALID_METAFIELD_VALUE_FOR_LINKED_OPTION","DUPLICATE_LINKED_OPTION","DUPLICATED_METAFIELD_VALUE","LINKED_OPTIONS_NOT_SUPPORTED_FOR_SHOP","LINKED_METAFIELD_DEFINITION_NOT_FOUND","DUPLICATED_VALUE","HANDLE_NOT_UNIQUE","INCOMPATIBLE_BARCODE_FIELDS","BLANK_BARCODE_VALUE","TOO_MANY_BARCODES","BARCODE_VALUE_TOO_LONG","DUPLICATE_BARCODE_VALUE","INVALID_BARCODE_TYPE","INVALID_BARCODE_SEPARATORS","INVALID_BARCODE_LENGTH","INVALID_BARCODE_PREFIX","INVALID_BARCODE_CHARACTERS","BARCODE_CHECKSUM_VALIDATION_FAILED","PRODUCT_MUST_BE_GIFT_CARD"]}, +"GiftCardProductSettings":{"o":{"f":{"crossCurrencyRedeemable":"Boolean!","issuanceCurrency":"CurrencyCode"}}}, +"GiftCardProductVariantSetInput":{"i":{"f":{"barcode":"String","barcodes":"[BarcodeInput!]","file":"FileSetInput","id":"ID","metafields":"[MetafieldInput!]","optionValues":"[VariantOptionValueInput!]!","position":"Int","price":"Money","published":"Boolean","sku":"String"},"d":{"barcode":"Use `barcodes` instead."}}}, +"GiftCardRecipient":{"o":{"f":{"message":"String","preferredName":"String","recipient":"Customer!","sendNotificationAt":"DateTime"}}}, +"GiftCardRecipientInput":{"i":{"id":"ID!","message":"String","preferredName":"String","sendNotificationAt":"DateTime"}}, +"GiftCardSale":{"o":{"f":{"actionType":"SaleActionType!","id":"ID!","lineItem":"LineItem!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"GiftCardSendNotificationToCustomerPayload":{"o":{"f":{"giftCard":"GiftCard","userErrors":"[GiftCardSendNotificationToCustomerUserError!]!"}}}, +"GiftCardSendNotificationToCustomerUserError":{"o":{"f":{"code":"GiftCardSendNotificationToCustomerUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"GiftCardSendNotificationToCustomerUserErrorCode":{"e":["INVALID","CUSTOMER_NOT_FOUND","GIFT_CARD_NOT_FOUND"]}, +"GiftCardSendNotificationToRecipientPayload":{"o":{"f":{"giftCard":"GiftCard","userErrors":"[GiftCardSendNotificationToRecipientUserError!]!"}}}, +"GiftCardSendNotificationToRecipientUserError":{"o":{"f":{"code":"GiftCardSendNotificationToRecipientUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"GiftCardSendNotificationToRecipientUserErrorCode":{"e":["INVALID","RECIPIENT_NOT_FOUND","GIFT_CARD_NOT_FOUND"]}, +"GiftCardSortKeys":{"e":["AMOUNT_SPENT","BALANCE","CODE","CREATED_AT","CUSTOMER_NAME","DISABLED_AT","EXPIRES_ON","ID","INITIAL_VALUE","UPDATED_AT"]}, +"GiftCardTransaction":{"n":{"f":{"amount":"MoneyV2!","giftCard":"GiftCard!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"note":"String","processedAt":"DateTime!"},"t":["GiftCardCashOutTransaction","GiftCardCreditTransaction","GiftCardDebitTransaction"]}}, +"GiftCardTransactionConnection":{"o":{"f":{"edges":"[GiftCardTransactionEdge!]!","nodes":"[GiftCardTransaction!]!","pageInfo":"PageInfo!"}}}, +"GiftCardTransactionEdge":{"o":{"f":{"cursor":"String!","node":"GiftCardTransaction!"}}}, +"GiftCardTransactionUserError":{"o":{"f":{"code":"GiftCardTransactionUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"GiftCardTransactionUserErrorCode":{"e":["INVALID","INTERNAL_ERROR","GIFT_CARD_LIMIT_EXCEEDED","GIFT_CARD_NOT_FOUND","NEGATIVE_OR_ZERO_AMOUNT","INSUFFICIENT_FUNDS","MISMATCHING_CURRENCY"]}, +"GiftCardUpdateInput":{"i":{"crossCurrencyRedemptionStrategy":"GiftCardCrossCurrencyRedemptionStrategy","customerId":"ID","expiresOn":"Date","note":"String","recipientAttributes":"GiftCardRecipientInput","templateSuffix":"String"}}, +"GiftCardUpdatePayload":{"o":{"f":{"giftCard":"GiftCard","userErrors":"[UserError!]!"}}}, +"GiftCardUserError":{"o":{"f":{"code":"GiftCardErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"HTML":"s", +"HasCompareDigest":{"n":{"f":{"compareDigest":"String!"},"t":["Metafield"]}}, +"HasEvents":{"n":{"f":{"events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}]},"t":["Article","Blog","Collection","Comment","Company","CompanyLocation","Customer","DiscountAutomaticBxgy","DiscountAutomaticNode","DiscountCodeNode","DiscountNode","DraftOrder","InventoryTransfer","Order","Page","Product","ProductVariant"]}}, +"HasLocalizationExtensions":{"n":{"f":{"localizationExtensions":["LocalizationExtensionConnection!",{"after":"String","before":"String","countryCodes":"[CountryCode!]","first":"Int","last":"Int","purposes":"[LocalizationExtensionPurpose!]","reverse":"Boolean="}]},"t":["DraftOrder","Order"],"d":{"localizationExtensions":"This connection will be removed in a future version. Use `localizedFields` instead."}}}, +"HasLocalizedFields":{"n":{"f":{"localizedFields":["LocalizedFieldConnection!",{"after":"String","before":"String","countryCodes":"[CountryCode!]","first":"Int","last":"Int","purposes":"[LocalizedFieldPurpose!]","reverse":"Boolean="}]},"t":["DraftOrder","Order"]}}, +"HasMetafieldDefinitions":{"n":{"f":{"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}]},"t":["Article","Blog","Collection","Company","CompanyLocation","Customer","DeliveryCustomization","DiscountAutomaticNode","DiscountCodeNode","DiscountNode","InventoryTransfer","Location","Market","Order","Page","PaymentCustomization","Product","ProductVariant","SellingPlan","Shop","Validation"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"HasMetafields":{"n":{"f":{"metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}]},"t":["AppInstallation","Article","Blog","CartTransform","Collection","Company","CompanyLocation","Customer","CustomerSegmentMember","DeliveryCustomization","DiscountAutomaticNode","DiscountCodeNode","DiscountNode","DraftOrder","FulfillmentConstraintRule","GiftCardCashOutTransaction","GiftCardCreditTransaction","GiftCardDebitTransaction","Image","InventoryTransfer","Location","Market","MediaImage","Order","Page","PaymentCustomization","Product","ProductVariant","SellingPlan","Shop","Validation"]}}, +"HasMetafieldsMetafieldIdentifierInput":{"i":{"key":"String!","namespace":"String"}}, +"HasPublishedTranslations":{"n":{"f":{"translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}]},"t":["Article","Blog","Collection","CookieBanner","Image","Link","MediaImage","Menu","Metafield","OnlineStoreTheme","Page","Product","ProductOption","ProductOptionValue","ProductVariant","SellingPlan","SellingPlanGroup","Shop","ShopPolicy"]}}, +"HasRollouts":{"n":{"f":{"rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}]},"t":["DiscountAutomaticApp","DiscountAutomaticBasic","DiscountAutomaticBxgy","DiscountAutomaticFreeShipping","DiscountCodeApp","DiscountCodeBasic","DiscountCodeBxgy","DiscountCodeFreeShipping"]}}, +"HasStoreCreditAccounts":{"n":{"f":{"storeCreditAccounts":["StoreCreditAccountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String"}]},"t":["CompanyLocation","Customer"]}}, +"ID":"s", +"IdentityProviderSubject":{"o":{"f":{"createdAt":"DateTime!","id":"ID!","providerName":"String","subject":"String!","updatedAt":"DateTime!"},"t":["Node"]}}, +"Image":{"o":{"f":{"altText":"String","height":"Int","id":"ID","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"originalSrc":"URL!","src":"URL!","thumbhash":"String","transformedSrc":["URL!",{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","preferredContentType":"ImageContentType","scale":"Int="}],"translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"url":["URL!",{"transform":"ImageTransformInput"}],"width":"Int"},"t":["HasMetafields","HasPublishedTranslations"],"d":{"originalSrc":"Use `url` instead.","src":"Use `url` instead.","transformedSrc":"Use `url(transform:)` instead"}}}, +"ImageConnection":{"o":{"f":{"edges":"[ImageEdge!]!","nodes":"[Image!]!","pageInfo":"PageInfo!"}}}, +"ImageContentType":{"e":["PNG","JPG","WEBP"]}, +"ImageEdge":{"o":{"f":{"cursor":"String!","node":"Image!"}}}, +"ImageInput":{"i":{"altText":"String","id":"ID","src":"String"}}, +"ImageTransformInput":{"i":{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","preferredContentType":"ImageContentType","scale":"Int="}}, +"ImageUploadParameter":{"o":{"f":{"name":"String!","value":"String!"}}}, +"InclusiveDutiesPricingStrategy":{"e":["ADD_DUTIES_AT_CHECKOUT","INCLUDE_DUTIES_IN_PRICE"]}, +"InclusiveTaxPricingStrategy":{"e":["ADD_TAXES_AT_CHECKOUT","INCLUDES_TAXES_IN_PRICE","INCLUDES_TAXES_IN_PRICE_BASED_ON_COUNTRY"]}, +"IncomingRequestLineItemInput":{"i":{"fulfillmentOrderLineItemId":"ID!","message":"String"}}, +"Int":"s", +"InventoryActivatePayload":{"o":{"f":{"inventoryLevel":"InventoryLevel","userErrors":"[UserError!]!"}}}, +"InventoryAdjustQuantitiesInput":{"i":{"changes":"[InventoryChangeInput!]!","name":"String!","reason":"String!","referenceDocumentUri":"String"}}, +"InventoryAdjustQuantitiesPayload":{"o":{"f":{"inventoryAdjustmentGroup":"InventoryAdjustmentGroup","userErrors":"[InventoryAdjustQuantitiesUserError!]!"}}}, +"InventoryAdjustQuantitiesUserError":{"o":{"f":{"code":"InventoryAdjustQuantitiesUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryAdjustQuantitiesUserErrorCode":{"e":["INTERNAL_LEDGER_DOCUMENT","INVALID_AVAILABLE_DOCUMENT","INVALID_INVENTORY_ITEM","INVALID_LEDGER_DOCUMENT","INVALID_LOCATION","INVALID_QUANTITY_DOCUMENT","INVALID_QUANTITY_NAME","INVALID_QUANTITY_TOO_LOW","INVALID_QUANTITY_TOO_HIGH","INVALID_REASON","INVALID_REFERENCE_DOCUMENT","SERVICE_UNAVAILABLE","CHANGE_FROM_QUANTITY_STALE","ADJUST_QUANTITIES_FAILED","MAX_ONE_LEDGER_DOCUMENT","NON_MUTABLE_INVENTORY_ITEM","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED"]}, +"InventoryAdjustmentGroup":{"o":{"f":{"app":"App","changes":["[InventoryChange!]!",{"inventoryItemIds":"[ID!]","locationIds":"[ID!]","quantityNames":"[String!]"}],"createdAt":"DateTime!","id":"ID!","reason":"String!","referenceDocumentUri":"String","staffMember":"StaffMember"},"t":["Node"]}}, +"InventoryAdjustmentInput":{"i":{"adjustment":"Int","changeFromQuantity":"Int","locationId":"ID!"}}, +"InventoryBulkToggleActivationInput":{"i":{"activate":"Boolean!","locationId":"ID!"}}, +"InventoryBulkToggleActivationPayload":{"o":{"f":{"inventoryItem":"InventoryItem","inventoryLevels":"[InventoryLevel!]","userErrors":"[InventoryBulkToggleActivationUserError!]!"}}}, +"InventoryBulkToggleActivationUserError":{"o":{"f":{"code":"InventoryBulkToggleActivationUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryBulkToggleActivationUserErrorCode":{"e":{"v":["GENERIC_ERROR","CANNOT_DEACTIVATE_FROM_ONLY_LOCATION","COMMITTED_AND_INCOMING_INVENTORY_AT_LOCATION","INCOMING_INVENTORY_AT_LOCATION","COMMITTED_INVENTORY_AT_LOCATION","RESERVED_INVENTORY_AT_LOCATION","FAILED_TO_UNSTOCK_FROM_LOCATION","INVENTORY_MANAGED_BY_3RD_PARTY","INVENTORY_MANAGED_BY_SHOPIFY","FAILED_TO_STOCK_AT_LOCATION","MISSING_SKU","LOCATION_NOT_FOUND","INVENTORY_ITEM_NOT_FOUND"],"d":{"COMMITTED_AND_INCOMING_INVENTORY_AT_LOCATION":"This error code is deprecated. Both INCOMING_INVENTORY_AT_LOCATION and COMMITTED_INVENTORY_AT_LOCATION codes will be returned as individual errors instead."}}}, +"InventoryChange":{"o":{"f":{"delta":"Int!","item":"InventoryItem","ledgerDocumentUri":"String","location":"Location","name":"String!","quantityAfterChange":"Int"}}}, +"InventoryChangeInput":{"i":{"changeFromQuantity":"Int","delta":"Int!","inventoryItemId":"ID!","ledgerDocumentUri":"String","locationId":"ID!"}}, +"InventoryDeactivatePayload":{"o":{"f":{"userErrors":"[UserError!]!"}}}, +"InventoryItem":{"o":{"f":{"countryCodeOfOrigin":"CountryCode","countryHarmonizedSystemCodes":["CountryHarmonizedSystemCodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"createdAt":"DateTime!","duplicateSkuCount":"Int!","harmonizedSystemCode":"String","id":"ID!","inventoryHistoryUrl":"URL","inventoryLevel":["InventoryLevel",{"includeInactive":"Boolean=","locationId":"ID!"}],"inventoryLevels":["InventoryLevelConnection!",{"after":"String","before":"String","first":"Int","includeInactive":"Boolean=","last":"Int","query":"String","reverse":"Boolean="}],"legacyResourceId":"UnsignedInt64!","locationsCount":"Count","measurement":"InventoryItemMeasurement!","provinceCodeOfOrigin":"String","requiresShipping":"Boolean!","sku":"String","tracked":"Boolean!","trackedEditable":"EditableProperty!","unitCost":"MoneyV2","updatedAt":"DateTime!","variant":"ProductVariant!","variants":["ProductVariantConnection",{"after":"String","before":"String","first":"Int","last":"Int"}]},"t":["LegacyInteroperability","Node"],"d":{"variant":"Use `variants` instead."}}}, +"InventoryItemConnection":{"o":{"f":{"edges":"[InventoryItemEdge!]!","nodes":"[InventoryItem!]!","pageInfo":"PageInfo!"}}}, +"InventoryItemEdge":{"o":{"f":{"cursor":"String!","node":"InventoryItem!"}}}, +"InventoryItemInput":{"i":{"cost":"Decimal","countryCodeOfOrigin":"CountryCode","countryHarmonizedSystemCodes":"[CountryHarmonizedSystemCodeInput!]","harmonizedSystemCode":"String","measurement":"InventoryItemMeasurementInput","provinceCodeOfOrigin":"String","requiresShipping":"Boolean","sku":"String","tracked":"Boolean"}}, +"InventoryItemMeasurement":{"o":{"f":{"id":"ID!","weight":"Weight"},"t":["Node"]}}, +"InventoryItemMeasurementInput":{"i":{"shippingPackageId":"ID","weight":"WeightInput"}}, +"InventoryItemUpdatePayload":{"o":{"f":{"inventoryItem":"InventoryItem","userErrors":"[UserError!]!"}}}, +"InventoryLevel":{"o":{"f":{"canDeactivate":"Boolean!","createdAt":"DateTime!","deactivationAlert":"String","id":"ID!","isActive":"Boolean!","item":"InventoryItem!","location":"Location!","quantities":["[InventoryQuantity!]!",{"names":"[String!]!"}],"scheduledChanges":["InventoryScheduledChangeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"ScheduledChangeSortKeys="}],"updatedAt":"DateTime!"},"t":["Node"],"d":{"scheduledChanges":"Scheduled changes will be phased out in a future version."}}}, +"InventoryLevelConnection":{"o":{"f":{"edges":"[InventoryLevelEdge!]!","nodes":"[InventoryLevel!]!","pageInfo":"PageInfo!"}}}, +"InventoryLevelEdge":{"o":{"f":{"cursor":"String!","node":"InventoryLevel!"}}}, +"InventoryLevelInput":{"i":{"availableQuantity":"Int!","locationId":"ID!"}}, +"InventoryMoveQuantitiesInput":{"i":{"changes":"[InventoryMoveQuantityChange!]!","reason":"String!","referenceDocumentUri":"String!"}}, +"InventoryMoveQuantitiesPayload":{"o":{"f":{"inventoryAdjustmentGroup":"InventoryAdjustmentGroup","userErrors":"[InventoryMoveQuantitiesUserError!]!"}}}, +"InventoryMoveQuantitiesUserError":{"o":{"f":{"code":"InventoryMoveQuantitiesUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryMoveQuantitiesUserErrorCode":{"e":["INTERNAL_LEDGER_DOCUMENT","INVALID_AVAILABLE_DOCUMENT","INVALID_INVENTORY_ITEM","INVALID_LEDGER_DOCUMENT","INVALID_LOCATION","INVALID_QUANTITY_DOCUMENT","INVALID_QUANTITY_NAME","INVALID_QUANTITY_NEGATIVE","INVALID_QUANTITY_TOO_HIGH","INVALID_REASON","INVALID_REFERENCE_DOCUMENT","SERVICE_UNAVAILABLE","CHANGE_FROM_QUANTITY_STALE","MOVE_QUANTITIES_FAILED","DIFFERENT_LOCATIONS","SAME_QUANTITY_NAME","MAXIMUM_LEDGER_DOCUMENT_URIS","NON_MUTABLE_INVENTORY_ITEM","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED"]}, +"InventoryMoveQuantityChange":{"i":{"from":"InventoryMoveQuantityTerminalInput!","inventoryItemId":"ID!","quantity":"Int!","to":"InventoryMoveQuantityTerminalInput!"}}, +"InventoryMoveQuantityTerminalInput":{"i":{"changeFromQuantity":"Int","ledgerDocumentUri":"String","locationId":"ID!","name":"String!"}}, +"InventoryProperties":{"o":{"f":{"quantityNames":"[InventoryQuantityName!]!"}}}, +"InventoryPurchaseOrder":{"o":{"f":{"archivedAt":"DateTime","currency":"CurrencyCode!","dateCreated":"DateTime!","destination":"LocationSnapshot","id":"ID!","lineItems":["InventoryPurchaseOrderLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","lineItemId":"ID","query":"String","reverse":"Boolean=","sortKey":"PurchaseOrderLineItemSortKeys="}],"name":"String!","orderedAt":"DateTime","origin":"InventorySupplierSnapshot","status":"InventoryPurchaseOrderStatus!","transfers":["InventoryTransferConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["Node"]}}, +"InventoryPurchaseOrderConnection":{"o":{"f":{"edges":"[InventoryPurchaseOrderEdge!]!","nodes":"[InventoryPurchaseOrder!]!","pageInfo":"PageInfo!"}}}, +"InventoryPurchaseOrderEdge":{"o":{"f":{"cursor":"String!","node":"InventoryPurchaseOrder!"}}}, +"InventoryPurchaseOrderLineItem":{"o":{"f":{"id":"ID!","inventoryItem":"InventoryItem","purchaseOrder":"InventoryPurchaseOrder","subtotal":"MoneyV2","supplierSku":"String","taxPercent":"Decimal","title":"String","totalCost":"MoneyV2","totalQuantity":"Int!","unitCost":"MoneyV2","variantTitle":"String"},"t":["Node"]}}, +"InventoryPurchaseOrderLineItemConnection":{"o":{"f":{"edges":"[InventoryPurchaseOrderLineItemEdge!]!","nodes":"[InventoryPurchaseOrderLineItem!]!","pageInfo":"PageInfo!"}}}, +"InventoryPurchaseOrderLineItemEdge":{"o":{"f":{"cursor":"String!","node":"InventoryPurchaseOrderLineItem!"}}}, +"InventoryPurchaseOrderStatus":{"e":["DRAFT","ORDERED"]}, +"InventoryQuantity":{"o":{"f":{"id":"ID!","name":"String!","quantity":"Int!","updatedAt":"DateTime"},"t":["Node"]}}, +"InventoryQuantityInput":{"i":{"changeFromQuantity":"Int","inventoryItemId":"ID!","locationId":"ID!","quantity":"Int!"}}, +"InventoryQuantityName":{"o":{"f":{"belongsTo":"[String!]!","comprises":"[String!]!","displayName":"String","isInUse":"Boolean!","name":"String!"}}}, +"InventoryScheduledChange":{"o":{"f":{"expectedAt":"DateTime!","fromName":"String!","inventoryLevel":"InventoryLevel!","ledgerDocumentUri":"URL!","quantity":"Int!","toName":"String!"}}}, +"InventoryScheduledChangeConnection":{"o":{"f":{"edges":"[InventoryScheduledChangeEdge!]!","nodes":"[InventoryScheduledChange!]!","pageInfo":"PageInfo!"}}}, +"InventoryScheduledChangeEdge":{"o":{"f":{"cursor":"String!","node":"InventoryScheduledChange!"}}}, +"InventorySetOnHandQuantitiesInput":{"i":{"reason":"String!","referenceDocumentUri":"String","setQuantities":"[InventorySetQuantityInput!]!"}}, +"InventorySetOnHandQuantitiesPayload":{"o":{"f":{"inventoryAdjustmentGroup":"InventoryAdjustmentGroup","userErrors":"[InventorySetOnHandQuantitiesUserError!]!"}}}, +"InventorySetOnHandQuantitiesUserError":{"o":{"f":{"code":"InventorySetOnHandQuantitiesUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventorySetOnHandQuantitiesUserErrorCode":{"e":["INVALID_INVENTORY_ITEM","INVALID_LOCATION","INVALID_QUANTITY_NEGATIVE","INVALID_REASON","INVALID_REFERENCE_DOCUMENT","CHANGE_FROM_QUANTITY_STALE","SET_ON_HAND_QUANTITIES_FAILED","NON_MUTABLE_INVENTORY_ITEM","INVALID_QUANTITY_TOO_HIGH","COMPARE_QUANTITY_STALE","SERVICE_UNAVAILABLE","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED"]}, +"InventorySetQuantitiesInput":{"i":{"name":"String!","quantities":"[InventoryQuantityInput!]!","reason":"String!","referenceDocumentUri":"String"}}, +"InventorySetQuantitiesPayload":{"o":{"f":{"inventoryAdjustmentGroup":"InventoryAdjustmentGroup","userErrors":"[InventorySetQuantitiesUserError!]!"}}}, +"InventorySetQuantitiesUserError":{"o":{"f":{"code":"InventorySetQuantitiesUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventorySetQuantitiesUserErrorCode":{"e":["INVALID_INVENTORY_ITEM","INVALID_LOCATION","INVALID_QUANTITY_NEGATIVE","INVALID_REASON","INVALID_REFERENCE_DOCUMENT","INVALID_QUANTITY_TOO_HIGH","INVALID_QUANTITY_TOO_LOW","COMPARE_QUANTITY_REQUIRED","COMPARE_QUANTITY_STALE","CHANGE_FROM_QUANTITY_STALE","INVALID_NAME","NO_DUPLICATE_INVENTORY_ITEM_ID_GROUP_ID_PAIR","NON_MUTABLE_INVENTORY_ITEM","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED"]}, +"InventorySetQuantityInput":{"i":{"changeFromQuantity":"Int","inventoryItemId":"ID!","locationId":"ID!","quantity":"Int!"}}, +"InventoryShipment":{"o":{"f":{"barcode":"String","dateCreated":"DateTime","dateReceived":"DateTime","dateShipped":"DateTime","id":"ID!","lineItemTotalQuantity":"Int!","lineItems":["InventoryShipmentLineItemConnection",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"ShipmentLineItemSortKeys="}],"lineItemsCount":["Count",{"limit":"Int=","query":"String"}],"name":"String!","status":"InventoryShipmentStatus!","totalAcceptedQuantity":"Int!","totalCanceledQuantity":"Int!","totalReceivedQuantity":"Int!","totalRejectedQuantity":"Int!","tracking":"InventoryShipmentTracking"},"t":["Node"]}}, +"InventoryShipmentAddItemsPayload":{"o":{"f":{"addedItems":"[InventoryShipmentLineItem!]","inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentAddItemsUserError!]!"}}}, +"InventoryShipmentAddItemsUserError":{"o":{"f":{"code":"InventoryShipmentAddItemsUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentAddItemsUserErrorCode":{"e":["LOCATION_NOT_FOUND","INVALID_SHIPMENT_STATUS","DUPLICATE_ITEM","INVALID_QUANTITY","ITEM_NOT_FOUND","INVENTORY_STATE_NOT_ACTIVE","UNTRACKED_ITEM","SHIPMENT_NOT_FOUND","LOCATION_NOT_ACTIVE","ACTIVATION_FAILED","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH"]}, +"InventoryShipmentConnection":{"o":{"f":{"edges":"[InventoryShipmentEdge!]!","nodes":"[InventoryShipment!]!","pageInfo":"PageInfo!"}}}, +"InventoryShipmentCreateInTransitPayload":{"o":{"f":{"inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentCreateInTransitUserError!]!"}}}, +"InventoryShipmentCreateInTransitUserError":{"o":{"f":{"code":"InventoryShipmentCreateInTransitUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentCreateInTransitUserErrorCode":{"e":["BARCODE_DUPLICATE","BARCODE_TOO_LONG","DUPLICATE_ITEM","INVALID_QUANTITY","ITEM_NOT_FOUND","INVALID_TRANSFER_STATUS","UNTRACKED_ITEM","EMPTY_SHIPMENT_INPUT","ITEMS_EMPTY","TRANSFER_NOT_FOUND","INVALID_URL","INVALID_SHIPMENT_INPUT","INVALID_ITEM","INVENTORY_STATE_NOT_ACTIVE","LOCATION_NOT_ACTIVE","SHIPMENT_NOT_FOUND","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH"]}, +"InventoryShipmentCreateInput":{"i":{"barcode":"String","dateCreated":"DateTime","lineItems":"[InventoryShipmentLineItemInput!]!","movementId":"ID!","trackingInput":"InventoryShipmentTrackingInput"}}, +"InventoryShipmentCreatePayload":{"o":{"f":{"inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentCreateUserError!]!"}}}, +"InventoryShipmentCreateUserError":{"o":{"f":{"code":"InventoryShipmentCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentCreateUserErrorCode":{"e":["BARCODE_DUPLICATE","BARCODE_TOO_LONG","EMPTY_SHIPMENT_INPUT","ITEM_NOT_FOUND","TRANSFER_NOT_FOUND","INVALID_TRANSFER_STATUS","BUNDLED_ITEM","INVALID_QUANTITY","UNTRACKED_ITEM","DUPLICATE_ITEM","INVALID_SHIPMENT_INPUT","INVALID_ITEM","INVALID_URL","LOCATION_NOT_ACTIVE","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","IDEMPOTENCY_RECORD_NOT_FOUND"]}, +"InventoryShipmentDeletePayload":{"o":{"f":{"id":"ID","userErrors":"[InventoryShipmentDeleteUserError!]!"}}}, +"InventoryShipmentDeleteUserError":{"o":{"f":{"code":"InventoryShipmentDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentDeleteUserErrorCode":{"e":["SHIPMENT_NOT_FOUND","INVALID_SHIPMENT_STATUS"]}, +"InventoryShipmentEdge":{"o":{"f":{"cursor":"String!","node":"InventoryShipment!"}}}, +"InventoryShipmentLineItem":{"o":{"f":{"acceptedQuantity":"Int!","canceledQuantity":"Int!","id":"ID!","inventoryItem":"InventoryItem","quantity":"Int!","rejectedQuantity":"Int!","unreceivedQuantity":"Int!"},"t":["Node"]}}, +"InventoryShipmentLineItemConnection":{"o":{"f":{"edges":"[InventoryShipmentLineItemEdge!]!","nodes":"[InventoryShipmentLineItem!]!","pageInfo":"PageInfo!"}}}, +"InventoryShipmentLineItemEdge":{"o":{"f":{"cursor":"String!","node":"InventoryShipmentLineItem!"}}}, +"InventoryShipmentLineItemInput":{"i":{"inventoryItemId":"ID!","quantity":"Int!"}}, +"InventoryShipmentMarkInTransitPayload":{"o":{"f":{"inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentMarkInTransitUserError!]!"}}}, +"InventoryShipmentMarkInTransitUserError":{"o":{"f":{"code":"InventoryShipmentMarkInTransitUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentMarkInTransitUserErrorCode":{"e":["SHIPMENT_NOT_FOUND","INVALID_SHIPMENT_STATUS","ITEM_NOT_FOUND","INVENTORY_STATE_NOT_ACTIVE","UNTRACKED_ITEM","INVALID_QUANTITY","ITEMS_EMPTY","LOCATION_NOT_ACTIVE","ACTIVATION_FAILED"]}, +"InventoryShipmentReceiveItemInput":{"i":{"quantity":"Int!","reason":"InventoryShipmentReceiveLineItemReason!","shipmentLineItemId":"ID!"}}, +"InventoryShipmentReceiveLineItemReason":{"e":["ACCEPTED","REJECTED","CANCELED"]}, +"InventoryShipmentReceivePayload":{"o":{"f":{"inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentReceiveUserError!]!"}}}, +"InventoryShipmentReceiveUserError":{"o":{"f":{"code":"InventoryShipmentReceiveUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentReceiveUserErrorCode":{"e":["LOCATION_NOT_FOUND","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","INTERNAL_ERROR","INVALID_SHIPMENT_INPUT","INVALID_SHIPMENT_STATUS","INVENTORY_STATE_NOT_ACTIVE","SHIPMENT_NOT_FOUND","INVALID_QUANTITY","ITEM_NOT_FOUND","LOCATION_NOT_ACTIVE"]}, +"InventoryShipmentRemoveItemsPayload":{"o":{"f":{"inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentRemoveItemsUserError!]!"}}}, +"InventoryShipmentRemoveItemsUserError":{"o":{"f":{"code":"InventoryShipmentRemoveItemsUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentRemoveItemsUserErrorCode":{"e":["LOCATION_NOT_FOUND","INTERNAL_ERROR","SHIPMENT_NOT_FOUND","ITEM_NOT_FOUND","INVALID_SHIPMENT_STATUS","LOCATION_NOT_ACTIVE"]}, +"InventoryShipmentSetBarcodePayload":{"o":{"f":{"inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentSetBarcodeUserError!]!"}}}, +"InventoryShipmentSetBarcodeUserError":{"o":{"f":{"code":"InventoryShipmentSetBarcodeUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentSetBarcodeUserErrorCode":{"e":["SHIPMENT_NOT_FOUND","BARCODE_DUPLICATE","BARCODE_TOO_LONG"]}, +"InventoryShipmentSetTrackingPayload":{"o":{"f":{"inventoryShipment":"InventoryShipment","userErrors":"[InventoryShipmentSetTrackingUserError!]!"}}}, +"InventoryShipmentSetTrackingUserError":{"o":{"f":{"code":"InventoryShipmentSetTrackingUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentSetTrackingUserErrorCode":{"e":["SHIPMENT_NOT_FOUND","INVALID_URL"]}, +"InventoryShipmentSortKeys":{"e":["ID","STATUS"]}, +"InventoryShipmentStatus":{"e":["DRAFT","IN_TRANSIT","PARTIALLY_RECEIVED","RECEIVED","OTHER"]}, +"InventoryShipmentTracking":{"o":{"f":{"arrivesAt":"DateTime","company":"String","trackingNumber":"String","trackingUrl":"URL"}}}, +"InventoryShipmentTrackingInput":{"i":{"arrivesAt":"DateTime","company":"String","trackingNumber":"String","trackingUrl":"URL"}}, +"InventoryShipmentUpdateItemQuantitiesInput":{"i":{"quantity":"Int!","shipmentLineItemId":"ID!"}}, +"InventoryShipmentUpdateItemQuantitiesPayload":{"o":{"f":{"shipment":"InventoryShipment","updatedLineItems":"[InventoryShipmentLineItem!]","userErrors":"[InventoryShipmentUpdateItemQuantitiesUserError!]!"}}}, +"InventoryShipmentUpdateItemQuantitiesUserError":{"o":{"f":{"code":"InventoryShipmentUpdateItemQuantitiesUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryShipmentUpdateItemQuantitiesUserErrorCode":{"e":["LOCATION_NOT_FOUND","SHIPMENT_NOT_FOUND","ITEM_NOT_FOUND","INVALID_QUANTITY","INVALID_SHIPMENT_STATUS","LOCATION_NOT_ACTIVE"]}, +"InventorySupplierSnapshot":{"o":{"f":{"supplierName":"String"}}}, +"InventoryTransfer":{"o":{"f":{"dateCreated":"DateTime","destination":"LocationSnapshot","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"hasTimelineComment":"Boolean!","id":"ID!","lineItems":["InventoryTransferLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"lineItemsCount":["Count",{"limit":"Int=","query":"String"}],"metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","note":"String","origin":"LocationSnapshot","receivedQuantity":"Int!","referenceName":"String","shipments":["InventoryShipmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"status":"InventoryTransferStatus!","tags":"[String!]!","totalQuantity":"Int!"},"t":["CommentEventSubject","HasEvents","HasMetafieldDefinitions","HasMetafields","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"InventoryTransferCancelPayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","userErrors":"[InventoryTransferCancelUserError!]!"}}}, +"InventoryTransferCancelUserError":{"o":{"f":{"code":"InventoryTransferCancelUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferCancelUserErrorCode":{"e":["INVALID_TRANSFER_STATUS","SHIPMENT_EXISTS","TRANSFER_NOT_FOUND"]}, +"InventoryTransferConnection":{"o":{"f":{"edges":"[InventoryTransferEdge!]!","nodes":"[InventoryTransfer!]!","pageInfo":"PageInfo!"}}}, +"InventoryTransferCreateAsReadyToShipInput":{"i":{"dateCreated":"DateTime","destinationLocationId":"ID","lineItems":"[InventoryTransferLineItemInput!]!=","metafields":"[MetafieldInput!]","note":"String","originLocationId":"ID","referenceName":"String","tags":"[String!]"}}, +"InventoryTransferCreateAsReadyToShipPayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","userErrors":"[InventoryTransferCreateAsReadyToShipUserError!]!"}}}, +"InventoryTransferCreateAsReadyToShipUserError":{"o":{"f":{"code":"InventoryTransferCreateAsReadyToShipUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferCreateAsReadyToShipUserErrorCode":{"e":["TRANSFER_NOT_FOUND","ITEMS_EMPTY","INVALID_TRANSFER_STATUS","LOCATION_NOT_ACTIVE","LOCATION_NOT_FOUND","TRANSFER_ORIGIN_CANNOT_BE_THE_SAME_AS_DESTINATION","TAG_EXCEEDS_MAX_LENGTH","INVALID_TAG","LOCATION_REQUIRED","INVALID_METAFIELDS","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","BUNDLED_ITEM","UNTRACKED_ITEM","ITEM_NOT_FOUND","INVALID_QUANTITY","DUPLICATE_ITEM","INVENTORY_STATE_NOT_ACTIVE"]}, +"InventoryTransferCreateInput":{"i":{"dateCreated":"DateTime","destinationLocationId":"ID","lineItems":"[InventoryTransferLineItemInput!]!=","metafields":"[MetafieldInput!]","note":"String","originLocationId":"ID","referenceName":"String","tags":"[String!]"}}, +"InventoryTransferCreatePayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","userErrors":"[InventoryTransferCreateUserError!]!"}}}, +"InventoryTransferCreateUserError":{"o":{"f":{"code":"InventoryTransferCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferCreateUserErrorCode":{"e":["TRANSFER_NOT_FOUND","LOCATION_NOT_FOUND","LOCATION_NOT_ACTIVE","TRANSFER_ORIGIN_CANNOT_BE_THE_SAME_AS_DESTINATION","TAG_EXCEEDS_MAX_LENGTH","INVALID_TAG","INVALID_METAFIELDS","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","BUNDLED_ITEM","UNTRACKED_ITEM","ITEM_NOT_FOUND","INVALID_QUANTITY","DUPLICATE_ITEM","INVENTORY_STATE_NOT_ACTIVE"]}, +"InventoryTransferDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[InventoryTransferDeleteUserError!]!"}}}, +"InventoryTransferDeleteUserError":{"o":{"f":{"code":"InventoryTransferDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferDeleteUserErrorCode":{"e":["INVALID_STATE","INVALID_TRANSFER_STATUS","TRANSFER_NOT_FOUND"]}, +"InventoryTransferDuplicatePayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","userErrors":"[InventoryTransferDuplicateUserError!]!"}}}, +"InventoryTransferDuplicateUserError":{"o":{"f":{"code":"InventoryTransferDuplicateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferDuplicateUserErrorCode":{"e":["TRANSFER_NOT_FOUND","INVALID_QUANTITY","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH"]}, +"InventoryTransferEdge":{"o":{"f":{"cursor":"String!","node":"InventoryTransfer!"}}}, +"InventoryTransferEditInput":{"i":{"dateCreated":"Date","destinationId":"ID","metafields":"[MetafieldInput!]","note":"String","originId":"ID","referenceName":"String","tags":"[String!]"}}, +"InventoryTransferEditPayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","userErrors":"[InventoryTransferEditUserError!]!"}}}, +"InventoryTransferEditUserError":{"o":{"f":{"code":"InventoryTransferEditUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferEditUserErrorCode":{"e":["INTERNAL_ERROR","TRANSFER_NOT_FOUND","TRANSFER_LOCATION_IMMUTABLE","TRANSFER_ORIGIN_CANNOT_BE_THE_SAME_AS_DESTINATION","LOCATION_NOT_ACTIVE","LOCATION_NOT_FOUND","INVENTORY_STATE_NOT_ACTIVE","TAG_EXCEEDS_MAX_LENGTH","INVALID_TAG","INVALID_METAFIELDS"]}, +"InventoryTransferLineItem":{"o":{"f":{"id":"ID!","inventoryItem":"InventoryItem","pickedForShipmentQuantity":"Int!","processableQuantity":"Int!","shippableQuantity":"Int!","shippedQuantity":"Int!","title":"String","totalQuantity":"Int!"},"t":["Node"]}}, +"InventoryTransferLineItemConnection":{"o":{"f":{"edges":"[InventoryTransferLineItemEdge!]!","nodes":"[InventoryTransferLineItem!]!","pageInfo":"PageInfo!"}}}, +"InventoryTransferLineItemEdge":{"o":{"f":{"cursor":"String!","node":"InventoryTransferLineItem!"}}}, +"InventoryTransferLineItemInput":{"i":{"inventoryItemId":"ID!","quantity":"Int!"}}, +"InventoryTransferLineItemUpdate":{"o":{"f":{"deltaQuantity":"Int","inventoryItemId":"ID","newQuantity":"Int"}}}, +"InventoryTransferMarkAsReadyToShipPayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","userErrors":"[InventoryTransferMarkAsReadyToShipUserError!]!"}}}, +"InventoryTransferMarkAsReadyToShipUserError":{"o":{"f":{"code":"InventoryTransferMarkAsReadyToShipUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferMarkAsReadyToShipUserErrorCode":{"e":["TRANSFER_NOT_FOUND","ITEMS_EMPTY","INVALID_TRANSFER_STATUS","LOCATION_REQUIRED","INVALID_ITEM","LOCATION_NOT_ACTIVE","LOCATION_NOT_FOUND"]}, +"InventoryTransferRemoveItemsInput":{"i":{"id":"ID!","transferLineItemIds":"[ID!]"}}, +"InventoryTransferRemoveItemsPayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","removedQuantities":"[InventoryTransferLineItemUpdate!]","userErrors":"[InventoryTransferRemoveItemsUserError!]!"}}}, +"InventoryTransferRemoveItemsUserError":{"o":{"f":{"code":"InventoryTransferRemoveItemsUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferRemoveItemsUserErrorCode":{"e":["TRANSFER_NOT_FOUND","CANT_REMOVE_ALL_ITEMS_FROM_READY_TO_SHIP_TRANSFER","ITEM_NOT_FOUND","ALL_QUANTITY_SHIPPED","ITEM_PRESENT_ON_DRAFT_SHIPMENT_WITH_ZERO_QUANTITY","INVALID_TRANSFER_STATUS","LOCATION_NOT_FOUND"]}, +"InventoryTransferSetItemsInput":{"i":{"id":"ID!","lineItems":"[InventoryTransferLineItemInput!]!"}}, +"InventoryTransferSetItemsPayload":{"o":{"f":{"inventoryTransfer":"InventoryTransfer","updatedLineItems":"[InventoryTransferLineItemUpdate!]","userErrors":"[InventoryTransferSetItemsUserError!]!"}}}, +"InventoryTransferSetItemsUserError":{"o":{"f":{"code":"InventoryTransferSetItemsUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"InventoryTransferSetItemsUserErrorCode":{"e":["TRANSFER_NOT_FOUND","INVALID_TRANSFER_STATUS","LOCATION_NOT_FOUND","LOCATION_NOT_ACTIVE","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED","IDEMPOTENCY_KEY_PARAMETER_MISMATCH","BUNDLED_ITEM","UNTRACKED_ITEM","ITEM_NOT_FOUND","INVALID_QUANTITY","DUPLICATE_ITEM","INVENTORY_STATE_NOT_ACTIVE"]}, +"InventoryTransferStatus":{"e":["DRAFT","READY_TO_SHIP","IN_PROGRESS","TRANSFERRED","CANCELED","OTHER"]}, +"InvoiceReturnOutcome":{"o":{"f":{"amount":"MoneyBag!"}}}, +"JSON":"s", +"Job":{"o":{"f":{"done":"Boolean!","id":"ID!","query":"QueryRoot"}}}, +"JobResult":{"n":{"f":{"done":"Boolean!","id":"ID!"},"t":["CustomerSegmentMembersQuery","OrderCancelJobResult","OrderCreateMandatePaymentJobResult","ShippingLabelPurchaseResult"]}}, +"LanguageCode":{"e":["AF","AK","AM","AR","AS","AZ","BE","BG","BM","BN","BO","BR","BS","CA","CE","CKB","CS","CY","DA","DE","DZ","EE","EL","EN","EO","ES","ET","EU","FA","FF","FI","FIL","FO","FR","FY","GA","GD","GL","GU","GV","HA","HE","HI","HR","HU","HY","IA","ID","IG","II","IS","IT","JA","JV","KA","KI","KK","KL","KM","KN","KO","KS","KU","KW","KY","LB","LG","LN","LO","LT","LU","LV","MG","MI","MK","ML","MN","MR","MS","MT","MY","NB","ND","NE","NL","NN","NO","OM","OR","OS","PA","PL","PS","PT_BR","PT_PT","QU","RM","RN","RO","RU","RW","SA","SC","SD","SE","SG","SI","SK","SL","SN","SO","SQ","SR","SU","SV","SW","TA","TE","TG","TH","TI","TK","TO","TR","TT","UG","UK","UR","UZ","VI","WO","XH","YI","YO","ZH_CN","ZH_TW","ZU","ZH","PT","CU","VO"]}, +"LegacyInteroperability":{"n":{"f":{"legacyResourceId":"UnsignedInt64!"},"t":["Customer","DraftOrder","Fulfillment","InventoryItem","Location","MarketingEvent","Metafield","Order","Product","ProductVariant","Refund","SavedSearch","ScriptTag","ShopifyPaymentsDispute","ShopifyPaymentsPayout","WebhookSubscription"]}}, +"LengthUnit":{"e":["MILLIMETERS","CENTIMETERS","METERS","INCHES","FEET","YARDS"]}, +"LimitedPendingOrderCount":{"o":{"f":{"atMax":"Boolean!","count":"Int!"}}}, +"LineItem":{"o":{"f":{"canRestock":"Boolean!","contract":"SubscriptionContract","createdAt":"DateTime!","currentQuantity":"Int!","customAttributes":"[Attribute!]!","discountAllocations":"[DiscountAllocation!]!","discountedTotal":"Money!","discountedTotalSet":["MoneyBag!",{"withCodeDiscounts":"Boolean="}],"discountedUnitPrice":"Money!","discountedUnitPriceAfterAllDiscountsSet":"MoneyBag!","discountedUnitPriceSet":"MoneyBag!","duties":"[Duty!]!","fulfillableQuantity":"Int!","fulfillmentService":"FulfillmentService","fulfillmentStatus":"String!","id":"ID!","image":["Image",{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","scale":"Int="}],"isGiftCard":"Boolean!","lineItemGroup":"LineItemGroup","merchantEditable":"Boolean!","name":"String!","nonFulfillableQuantity":"Int!","originalTotal":"Money!","originalTotalSet":"MoneyBag!","originalUnitPrice":"Money!","originalUnitPriceSet":"MoneyBag!","priceAfterAllDiscountsBeforeTaxesSet":"MoneyBag!","product":"Product","quantity":"Int!","refundableQuantity":"Int!","requiresShipping":"Boolean!","restockable":"Boolean!","sellingPlan":"LineItemSellingPlan","sku":"String","staffMember":"StaffMember","suggestedReturnReasonDefinitions":["ReturnReasonDefinitionConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"taxLines":["[TaxLine!]!",{"first":"Int"}],"taxable":"Boolean!","title":"String!","totalDiscount":"Money!","totalDiscountSet":"MoneyBag!","unfulfilledDiscountedTotal":"Money!","unfulfilledDiscountedTotalSet":"MoneyBag!","unfulfilledOriginalTotal":"Money!","unfulfilledOriginalTotalSet":"MoneyBag!","unfulfilledQuantity":"Int!","variant":"ProductVariant","variantTitle":"String","vendor":"String","weight":"Weight"},"t":["Node"],"d":{"canRestock":"Use `restockable` instead.","discountedTotal":"Use `discountedTotalSet` instead.","discountedUnitPrice":"Use `discountedUnitPriceSet` instead.","fulfillableQuantity":"Use [FulfillmentOrderLineItem#remainingQuantity](https://shopify.dev/api/admin-graphql/latest/objects/FulfillmentOrderLineItem#field-fulfillmentorderlineitem-remainingquantity) instead.","fulfillmentService":"The [relationship between a product variant and a fulfillment service was changed](/changelog/fulfillment-service-sku-sharing). A [ProductVariant](/api/admin-graphql/latest/objects/ProductVariant) can be stocked by multiple fulfillment services. As a result, we recommend that you use the [inventoryItem field](/api/admin-graphql/latest/objects/ProductVariant#field-productvariant-inventoryitem) if you need to determine where a product variant is stocked.\n\nIf you need to determine whether a product is a gift card, then you should continue to use this field until an alternative is available.\n\nAltering the locations which stock a product variant won't change the value of this field for existing orders.\n\nLearn about [managing inventory quantities and states](/apps/fulfillment/inventory-management-apps/quantities-states).","fulfillmentStatus":"Use [FulfillmentOrderLineItem#remainingQuantity](https://shopify.dev/api/admin-graphql/latest/objects/FulfillmentOrderLineItem#field-fulfillmentorderlineitem-remainingquantity) instead","image(crop)":"Use `Image.url(transform: { crop:})` instead.","image(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","image(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","image(scale)":"Use `Image.url(transform: { scale:})` instead.","originalTotal":"Use `originalTotalSet` instead.","originalUnitPrice":"Use `originalUnitPriceSet` instead.","totalDiscount":"Use `totalDiscountSet` instead.","unfulfilledDiscountedTotal":"Use `unfulfilledDiscountedTotalSet` instead.","unfulfilledOriginalTotal":"Use `unfulfilledOriginalTotalSet` instead."}}}, +"LineItemConnection":{"o":{"f":{"edges":"[LineItemEdge!]!","nodes":"[LineItem!]!","pageInfo":"PageInfo!"}}}, +"LineItemEdge":{"o":{"f":{"cursor":"String!","node":"LineItem!"}}}, +"LineItemGroup":{"o":{"f":{"customAttributes":"[Attribute!]!","id":"ID!","productId":"ID","quantity":"Int!","title":"String!","variantId":"ID","variantSku":"String"},"t":["Node"]}}, +"LineItemSellingPlan":{"o":{"f":{"name":"String!","sellingPlanId":"ID"}}}, +"Link":{"o":{"f":{"label":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"url":"URL!"},"t":["HasPublishedTranslations"]}}, +"LinkedMetafield":{"o":{"f":{"key":"String","namespace":"String"}}}, +"LinkedMetafieldCreateInput":{"i":{"key":"String!","namespace":"String!","values":"[String!]"}}, +"LinkedMetafieldInput":{"i":{"key":"String!","namespace":"String!","values":"[String!]!"}}, +"LinkedMetafieldUpdateInput":{"i":{"key":"String!","namespace":"String!"}}, +"LocalPaymentMethodsPaymentDetails":{"o":{"f":{"paymentDescriptor":"String","paymentMethodName":"String"},"t":["BasePaymentDetails"]}}, +"Locale":{"o":{"f":{"isoCode":"String!","name":"String!"}}}, +"LocalizableContentType":{"e":["JSON_STRING","JSON","LINK","LIST_LINK","LIST_MULTI_LINE_TEXT_FIELD","LIST_SINGLE_LINE_TEXT_FIELD","LIST_URL","MULTI_LINE_TEXT_FIELD","RICH_TEXT_FIELD","SINGLE_LINE_TEXT_FIELD","STRING","URL","FILE_REFERENCE","LIST_FILE_REFERENCE","HTML","URI","INLINE_RICH_TEXT"]}, +"LocalizationExtension":{"o":{"f":{"countryCode":"CountryCode!","key":"LocalizationExtensionKey!","purpose":"LocalizationExtensionPurpose!","title":"String!","value":"String!"}}}, +"LocalizationExtensionConnection":{"o":{"f":{"edges":"[LocalizationExtensionEdge!]!","nodes":"[LocalizationExtension!]!","pageInfo":"PageInfo!"}}}, +"LocalizationExtensionEdge":{"o":{"f":{"cursor":"String!","node":"LocalizationExtension!"}}}, +"LocalizationExtensionInput":{"i":{"key":"LocalizationExtensionKey!","value":"String!"}}, +"LocalizationExtensionKey":{"e":["TAX_CREDENTIAL_BR","SHIPPING_CREDENTIAL_BR","TAX_CREDENTIAL_CL","SHIPPING_CREDENTIAL_CL","SHIPPING_CREDENTIAL_CN","TAX_CREDENTIAL_CO","TAX_CREDENTIAL_TYPE_CO","SHIPPING_CREDENTIAL_CO","SHIPPING_CREDENTIAL_TYPE_CO","TAX_CREDENTIAL_CR","SHIPPING_CREDENTIAL_CR","TAX_CREDENTIAL_EC","SHIPPING_CREDENTIAL_EC","TAX_CREDENTIAL_GT","SHIPPING_CREDENTIAL_GT","TAX_CREDENTIAL_ID","SHIPPING_CREDENTIAL_ID","TAX_CREDENTIAL_IT","TAX_EMAIL_IT","TAX_CREDENTIAL_MY","SHIPPING_CREDENTIAL_MY","SHIPPING_CREDENTIAL_MX","TAX_CREDENTIAL_MX","TAX_CREDENTIAL_TYPE_MX","TAX_CREDENTIAL_USE_MX","TAX_CREDENTIAL_PY","SHIPPING_CREDENTIAL_PY","TAX_CREDENTIAL_PE","SHIPPING_CREDENTIAL_PE","TAX_CREDENTIAL_PT","SHIPPING_CREDENTIAL_PT","SHIPPING_CREDENTIAL_KR","TAX_CREDENTIAL_ES","SHIPPING_CREDENTIAL_ES","SHIPPING_CREDENTIAL_TW","TAX_CREDENTIAL_TR","SHIPPING_CREDENTIAL_TR"]}, +"LocalizationExtensionPurpose":{"e":["SHIPPING","TAX"]}, +"LocalizedField":{"o":{"f":{"countryCode":"CountryCode!","key":"LocalizedFieldKey!","purpose":"LocalizedFieldPurpose!","title":"String!","value":"String!"}}}, +"LocalizedFieldConnection":{"o":{"f":{"edges":"[LocalizedFieldEdge!]!","nodes":"[LocalizedField!]!","pageInfo":"PageInfo!"}}}, +"LocalizedFieldEdge":{"o":{"f":{"cursor":"String!","node":"LocalizedField!"}}}, +"LocalizedFieldInput":{"i":{"key":"LocalizedFieldKey!","value":"String!"}}, +"LocalizedFieldKey":{"e":["TAX_CREDENTIAL_BR","SHIPPING_CREDENTIAL_BR","TAX_CREDENTIAL_CL","SHIPPING_CREDENTIAL_CL","SHIPPING_CREDENTIAL_CN","TAX_CREDENTIAL_CO","TAX_CREDENTIAL_TYPE_CO","SHIPPING_CREDENTIAL_CO","SHIPPING_CREDENTIAL_TYPE_CO","TAX_CREDENTIAL_CR","SHIPPING_CREDENTIAL_CR","TAX_CREDENTIAL_EC","SHIPPING_CREDENTIAL_EC","TAX_CREDENTIAL_GT","SHIPPING_CREDENTIAL_GT","TAX_CREDENTIAL_ID","SHIPPING_CREDENTIAL_ID","TAX_CREDENTIAL_IT","TAX_EMAIL_IT","TAX_CREDENTIAL_MY","SHIPPING_CREDENTIAL_MY","SHIPPING_CREDENTIAL_MX","TAX_CREDENTIAL_MX","TAX_CREDENTIAL_TYPE_MX","TAX_CREDENTIAL_USE_MX","TAX_CREDENTIAL_PY","SHIPPING_CREDENTIAL_PY","TAX_CREDENTIAL_PE","SHIPPING_CREDENTIAL_PE","TAX_CREDENTIAL_PT","SHIPPING_CREDENTIAL_PT","SHIPPING_CREDENTIAL_KR","TAX_CREDENTIAL_ES","SHIPPING_CREDENTIAL_ES","SHIPPING_CREDENTIAL_TW","TAX_CREDENTIAL_TR","SHIPPING_CREDENTIAL_TR"]}, +"LocalizedFieldPurpose":{"e":["SHIPPING","TAX"]}, +"Location":{"o":{"f":{"activatable":"Boolean!","address":"LocationAddress!","addressVerified":"Boolean!","createdAt":"DateTime!","deactivatable":"Boolean!","deactivatedAt":"String","deletable":"Boolean!","fulfillmentService":"FulfillmentService","fulfillsOnlineOrders":"Boolean!","hasActiveInventory":"Boolean!","hasUnfulfilledOrders":"Boolean!","id":"ID!","inventoryLevel":["InventoryLevel",{"includeInactive":"Boolean=","inventoryItemId":"ID!"}],"inventoryLevels":["InventoryLevelConnection!",{"after":"String","before":"String","first":"Int","includeInactive":"Boolean=","last":"Int","query":"String","reverse":"Boolean="}],"isActive":"Boolean!","isFulfillmentService":"Boolean!","isPrimary":"Boolean!","legacyResourceId":"UnsignedInt64!","localPickupSettingsV2":"DeliveryLocalPickupSettings","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","shipsInventory":"Boolean!","suggestedAddresses":"[LocationSuggestedAddress!]!","updatedAt":"DateTime!"},"t":["HasMetafieldDefinitions","HasMetafields","LegacyInteroperability","Node"],"d":{"isPrimary":"The concept of a primary location is deprecated, shipsInventory can be used to get a fallback location","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"LocationActivatePayload":{"o":{"f":{"location":"Location","locationActivateUserErrors":"[LocationActivateUserError!]!"}}}, +"LocationActivateUserError":{"o":{"f":{"code":"LocationActivateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"LocationActivateUserErrorCode":{"e":["GENERIC_ERROR","LOCATION_LIMIT","HAS_ONGOING_RELOCATION","LOCATION_NOT_FOUND","HAS_NON_UNIQUE_NAME","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_KEY_PARAMETER_MISMATCH"]}, +"LocationAddAddressInput":{"i":{"address1":"String","address2":"String","city":"String","countryCode":"CountryCode!","phone":"String","provinceCode":"String","zip":"String"}}, +"LocationAddInput":{"i":{"address":"LocationAddAddressInput!","fulfillsOnlineOrders":"Boolean=","metafields":"[MetafieldInput!]","name":"String!"}}, +"LocationAddPayload":{"o":{"f":{"location":"Location","userErrors":"[LocationAddUserError!]!"}}}, +"LocationAddUserError":{"o":{"f":{"code":"LocationAddUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"LocationAddUserErrorCode":{"e":["INVALID","TOO_LONG","TAKEN","BLANK","INVALID_US_ZIPCODE","GENERIC_ERROR","INVALID_TYPE","INVALID_VALUE","APP_NOT_AUTHORIZED","UNSTRUCTURED_RESERVED_NAMESPACE","DISALLOWED_OWNER_TYPE","INCLUSION","PRESENT","TOO_SHORT","CAPABILITY_VIOLATION","INTERNAL_ERROR"]}, +"LocationAddress":{"o":{"f":{"address1":"String","address2":"String","city":"String","country":"String","countryCode":"String","formatted":"[String!]!","latitude":"Float","longitude":"Float","phone":"String","province":"String","provinceCode":"String","zip":"String"}}}, +"LocationConnection":{"o":{"f":{"edges":"[LocationEdge!]!","nodes":"[Location!]!","pageInfo":"PageInfo!"}}}, +"LocationDeactivatePayload":{"o":{"f":{"location":"Location","locationDeactivateUserErrors":"[LocationDeactivateUserError!]!"}}}, +"LocationDeactivateUserError":{"o":{"f":{"code":"LocationDeactivateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"LocationDeactivateUserErrorCode":{"e":["LOCATION_NOT_FOUND","PERMANENTLY_BLOCKED_FROM_DEACTIVATION_ERROR","TEMPORARILY_BLOCKED_FROM_DEACTIVATION_ERROR","HAS_ACTIVE_RETAIL_SUBSCRIPTIONS","DESTINATION_LOCATION_IS_THE_SAME_LOCATION","DESTINATION_LOCATION_NOT_FOUND_OR_INACTIVE","DESTINATION_LOCATION_NOT_SHOPIFY_MANAGED","HAS_ACTIVE_INVENTORY_ERROR","HAS_FULFILLMENT_ORDERS_ERROR","HAS_INCOMING_FROM_EXTERNAL_DOCUMENT_SOURCES","HAS_INCOMING_MOVEMENTS_ERROR","HAS_OPEN_PURCHASE_ORDERS_ERROR","FAILED_TO_RELOCATE_ACTIVE_INVENTORIES","FAILED_TO_RELOCATE_OPEN_PURCHASE_ORDERS","FAILED_TO_RELOCATE_INCOMING_MOVEMENTS","CANNOT_DISABLE_ONLINE_ORDER_FULFILLMENT","IDEMPOTENCY_CONCURRENT_REQUEST","IDEMPOTENCY_KEY_PARAMETER_MISMATCH"]}, +"LocationDeletePayload":{"o":{"f":{"deletedLocationId":"ID","locationDeleteUserErrors":"[LocationDeleteUserError!]!"}}}, +"LocationDeleteUserError":{"o":{"f":{"code":"LocationDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"LocationDeleteUserErrorCode":{"e":["LOCATION_NOT_FOUND","LOCATION_IS_ACTIVE","GENERIC_ERROR","LOCATION_HAS_INVENTORY","LOCATION_HAS_PENDING_ORDERS","LOCATION_HAS_ACTIVE_RETAIL_SUBSCRIPTION"]}, +"LocationEdge":{"o":{"f":{"cursor":"String!","node":"Location!"}}}, +"LocationEditAddressInput":{"i":{"address1":"String","address2":"String","city":"String","countryCode":"CountryCode","phone":"String","provinceCode":"String","zip":"String"}}, +"LocationEditInput":{"i":{"address":"LocationEditAddressInput","fulfillsOnlineOrders":"Boolean","metafields":"[MetafieldInput!]","name":"String"}}, +"LocationEditPayload":{"o":{"f":{"location":"Location","userErrors":"[LocationEditUserError!]!"}}}, +"LocationEditUserError":{"o":{"f":{"code":"LocationEditUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"LocationEditUserErrorCode":{"e":["TOO_LONG","BLANK","NOT_FOUND","INVALID","TAKEN","INVALID_US_ZIPCODE","GENERIC_ERROR","CANNOT_DISABLE_ONLINE_ORDER_FULFILLMENT","CANNOT_MODIFY_ONLINE_ORDER_FULFILLMENT_FOR_FS_LOCATION","INVALID_TYPE","INVALID_VALUE","APP_NOT_AUTHORIZED","UNSTRUCTURED_RESERVED_NAMESPACE","DISALLOWED_OWNER_TYPE","INCLUSION","PRESENT","TOO_SHORT","CAPABILITY_VIOLATION","INTERNAL_ERROR"]}, +"LocationIdentifierInput":{"i":{"f":{"customId":"UniqueMetafieldValueInput","id":"ID"},"o":true}}, +"LocationLocalPickupDisablePayload":{"o":{"f":{"locationId":"ID","userErrors":"[DeliveryLocationLocalPickupSettingsError!]!"}}}, +"LocationLocalPickupEnablePayload":{"o":{"f":{"localPickupSettings":"DeliveryLocalPickupSettings","userErrors":"[DeliveryLocationLocalPickupSettingsError!]!"}}}, +"LocationSnapshot":{"o":{"f":{"address":"LocationAddress!","location":"Location","name":"String!","snapshottedAt":"DateTime!"}}}, +"LocationSortKeys":{"e":["ID","NAME","RELEVANCE"]}, +"LocationSuggestedAddress":{"o":{"f":{"address1":"String","address2":"String","city":"String","country":"String","countryCode":"CountryCode","formatted":"[String!]!","province":"String","provinceCode":"String","zip":"String"}}}, +"LocationsCondition":{"o":{"f":{"applicationLevel":"MarketConditionApplicationType","locations":["LocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"MailingAddress":{"o":{"f":{"address1":"String","address2":"String","city":"String","company":"String","coordinatesValidated":"Boolean!","country":"String","countryCode":"String","countryCodeV2":"CountryCode","firstName":"String","formatted":["[String!]!",{"withCompany":"Boolean=","withName":"Boolean="}],"formattedArea":"String","id":"ID!","lastName":"String","latitude":"Float","longitude":"Float","name":"String","phone":"String","province":"String","provinceCode":"String","timeZone":"String","validationResultSummary":"MailingAddressValidationResult","zip":"String"},"t":["Node"],"d":{"countryCode":"Use `countryCodeV2` instead."}}}, +"MailingAddressConnection":{"o":{"f":{"edges":"[MailingAddressEdge!]!","nodes":"[MailingAddress!]!","pageInfo":"PageInfo!"}}}, +"MailingAddressEdge":{"o":{"f":{"cursor":"String!","node":"MailingAddress!"}}}, +"MailingAddressInput":{"i":{"f":{"address1":"String","address2":"String","city":"String","company":"String","country":"String","countryCode":"CountryCode","firstName":"String","id":"ID","lastName":"String","phone":"String","province":"String","provinceCode":"String","zip":"String"},"d":{"country":"Use `countryCode` instead.","id":"Not needed for 90% of mutations, and provided separately where it is needed.","province":"Use `provinceCode` instead."}}}, +"MailingAddressValidationResult":{"e":["NO_ISSUES","ERROR","WARNING"]}, +"MandateResourceType":{"e":["CREDENTIAL_ON_FILE","CHECKOUT","DRAFT_ORDER","ORDER","SUBSCRIPTIONS"]}, +"ManualDiscountApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","description":"String","index":"Int!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","title":"String!","value":"PricingValue!"},"t":["DiscountApplication"]}}, +"Market":{"o":{"f":{"assignedCustomization":["Boolean!",{"customizationId":"ID!"}],"catalogs":["MarketCatalogConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"catalogsCount":"Count","childMarkets":["MarketConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"childMarketsCount":"Count","conditions":"MarketConditions","currencySettings":"MarketCurrencySettings","delivery":"MarketDeliveryConfigurations!","discounts":["DiscountNodeConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"discountsCount":"Count","enabled":"Boolean!","handle":"String!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","parentMarkets":["MarketConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"parentMarketsCount":"Count","priceInclusions":"MarketPriceInclusions","priceList":"PriceList","primary":"Boolean!","regions":["MarketRegionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"returnPolicyProfile":"ReturnPolicyProfile","status":"MarketStatus!","type":"MarketType!","webPresence":"MarketWebPresence","webPresences":["MarketWebPresenceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["HasMetafieldDefinitions","HasMetafields","Node"],"d":{"enabled":"Use `status` instead.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","priceList":"Use `catalogs` instead.","primary":"This field is deprecated and will be removed in the future.","regions":"This field is deprecated and will be removed in the future. Use `conditions.regionConditions` instead.","webPresence":"Use `webPresences` instead."}}}, +"MarketCatalog":{"o":{"f":{"id":"ID!","markets":["MarketConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","status":"MarketStatus=","type":"MarketType="}],"marketsCount":["Count",{"limit":"Int","query":"String","status":"MarketStatus=","type":"MarketType="}],"operations":"[ResourceOperation!]!","priceList":"PriceList","publication":"Publication","status":"CatalogStatus!","title":"String!"},"t":["Catalog","Node"]}}, +"MarketCatalogConnection":{"o":{"f":{"edges":"[MarketCatalogEdge!]!","nodes":"[MarketCatalog!]!","pageInfo":"PageInfo!"}}}, +"MarketCatalogEdge":{"o":{"f":{"cursor":"String!","node":"MarketCatalog!"}}}, +"MarketConditionApplicationType":{"e":["SPECIFIED","ALL"]}, +"MarketConditionType":{"e":["REGION","LOCATION","COMPANY_LOCATION","CHANNEL"]}, +"MarketConditions":{"o":{"f":{"channelsCondition":"ChannelsCondition","companyLocationsCondition":"CompanyLocationsCondition","conditionTypes":"[MarketConditionType!]!","locationsCondition":"LocationsCondition","regionsCondition":"RegionsCondition"}}}, +"MarketConditionsChannelsInput":{"i":{"channelIds":"[ID!]"}}, +"MarketConditionsCompanyLocationsInput":{"i":{"f":{"applicationLevel":"MarketConditionApplicationType","companyLocationIds":"[ID!]"},"o":true}}, +"MarketConditionsInput":{"i":{"channelsCondition":"MarketConditionsChannelsInput","companyLocationsCondition":"MarketConditionsCompanyLocationsInput","locationsCondition":"MarketConditionsLocationsInput","regionsCondition":"MarketConditionsRegionsInput"}}, +"MarketConditionsLocationsInput":{"i":{"f":{"applicationLevel":"MarketConditionApplicationType","locationIds":"[ID!]"},"o":true}}, +"MarketConditionsRegionInput":{"i":{"countryCode":"CountryCode!","subdivision":"String"}}, +"MarketConditionsRegionsInput":{"i":{"f":{"applicationLevel":"MarketConditionApplicationType","regionIds":"[ID!]","regions":"[MarketConditionsRegionInput!]"},"o":true}}, +"MarketConditionsUpdateInput":{"i":{"conditionsToAdd":"MarketConditionsInput","conditionsToDelete":"MarketConditionsInput"}}, +"MarketConnection":{"o":{"f":{"edges":"[MarketEdge!]!","nodes":"[Market!]!","pageInfo":"PageInfo!"}}}, +"MarketCreateInput":{"i":{"f":{"catalogs":"[ID!]","conditions":"MarketConditionsInput","currencySettings":"MarketCurrencySettingsUpdateInput","delivery":"MarketDeliveryConfigurationsCreateInput","discounts":"[ID!]","enabled":"Boolean","handle":"String","makeDuplicateRegionMarketsDraft":"Boolean","makeDuplicateUniqueMarketsDraft":"Boolean","name":"String!","priceInclusions":"MarketPriceInclusionsInput","regions":"[MarketRegionCreateInput!]","returnPolicyProfileId":"ID","status":"MarketStatus","webPresences":"[ID!]"},"d":{"enabled":"Use `status` instead.","makeDuplicateRegionMarketsDraft":"Use `makeDuplicateUniqueMarketsDraft` instead.","regions":"Use `conditions` instead."}}}, +"MarketCreatePayload":{"o":{"f":{"market":"Market","userErrors":"[MarketUserError!]!"}}}, +"MarketCurrencySettings":{"o":{"f":{"baseCurrency":"CurrencySetting!","localCurrencies":"Boolean!","roundingEnabled":"Boolean!"}}}, +"MarketCurrencySettingsUpdateInput":{"i":{"baseCurrency":"CurrencyCode","baseCurrencyManualRate":"Decimal","localCurrencies":"Boolean","roundingEnabled":"Boolean"}}, +"MarketCurrencySettingsUpdatePayload":{"o":{"f":{"market":"Market","userErrors":"[MarketCurrencySettingsUserError!]!"},"d":{"market":"Use `marketCreate` and `marketUpdate` mutations instead."}}}, +"MarketCurrencySettingsUserError":{"o":{"f":{"code":"MarketCurrencySettingsUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MarketCurrencySettingsUserErrorCode":{"e":["MARKET_NOT_FOUND","MANAGED_MARKET","UNIFIED_MARKETS_ENABLED","MULTIPLE_CURRENCIES_NOT_SUPPORTED","NO_LOCAL_CURRENCIES_ON_SINGLE_COUNTRY_MARKET","UNSUPPORTED_CURRENCY","PRIMARY_MARKET_USES_SHOP_CURRENCY","ADAPTIVE_PRICING_REQUIRES_LOCAL_CURRENCIES"]}, +"MarketDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[MarketUserError!]!"}}}, +"MarketDeliveryConfigurations":{"o":{"f":{"shipping":"ShippingConfiguration"}}}, +"MarketDeliveryConfigurationsCreateInput":{"i":{"shipping":"ShippingConfigurationCreateInput"}}, +"MarketDeliveryConfigurationsUpdateInput":{"i":{"removeShipping":"Boolean","shipping":"ShippingConfigurationUpdateInput"}}, +"MarketEdge":{"o":{"f":{"cursor":"String!","node":"Market!"}}}, +"MarketLocalizableContent":{"o":{"f":{"digest":"String","key":"String!","value":"String"}}}, +"MarketLocalizableResource":{"o":{"f":{"marketLocalizableContent":"[MarketLocalizableContent!]!","marketLocalizations":["[MarketLocalization!]!",{"marketId":"ID!"}],"resourceId":"ID!"}}}, +"MarketLocalizableResourceConnection":{"o":{"f":{"edges":"[MarketLocalizableResourceEdge!]!","nodes":"[MarketLocalizableResource!]!","pageInfo":"PageInfo!"}}}, +"MarketLocalizableResourceEdge":{"o":{"f":{"cursor":"String!","node":"MarketLocalizableResource!"}}}, +"MarketLocalizableResourceType":{"e":["METAFIELD","METAOBJECT"]}, +"MarketLocalization":{"o":{"f":{"key":"String!","market":"Market!","outdated":"Boolean!","updatedAt":"DateTime","value":"String"}}}, +"MarketLocalizationRegisterInput":{"i":{"key":"String!","marketId":"ID!","marketLocalizableContentDigest":"String!","value":"String!"}}, +"MarketLocalizationsRegisterPayload":{"o":{"f":{"marketLocalizations":"[MarketLocalization!]","userErrors":"[TranslationUserError!]!"}}}, +"MarketLocalizationsRemovePayload":{"o":{"f":{"marketLocalizations":"[MarketLocalization!]","userErrors":"[TranslationUserError!]!"}}}, +"MarketPriceInclusions":{"o":{"f":{"adaptivePricingEnabled":"Boolean!","inclusiveDutiesPricingStrategy":"InclusiveDutiesPricingStrategy!","inclusiveTaxPricingStrategy":"InclusiveTaxPricingStrategy!"}}}, +"MarketPriceInclusionsInput":{"i":{"adaptivePricingEnabled":"Boolean","dutiesPricingStrategy":"InclusiveDutiesPricingStrategy","taxPricingStrategy":"InclusiveTaxPricingStrategy"}}, +"MarketRegion":{"n":{"f":{"id":"ID!","name":"String!"},"t":["MarketRegionCountry","MarketRegionSubdivision"]}}, +"MarketRegionConnection":{"o":{"f":{"edges":"[MarketRegionEdge!]!","nodes":"[MarketRegion!]!","pageInfo":"PageInfo!"}}}, +"MarketRegionCountry":{"o":{"f":{"code":"CountryCode!","currency":"CurrencySetting!","id":"ID!","name":"String!"},"t":["MarketRegion","Node"]}}, +"MarketRegionCreateInput":{"i":{"countryCode":"CountryCode!"}}, +"MarketRegionDeletePayload":{"o":{"f":{"deletedId":"ID","market":"Market","userErrors":"[MarketUserError!]!"}}}, +"MarketRegionEdge":{"o":{"f":{"cursor":"String!","node":"MarketRegion!"}}}, +"MarketRegionSubdivision":{"o":{"f":{"code":"String!","country":"MarketRegionSubdivisionCountry!","id":"ID!","name":"String!"},"t":["MarketRegion","Node"]}}, +"MarketRegionSubdivisionCountry":{"o":{"f":{"code":"CountryCode!","name":"String!"}}}, +"MarketRegionsCreatePayload":{"o":{"f":{"market":"Market","userErrors":"[MarketUserError!]!"}}}, +"MarketRegionsDeletePayload":{"o":{"f":{"deletedIds":"[ID!]","userErrors":"[MarketUserError!]!"}}}, +"MarketRelationship":{"o":{"f":{"childMarket":"Market!","id":"ID!","parentMarket":"Market"},"t":["Node"]}}, +"MarketRelationshipConnection":{"o":{"f":{"edges":"[MarketRelationshipEdge!]!","nodes":"[MarketRelationship!]!","pageInfo":"PageInfo!"}}}, +"MarketRelationshipEdge":{"o":{"f":{"cursor":"String!","node":"MarketRelationship!"}}}, +"MarketRelationshipsStatus":{"o":{"f":{"version":"String!"}}}, +"MarketStatus":{"e":["ACTIVE","DRAFT"]}, +"MarketType":{"e":["NONE","REGION","LOCATION","COMPANY_LOCATION","CHANNEL"]}, +"MarketUpdateInput":{"i":{"f":{"catalogsToAdd":"[ID!]","catalogsToDelete":"[ID!]","conditions":"MarketConditionsUpdateInput","currencySettings":"MarketCurrencySettingsUpdateInput","delivery":"MarketDeliveryConfigurationsUpdateInput","discountsToAdd":"[ID!]","discountsToDelete":"[ID!]","enabled":"Boolean","handle":"String","makeDuplicateRegionMarketsDraft":"Boolean","makeDuplicateUniqueMarketsDraft":"Boolean","name":"String","priceInclusions":"MarketPriceInclusionsInput","removeCurrencySettings":"Boolean","removePriceInclusions":"Boolean","removeReturnPolicyProfile":"Boolean","returnPolicyProfileId":"ID","status":"MarketStatus","webPresencesToAdd":"[ID!]","webPresencesToDelete":"[ID!]"},"d":{"enabled":"Use `status` instead.","makeDuplicateRegionMarketsDraft":"Use `makeDuplicateUniqueMarketsDraft` instead."}}}, +"MarketUpdatePayload":{"o":{"f":{"market":"Market","userErrors":"[MarketUserError!]!"}}}, +"MarketUserError":{"o":{"f":{"code":"MarketUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MarketUserErrorCode":{"e":{"v":["INVALID","TAKEN","TOO_LONG","TOO_SHORT","BLANK","INCLUSION","MARKET_NOT_FOUND","REGION_NOT_FOUND","PROVINCE_DOES_NOT_EXIST","SUBDIVISION_DOES_NOT_EXIST","WEB_PRESENCE_NOT_FOUND","CANNOT_ADD_REGIONS_TO_PRIMARY_MARKET","CANNOT_DELETE_ONLY_REGION","REQUIRES_EXACTLY_ONE_OPTION","CANNOT_DELETE_PRIMARY_MARKET","CANNOT_DELETE_SUBDIVISION_MARKET","EXCEEDS_MAX_MULTI_CONTEXT_MARKETS","DOMAIN_NOT_FOUND","SUBFOLDER_SUFFIX_MUST_CONTAIN_ONLY_LETTERS","SUBFOLDER_SUFFIX_MUST_BE_AT_LEAST_2_LETTERS","SUBFOLDER_SUFFIX_CANNOT_BE_SCRIPT_CODE","NO_LANGUAGES","NO_LOCAL_CURRENCIES_ON_SINGLE_COUNTRY_MARKET","NO_ROUNDING_ON_LEGACY_MARKET","DUPLICATE_LANGUAGES","DUPLICATE_REGION_MARKET","DUPLICATE_UNIQUE_MARKET","REGION_SPECIFIC_LANGUAGE","CANNOT_HAVE_SUBFOLDER_AND_DOMAIN","CANNOT_ADD_WEB_PRESENCE_TO_PRIMARY_MARKET","MARKET_REACHED_WEB_PRESENCE_LIMIT","MARKET_NOT_COMPATIBLE_WITH_CONDITION_TYPES","MISSING_COUNTRY_CODE","MISSING_PROVINCE_CODE","MISSING_SUBDIVISION_CODE","CANNOT_HAVE_MULTIPLE_SUBFOLDERS_PER_MARKET","CANNOT_HAVE_BOTH_SUBFOLDER_AND_DOMAIN_WEB_PRESENCES","REQUIRES_DOMAIN_OR_SUBFOLDER","PRIMARY_MARKET_MUST_USE_PRIMARY_DOMAIN","CANNOT_DELETE_PRIMARY_MARKET_WEB_PRESENCE","SHOP_REACHED_MARKETS_LIMIT","CANNOT_DISABLE_PRIMARY_MARKET","UNPUBLISHED_LANGUAGE","DISABLED_LANGUAGE","CANNOT_SET_DEFAULT_LOCALE_TO_NULL","UNSUPPORTED_COUNTRY_REGION","CANNOT_ADD_CUSTOMER_DOMAIN","MARKET_MANAGER_NOT_COMPATIBLE_WITH_CONDITION_TYPES","GENERIC_ERROR","MARKET_UPDATE_CONCURRENT_MODIFICATION","INVALID_STATUS_AND_ENABLED_COMBINATION","INVALID_PROVINCE_FORMAT","INVALID_SUBDIVISION_FORMAT","CONDITIONS_NOT_FOUND","SPECIFIED_CONDITIONS_CANNOT_BE_EMPTY","CUSTOMIZATIONS_NOT_FOUND","DISCOUNT_NOT_MARKET_CONTEXTUAL","DISCOUNT_EXCEEDS_MARKET_LIMIT","DISCOUNT_NOT_COMPATIBLE_WITH_B2B_MARKET","WILDCARD_NOT_SUPPORTED","SPECIFIED_NOT_VALID_FOR_INPUT","WEB_PRESENCE_NOT_COMPATIBLE_WITH_CONDITION_TYPES","CATALOG_NOT_COMPATIBLE_WITH_CONDITION_TYPES","CATALOG_TYPE_NOT_SUPPORTED","INCLUSIVE_PRICING_NOT_COMPATIBLE_WITH_CONDITION_TYPES","INCOMPATIBLE_CONDITIONS","SHIPPING_NOT_COMPATIBLE_WITH_CONDITION_TYPES","MANAGED_MARKET","MULTIPLE_CURRENCIES_NOT_SUPPORTED","UNSUPPORTED_CURRENCY","ADAPTIVE_PRICING_REQUIRES_LOCAL_CURRENCIES","SHOP_MUST_HAVE_PRIMARY_DOMAIN_WEB_PRESENCE","MUST_HAVE_AT_LEAST_ONE_ACTIVE_REGION_MARKET","USER_LACKS_PERMISSION","CONTAINS_REGIONS_THAT_CANNOT_BE_MANAGED","UNIFIED_MARKETS_NOT_ENABLED","WEB_PRESENCE_REACHED_MARKETS_LIMIT","WEB_PRESENCE_RETAIL_LOCATION","CATALOG_CONDITION_TYPES_MUST_BE_THE_SAME","MARKET_CANT_HAVE_DIRECT_CONNECTION_CATALOG","NOT_ENTITLED_TO_ACTIVATE_MARKET","B2B_MARKET_MUST_BE_MERCHANT_MANAGED","POS_LOCATION_MARKET_MUST_BE_MERCHANT_MANAGED","MANAGED_MARKETS_CATALOG_NOT_ALLOWED","MANAGED_MARKETS_RESOURCE_NOT_ALLOWED","RETAIL_LOCATION_CURRENCY_MUST_BE_LOCAL","MANAGED_MARKET_CURRENCY_MUST_MATCH_COUNTRY","CATALOGS_WITH_VOLUME_PRICING_OR_QUANTITY_RULES_NOT_SUPPORTED","MIXED_COUNTRY_LOCATIONS_NOT_ALLOWED","MIXED_COUNTRY_SUBDIVISIONS_NOT_ALLOWED","SUBDIVISION_MARKET_REQUIRES_COUNTRY_COVERAGE","LOCATION_MATCH_ALL_REQUIRES_ONE_SPECIFIC_REGION","LOCATION_REGION_COUNTRY_MISMATCH","UNPERMITTED_ENTITLEMENTS_MARKET_CATALOGS","CANNOT_ACTIVATE_MARKET_B2B_CATALOG_LIMIT_REACHED","B2B_CATALOG_LIMIT_REACHED","INVALID_CHANNEL_IDS","INVALID_COUNTRY_AND_SUBDIVISION_CONDITIONS","SUBDIVISION_MUST_BELONG_TO_COUNTRY","CANNOT_ADD_ALL_SUBDIVISIONS_FOR_A_COUNTRY_TO_A_MARKET","INVALID_RESPONDER_FOR_PROVINCE_DRIVEN_MARKET","INVALID_CUSTOMIZATION_FOR_SUBDIVISION_CONDITION","INCOMPATIBLE_CONFIGURATION","CHANNEL_MARKET_MUST_HAVE_SINGLE_CHANNEL_DRIVER","CHANNEL_NOT_VALID_FOR_CHANNEL_MARKET","CHANNEL_DRIVER_MUST_HAVE_CHANNEL_SPECIFICATION","REGION_NOT_SUPPORTED_FOR_CHANNEL","ADAPTIVE_PRICING_REQUIRES_MANAGED_MARKETS","ADAPTIVE_PRICING_REQUIRED_SETUP_ERROR","GLOBAL_E_PRICING_STRATEGY_NOT_PERMITTED"],"d":{"CANNOT_ADD_REGIONS_TO_PRIMARY_MARKET":"This will no longer be used after legacy markets are removed in April 2026","CANNOT_ADD_WEB_PRESENCE_TO_PRIMARY_MARKET":"No longer used","CANNOT_DELETE_PRIMARY_MARKET_WEB_PRESENCE":"No longer used","INVALID_RESPONDER_FOR_PROVINCE_DRIVEN_MARKET":"No longer used","MARKET_NOT_COMPATIBLE_WITH_CONDITION_TYPES":"This will no longer be used after legacy markets are removed in April 2026","NO_LOCAL_CURRENCIES_ON_SINGLE_COUNTRY_MARKET":"This will no longer be used after legacy markets are removed in April 2026","NO_ROUNDING_ON_LEGACY_MARKET":"This will no longer be used after legacy markets are removed in April 2026","PRIMARY_MARKET_MUST_USE_PRIMARY_DOMAIN":"This will no longer be used after legacy markets are removed in April 2026","REQUIRES_EXACTLY_ONE_OPTION":"No longer used","SHOP_REACHED_MARKETS_LIMIT":"No longer used","SUBFOLDER_SUFFIX_MUST_CONTAIN_ONLY_LETTERS":"No longer used","UNIFIED_MARKETS_NOT_ENABLED":"This will no longer be used after legacy markets are removed in April 2026","WEB_PRESENCE_RETAIL_LOCATION":"No longer used"}}}, +"MarketWebPresence":{"o":{"f":{"alternateLocales":"[ShopLocale!]!","defaultLocale":"ShopLocale!","domain":"Domain","id":"ID!","market":"Market","markets":["MarketConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"rootUrls":"[MarketWebPresenceRootUrl!]!","subfolderSuffix":"String"},"t":["Node"],"d":{"market":"Use `markets` instead."}}}, +"MarketWebPresenceConnection":{"o":{"f":{"edges":"[MarketWebPresenceEdge!]!","nodes":"[MarketWebPresence!]!","pageInfo":"PageInfo!"}}}, +"MarketWebPresenceCreateInput":{"i":{"alternateLocales":"[String!]","defaultLocale":"String!","domainId":"ID","subfolderSuffix":"String"}}, +"MarketWebPresenceCreatePayload":{"o":{"f":{"market":"Market","userErrors":"[MarketUserError!]!"}}}, +"MarketWebPresenceDeletePayload":{"o":{"f":{"deletedId":"ID","market":"Market","userErrors":"[MarketUserError!]!"}}}, +"MarketWebPresenceEdge":{"o":{"f":{"cursor":"String!","node":"MarketWebPresence!"}}}, +"MarketWebPresenceRootUrl":{"o":{"f":{"locale":"String!","url":"URL!"}}}, +"MarketWebPresenceUpdateInput":{"i":{"alternateLocales":"[String!]","defaultLocale":"String","domainId":"ID","subfolderSuffix":"String"}}, +"MarketWebPresenceUpdatePayload":{"o":{"f":{"market":"Market","userErrors":"[MarketUserError!]!"}}}, +"MarketingActivitiesDeleteAllExternalPayload":{"o":{"f":{"job":"Job","userErrors":"[MarketingActivityUserError!]!"}}}, +"MarketingActivity":{"o":{"f":{"activityListUrl":"URL","adSpend":"MoneyV2","app":"App!","appErrors":"MarketingActivityExtensionAppErrors","budget":"MarketingBudget","createdAt":"DateTime!","formData":"String","hierarchyLevel":"MarketingActivityHierarchyLevel","id":"ID!","inMainWorkflowVersion":"Boolean!","isExternal":"Boolean!","marketingChannel":"MarketingChannel!","marketingChannelType":"MarketingChannel!","marketingEvent":"MarketingEvent","parentActivityId":"ID","parentRemoteId":"String","sourceAndMedium":"String!","status":"MarketingActivityStatus!","statusBadgeType":"MarketingActivityStatusBadgeType","statusBadgeTypeV2":"BadgeType","statusLabel":"String!","statusTransitionedAt":"DateTime","tactic":"MarketingTactic!","targetStatus":"MarketingActivityStatus","title":"String!","updatedAt":"DateTime!","urlParameterValue":"String","utmParameters":"UTMParameters"},"t":["Node"],"d":{"marketingChannel":"Use `marketingChannelType` instead.","statusBadgeType":"Use `statusBadgeTypeV2` instead."}}}, +"MarketingActivityBudgetInput":{"i":{"budgetType":"MarketingBudgetBudgetType","total":"MoneyInput"}}, +"MarketingActivityConnection":{"o":{"f":{"edges":"[MarketingActivityEdge!]!","nodes":"[MarketingActivity!]!","pageInfo":"PageInfo!"}}}, +"MarketingActivityCreateExternalInput":{"i":{"f":{"adSpend":"MoneyInput","budget":"MarketingActivityBudgetInput","channel":"MarketingChannel","channelHandle":"String","end":"DateTime","hierarchyLevel":"MarketingActivityHierarchyLevel","marketingChannelType":"MarketingChannel!","parentActivityId":"ID","parentRemoteId":"String","referringDomain":"String","remoteId":"String","remotePreviewImageUrl":"URL","remoteUrl":"URL!","scheduledEnd":"DateTime","scheduledStart":"DateTime","start":"DateTime","status":"MarketingActivityExternalStatus","tactic":"MarketingTactic!","title":"String!","urlParameterValue":"String","utm":"UTMInput"},"d":{"channel":"This field was renamed for clarity, please switch to using marketingChannelType when migrating to the latest API version."}}}, +"MarketingActivityCreateExternalPayload":{"o":{"f":{"marketingActivity":"MarketingActivity","userErrors":"[MarketingActivityUserError!]!"}}}, +"MarketingActivityCreateInput":{"i":{"f":{"budget":"MarketingActivityBudgetInput","context":"String","formData":"String","marketingActivityExtensionId":"ID!","marketingActivityTitle":"String","status":"MarketingActivityStatus!","urlParameterValue":"String","utm":"UTMInput"},"d":{"budget":"Marketing activity app extensions are deprecated and will be removed in the near future.","context":"Marketing activity app extensions are deprecated and will be removed in the near future.","formData":"Marketing activity app extensions are deprecated and will be removed in the near future.","marketingActivityTitle":"Marketing activity app extensions are deprecated and will be removed in the near future.","urlParameterValue":"Marketing activity app extensions are deprecated and will be removed in the near future.","utm":"Marketing activity app extensions are deprecated and will be removed in the near future."}}}, +"MarketingActivityCreatePayload":{"o":{"f":{"marketingActivity":"MarketingActivity","redirectPath":"String","userErrors":"[UserError!]!"},"d":{"marketingActivity":"Marketing activity app extensions are deprecated and will be removed in the near future.","redirectPath":"Marketing activity app extensions are deprecated and will be removed in the near future."}}}, +"MarketingActivityDeleteExternalPayload":{"o":{"f":{"deletedMarketingActivityId":"ID","userErrors":"[MarketingActivityUserError!]!"}}}, +"MarketingActivityEdge":{"o":{"f":{"cursor":"String!","node":"MarketingActivity!"}}}, +"MarketingActivityExtensionAppErrorCode":{"e":["NOT_ONBOARDED_ERROR","VALIDATION_ERROR","API_ERROR","PLATFORM_ERROR","INSTALL_REQUIRED_ERROR"]}, +"MarketingActivityExtensionAppErrors":{"o":{"f":{"code":"MarketingActivityExtensionAppErrorCode!","userErrors":"[UserError!]!"}}}, +"MarketingActivityExternalStatus":{"e":["ACTIVE","INACTIVE","PAUSED","SCHEDULED","DELETED_EXTERNALLY","UNDEFINED"]}, +"MarketingActivityHierarchyLevel":{"e":["AD","AD_GROUP","CAMPAIGN"]}, +"MarketingActivitySortKeys":{"e":["CREATED_AT","ID","TITLE"]}, +"MarketingActivityStatus":{"e":["ACTIVE","DELETED","DELETED_EXTERNALLY","DISCONNECTED","DRAFT","FAILED","INACTIVE","PAUSED","PENDING","SCHEDULED","UNDEFINED"]}, +"MarketingActivityStatusBadgeType":{"e":["DEFAULT","SUCCESS","ATTENTION","WARNING","INFO","CRITICAL"]}, +"MarketingActivityUpdateExternalInput":{"i":{"f":{"adSpend":"MoneyInput","budget":"MarketingActivityBudgetInput","channel":"MarketingChannel","end":"DateTime","marketingChannelType":"MarketingChannel","referringDomain":"String","remotePreviewImageUrl":"URL","remoteUrl":"URL","scheduledEnd":"DateTime","scheduledStart":"DateTime","start":"DateTime","status":"MarketingActivityExternalStatus","tactic":"MarketingTactic","title":"String"},"d":{"channel":"This field was renamed for clarity, please switch to using marketingChannelType when migrating to the latest API version."}}}, +"MarketingActivityUpdateExternalPayload":{"o":{"f":{"marketingActivity":"MarketingActivity","userErrors":"[MarketingActivityUserError!]!"}}}, +"MarketingActivityUpdateInput":{"i":{"f":{"adSpend":"MoneyInput","budget":"MarketingActivityBudgetInput","context":"String","errors":"JSON","formData":"String","id":"ID!","marketedResources":"[ID!]","marketingRecommendationId":"ID","status":"MarketingActivityStatus","targetStatus":"MarketingActivityStatus","title":"String","urlParameterValue":"String","utm":"UTMInput"},"d":{"adSpend":"Use `MarketingEngagementCreate.MarketingEngagementInput.adSpend` GraphQL to send the ad spend.","budget":"Marketing activity app extensions are deprecated and will be removed in the near future.","context":"This context is no longer needed by Shopify in the callback.","errors":"Marketing activity app extensions are deprecated and will be removed in the near future.","formData":"Marketing activity app extensions are deprecated and will be removed in the near future.","marketedResources":"Marketing activity app extensions are deprecated and will be removed in the near future.","marketingRecommendationId":"Marketing activity app extensions are deprecated and will be removed in the near future.","status":"Marketing activity app extensions are deprecated and will be removed in the near future.","targetStatus":"Marketing activity app extensions are deprecated and will be removed in the near future.","title":"Marketing activity app extensions are deprecated and will be removed in the near future.","urlParameterValue":"Marketing activity app extensions are deprecated and will be removed in the near future.","utm":"Marketing activity app extensions are deprecated and will be removed in the near future."}}}, +"MarketingActivityUpdatePayload":{"o":{"f":{"marketingActivity":"MarketingActivity","redirectPath":"String","userErrors":"[UserError!]!"}}}, +"MarketingActivityUpsertExternalInput":{"i":{"adSpend":"MoneyInput","budget":"MarketingActivityBudgetInput","channelHandle":"String","end":"DateTime","hierarchyLevel":"MarketingActivityHierarchyLevel","marketingChannelType":"MarketingChannel!","parentRemoteId":"String","referringDomain":"String","remoteId":"String!","remotePreviewImageUrl":"URL","remoteUrl":"URL!","scheduledEnd":"DateTime","scheduledStart":"DateTime","start":"DateTime","status":"MarketingActivityExternalStatus!","tactic":"MarketingTactic!","title":"String!","urlParameterValue":"String","utm":"UTMInput"}}, +"MarketingActivityUpsertExternalPayload":{"o":{"f":{"marketingActivity":"MarketingActivity","userErrors":"[MarketingActivityUserError!]!"}}}, +"MarketingActivityUserError":{"o":{"f":{"code":"MarketingActivityUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MarketingActivityUserErrorCode":{"e":["INVALID","TAKEN","MARKETING_ACTIVITY_DOES_NOT_EXIST","MARKETING_ACTIVITY_WITH_REMOTE_ID_ALREADY_EXISTS","MARKETING_ACTIVITY_WITH_UTM_CAMPAIGN_ALREADY_EXISTS","MARKETING_ACTIVITY_WITH_URL_PARAMETER_VALUE_ALREADY_EXISTS","MARKETING_EVENT_DOES_NOT_EXIST","CURRENCY_CODE_MISMATCH_INPUT","MARKETING_ACTIVITY_CURRENCY_CODE_MISMATCH","DELETE_JOB_FAILED_TO_ENQUEUE","NON_HIERARCHIAL_REQUIRES_UTM_URL_PARAMETER","DELETE_JOB_ENQUEUED","ACTIVITY_NOT_EXTERNAL","IMMUTABLE_CHANNEL_HANDLE","IMMUTABLE_URL_PARAMETER","IMMUTABLE_UTM_PARAMETERS","IMMUTABLE_PARENT_ID","IMMUTABLE_HIERARCHY_LEVEL","INVALID_REMOTE_ID","INVALID_CHANNEL_HANDLE","INVALID_DELETE_ACTIVITY_EXTERNAL_ARGUMENTS","INVALID_DELETE_ENGAGEMENTS_ARGUMENTS","INVALID_MARKETING_ACTIVITY_EXTERNAL_ARGUMENTS","INVALID_MARKETING_ENGAGEMENT_ARGUMENTS","INVALID_MARKETING_ENGAGEMENT_ARGUMENT_MISSING","CANNOT_DELETE_ACTIVITY_WITH_CHILD_EVENTS","CANNOT_UPDATE_TACTIC_TO_STOREFRONT_APP","CANNOT_UPDATE_TACTIC_IF_ORIGINALLY_STOREFRONT_APP"]}, +"MarketingBudget":{"o":{"f":{"budgetType":"MarketingBudgetBudgetType!","total":"MoneyV2!"}}}, +"MarketingBudgetBudgetType":{"e":["DAILY","LIFETIME"]}, +"MarketingChannel":{"e":["SEARCH","DISPLAY","SOCIAL","EMAIL","REFERRAL"]}, +"MarketingEngagement":{"o":{"f":{"adSpend":"MoneyV2","allConversions":"Decimal","channelHandle":"String","clicksCount":"Int","commentsCount":"Int","complaintsCount":"Int","failsCount":"Int","favoritesCount":"Int","firstTimeCustomers":"Decimal","impressionsCount":"Int","isCumulative":"Boolean!","marketingActivity":"MarketingActivity","occurredOn":"Date!","orders":"Decimal","primaryConversions":"Decimal","returningCustomers":"Decimal","sales":"MoneyV2","sendsCount":"Int","sessionsCount":"Int","sharesCount":"Int","uniqueClicksCount":"Int","uniqueViewsCount":"Int","unsubscribesCount":"Int","utcOffset":"UtcOffset!","viewsCount":"Int"},"d":{"channelHandle":"Channel-level engagements are deprecated. Provide engagement metrics on a marketing activity using `marketingActivityId` or `remoteId` instead.","isCumulative":"Cumulative metrics are being phased out. Send non-cumulative engagement metrics instead (values aggregated over the single day indicated in `occurredOn`, with `isCumulative: false`). Existing activities that have been sending cumulative metrics can migrate to non-cumulative at any time."}}}, +"MarketingEngagementCreatePayload":{"o":{"f":{"marketingEngagement":"MarketingEngagement","userErrors":"[MarketingActivityUserError!]!"}}}, +"MarketingEngagementInput":{"i":{"f":{"adSpend":"MoneyInput","allConversions":"Decimal","clicksCount":"Int","commentsCount":"Int","complaintsCount":"Int","failsCount":"Int","favoritesCount":"Int","firstTimeCustomers":"Decimal","impressionsCount":"Int","isCumulative":"Boolean=","occurredOn":"Date!","orders":"Decimal","primaryConversions":"Decimal","returningCustomers":"Decimal","sales":"MoneyInput","sendsCount":"Int","sessionsCount":"Int","sharesCount":"Int","uniqueClicksCount":"Int","uniqueViewsCount":"Int","unsubscribesCount":"Int","utcOffset":"UtcOffset!","viewsCount":"Int"},"d":{"isCumulative":"Cumulative metrics are being phased out. Send non-cumulative engagement metrics instead (values aggregated over the single day indicated in `occurredOn`, with `isCumulative: false`). Existing activities that have been sending cumulative metrics can migrate to non-cumulative at any time."}}}, +"MarketingEngagementsDeletePayload":{"o":{"f":{"result":"String","userErrors":"[MarketingActivityUserError!]!"}}}, +"MarketingEvent":{"o":{"f":{"app":"App!","channel":"MarketingChannel","channelHandle":"String","description":"String","endedAt":"DateTime","id":"ID!","legacyResourceId":"UnsignedInt64!","manageUrl":"URL","marketingChannelType":"MarketingChannel","previewUrl":"URL","remoteId":"String","scheduledToEndAt":"DateTime","sourceAndMedium":"String!","startedAt":"DateTime!","targetTypeDisplayText":"String!","type":"MarketingTactic!","utmCampaign":"String","utmMedium":"String","utmSource":"String"},"t":["LegacyInteroperability","Node"],"d":{"channel":"Use `marketingChannelType` instead.","targetTypeDisplayText":"Use `sourceAndMedium` instead."}}}, +"MarketingEventConnection":{"o":{"f":{"edges":"[MarketingEventEdge!]!","nodes":"[MarketingEvent!]!","pageInfo":"PageInfo!"}}}, +"MarketingEventEdge":{"o":{"f":{"cursor":"String!","node":"MarketingEvent!"}}}, +"MarketingEventSortKeys":{"e":["ID","STARTED_AT"]}, +"MarketingTactic":{"e":["ABANDONED_CART","AD","AFFILIATE","LINK","LOYALTY","MESSAGE","NEWSLETTER","NOTIFICATION","POST","RETARGETING","TRANSACTIONAL","STOREFRONT_APP","SEO"]}, +"MarketsB2BEntitlement":{"o":{"f":{"catalogs":"MarketsCatalogsEntitlement!","enabled":"Boolean!"}}}, +"MarketsCatalogsEntitlement":{"o":{"f":{"enabled":"Boolean!","limit":"Int!"}}}, +"MarketsRegionsEntitlement":{"o":{"f":{"catalogs":"MarketsCatalogsEntitlement!","enabled":"Boolean!"}}}, +"MarketsResolvedValues":{"o":{"f":{"catalogs":["MarketCatalogConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"currencyCode":"CurrencyCode!","priceInclusivity":"ResolvedPriceInclusivity!","webPresences":["MarketWebPresenceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"MarketsRetailEntitlement":{"o":{"f":{"catalogs":"MarketsCatalogsEntitlement!","enabled":"Boolean!"}}}, +"MarketsSortKeys":{"e":["CREATED_AT","ID","MARKET_CONDITION_TYPES","MARKET_TYPE","NAME","STATUS","UPDATED_AT"]}, +"MarketsThemesEntitlement":{"o":{"f":{"enabled":"Boolean!"}}}, +"MarketsType":{"o":{"f":{"b2b":"MarketsB2BEntitlement!","regions":"MarketsRegionsEntitlement!","retail":"MarketsRetailEntitlement!","themes":"MarketsThemesEntitlement!"}}}, +"Media":{"n":{"f":{"alt":"String","id":"ID!","mediaContentType":"MediaContentType!","mediaErrors":"[MediaError!]!","mediaWarnings":"[MediaWarning!]!","preview":"MediaPreviewImage","status":"MediaStatus!"},"t":["ExternalVideo","MediaImage","Model3d","Video"]}}, +"MediaConnection":{"o":{"f":{"edges":"[MediaEdge!]!","nodes":"[Media!]!","pageInfo":"PageInfo!"}}}, +"MediaContentType":{"e":["VIDEO","EXTERNAL_VIDEO","MODEL_3D","IMAGE"]}, +"MediaEdge":{"o":{"f":{"cursor":"String!","node":"Media!"}}}, +"MediaError":{"o":{"f":{"code":"MediaErrorCode!","details":"String","message":"String!"}}}, +"MediaErrorCode":{"e":["UNKNOWN","INVALID_SIGNED_URL","IMAGE_DOWNLOAD_FAILURE","IMAGE_PROCESSING_FAILURE","MEDIA_TIMEOUT_ERROR","EXTERNAL_VIDEO_NOT_FOUND","EXTERNAL_VIDEO_UNLISTED","EXTERNAL_VIDEO_INVALID_ASPECT_RATIO","EXTERNAL_VIDEO_EMBED_DISABLED","EXTERNAL_VIDEO_EMBED_NOT_FOUND_OR_TRANSCODING","GENERIC_FILE_DOWNLOAD_FAILURE","GENERIC_FILE_INVALID_SIZE","VIDEO_METADATA_READ_ERROR","VIDEO_INVALID_FILETYPE_ERROR","VIDEO_MIN_WIDTH_ERROR","VIDEO_MAX_WIDTH_ERROR","VIDEO_MIN_HEIGHT_ERROR","VIDEO_MAX_HEIGHT_ERROR","VIDEO_MIN_DURATION_ERROR","VIDEO_MAX_DURATION_ERROR","VIDEO_VALIDATION_ERROR","MODEL3D_VALIDATION_ERROR","MODEL3D_THUMBNAIL_GENERATION_ERROR","MODEL3D_THUMBNAIL_REGENERATION_ERROR","MODEL3D_GLB_TO_USDZ_CONVERSION_ERROR","MODEL3D_GLB_OUTPUT_CREATION_ERROR","MODEL3D_PROCESSING_FAILURE","UNSUPPORTED_IMAGE_FILE_TYPE","INVALID_IMAGE_FILE_SIZE","INVALID_IMAGE_ASPECT_RATIO","INVALID_IMAGE_RESOLUTION","FILE_STORAGE_LIMIT_EXCEEDED","DUPLICATE_FILENAME_ERROR"]}, +"MediaHost":{"e":["YOUTUBE","VIMEO"]}, +"MediaImage":{"o":{"f":{"alt":"String","createdAt":"DateTime!","fileErrors":"[FileError!]!","fileStatus":"FileStatus!","id":"ID!","image":"Image","mediaContentType":"MediaContentType!","mediaErrors":"[MediaError!]!","mediaWarnings":"[MediaWarning!]!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"mimeType":"String","originalSource":"MediaImageOriginalSource","preview":"MediaPreviewImage","status":"MediaStatus!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"updatedAt":"DateTime!"},"t":["File","HasMetafields","HasPublishedTranslations","Media","Node"],"d":{"metafield":"No longer supported. Use metaobjects instead.","metafields":"No longer supported. Use metaobjects instead."}}}, +"MediaImageOriginalSource":{"o":{"f":{"fileSize":"Int","url":"URL"}}}, +"MediaPreviewImage":{"o":{"f":{"image":"Image","status":"MediaPreviewImageStatus!"}}}, +"MediaPreviewImageStatus":{"e":["UPLOADED","PROCESSING","READY","FAILED"]}, +"MediaStatus":{"e":["UPLOADED","PROCESSING","READY","FAILED"]}, +"MediaUserError":{"o":{"f":{"code":"MediaUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MediaUserErrorCode":{"e":["INVALID","BLANK","VIDEO_VALIDATION_ERROR","MODEL3D_VALIDATION_ERROR","VIDEO_THROTTLE_EXCEEDED","MODEL3D_THROTTLE_EXCEEDED","PRODUCT_MEDIA_LIMIT_EXCEEDED","SHOP_MEDIA_LIMIT_EXCEEDED","PRODUCT_DOES_NOT_EXIST","MEDIA_DOES_NOT_EXIST","MEDIA_DOES_NOT_EXIST_ON_PRODUCT","TOO_MANY_MEDIA_PER_INPUT_PAIR","MAXIMUM_VARIANT_MEDIA_PAIRS_EXCEEDED","INVALID_MEDIA_TYPE","PRODUCT_VARIANT_SPECIFIED_MULTIPLE_TIMES","PRODUCT_VARIANT_DOES_NOT_EXIST_ON_PRODUCT","NON_READY_MEDIA","PRODUCT_VARIANT_ALREADY_HAS_MEDIA","MEDIA_IS_NOT_ATTACHED_TO_VARIANT","MEDIA_CANNOT_BE_MODIFIED","PRODUCT_SUSPENDED","MISSING_ARGUMENTS"]}, +"MediaWarning":{"o":{"f":{"code":"MediaWarningCode!","message":"String"}}}, +"MediaWarningCode":{"e":["MODEL_SMALL_PHYSICAL_SIZE","MODEL_LARGE_PHYSICAL_SIZE","MODEL_PREVIEW_IMAGE_FAIL"]}, +"Menu":{"o":{"f":{"createdAt":"DateTime!","handle":"String!","id":"ID!","isDefault":"Boolean!","items":["[MenuItem!]!",{"limit":"Int"}],"title":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}]},"t":["HasPublishedTranslations","Node"]}}, +"MenuConnection":{"o":{"f":{"edges":"[MenuEdge!]!","nodes":"[Menu!]!","pageInfo":"PageInfo!"}}}, +"MenuCreatePayload":{"o":{"f":{"menu":"Menu","userErrors":"[MenuCreateUserError!]!"}}}, +"MenuCreateUserError":{"o":{"f":{"code":"MenuCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MenuCreateUserErrorCode":{"e":["NOT_FOUND","NESTING_TOO_DEEP"]}, +"MenuDeletePayload":{"o":{"f":{"deletedMenuId":"ID","userErrors":"[MenuDeleteUserError!]!"}}}, +"MenuDeleteUserError":{"o":{"f":{"code":"MenuDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MenuDeleteUserErrorCode":{"e":["MENU_DOES_NOT_EXIST","UNABLE_TO_DELETE_DEFAULT_MENU"]}, +"MenuEdge":{"o":{"f":{"cursor":"String!","node":"Menu!"}}}, +"MenuItem":{"o":{"f":{"id":"ID!","items":"[MenuItem!]!","resourceId":"ID","tags":"[String!]!","title":"String!","type":"MenuItemType!","url":"String"}}}, +"MenuItemCreateInput":{"i":{"items":"[MenuItemCreateInput!]","resourceId":"ID","tags":"[String!]","title":"String!","type":"MenuItemType!","url":"String"}}, +"MenuItemType":{"e":["FRONTPAGE","COLLECTION","COLLECTIONS","PRODUCT","CATALOG","PAGE","BLOG","ARTICLE","SEARCH","SHOP_POLICY","HTTP","METAOBJECT","CUSTOMER_ACCOUNT_PAGE"]}, +"MenuItemUpdateInput":{"i":{"id":"ID","items":"[MenuItemUpdateInput!]","resourceId":"ID","tags":"[String!]","title":"String!","type":"MenuItemType!","url":"String"}}, +"MenuSortKeys":{"e":["ID","TITLE","UPDATED_AT"]}, +"MenuUpdatePayload":{"o":{"f":{"menu":"Menu","userErrors":"[MenuUpdateUserError!]!"}}}, +"MenuUpdateUserError":{"o":{"f":{"code":"MenuUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MenuUpdateUserErrorCode":{"e":["NOT_FOUND","NESTING_TOO_DEEP"]}, +"MerchandiseDiscountClass":{"e":["PRODUCT","ORDER"]}, +"MerchantApprovalSignals":{"o":{"f":{"identityVerified":"Boolean!","verifiedByShopify":"Boolean!","verifiedByShopifyTier":"String!"}}}, +"Metafield":{"o":{"f":{"compareDigest":"String!","createdAt":"DateTime!","definition":"MetafieldDefinition","description":"String","id":"ID!","jsonValue":"JSON!","key":"String!","legacyResourceId":"UnsignedInt64!","namespace":"String!","owner":"HasMetafields!","ownerType":"MetafieldOwnerType!","reference":"MetafieldReference","references":["MetafieldReferenceConnection",{"after":"String","before":"String","first":"Int","last":"Int"}],"sizeInBytes":"Int!","translatable":"Boolean!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"type":"String!","updatedAt":"DateTime!","value":"String!"},"t":["HasCompareDigest","HasPublishedTranslations","LegacyInteroperability","Node"],"d":{"description":"This field will be removed in a future release. Use the `description` on the metafield definition instead."}}}, +"MetafieldAccess":{"o":{"f":{"admin":"MetafieldAdminAccess","customerAccount":"MetafieldCustomerAccountAccess!","storefront":"MetafieldStorefrontAccess"}}}, +"MetafieldAccessInput":{"i":{"admin":"MetafieldAdminAccessInput","customerAccount":"MetafieldCustomerAccountAccessInput","storefront":"MetafieldStorefrontAccessInput"}}, +"MetafieldAccessUpdateInput":{"i":{"admin":"MetafieldAdminAccessInput","customerAccount":"MetafieldCustomerAccountAccessInput","storefront":"MetafieldStorefrontAccessInput"}}, +"MetafieldAdminAccess":{"e":["PRIVATE","PUBLIC_READ","PUBLIC_READ_WRITE","MERCHANT_READ","MERCHANT_READ_WRITE"]}, +"MetafieldAdminAccessInput":{"e":["MERCHANT_READ","MERCHANT_READ_WRITE"]}, +"MetafieldCapabilities":{"o":{"f":{"adminFilterable":"MetafieldCapabilityAdminFilterable!","analyticsQueryable":"MetafieldCapabilityAnalyticsQueryable!","cartToOrderCopyable":"MetafieldCapabilityCartToOrderCopyable!","smartCollectionCondition":"MetafieldCapabilitySmartCollectionCondition!","uniqueValues":"MetafieldCapabilityUniqueValues!"}}}, +"MetafieldCapabilityAdminFilterable":{"o":{"f":{"eligible":"Boolean!","enabled":"Boolean!","status":"MetafieldDefinitionAdminFilterStatus!"}}}, +"MetafieldCapabilityAdminFilterableInput":{"i":{"enabled":"Boolean!"}}, +"MetafieldCapabilityAnalyticsQueryable":{"o":{"f":{"eligible":"Boolean!","enabled":"Boolean!"}}}, +"MetafieldCapabilityAnalyticsQueryableInput":{"i":{"enabled":"Boolean!"}}, +"MetafieldCapabilityCartToOrderCopyable":{"o":{"f":{"eligible":"Boolean!","enabled":"Boolean!"}}}, +"MetafieldCapabilityCartToOrderCopyableInput":{"i":{"enabled":"Boolean!"}}, +"MetafieldCapabilityCreateInput":{"i":{"adminFilterable":"MetafieldCapabilityAdminFilterableInput","analyticsQueryable":"MetafieldCapabilityAnalyticsQueryableInput","cartToOrderCopyable":"MetafieldCapabilityCartToOrderCopyableInput","smartCollectionCondition":"MetafieldCapabilitySmartCollectionConditionInput","uniqueValues":"MetafieldCapabilityUniqueValuesInput"}}, +"MetafieldCapabilitySmartCollectionCondition":{"o":{"f":{"eligible":"Boolean!","enabled":"Boolean!"}}}, +"MetafieldCapabilitySmartCollectionConditionInput":{"i":{"enabled":"Boolean!"}}, +"MetafieldCapabilityUniqueValues":{"o":{"f":{"eligible":"Boolean!","enabled":"Boolean!"}}}, +"MetafieldCapabilityUniqueValuesInput":{"i":{"enabled":"Boolean!"}}, +"MetafieldCapabilityUpdateInput":{"i":{"adminFilterable":"MetafieldCapabilityAdminFilterableInput","analyticsQueryable":"MetafieldCapabilityAnalyticsQueryableInput","cartToOrderCopyable":"MetafieldCapabilityCartToOrderCopyableInput","smartCollectionCondition":"MetafieldCapabilitySmartCollectionConditionInput","uniqueValues":"MetafieldCapabilityUniqueValuesInput"}}, +"MetafieldConnection":{"o":{"f":{"edges":"[MetafieldEdge!]!","nodes":"[Metafield!]!","pageInfo":"PageInfo!"}}}, +"MetafieldCustomerAccountAccess":{"e":["READ_WRITE","READ","NONE"]}, +"MetafieldCustomerAccountAccessInput":{"e":["READ_WRITE","READ","NONE"]}, +"MetafieldDefinition":{"o":{"f":{"access":"MetafieldAccess!","capabilities":"MetafieldCapabilities!","constraints":"MetafieldDefinitionConstraints","description":"String","id":"ID!","key":"String!","metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","validationStatus":"MetafieldValidationStatus="}],"metafieldsCount":["Int!",{"validationStatus":"MetafieldValidationStatus"}],"name":"String!","namespace":"String!","ownerType":"MetafieldOwnerType!","pinnedPosition":"Int","standardTemplate":"StandardMetafieldDefinitionTemplate","type":"MetafieldDefinitionType!","useAsCollectionCondition":"Boolean!","validationStatus":"MetafieldDefinitionValidationStatus!","validations":"[MetafieldDefinitionValidation!]!"},"t":["Node"]}}, +"MetafieldDefinitionAdminFilterStatus":{"e":["NOT_FILTERABLE","IN_PROGRESS","FILTERABLE","FAILED"]}, +"MetafieldDefinitionConnection":{"o":{"f":{"edges":"[MetafieldDefinitionEdge!]!","nodes":"[MetafieldDefinition!]!","pageInfo":"PageInfo!"}}}, +"MetafieldDefinitionConstraintStatus":{"e":["CONSTRAINED_AND_UNCONSTRAINED","CONSTRAINED_ONLY","UNCONSTRAINED_ONLY"]}, +"MetafieldDefinitionConstraintSubtypeIdentifier":{"i":{"key":"String!","value":"String!"}}, +"MetafieldDefinitionConstraintValue":{"o":{"f":{"value":"String!"}}}, +"MetafieldDefinitionConstraintValueConnection":{"o":{"f":{"edges":"[MetafieldDefinitionConstraintValueEdge!]!","nodes":"[MetafieldDefinitionConstraintValue!]!","pageInfo":"PageInfo!"}}}, +"MetafieldDefinitionConstraintValueEdge":{"o":{"f":{"cursor":"String!","node":"MetafieldDefinitionConstraintValue!"}}}, +"MetafieldDefinitionConstraintValueUpdateInput":{"i":{"create":"String","delete":"String"}}, +"MetafieldDefinitionConstraints":{"o":{"f":{"key":"String","values":["MetafieldDefinitionConstraintValueConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"MetafieldDefinitionConstraintsInput":{"i":{"key":"String!","values":"[String!]!"}}, +"MetafieldDefinitionConstraintsUpdatesInput":{"i":{"key":"String","values":"[MetafieldDefinitionConstraintValueUpdateInput!]"}}, +"MetafieldDefinitionCreatePayload":{"o":{"f":{"createdDefinition":"MetafieldDefinition","userErrors":"[MetafieldDefinitionCreateUserError!]!"}}}, +"MetafieldDefinitionCreateUserError":{"o":{"f":{"code":"MetafieldDefinitionCreateUserErrorCode","elementIndex":"Int","elementKey":"String","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MetafieldDefinitionCreateUserErrorCode":{"e":["INVALID","INCLUSION","PRESENT","TAKEN","TOO_LONG","TOO_SHORT","BLANK","CAPABILITY_REQUIRED_BUT_DISABLED","RESOURCE_TYPE_LIMIT_EXCEEDED","RESOURCE_TYPE_LIMIT_EXCEEDED_BY_APP","LIMIT_EXCEEDED","INVALID_OPTION","DUPLICATE_OPTION","RESERVED_NAMESPACE_KEY","PINNED_LIMIT_REACHED","UNSTRUCTURED_ALREADY_EXISTS","UNSUPPORTED_PINNING","INVALID_CHARACTER","TYPE_NOT_ALLOWED_FOR_CONDITIONS","OWNER_TYPE_LIMIT_EXCEEDED_FOR_AUTOMATED_COLLECTIONS","OWNER_TYPE_LIMIT_EXCEEDED_FOR_USE_AS_ADMIN_FILTERS","INVALID_CONSTRAINTS","INVALID_INPUT_COMBINATION","INVALID_CAPABILITY","ADMIN_ACCESS_INPUT_NOT_ALLOWED"]}, +"MetafieldDefinitionDeletePayload":{"o":{"f":{"deletedDefinition":"MetafieldDefinitionIdentifier","deletedDefinitionId":"ID","userErrors":"[MetafieldDefinitionDeleteUserError!]!"}}}, +"MetafieldDefinitionDeleteUserError":{"o":{"f":{"code":"MetafieldDefinitionDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MetafieldDefinitionDeleteUserErrorCode":{"e":["PRESENT","NOT_FOUND","INTERNAL_ERROR","ID_TYPE_DELETION_ERROR","REFERENCE_TYPE_DELETION_ERROR","RESERVED_NAMESPACE_ORPHANED_METAFIELDS","METAFIELD_DEFINITION_IN_USE","APP_CONFIG_MANAGED","STANDARD_METAFIELD_DEFINITION_DEPENDENT_ON_APP","DISALLOWED_OWNER_TYPE"]}, +"MetafieldDefinitionEdge":{"o":{"f":{"cursor":"String!","node":"MetafieldDefinition!"}}}, +"MetafieldDefinitionIdentifier":{"o":{"f":{"key":"String!","namespace":"String!","ownerType":"MetafieldOwnerType!"}}}, +"MetafieldDefinitionIdentifierInput":{"i":{"key":"String!","namespace":"String","ownerType":"MetafieldOwnerType!"}}, +"MetafieldDefinitionInput":{"i":{"f":{"access":"MetafieldAccessInput","capabilities":"MetafieldCapabilityCreateInput","constraints":"MetafieldDefinitionConstraintsInput","description":"String","key":"String!","name":"String!","namespace":"String","ownerType":"MetafieldOwnerType!","pin":"Boolean=","type":"String!","useAsCollectionCondition":"Boolean=","validations":"[MetafieldDefinitionValidationInput!]"},"d":{"useAsCollectionCondition":"Use `smartCollectionCondition` instead."}}}, +"MetafieldDefinitionPinPayload":{"o":{"f":{"pinnedDefinition":"MetafieldDefinition","userErrors":"[MetafieldDefinitionPinUserError!]!"}}}, +"MetafieldDefinitionPinUserError":{"o":{"f":{"code":"MetafieldDefinitionPinUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MetafieldDefinitionPinUserErrorCode":{"e":["NOT_FOUND","PINNED_LIMIT_REACHED","ALREADY_PINNED","INTERNAL_ERROR","UNSUPPORTED_PINNING","DISALLOWED_OWNER_TYPE"]}, +"MetafieldDefinitionPinnedStatus":{"e":["ANY","PINNED","UNPINNED"]}, +"MetafieldDefinitionSortKeys":{"e":["ID","NAME","PINNED_POSITION","RELEVANCE"]}, +"MetafieldDefinitionSupportedValidation":{"o":{"f":{"name":"String!","type":"String!"}}}, +"MetafieldDefinitionType":{"o":{"f":{"category":"String!","name":"String!","supportedValidations":"[MetafieldDefinitionSupportedValidation!]!","supportsDefinitionMigrations":"Boolean!","valueType":"MetafieldValueType!"},"d":{"valueType":"`valueType` is deprecated and `name` should be used for type information."}}}, +"MetafieldDefinitionUnpinPayload":{"o":{"f":{"unpinnedDefinition":"MetafieldDefinition","userErrors":"[MetafieldDefinitionUnpinUserError!]!"}}}, +"MetafieldDefinitionUnpinUserError":{"o":{"f":{"code":"MetafieldDefinitionUnpinUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MetafieldDefinitionUnpinUserErrorCode":{"e":["NOT_FOUND","NOT_PINNED","INTERNAL_ERROR","APP_CONFIG_MANAGED","DISALLOWED_OWNER_TYPE"]}, +"MetafieldDefinitionUpdateInput":{"i":{"f":{"access":"MetafieldAccessUpdateInput","capabilities":"MetafieldCapabilityUpdateInput","constraintsUpdates":"MetafieldDefinitionConstraintsUpdatesInput","description":"String","key":"String!","name":"String","namespace":"String","ownerType":"MetafieldOwnerType!","pin":"Boolean","useAsCollectionCondition":"Boolean=","validations":"[MetafieldDefinitionValidationInput!]"},"d":{"useAsCollectionCondition":"Use `smartCollectionCondition` instead."}}}, +"MetafieldDefinitionUpdatePayload":{"o":{"f":{"updatedDefinition":"MetafieldDefinition","userErrors":"[MetafieldDefinitionUpdateUserError!]!","validationJob":"Job"}}}, +"MetafieldDefinitionUpdateUserError":{"o":{"f":{"code":"MetafieldDefinitionUpdateUserErrorCode","elementIndex":"Int","elementKey":"String","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MetafieldDefinitionUpdateUserErrorCode":{"e":["PRESENT","TOO_LONG","BLANK","INVALID","NOT_FOUND","INVALID_INPUT","CAPABILITY_REQUIRED_BUT_DISABLED","PINNED_LIMIT_REACHED","INTERNAL_ERROR","UNSUPPORTED_PINNING","INVALID_OPTION","DUPLICATE_OPTION","TYPE_NOT_ALLOWED_FOR_CONDITIONS","METAFIELD_DEFINITION_IN_USE","OWNER_TYPE_LIMIT_EXCEEDED_FOR_AUTOMATED_COLLECTIONS","OWNER_TYPE_LIMIT_EXCEEDED_FOR_USE_AS_ADMIN_FILTERS","METAOBJECT_DEFINITION_CHANGED","DISALLOWED_OWNER_TYPE","INVALID_INPUT_COMBINATION","INVALID_CONSTRAINTS","INVALID_CAPABILITY","CAPABILITY_CANNOT_BE_DISABLED","ADMIN_ACCESS_INPUT_NOT_ALLOWED","APP_CONFIG_MANAGED"]}, +"MetafieldDefinitionValidation":{"o":{"f":{"name":"String!","type":"String!","value":"String"}}}, +"MetafieldDefinitionValidationInput":{"i":{"name":"String!","value":"String!"}}, +"MetafieldDefinitionValidationStatus":{"e":["ALL_VALID","IN_PROGRESS","SOME_INVALID"]}, +"MetafieldEdge":{"o":{"f":{"cursor":"String!","node":"Metafield!"}}}, +"MetafieldIdentifier":{"o":{"f":{"key":"String!","namespace":"String!","ownerId":"ID!"}}}, +"MetafieldIdentifierInput":{"i":{"key":"String!","namespace":"String!","ownerId":"ID!"}}, +"MetafieldInput":{"i":{"id":"ID","key":"String","namespace":"String","type":"String","value":"String"}}, +"MetafieldOwnerType":{"e":{"v":["API_PERMISSION","COMPANY","COMPANY_LOCATION","PAYMENT_CUSTOMIZATION","VALIDATION","CUSTOMER","DELIVERY_CUSTOMIZATION","DRAFTORDER","GIFT_CARD_TRANSACTION","TRANSFER","MARKET","CARTTRANSFORM","COLLECTION","MEDIA_IMAGE","PRODUCT","PRODUCTVARIANT","SELLING_PLAN","ARTICLE","BLOG","PAGE","FULFILLMENT_CONSTRAINT_RULE","ORDER_ROUTING_LOCATION_RULE","DISCOUNT","ORDER","LOCATION","SHOP"],"d":{"MEDIA_IMAGE":"`MEDIA_IMAGE` is deprecated."}}}, +"MetafieldReference":{"u":["Article","Collection","Company","Customer","GenericFile","MediaImage","Metaobject","Model3d","Order","Page","Product","ProductVariant","TaxonomyValue","Video"]}, +"MetafieldReferenceConnection":{"o":{"f":{"edges":"[MetafieldReferenceEdge!]!","nodes":"[MetafieldReference]!","pageInfo":"PageInfo!"}}}, +"MetafieldReferenceEdge":{"o":{"f":{"cursor":"String!","node":"MetafieldReference"}}}, +"MetafieldReferencer":{"u":["AppInstallation","Article","Blog","Collection","Company","CompanyLocation","Customer","DeliveryCustomization","DiscountAutomaticNode","DiscountCodeNode","DiscountNode","DraftOrder","FulfillmentOrder","Location","Market","Metaobject","Order","Page","PaymentCustomization","Product","ProductVariant","Shop"]}, +"MetafieldRelation":{"o":{"f":{"key":"String!","name":"String!","namespace":"String!","referencer":"MetafieldReferencer!","target":"MetafieldReference!"},"d":{"target":"No longer supported. Access the object directly instead."}}}, +"MetafieldRelationConnection":{"o":{"f":{"edges":"[MetafieldRelationEdge!]!","nodes":"[MetafieldRelation!]!","pageInfo":"PageInfo!"}}}, +"MetafieldRelationEdge":{"o":{"f":{"cursor":"String!","node":"MetafieldRelation!"}}}, +"MetafieldStorefrontAccess":{"e":["PUBLIC_READ","NONE"]}, +"MetafieldStorefrontAccessInput":{"e":["PUBLIC_READ","NONE"]}, +"MetafieldValidationStatus":{"e":["ANY","VALID","INVALID"]}, +"MetafieldValueType":{"e":["STRING","INTEGER","JSON_STRING","BOOLEAN"]}, +"MetafieldsDeletePayload":{"o":{"f":{"deletedMetafields":"[MetafieldIdentifier]","userErrors":"[UserError!]!"}}}, +"MetafieldsSetInput":{"i":{"compareDigest":"String","key":"String!","namespace":"String","ownerId":"ID!","type":"String","value":"String!"}}, +"MetafieldsSetPayload":{"o":{"f":{"metafields":"[Metafield!]","userErrors":"[MetafieldsSetUserError!]!"}}}, +"MetafieldsSetUserError":{"o":{"f":{"code":"MetafieldsSetUserErrorCode","elementIndex":"Int","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MetafieldsSetUserErrorCode":{"e":["CAPABILITY_VIOLATION","STALE_OBJECT","INVALID_COMPARE_DIGEST","INVALID_TYPE","INVALID_VALUE","APP_NOT_AUTHORIZED","INCLUSION","TAKEN","PRESENT","BLANK","TOO_LONG","TOO_SHORT","LESS_THAN_OR_EQUAL_TO","INVALID","INTERNAL_ERROR"]}, +"Metaobject":{"o":{"f":{"capabilities":"MetaobjectCapabilityData!","createdAt":"DateTime!","createdBy":"App!","createdByApp":"App!","createdByStaff":"StaffMember","definition":"MetaobjectDefinition!","displayName":"String!","field":["MetaobjectField",{"key":"String!"}],"fields":"[MetaobjectField!]!","handle":"String!","id":"ID!","referencedBy":["MetafieldRelationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"staffMember":"StaffMember","thumbnailField":"MetaobjectField","type":"String!","updatedAt":"DateTime!","values":"JSON!"},"t":["Node"],"d":{"staffMember":"Use `createdByStaff` instead."}}}, +"MetaobjectAccess":{"o":{"f":{"admin":"MetaobjectAdminAccess!","customerAccount":"MetaobjectCustomerAccountAccess!","storefront":"MetaobjectStorefrontAccess!"}}}, +"MetaobjectAccessInput":{"i":{"admin":"MetaobjectAdminAccessInput","customerAccount":"MetaobjectCustomerAccountAccess","storefront":"MetaobjectStorefrontAccess"}}, +"MetaobjectAdminAccess":{"e":{"v":["PRIVATE","MERCHANT_READ","MERCHANT_READ_WRITE","PUBLIC_READ","PUBLIC_READ_WRITE"],"d":{"PRIVATE":"Use MERCHANT_READ instead. Removed in API version 2027-01.","PUBLIC_READ":"Use MERCHANT_READ instead. Removed in API version 2027-01."}}}, +"MetaobjectAdminAccessInput":{"e":["MERCHANT_READ","MERCHANT_READ_WRITE"]}, +"MetaobjectBulkDeletePayload":{"o":{"f":{"job":"Job","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectBulkDeleteWhereCondition":{"i":{"ids":"[ID!]","type":"String"}}, +"MetaobjectCapabilities":{"o":{"f":{"onlineStore":"MetaobjectCapabilitiesOnlineStore","publishable":"MetaobjectCapabilitiesPublishable!","renderable":"MetaobjectCapabilitiesRenderable","translatable":"MetaobjectCapabilitiesTranslatable!"}}}, +"MetaobjectCapabilitiesOnlineStore":{"o":{"f":{"data":"MetaobjectCapabilityDefinitionDataOnlineStore","enabled":"Boolean!"}}}, +"MetaobjectCapabilitiesPublishable":{"o":{"f":{"enabled":"Boolean!"}}}, +"MetaobjectCapabilitiesRenderable":{"o":{"f":{"data":"MetaobjectCapabilityDefinitionDataRenderable","enabled":"Boolean!"}}}, +"MetaobjectCapabilitiesTranslatable":{"o":{"f":{"enabled":"Boolean!"}}}, +"MetaobjectCapabilityCreateInput":{"i":{"onlineStore":"MetaobjectCapabilityOnlineStoreInput","publishable":"MetaobjectCapabilityPublishableInput","renderable":"MetaobjectCapabilityRenderableInput","translatable":"MetaobjectCapabilityTranslatableInput"}}, +"MetaobjectCapabilityData":{"o":{"f":{"onlineStore":"MetaobjectCapabilityDataOnlineStore","publishable":"MetaobjectCapabilityDataPublishable"}}}, +"MetaobjectCapabilityDataInput":{"i":{"onlineStore":"MetaobjectCapabilityDataOnlineStoreInput","publishable":"MetaobjectCapabilityDataPublishableInput"}}, +"MetaobjectCapabilityDataOnlineStore":{"o":{"f":{"templateSuffix":"String"}}}, +"MetaobjectCapabilityDataOnlineStoreInput":{"i":{"templateSuffix":"String"}}, +"MetaobjectCapabilityDataPublishable":{"o":{"f":{"status":"MetaobjectStatus!"}}}, +"MetaobjectCapabilityDataPublishableInput":{"i":{"status":"MetaobjectStatus!"}}, +"MetaobjectCapabilityDefinitionDataOnlineStore":{"o":{"f":{"canCreateRedirects":"Boolean!","urlHandle":"String!"}}}, +"MetaobjectCapabilityDefinitionDataOnlineStoreInput":{"i":{"createRedirects":"Boolean=","urlHandle":"String!"}}, +"MetaobjectCapabilityDefinitionDataRenderable":{"o":{"f":{"metaDescriptionKey":"String","metaTitleKey":"String"}}}, +"MetaobjectCapabilityDefinitionDataRenderableInput":{"i":{"metaDescriptionKey":"String","metaTitleKey":"String"}}, +"MetaobjectCapabilityOnlineStoreInput":{"i":{"data":"MetaobjectCapabilityDefinitionDataOnlineStoreInput","enabled":"Boolean!"}}, +"MetaobjectCapabilityPublishableInput":{"i":{"enabled":"Boolean!"}}, +"MetaobjectCapabilityRenderableInput":{"i":{"data":"MetaobjectCapabilityDefinitionDataRenderableInput","enabled":"Boolean!"}}, +"MetaobjectCapabilityTranslatableInput":{"i":{"enabled":"Boolean!"}}, +"MetaobjectCapabilityType":{"e":["PUBLISHABLE","TRANSLATABLE","RENDERABLE","ONLINE_STORE"]}, +"MetaobjectCapabilityUpdateInput":{"i":{"onlineStore":"MetaobjectCapabilityOnlineStoreInput","publishable":"MetaobjectCapabilityPublishableInput","renderable":"MetaobjectCapabilityRenderableInput","translatable":"MetaobjectCapabilityTranslatableInput"}}, +"MetaobjectConnection":{"o":{"f":{"edges":"[MetaobjectEdge!]!","nodes":"[Metaobject!]!","pageInfo":"PageInfo!"}}}, +"MetaobjectCreateInput":{"i":{"capabilities":"MetaobjectCapabilityDataInput","fields":"[MetaobjectFieldInput!]","handle":"String","type":"String!","values":"JSON"}}, +"MetaobjectCreatePayload":{"o":{"f":{"metaobject":"Metaobject","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectCustomerAccountAccess":{"e":["NONE","READ"]}, +"MetaobjectDefinition":{"o":{"f":{"access":"MetaobjectAccess!","capabilities":"MetaobjectCapabilities!","createdAt":"DateTime!","createdByApp":"App!","createdByStaff":"StaffMember","description":"String","displayNameKey":"String","fieldDefinitions":"[MetaobjectFieldDefinition!]!","hasThumbnailField":"Boolean!","id":"ID!","metaobjects":["MetaobjectConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"metaobjectsCount":"Int!","name":"String!","standardTemplate":"StandardMetaobjectDefinitionTemplate","type":"String!","updatedAt":"DateTime!"},"t":["Node"]}}, +"MetaobjectDefinitionConnection":{"o":{"f":{"edges":"[MetaobjectDefinitionEdge!]!","nodes":"[MetaobjectDefinition!]!","pageInfo":"PageInfo!"}}}, +"MetaobjectDefinitionCreateInput":{"i":{"access":"MetaobjectAccessInput","capabilities":"MetaobjectCapabilityCreateInput","description":"String","displayNameKey":"String","fieldDefinitions":"[MetaobjectFieldDefinitionCreateInput!]","name":"String","type":"String!"}}, +"MetaobjectDefinitionCreatePayload":{"o":{"f":{"metaobjectDefinition":"MetaobjectDefinition","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectDefinitionDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectDefinitionEdge":{"o":{"f":{"cursor":"String!","node":"MetaobjectDefinition!"}}}, +"MetaobjectDefinitionUpdateInput":{"i":{"access":"MetaobjectAccessInput","capabilities":"MetaobjectCapabilityUpdateInput","description":"String","displayNameKey":"String","fieldDefinitions":"[MetaobjectFieldDefinitionOperationInput!]","name":"String","resetFieldOrder":"Boolean="}}, +"MetaobjectDefinitionUpdatePayload":{"o":{"f":{"metaobjectDefinition":"MetaobjectDefinition","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectEdge":{"o":{"f":{"cursor":"String!","node":"Metaobject!"}}}, +"MetaobjectField":{"o":{"f":{"definition":"MetaobjectFieldDefinition!","jsonValue":"JSON","key":"String!","reference":"MetafieldReference","references":["MetafieldReferenceConnection",{"after":"String","before":"String","first":"Int","last":"Int"}],"thumbnail":"MetaobjectThumbnail","type":"String!","value":"String"}}}, +"MetaobjectFieldCapabilityAdminFilterable":{"o":{"f":{"eligible":"Boolean!","enabled":"Boolean!"}}}, +"MetaobjectFieldCapabilityAdminFilterableInput":{"i":{"enabled":"Boolean!"}}, +"MetaobjectFieldDefinition":{"o":{"f":{"capabilities":"MetaobjectFieldDefinitionCapabilities!","description":"String","key":"String!","name":"String!","required":"Boolean!","type":"MetafieldDefinitionType!","validations":"[MetafieldDefinitionValidation!]!"}}}, +"MetaobjectFieldDefinitionCapabilities":{"o":{"f":{"adminFilterable":"MetaobjectFieldCapabilityAdminFilterable!"}}}, +"MetaobjectFieldDefinitionCapabilityCreateInput":{"i":{"adminFilterable":"MetaobjectFieldCapabilityAdminFilterableInput"}}, +"MetaobjectFieldDefinitionCreateInput":{"i":{"capabilities":"MetaobjectFieldDefinitionCapabilityCreateInput","description":"String","key":"String!","name":"String","required":"Boolean=","type":"String!","validations":"[MetafieldDefinitionValidationInput!]"}}, +"MetaobjectFieldDefinitionDeleteInput":{"i":{"key":"String!"}}, +"MetaobjectFieldDefinitionOperationInput":{"i":{"create":"MetaobjectFieldDefinitionCreateInput","delete":"MetaobjectFieldDefinitionDeleteInput","update":"MetaobjectFieldDefinitionUpdateInput"}}, +"MetaobjectFieldDefinitionUpdateInput":{"i":{"capabilities":"MetaobjectFieldDefinitionCapabilityCreateInput","description":"String","key":"String!","name":"String","required":"Boolean","validations":"[MetafieldDefinitionValidationInput!]"}}, +"MetaobjectFieldInput":{"i":{"key":"String!","value":"String!"}}, +"MetaobjectHandleInput":{"i":{"handle":"String!","type":"String!"}}, +"MetaobjectStatus":{"e":["DRAFT","ACTIVE"]}, +"MetaobjectStorefrontAccess":{"e":["NONE","PUBLIC_READ"]}, +"MetaobjectThumbnail":{"o":{"f":{"file":"File","hex":"String"}}}, +"MetaobjectUpdateInput":{"i":{"capabilities":"MetaobjectCapabilityDataInput","fields":"[MetaobjectFieldInput!]","handle":"String","redirectNewHandle":"Boolean=","values":"JSON"}}, +"MetaobjectUpdatePayload":{"o":{"f":{"metaobject":"Metaobject","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectUpsertInput":{"i":{"capabilities":"MetaobjectCapabilityDataInput","fields":"[MetaobjectFieldInput!]","handle":"String"}}, +"MetaobjectUpsertPayload":{"o":{"f":{"metaobject":"Metaobject","userErrors":"[MetaobjectUserError!]!"}}}, +"MetaobjectUserError":{"o":{"f":{"code":"MetaobjectUserErrorCode","elementIndex":"Int","elementKey":"String","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MetaobjectUserErrorCode":{"e":["INVALID","INCLUSION","TAKEN","TOO_LONG","TOO_SHORT","PRESENT","BLANK","INVALID_TYPE","INVALID_VALUE","INVALID_OPTION","DUPLICATE_FIELD_INPUT","UNDEFINED_OBJECT_TYPE","UNDEFINED_OBJECT_FIELD","OBJECT_FIELD_TAKEN","OBJECT_FIELD_REQUIRED","RECORD_NOT_FOUND","INTERNAL_ERROR","MAX_DEFINITIONS_EXCEEDED","MAX_OBJECTS_EXCEEDED","INPUT_LIMIT_EXCEEDED","IMMUTABLE","NOT_AUTHORIZED","RESERVED_NAME","DISPLAY_NAME_CONFLICT","ADMIN_ACCESS_INPUT_NOT_ALLOWED","APP_CONFIG_MANAGED","STANDARD_METAOBJECT_DEFINITION_DEPENDENT_ON_APP","CAPABILITY_NOT_ENABLED","URL_HANDLE_TAKEN","URL_HANDLE_INVALID","URL_HANDLE_BLANK","FIELD_TYPE_INVALID","MISSING_REQUIRED_KEYS","REFERENCE_EXISTS_ERROR"]}, +"MethodDefinitionSortKeys":{"e":["ID","RATE_PROVIDER_TYPE"]}, +"MobilePlatformApplication":{"u":["AndroidApplication","AppleApplication"]}, +"MobilePlatformApplicationConnection":{"o":{"f":{"edges":"[MobilePlatformApplicationEdge!]!","nodes":"[MobilePlatformApplication!]!","pageInfo":"PageInfo!"}}}, +"MobilePlatformApplicationCreateAndroidInput":{"i":{"appLinksEnabled":"Boolean!","applicationId":"String","sha256CertFingerprints":"[String!]!"}}, +"MobilePlatformApplicationCreateAppleInput":{"i":{"appClipApplicationId":"String","appClipsEnabled":"Boolean","appId":"String","sharedWebCredentialsEnabled":"Boolean!","universalLinksEnabled":"Boolean!"}}, +"MobilePlatformApplicationCreateInput":{"i":{"f":{"android":"MobilePlatformApplicationCreateAndroidInput","apple":"MobilePlatformApplicationCreateAppleInput"},"o":true}}, +"MobilePlatformApplicationCreatePayload":{"o":{"f":{"mobilePlatformApplication":"MobilePlatformApplication","userErrors":"[MobilePlatformApplicationUserError!]!"}}}, +"MobilePlatformApplicationDeletePayload":{"o":{"f":{"deletedMobilePlatformApplicationId":"ID","userErrors":"[MobilePlatformApplicationUserError!]!"}}}, +"MobilePlatformApplicationEdge":{"o":{"f":{"cursor":"String!","node":"MobilePlatformApplication!"}}}, +"MobilePlatformApplicationUpdateAndroidInput":{"i":{"appLinksEnabled":"Boolean","applicationId":"String","sha256CertFingerprints":"[String!]"}}, +"MobilePlatformApplicationUpdateAppleInput":{"i":{"appClipApplicationId":"String","appClipsEnabled":"Boolean","appId":"String","sharedWebCredentialsEnabled":"Boolean","universalLinksEnabled":"Boolean"}}, +"MobilePlatformApplicationUpdateInput":{"i":{"f":{"android":"MobilePlatformApplicationUpdateAndroidInput","apple":"MobilePlatformApplicationUpdateAppleInput"},"o":true}}, +"MobilePlatformApplicationUpdatePayload":{"o":{"f":{"mobilePlatformApplication":"MobilePlatformApplication","userErrors":"[MobilePlatformApplicationUserError!]!"}}}, +"MobilePlatformApplicationUserError":{"o":{"f":{"code":"MobilePlatformApplicationUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"MobilePlatformApplicationUserErrorCode":{"e":["INVALID","NOT_FOUND","TOO_LONG"]}, +"Model3d":{"o":{"f":{"alt":"String","boundingBox":"Model3dBoundingBox","createdAt":"DateTime!","fileErrors":"[FileError!]!","fileStatus":"FileStatus!","filename":"String!","id":"ID!","mediaContentType":"MediaContentType!","mediaErrors":"[MediaError!]!","mediaWarnings":"[MediaWarning!]!","originalSource":"Model3dSource","preview":"MediaPreviewImage","sources":"[Model3dSource!]!","status":"MediaStatus!","updatedAt":"DateTime!"},"t":["File","Media","Node"]}}, +"Model3dBoundingBox":{"o":{"f":{"size":"Vector3!"}}}, +"Model3dSource":{"o":{"f":{"filesize":"Int!","format":"String!","mimeType":"String!","url":"String!"}}}, +"Money":"s", +"MoneyBag":{"o":{"f":{"presentmentMoney":"MoneyV2!","shopMoney":"MoneyV2!"}}}, +"MoneyBagInput":{"i":{"presentmentMoney":"MoneyInput","shopMoney":"MoneyInput!"}}, +"MoneyInput":{"i":{"amount":"Decimal!","currencyCode":"CurrencyCode!"}}, +"MoneyV2":{"o":{"f":{"amount":"Decimal!","currencyCode":"CurrencyCode!"}}}, +"MoveInput":{"i":{"id":"ID!","newPosition":"UnsignedInt64!"}}, +"Mutation":{"o":{"f":{"abandonmentEmailStateUpdate":["AbandonmentEmailStateUpdatePayload",{"emailSentAt":"DateTime","emailState":"AbandonmentEmailState!","emailStateChangeReason":"String","id":"ID!"}],"abandonmentUpdateActivitiesDeliveryStatuses":["AbandonmentUpdateActivitiesDeliveryStatusesPayload",{"abandonmentId":"ID!","deliveredAt":"DateTime","deliveryStatus":"AbandonmentDeliveryState!","deliveryStatusChangeReason":"String","marketingActivityId":"ID!"}],"analyticsAnnotationCreate":["AnalyticsAnnotationCreatePayload",{"input":"AnalyticsAnnotationCreateInput!"}],"analyticsAnnotationDelete":["AnalyticsAnnotationDeletePayload",{"id":"ID!"}],"analyticsAnnotationUpdate":["AnalyticsAnnotationUpdatePayload",{"id":"ID!","input":"AnalyticsAnnotationUpdateInput!"}],"analyticsTargetCreate":["AnalyticsTargetCreatePayload",{"input":"AnalyticsTargetCreateInput!"}],"analyticsTargetUpdate":["AnalyticsTargetUpdatePayload",{"id":"ID!","input":"AnalyticsTargetUpdateInput!"}],"analyticsTargetsDelete":["AnalyticsTargetsDeletePayload",{"ids":"[ID!]!"}],"appPurchaseOneTimeCreate":["AppPurchaseOneTimeCreatePayload",{"name":"String!","price":"MoneyInput!","returnUrl":"URL!","test":"Boolean="}],"appRevokeAccessScopes":["AppRevokeAccessScopesPayload",{"scopes":"[String!]!"}],"appSubscriptionCancel":["AppSubscriptionCancelPayload",{"id":"ID!","prorate":"Boolean="}],"appSubscriptionCreate":["AppSubscriptionCreatePayload",{"lineItems":"[AppSubscriptionLineItemInput!]!","name":"String!","replacementBehavior":"AppSubscriptionReplacementBehavior=","returnUrl":"URL!","test":"Boolean=","trialDays":"Int"}],"appSubscriptionLineItemUpdate":["AppSubscriptionLineItemUpdatePayload",{"cappedAmount":"MoneyInput!","id":"ID!"}],"appSubscriptionTrialExtend":["AppSubscriptionTrialExtendPayload",{"days":"Int!","id":"ID!"}],"appUninstall":"AppUninstallPayload","appUsageRecordCreate":["AppUsageRecordCreatePayload",{"description":"String!","idempotencyKey":"String","price":"MoneyInput!","subscriptionLineItemId":"ID!"}],"articleCreate":["ArticleCreatePayload",{"article":"ArticleCreateInput!","blog":"ArticleBlogInput"}],"articleDelete":["ArticleDeletePayload",{"id":"ID!"}],"articleUpdate":["ArticleUpdatePayload",{"article":"ArticleUpdateInput!","blog":"ArticleBlogInput","id":"ID!"}],"backupRegionUpdate":["BackupRegionUpdatePayload",{"region":"BackupRegionUpdateInput"}],"blogCreate":["BlogCreatePayload",{"blog":"BlogCreateInput!"}],"blogDelete":["BlogDeletePayload",{"id":"ID!"}],"blogUpdate":["BlogUpdatePayload",{"blog":"BlogUpdateInput!","id":"ID!"}],"bulkOperationCancel":["BulkOperationCancelPayload",{"id":"ID!"}],"bulkOperationRunMutation":["BulkOperationRunMutationPayload",{"clientIdentifier":"String","groupObjects":"Boolean=","mutation":"String!","stagedUploadPath":"String!"}],"bulkOperationRunQuery":["BulkOperationRunQueryPayload",{"groupObjects":"Boolean!=","query":"String!"}],"bulkProductResourceFeedbackCreate":["BulkProductResourceFeedbackCreatePayload",{"feedbackInput":"[ProductResourceFeedbackInput!]!"}],"carrierServiceCreate":["CarrierServiceCreatePayload",{"input":"DeliveryCarrierServiceCreateInput!"}],"carrierServiceDelete":["CarrierServiceDeletePayload",{"id":"ID!"}],"carrierServiceUpdate":["CarrierServiceUpdatePayload",{"input":"DeliveryCarrierServiceUpdateInput!"}],"cartTransformCreate":["CartTransformCreatePayload",{"blockOnFailure":"Boolean=","functionHandle":"String","functionId":"String","metafields":"[MetafieldInput!]="}],"cartTransformDelete":["CartTransformDeletePayload",{"id":"ID!"}],"cashDrawerCreate":["CashDrawerCreatePayload",{"locationId":"ID!","name":"String!"}],"cashDrawerFindOrCreate":["CashDrawerFindOrCreatePayload",{"locationId":"ID!","name":"String!","pointOfSaleDeviceId":"ID!"}],"cashDrawerUpdate":["CashDrawerUpdatePayload",{"id":"ID!","input":"CashDrawerUpdateInput!"}],"cashManagementReasonCodeCreate":["CashManagementReasonCodeCreatePayload",{"code":"String!"}],"cashManagementReasonCodeDelete":["CashManagementReasonCodeDeletePayload",{"id":"ID!"}],"catalogContextUpdate":["CatalogContextUpdatePayload",{"catalogId":"ID!","contextsToAdd":"CatalogContextInput","contextsToRemove":"CatalogContextInput"}],"catalogCreate":["CatalogCreatePayload",{"input":"CatalogCreateInput!"}],"catalogDelete":["CatalogDeletePayload",{"deleteDependentResources":"Boolean=","id":"ID!"}],"catalogUpdate":["CatalogUpdatePayload",{"id":"ID!","input":"CatalogUpdateInput!"}],"channelCreate":["ChannelCreatePayload",{"input":"ChannelCreateInput!"}],"channelDelete":["ChannelDeletePayload",{"id":"ID!"}],"channelFullSync":["ChannelFullSyncPayload",{"beforeUpdatedAt":"DateTime","channelId":"ID!","country":"CountryCode","language":"LanguageCode","updatedAtSince":"DateTime"}],"channelUpdate":["ChannelUpdatePayload",{"id":"ID!","input":"ChannelUpdateInput!"}],"checkoutAndAccountsConfigurationUpdate":["CheckoutAndAccountsConfigurationUpdatePayload",{"configuration":"CheckoutAndAccountsConfigurationInput!","id":"ID!"}],"checkoutBrandingUpsert":["CheckoutBrandingUpsertPayload",{"checkoutBrandingInput":"CheckoutBrandingInput","checkoutProfileId":"ID!"}],"collectionAddProducts":["CollectionAddProductsPayload",{"id":"ID!","productIds":"[ID!]!"}],"collectionAddProductsV2":["CollectionAddProductsV2Payload",{"id":"ID!","productIds":"[ID!]!"}],"collectionConditionsSourceCreate":["CollectionConditionsSourceCreatePayload",{"input":"CollectionCreateConditionsSourceInput!"}],"collectionConditionsSourceDelete":["CollectionConditionsSourceDeletePayload",{"id":"ID!"}],"collectionConditionsSourceUpdate":["CollectionConditionsSourceUpdatePayload",{"input":"CollectionUpdateConditionsSourceInput!"}],"collectionCreate":["CollectionCreatePayload",{"collection":"CollectionCreateInput","input":"CollectionInput"}],"collectionDelete":["CollectionDeletePayload",{"input":"CollectionDeleteInput!"}],"collectionDuplicate":["CollectionDuplicatePayload",{"input":"CollectionDuplicateInput!"}],"collectionPublish":["CollectionPublishPayload",{"input":"CollectionPublishInput!"}],"collectionRemoveProducts":["CollectionRemoveProductsPayload",{"id":"ID!","productIds":"[ID!]!"}],"collectionReorderProducts":["CollectionReorderProductsPayload",{"id":"ID!","moves":"[MoveInput!]!"}],"collectionUnpublish":["CollectionUnpublishPayload",{"input":"CollectionUnpublishInput!"}],"collectionUpdate":["CollectionUpdatePayload",{"collection":"CollectionUpdateInput","input":"CollectionInput"}],"combinedListingUpdate":["CombinedListingUpdatePayload",{"optionsAndValues":"[OptionAndValueInput!]","parentProductId":"ID!","productsAdded":"[ChildProductRelationInput!]","productsEdited":"[ChildProductRelationInput!]","productsRemovedIds":"[ID!]","title":"String"}],"commentApprove":["CommentApprovePayload",{"id":"ID!"}],"commentDelete":["CommentDeletePayload",{"id":"ID!"}],"commentNotSpam":["CommentNotSpamPayload",{"id":"ID!"}],"commentSpam":["CommentSpamPayload",{"id":"ID!"}],"companiesDelete":["CompaniesDeletePayload",{"companyIds":"[ID!]!"}],"companyAddressDelete":["CompanyAddressDeletePayload",{"addressId":"ID!"}],"companyAssignCustomerAsContact":["CompanyAssignCustomerAsContactPayload",{"companyId":"ID!","customerId":"ID!"}],"companyAssignMainContact":["CompanyAssignMainContactPayload",{"companyContactId":"ID!","companyId":"ID!"}],"companyContactAssignRole":["CompanyContactAssignRolePayload",{"companyContactId":"ID!","companyContactRoleId":"ID!","companyLocationId":"ID!"}],"companyContactAssignRoles":["CompanyContactAssignRolesPayload",{"companyContactId":"ID!","rolesToAssign":"[CompanyContactRoleAssign!]!"}],"companyContactCreate":["CompanyContactCreatePayload",{"companyId":"ID!","input":"CompanyContactInput!"}],"companyContactDelete":["CompanyContactDeletePayload",{"companyContactId":"ID!"}],"companyContactRemoveFromCompany":["CompanyContactRemoveFromCompanyPayload",{"companyContactId":"ID!"}],"companyContactRevokeRole":["CompanyContactRevokeRolePayload",{"companyContactId":"ID!","companyContactRoleAssignmentId":"ID!"}],"companyContactRevokeRoles":["CompanyContactRevokeRolesPayload",{"companyContactId":"ID!","revokeAll":"Boolean=","roleAssignmentIds":"[ID!]"}],"companyContactSendWelcomeEmail":["CompanyContactSendWelcomeEmailPayload",{"companyContactId":"ID!","email":"EmailInput"}],"companyContactUpdate":["CompanyContactUpdatePayload",{"companyContactId":"ID!","input":"CompanyContactInput!"}],"companyContactsDelete":["CompanyContactsDeletePayload",{"companyContactIds":"[ID!]!"}],"companyCreate":["CompanyCreatePayload",{"input":"CompanyCreateInput!"}],"companyDelete":["CompanyDeletePayload",{"id":"ID!"}],"companyLocationAssignAddress":["CompanyLocationAssignAddressPayload",{"address":"CompanyAddressInput!","addressTypes":"[CompanyAddressType!]!","locationId":"ID!"}],"companyLocationAssignRoles":["CompanyLocationAssignRolesPayload",{"companyLocationId":"ID!","rolesToAssign":"[CompanyLocationRoleAssign!]!"}],"companyLocationAssignStaffMembers":["CompanyLocationAssignStaffMembersPayload",{"companyLocationId":"ID!","staffMemberIds":"[ID!]!"}],"companyLocationAssignTaxExemptions":["CompanyLocationAssignTaxExemptionsPayload",{"companyLocationId":"ID!","taxExemptions":"[TaxExemption!]!"}],"companyLocationCreate":["CompanyLocationCreatePayload",{"companyId":"ID!","input":"CompanyLocationInput!"}],"companyLocationCreateTaxRegistration":["CompanyLocationCreateTaxRegistrationPayload",{"locationId":"ID!","taxId":"String!"}],"companyLocationDelete":["CompanyLocationDeletePayload",{"companyLocationId":"ID!"}],"companyLocationRemoveStaffMembers":["CompanyLocationRemoveStaffMembersPayload",{"companyLocationStaffMemberAssignmentIds":"[ID!]!"}],"companyLocationRevokeRoles":["CompanyLocationRevokeRolesPayload",{"companyLocationId":"ID!","rolesToRevoke":"[ID!]!"}],"companyLocationRevokeTaxExemptions":["CompanyLocationRevokeTaxExemptionsPayload",{"companyLocationId":"ID!","taxExemptions":"[TaxExemption!]!"}],"companyLocationRevokeTaxRegistration":["CompanyLocationRevokeTaxRegistrationPayload",{"companyLocationId":"ID!"}],"companyLocationTaxSettingsUpdate":["CompanyLocationTaxSettingsUpdatePayload",{"companyLocationId":"ID!","exemptionsToAssign":"[TaxExemption!]","exemptionsToRemove":"[TaxExemption!]","taxExempt":"Boolean","taxRegistrationId":"String"}],"companyLocationUpdate":["CompanyLocationUpdatePayload",{"companyLocationId":"ID!","input":"CompanyLocationUpdateInput!"}],"companyLocationsDelete":["CompanyLocationsDeletePayload",{"companyLocationIds":"[ID!]!"}],"companyRevokeMainContact":["CompanyRevokeMainContactPayload",{"companyId":"ID!"}],"companyUpdate":["CompanyUpdatePayload",{"companyId":"ID!","input":"CompanyInput!"}],"consentPolicyUpdate":["ConsentPolicyUpdatePayload",{"consentPolicies":"[ConsentPolicyInput!]!"}],"customerAddTaxExemptions":["CustomerAddTaxExemptionsPayload",{"customerId":"ID!","taxExemptions":"[TaxExemption!]!"}],"customerAddressCreate":["CustomerAddressCreatePayload",{"address":"MailingAddressInput!","customerId":"ID!","setAsDefault":"Boolean"}],"customerAddressDelete":["CustomerAddressDeletePayload",{"addressId":"ID!","customerId":"ID!"}],"customerAddressUpdate":["CustomerAddressUpdatePayload",{"address":"MailingAddressInput!","addressId":"ID!","customerId":"ID!","setAsDefault":"Boolean"}],"customerCancelDataErasure":["CustomerCancelDataErasurePayload",{"customerId":"ID!"}],"customerCreate":["CustomerCreatePayload",{"input":"CustomerInput!"}],"customerDelete":["CustomerDeletePayload",{"input":"CustomerDeleteInput!"}],"customerEmailMarketingConsentUpdate":["CustomerEmailMarketingConsentUpdatePayload",{"input":"CustomerEmailMarketingConsentUpdateInput!"}],"customerGenerateAccountActivationUrl":["CustomerGenerateAccountActivationUrlPayload",{"customerId":"ID!"}],"customerMerge":["CustomerMergePayload",{"customerOneId":"ID!","customerTwoId":"ID!","overrideFields":"CustomerMergeOverrideFields"}],"customerPaymentMethodCreateFromDuplicationData":["CustomerPaymentMethodCreateFromDuplicationDataPayload",{"billingAddress":"MailingAddressInput!","customerId":"ID!","encryptedDuplicationData":"String!"}],"customerPaymentMethodCreditCardCreate":["CustomerPaymentMethodCreditCardCreatePayload",{"billingAddress":"MailingAddressInput!","customerId":"ID!","sessionId":"String!"}],"customerPaymentMethodCreditCardUpdate":["CustomerPaymentMethodCreditCardUpdatePayload",{"billingAddress":"MailingAddressInput!","id":"ID!","sessionId":"String!"}],"customerPaymentMethodGetDuplicationData":["CustomerPaymentMethodGetDuplicationDataPayload",{"customerPaymentMethodId":"ID!","targetCustomerId":"ID!","targetShopId":"ID!"}],"customerPaymentMethodGetUpdateUrl":["CustomerPaymentMethodGetUpdateUrlPayload",{"customerPaymentMethodId":"ID!"}],"customerPaymentMethodPaypalBillingAgreementCreate":["CustomerPaymentMethodPaypalBillingAgreementCreatePayload",{"billingAddress":"MailingAddressInput","billingAgreementId":"String!","customerId":"ID!","inactive":"Boolean="}],"customerPaymentMethodPaypalBillingAgreementUpdate":["CustomerPaymentMethodPaypalBillingAgreementUpdatePayload",{"billingAddress":"MailingAddressInput!","id":"ID!"}],"customerPaymentMethodRemoteCreate":["CustomerPaymentMethodRemoteCreatePayload",{"customerId":"ID!","remoteReference":"CustomerPaymentMethodRemoteInput!"}],"customerPaymentMethodRevoke":["CustomerPaymentMethodRevokePayload",{"customerPaymentMethodId":"ID!"}],"customerPaymentMethodSendUpdateEmail":["CustomerPaymentMethodSendUpdateEmailPayload",{"customerPaymentMethodId":"ID!","email":"EmailInput"}],"customerRemoveTaxExemptions":["CustomerRemoveTaxExemptionsPayload",{"customerId":"ID!","taxExemptions":"[TaxExemption!]!"}],"customerReplaceTaxExemptions":["CustomerReplaceTaxExemptionsPayload",{"customerId":"ID!","taxExemptions":"[TaxExemption!]!"}],"customerRequestDataErasure":["CustomerRequestDataErasurePayload",{"customerId":"ID!"}],"customerSegmentMembersQueryCreate":["CustomerSegmentMembersQueryCreatePayload",{"input":"CustomerSegmentMembersQueryInput!"}],"customerSendAccountInviteEmail":["CustomerSendAccountInviteEmailPayload",{"customerId":"ID!","email":"EmailInput"}],"customerSet":["CustomerSetPayload",{"identifier":"CustomerSetIdentifiers","input":"CustomerSetInput!"}],"customerSmsMarketingConsentUpdate":["CustomerSmsMarketingConsentUpdatePayload",{"input":"CustomerSmsMarketingConsentUpdateInput!"}],"customerUpdate":["CustomerUpdatePayload",{"input":"CustomerInput!"}],"customerUpdateDefaultAddress":["CustomerUpdateDefaultAddressPayload",{"addressId":"ID!","customerId":"ID!"}],"customerWhatsAppMarketingConsentUpdate":["CustomerWhatsAppMarketingConsentUpdatePayload",{"input":"CustomerWhatsAppMarketingConsentUpdateInput!"}],"dataSaleOptOut":["DataSaleOptOutPayload",{"email":"String!"}],"delegateAccessTokenCreate":["DelegateAccessTokenCreatePayload",{"input":"DelegateAccessTokenInput!"}],"delegateAccessTokenDestroy":["DelegateAccessTokenDestroyPayload",{"accessToken":"String!"}],"deliveryCustomizationActivation":["DeliveryCustomizationActivationPayload",{"enabled":"Boolean!","ids":"[ID!]!"}],"deliveryCustomizationCreate":["DeliveryCustomizationCreatePayload",{"deliveryCustomization":"DeliveryCustomizationInput!"}],"deliveryCustomizationDelete":["DeliveryCustomizationDeletePayload",{"id":"ID!"}],"deliveryCustomizationUpdate":["DeliveryCustomizationUpdatePayload",{"deliveryCustomization":"DeliveryCustomizationInput!","id":"ID!"}],"deliveryProfileCreate":["DeliveryProfileCreatePayload",{"profile":"DeliveryProfileInput!"}],"deliveryProfileRemove":["DeliveryProfileRemovePayload",{"id":"ID!"}],"deliveryProfileUpdate":["DeliveryProfileUpdatePayload",{"id":"ID!","profile":"DeliveryProfileInput!"}],"deliveryPromiseParticipantsUpdate":["DeliveryPromiseParticipantsUpdatePayload",{"brandedPromiseHandle":"String!","ownersToAdd":"[ID!]=","ownersToRemove":"[ID!]="}],"deliveryPromiseProviderUpsert":["DeliveryPromiseProviderUpsertPayload",{"active":"Boolean","fulfillmentDelay":"Int","locationId":"ID!","timeZone":"String"}],"deliverySettingUpdate":"DeliverySettingUpdatePayload","deliveryShippingOriginAssign":["DeliveryShippingOriginAssignPayload",{"locationId":"ID!"}],"discountAutomaticActivate":["DiscountAutomaticActivatePayload",{"id":"ID!"}],"discountAutomaticAppCreate":["DiscountAutomaticAppCreatePayload",{"automaticAppDiscount":"DiscountAutomaticAppInput!"}],"discountAutomaticAppUpdate":["DiscountAutomaticAppUpdatePayload",{"automaticAppDiscount":"DiscountAutomaticAppInput!","id":"ID!"}],"discountAutomaticBasicCreate":["DiscountAutomaticBasicCreatePayload",{"automaticBasicDiscount":"DiscountAutomaticBasicInput!"}],"discountAutomaticBasicUpdate":["DiscountAutomaticBasicUpdatePayload",{"automaticBasicDiscount":"DiscountAutomaticBasicInput!","id":"ID!"}],"discountAutomaticBulkDelete":["DiscountAutomaticBulkDeletePayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String"}],"discountAutomaticBxgyCreate":["DiscountAutomaticBxgyCreatePayload",{"automaticBxgyDiscount":"DiscountAutomaticBxgyInput!"}],"discountAutomaticBxgyUpdate":["DiscountAutomaticBxgyUpdatePayload",{"automaticBxgyDiscount":"DiscountAutomaticBxgyInput!","id":"ID!"}],"discountAutomaticDeactivate":["DiscountAutomaticDeactivatePayload",{"id":"ID!"}],"discountAutomaticDelete":["DiscountAutomaticDeletePayload",{"id":"ID!"}],"discountAutomaticFreeShippingCreate":["DiscountAutomaticFreeShippingCreatePayload",{"freeShippingAutomaticDiscount":"DiscountAutomaticFreeShippingInput!"}],"discountAutomaticFreeShippingUpdate":["DiscountAutomaticFreeShippingUpdatePayload",{"freeShippingAutomaticDiscount":"DiscountAutomaticFreeShippingInput!","id":"ID!"}],"discountBulkTagsAdd":["DiscountBulkTagsAddPayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String","tags":"[String!]!"}],"discountBulkTagsRemove":["DiscountBulkTagsRemovePayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String","tags":"[String!]!"}],"discountCodeActivate":["DiscountCodeActivatePayload",{"id":"ID!"}],"discountCodeAppCreate":["DiscountCodeAppCreatePayload",{"codeAppDiscount":"DiscountCodeAppInput!"}],"discountCodeAppUpdate":["DiscountCodeAppUpdatePayload",{"codeAppDiscount":"DiscountCodeAppInput!","id":"ID!"}],"discountCodeBasicCreate":["DiscountCodeBasicCreatePayload",{"basicCodeDiscount":"DiscountCodeBasicInput!"}],"discountCodeBasicUpdate":["DiscountCodeBasicUpdatePayload",{"basicCodeDiscount":"DiscountCodeBasicInput!","id":"ID!"}],"discountCodeBulkActivate":["DiscountCodeBulkActivatePayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String"}],"discountCodeBulkDeactivate":["DiscountCodeBulkDeactivatePayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String"}],"discountCodeBulkDelete":["DiscountCodeBulkDeletePayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String"}],"discountCodeBxgyCreate":["DiscountCodeBxgyCreatePayload",{"bxgyCodeDiscount":"DiscountCodeBxgyInput!"}],"discountCodeBxgyUpdate":["DiscountCodeBxgyUpdatePayload",{"bxgyCodeDiscount":"DiscountCodeBxgyInput!","id":"ID!"}],"discountCodeDeactivate":["DiscountCodeDeactivatePayload",{"id":"ID!"}],"discountCodeDelete":["DiscountCodeDeletePayload",{"id":"ID!"}],"discountCodeFreeShippingCreate":["DiscountCodeFreeShippingCreatePayload",{"freeShippingCodeDiscount":"DiscountCodeFreeShippingInput!"}],"discountCodeFreeShippingUpdate":["DiscountCodeFreeShippingUpdatePayload",{"freeShippingCodeDiscount":"DiscountCodeFreeShippingInput!","id":"ID!"}],"discountCodeRedeemCodeBulkDelete":["DiscountCodeRedeemCodeBulkDeletePayload",{"discountId":"ID!","ids":"[ID!]","savedSearchId":"ID","search":"String"}],"discountRedeemCodeBulkAdd":["DiscountRedeemCodeBulkAddPayload",{"codes":"[DiscountRedeemCodeInput!]!","discountId":"ID!"}],"disputeEvidenceUpdate":["DisputeEvidenceUpdatePayload",{"id":"ID!","input":"ShopifyPaymentsDisputeEvidenceUpdateInput!"}],"draftOrderBulkAddTags":["DraftOrderBulkAddTagsPayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String","tags":"[String!]!"}],"draftOrderBulkDelete":["DraftOrderBulkDeletePayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String"}],"draftOrderBulkRemoveTags":["DraftOrderBulkRemoveTagsPayload",{"ids":"[ID!]","savedSearchId":"ID","search":"String","tags":"[String!]!"}],"draftOrderCalculate":["DraftOrderCalculatePayload",{"input":"DraftOrderInput!"}],"draftOrderComplete":["DraftOrderCompletePayload",{"id":"ID!","paymentGatewayId":"ID","paymentPending":"Boolean=","sourceName":"String"}],"draftOrderCreate":["DraftOrderCreatePayload",{"input":"DraftOrderInput!"}],"draftOrderCreateFromOrder":["DraftOrderCreateFromOrderPayload",{"orderId":"ID!"}],"draftOrderDelete":["DraftOrderDeletePayload",{"input":"DraftOrderDeleteInput!"}],"draftOrderDuplicate":["DraftOrderDuplicatePayload",{"draftOrderId":"ID","id":"ID"}],"draftOrderInvoicePreview":["DraftOrderInvoicePreviewPayload",{"email":"EmailInput","id":"ID!"}],"draftOrderInvoiceSend":["DraftOrderInvoiceSendPayload",{"email":"EmailInput","id":"ID!"}],"draftOrderUpdate":["DraftOrderUpdatePayload",{"id":"ID!","input":"DraftOrderInput!"}],"eventBridgeServerPixelUpdate":["EventBridgeServerPixelUpdatePayload",{"arn":"ARN!"}],"eventBridgeWebhookSubscriptionCreate":["EventBridgeWebhookSubscriptionCreatePayload",{"topic":"WebhookSubscriptionTopic!","webhookSubscription":"EventBridgeWebhookSubscriptionInput!"}],"eventBridgeWebhookSubscriptionUpdate":["EventBridgeWebhookSubscriptionUpdatePayload",{"id":"ID!","webhookSubscription":"EventBridgeWebhookSubscriptionInput!"}],"fileAcknowledgeUpdateFailed":["FileAcknowledgeUpdateFailedPayload",{"fileIds":"[ID!]!"}],"fileCreate":["FileCreatePayload",{"files":"[FileCreateInput!]!"}],"fileDelete":["FileDeletePayload",{"fileIds":"[ID!]!"}],"fileUpdate":["FileUpdatePayload",{"files":"[FileUpdateInput!]!"}],"flowGenerateSignature":["FlowGenerateSignaturePayload",{"id":"ID!","payload":"String!"}],"flowTriggerReceive":["FlowTriggerReceivePayload",{"body":"String","handle":"String","payload":"JSON"}],"fulfillmentCancel":["FulfillmentCancelPayload",{"id":"ID!"}],"fulfillmentConstraintRuleCreate":["FulfillmentConstraintRuleCreatePayload",{"deliveryMethodTypes":"[DeliveryMethodType!]!","functionHandle":"String","functionId":"String","metafields":"[MetafieldInput!]="}],"fulfillmentConstraintRuleDelete":["FulfillmentConstraintRuleDeletePayload",{"id":"ID!"}],"fulfillmentConstraintRuleUpdate":["FulfillmentConstraintRuleUpdatePayload",{"deliveryMethodTypes":"[DeliveryMethodType!]!","id":"ID!"}],"fulfillmentCreate":["FulfillmentCreatePayload",{"fulfillment":"FulfillmentInput!","message":"String"}],"fulfillmentCreateV2":["FulfillmentCreateV2Payload",{"fulfillment":"FulfillmentV2Input!","message":"String"}],"fulfillmentEventCreate":["FulfillmentEventCreatePayload",{"fulfillmentEvent":"FulfillmentEventInput!"}],"fulfillmentOrderAcceptCancellationRequest":["FulfillmentOrderAcceptCancellationRequestPayload",{"id":"ID!","message":"String"}],"fulfillmentOrderAcceptFulfillmentRequest":["FulfillmentOrderAcceptFulfillmentRequestPayload",{"estimatedShippedAt":"DateTime","id":"ID!","message":"String"}],"fulfillmentOrderCancel":["FulfillmentOrderCancelPayload",{"id":"ID!"}],"fulfillmentOrderClose":["FulfillmentOrderClosePayload",{"id":"ID!","message":"String"}],"fulfillmentOrderHold":["FulfillmentOrderHoldPayload",{"fulfillmentHold":"FulfillmentOrderHoldInput!","id":"ID!"}],"fulfillmentOrderLineItemsPreparedForPickup":["FulfillmentOrderLineItemsPreparedForPickupPayload",{"input":"FulfillmentOrderLineItemsPreparedForPickupInput!"}],"fulfillmentOrderMerge":["FulfillmentOrderMergePayload",{"fulfillmentOrderMergeInputs":"[FulfillmentOrderMergeInput!]!"}],"fulfillmentOrderMove":["FulfillmentOrderMovePayload",{"fulfillmentOrderLineItems":"[FulfillmentOrderLineItemInput!]","id":"ID!","newLocationId":"ID!"}],"fulfillmentOrderOpen":["FulfillmentOrderOpenPayload",{"id":"ID!"}],"fulfillmentOrderRejectCancellationRequest":["FulfillmentOrderRejectCancellationRequestPayload",{"id":"ID!","message":"String"}],"fulfillmentOrderRejectFulfillmentRequest":["FulfillmentOrderRejectFulfillmentRequestPayload",{"id":"ID!","lineItems":"[IncomingRequestLineItemInput!]","message":"String","reason":"FulfillmentOrderRejectionReason"}],"fulfillmentOrderReleaseHold":["FulfillmentOrderReleaseHoldPayload",{"externalId":"String","holdIds":"[ID!]","id":"ID!"}],"fulfillmentOrderReportProgress":["FulfillmentOrderReportProgressPayload",{"id":"ID!","progressReport":"FulfillmentOrderReportProgressInput"}],"fulfillmentOrderReschedule":["FulfillmentOrderReschedulePayload",{"fulfillAt":"DateTime!","id":"ID!"}],"fulfillmentOrderSplit":["FulfillmentOrderSplitPayload",{"fulfillmentOrderSplits":"[FulfillmentOrderSplitInput!]!"}],"fulfillmentOrderSubmitCancellationRequest":["FulfillmentOrderSubmitCancellationRequestPayload",{"id":"ID!","message":"String"}],"fulfillmentOrderSubmitFulfillmentRequest":["FulfillmentOrderSubmitFulfillmentRequestPayload",{"fulfillmentOrderLineItems":"[FulfillmentOrderLineItemInput!]","id":"ID!","message":"String","notifyCustomer":"Boolean"}],"fulfillmentOrdersReroute":["FulfillmentOrdersReroutePayload",{"excludedLocationIds":"[ID!]","fulfillmentOrderIds":"[ID!]!","includedLocationIds":"[ID!]"}],"fulfillmentOrdersSetFulfillmentDeadline":["FulfillmentOrdersSetFulfillmentDeadlinePayload",{"fulfillmentDeadline":"DateTime!","fulfillmentOrderIds":"[ID!]!"}],"fulfillmentServiceCreate":["FulfillmentServiceCreatePayload",{"callbackUrl":"URL","fulfillmentOrdersOptIn":"Boolean=","inventoryManagement":"Boolean=","name":"String!","requiresShippingMethod":"Boolean=","trackingSupport":"Boolean="}],"fulfillmentServiceDelete":["FulfillmentServiceDeletePayload",{"destinationLocationId":"ID","id":"ID!","inventoryAction":"FulfillmentServiceDeleteInventoryAction="}],"fulfillmentServiceUpdate":["FulfillmentServiceUpdatePayload",{"callbackUrl":"URL","fulfillmentOrdersOptIn":"Boolean","id":"ID!","inventoryManagement":"Boolean","name":"String","requiresShippingMethod":"Boolean=","trackingSupport":"Boolean"}],"fulfillmentTrackingInfoUpdate":["FulfillmentTrackingInfoUpdatePayload",{"fulfillmentId":"ID!","notifyCustomer":"Boolean","trackingInfoInput":"FulfillmentTrackingInput!"}],"fulfillmentTrackingInfoUpdateV2":["FulfillmentTrackingInfoUpdateV2Payload",{"fulfillmentId":"ID!","notifyCustomer":"Boolean","trackingInfoInput":"FulfillmentTrackingInput!"}],"giftCardCreate":["GiftCardCreatePayload",{"input":"GiftCardCreateInput!"}],"giftCardCredit":["GiftCardCreditPayload",{"creditInput":"GiftCardCreditInput!","id":"ID!"}],"giftCardDeactivate":["GiftCardDeactivatePayload",{"id":"ID!"}],"giftCardDebit":["GiftCardDebitPayload",{"debitInput":"GiftCardDebitInput!","id":"ID!"}],"giftCardProductSet":["GiftCardProductSetPayload",{"identifier":"ProductSetIdentifiers","input":"GiftCardProductSetInput!","synchronous":"Boolean="}],"giftCardSendNotificationToCustomer":["GiftCardSendNotificationToCustomerPayload",{"id":"ID!"}],"giftCardSendNotificationToRecipient":["GiftCardSendNotificationToRecipientPayload",{"id":"ID!"}],"giftCardUpdate":["GiftCardUpdatePayload",{"id":"ID!","input":"GiftCardUpdateInput!"}],"inventoryActivate":["InventoryActivatePayload",{"available":"Int","inventoryItemId":"ID!","locationId":"ID!","onHand":"Int","stockAtLegacyLocation":"Boolean="}],"inventoryAdjustQuantities":["InventoryAdjustQuantitiesPayload",{"input":"InventoryAdjustQuantitiesInput!"}],"inventoryBulkToggleActivation":["InventoryBulkToggleActivationPayload",{"inventoryItemId":"ID!","inventoryItemUpdates":"[InventoryBulkToggleActivationInput!]!"}],"inventoryDeactivate":["InventoryDeactivatePayload",{"inventoryLevelId":"ID!"}],"inventoryItemUpdate":["InventoryItemUpdatePayload",{"id":"ID!","input":"InventoryItemInput!"}],"inventoryMoveQuantities":["InventoryMoveQuantitiesPayload",{"input":"InventoryMoveQuantitiesInput!"}],"inventorySetOnHandQuantities":["InventorySetOnHandQuantitiesPayload",{"input":"InventorySetOnHandQuantitiesInput!"}],"inventorySetQuantities":["InventorySetQuantitiesPayload",{"input":"InventorySetQuantitiesInput!"}],"inventoryShipmentAddItems":["InventoryShipmentAddItemsPayload",{"id":"ID!","lineItems":"[InventoryShipmentLineItemInput!]!"}],"inventoryShipmentCreate":["InventoryShipmentCreatePayload",{"input":"InventoryShipmentCreateInput!"}],"inventoryShipmentCreateInTransit":["InventoryShipmentCreateInTransitPayload",{"input":"InventoryShipmentCreateInput!"}],"inventoryShipmentDelete":["InventoryShipmentDeletePayload",{"id":"ID!"}],"inventoryShipmentMarkInTransit":["InventoryShipmentMarkInTransitPayload",{"dateShipped":"DateTime","id":"ID!"}],"inventoryShipmentReceive":["InventoryShipmentReceivePayload",{"bulkReceiveAction":"InventoryShipmentReceiveLineItemReason","dateReceived":"DateTime","id":"ID!","lineItems":"[InventoryShipmentReceiveItemInput!]"}],"inventoryShipmentRemoveItems":["InventoryShipmentRemoveItemsPayload",{"id":"ID!","lineItems":"[ID!]!"}],"inventoryShipmentSetBarcode":["InventoryShipmentSetBarcodePayload",{"barcode":"String!","id":"ID!"}],"inventoryShipmentSetTracking":["InventoryShipmentSetTrackingPayload",{"id":"ID!","tracking":"InventoryShipmentTrackingInput!"}],"inventoryShipmentUpdateItemQuantities":["InventoryShipmentUpdateItemQuantitiesPayload",{"id":"ID!","items":"[InventoryShipmentUpdateItemQuantitiesInput!]="}],"inventoryTransferCancel":["InventoryTransferCancelPayload",{"id":"ID!"}],"inventoryTransferCreate":["InventoryTransferCreatePayload",{"input":"InventoryTransferCreateInput!"}],"inventoryTransferCreateAsReadyToShip":["InventoryTransferCreateAsReadyToShipPayload",{"input":"InventoryTransferCreateAsReadyToShipInput!"}],"inventoryTransferDelete":["InventoryTransferDeletePayload",{"id":"ID!"}],"inventoryTransferDuplicate":["InventoryTransferDuplicatePayload",{"id":"ID!"}],"inventoryTransferEdit":["InventoryTransferEditPayload",{"id":"ID!","input":"InventoryTransferEditInput!"}],"inventoryTransferMarkAsReadyToShip":["InventoryTransferMarkAsReadyToShipPayload",{"id":"ID!"}],"inventoryTransferRemoveItems":["InventoryTransferRemoveItemsPayload",{"input":"InventoryTransferRemoveItemsInput!"}],"inventoryTransferSetItems":["InventoryTransferSetItemsPayload",{"input":"InventoryTransferSetItemsInput!"}],"locationActivate":["LocationActivatePayload",{"locationId":"ID!"}],"locationAdd":["LocationAddPayload",{"input":"LocationAddInput!"}],"locationDeactivate":["LocationDeactivatePayload",{"destinationLocationId":"ID","locationId":"ID!"}],"locationDelete":["LocationDeletePayload",{"locationId":"ID!"}],"locationEdit":["LocationEditPayload",{"id":"ID!","input":"LocationEditInput!"}],"locationLocalPickupDisable":["LocationLocalPickupDisablePayload",{"locationId":"ID!"}],"locationLocalPickupEnable":["LocationLocalPickupEnablePayload",{"localPickupSettings":"DeliveryLocationLocalPickupEnableInput!"}],"marketCreate":["MarketCreatePayload",{"input":"MarketCreateInput!"}],"marketCurrencySettingsUpdate":["MarketCurrencySettingsUpdatePayload",{"input":"MarketCurrencySettingsUpdateInput!","marketId":"ID!"}],"marketDelete":["MarketDeletePayload",{"id":"ID!"}],"marketLocalizationsRegister":["MarketLocalizationsRegisterPayload",{"marketLocalizations":"[MarketLocalizationRegisterInput!]!","resourceId":"ID!"}],"marketLocalizationsRemove":["MarketLocalizationsRemovePayload",{"marketIds":"[ID!]!","marketLocalizationKeys":"[String!]!","resourceId":"ID!"}],"marketRegionDelete":["MarketRegionDeletePayload",{"id":"ID!"}],"marketRegionsCreate":["MarketRegionsCreatePayload",{"marketId":"ID!","regions":"[MarketRegionCreateInput!]!"}],"marketRegionsDelete":["MarketRegionsDeletePayload",{"ids":"[ID!]!"}],"marketUpdate":["MarketUpdatePayload",{"id":"ID!","input":"MarketUpdateInput!"}],"marketWebPresenceCreate":["MarketWebPresenceCreatePayload",{"marketId":"ID!","webPresence":"MarketWebPresenceCreateInput!"}],"marketWebPresenceDelete":["MarketWebPresenceDeletePayload",{"webPresenceId":"ID!"}],"marketWebPresenceUpdate":["MarketWebPresenceUpdatePayload",{"webPresence":"MarketWebPresenceUpdateInput!","webPresenceId":"ID!"}],"marketingActivitiesDeleteAllExternal":"MarketingActivitiesDeleteAllExternalPayload","marketingActivityCreate":["MarketingActivityCreatePayload",{"input":"MarketingActivityCreateInput!"}],"marketingActivityCreateExternal":["MarketingActivityCreateExternalPayload",{"input":"MarketingActivityCreateExternalInput!"}],"marketingActivityDeleteExternal":["MarketingActivityDeleteExternalPayload",{"marketingActivityId":"ID","remoteId":"String"}],"marketingActivityUpdate":["MarketingActivityUpdatePayload",{"input":"MarketingActivityUpdateInput!"}],"marketingActivityUpdateExternal":["MarketingActivityUpdateExternalPayload",{"input":"MarketingActivityUpdateExternalInput!","marketingActivityId":"ID","remoteId":"String","utm":"UTMInput"}],"marketingActivityUpsertExternal":["MarketingActivityUpsertExternalPayload",{"input":"MarketingActivityUpsertExternalInput!"}],"marketingEngagementCreate":["MarketingEngagementCreatePayload",{"channelHandle":"String","marketingActivityId":"ID","marketingEngagement":"MarketingEngagementInput!","remoteId":"String"}],"marketingEngagementsDelete":["MarketingEngagementsDeletePayload",{"channelHandle":"String","deleteEngagementsForAllChannels":"Boolean="}],"menuCreate":["MenuCreatePayload",{"handle":"String!","items":"[MenuItemCreateInput!]!","title":"String!"}],"menuDelete":["MenuDeletePayload",{"id":"ID!"}],"menuUpdate":["MenuUpdatePayload",{"handle":"String","id":"ID!","items":"[MenuItemUpdateInput!]!","title":"String!"}],"metafieldDefinitionCreate":["MetafieldDefinitionCreatePayload",{"definition":"MetafieldDefinitionInput!"}],"metafieldDefinitionDelete":["MetafieldDefinitionDeletePayload",{"deleteAllAssociatedMetafields":"Boolean=","id":"ID","identifier":"MetafieldDefinitionIdentifierInput"}],"metafieldDefinitionPin":["MetafieldDefinitionPinPayload",{"definitionId":"ID","identifier":"MetafieldDefinitionIdentifierInput"}],"metafieldDefinitionUnpin":["MetafieldDefinitionUnpinPayload",{"definitionId":"ID","identifier":"MetafieldDefinitionIdentifierInput"}],"metafieldDefinitionUpdate":["MetafieldDefinitionUpdatePayload",{"definition":"MetafieldDefinitionUpdateInput!"}],"metafieldsDelete":["MetafieldsDeletePayload",{"metafields":"[MetafieldIdentifierInput!]!"}],"metafieldsSet":["MetafieldsSetPayload",{"metafields":"[MetafieldsSetInput!]!"}],"metaobjectBulkDelete":["MetaobjectBulkDeletePayload",{"where":"MetaobjectBulkDeleteWhereCondition!"}],"metaobjectCreate":["MetaobjectCreatePayload",{"metaobject":"MetaobjectCreateInput!"}],"metaobjectDefinitionCreate":["MetaobjectDefinitionCreatePayload",{"definition":"MetaobjectDefinitionCreateInput!"}],"metaobjectDefinitionDelete":["MetaobjectDefinitionDeletePayload",{"id":"ID!"}],"metaobjectDefinitionUpdate":["MetaobjectDefinitionUpdatePayload",{"definition":"MetaobjectDefinitionUpdateInput!","id":"ID!"}],"metaobjectDelete":["MetaobjectDeletePayload",{"id":"ID!"}],"metaobjectUpdate":["MetaobjectUpdatePayload",{"id":"ID!","metaobject":"MetaobjectUpdateInput!"}],"metaobjectUpsert":["MetaobjectUpsertPayload",{"handle":"MetaobjectHandleInput!","metaobject":"MetaobjectUpsertInput","values":"JSON"}],"mobilePlatformApplicationCreate":["MobilePlatformApplicationCreatePayload",{"input":"MobilePlatformApplicationCreateInput!"}],"mobilePlatformApplicationDelete":["MobilePlatformApplicationDeletePayload",{"id":"ID!"}],"mobilePlatformApplicationUpdate":["MobilePlatformApplicationUpdatePayload",{"id":"ID!","input":"MobilePlatformApplicationUpdateInput!"}],"orderAttributionDefinitionDelete":["OrderAttributionDefinitionDeletePayload",{"id":"ID!"}],"orderAttributionDefinitionUpsert":["OrderAttributionDefinitionUpsertPayload",{"input":"OrderAttributionDefinitionUpsertInput!"}],"orderCancel":["OrderCancelPayload",{"notifyCustomer":"Boolean=","orderId":"ID!","reason":"OrderCancelReason!","refund":"Boolean","refundMethod":"OrderCancelRefundMethodInput","restock":"Boolean!","staffNote":"String="}],"orderCapture":["OrderCapturePayload",{"input":"OrderCaptureInput!"}],"orderClose":["OrderClosePayload",{"input":"OrderCloseInput!"}],"orderCreate":["OrderCreatePayload",{"options":"OrderCreateOptionsInput","order":"OrderCreateOrderInput!"}],"orderCreateMandatePayment":["OrderCreateMandatePaymentPayload",{"amount":"MoneyInput","autoCapture":"Boolean=","id":"ID!","idempotencyKey":"String!","mandateId":"ID!","paymentScheduleId":"ID"}],"orderCreateManualPayment":["OrderCreateManualPaymentPayload",{"amount":"MoneyInput","id":"ID!","paymentMethodName":"String","processedAt":"DateTime"}],"orderCustomerRemove":["OrderCustomerRemovePayload",{"orderId":"ID!"}],"orderCustomerSet":["OrderCustomerSetPayload",{"customerId":"ID!","orderId":"ID!"}],"orderDelete":["OrderDeletePayload",{"orderId":"ID!"}],"orderEditAddCustomItem":["OrderEditAddCustomItemPayload",{"id":"ID!","locationId":"ID","price":"MoneyInput!","quantity":"Int!","requiresShipping":"Boolean","taxable":"Boolean","title":"String!"}],"orderEditAddLineItemDiscount":["OrderEditAddLineItemDiscountPayload",{"discount":"OrderEditAppliedDiscountInput!","id":"ID!","lineItemId":"ID!"}],"orderEditAddShippingLine":["OrderEditAddShippingLinePayload",{"id":"ID!","shippingLine":"OrderEditAddShippingLineInput!"}],"orderEditAddVariant":["OrderEditAddVariantPayload",{"allowDuplicates":"Boolean=","id":"ID!","locationId":"ID","quantity":"Int!","variantId":"ID!"}],"orderEditBegin":["OrderEditBeginPayload",{"id":"ID!"}],"orderEditCommit":["OrderEditCommitPayload",{"id":"ID!","notifyCustomer":"Boolean","staffNote":"String"}],"orderEditRemoveDiscount":["OrderEditRemoveDiscountPayload",{"discountApplicationId":"ID!","id":"ID!"}],"orderEditRemoveLineItemDiscount":["OrderEditRemoveLineItemDiscountPayload",{"discountApplicationId":"ID!","id":"ID!"}],"orderEditRemoveShippingLine":["OrderEditRemoveShippingLinePayload",{"id":"ID!","shippingLineId":"ID!"}],"orderEditSetQuantity":["OrderEditSetQuantityPayload",{"id":"ID!","lineItemId":"ID!","locationId":"ID","quantity":"Int!","restock":"Boolean"}],"orderEditUpdateDiscount":["OrderEditUpdateDiscountPayload",{"discount":"OrderEditAppliedDiscountInput!","discountApplicationId":"ID!","id":"ID!"}],"orderEditUpdateShippingLine":["OrderEditUpdateShippingLinePayload",{"id":"ID!","shippingLine":"OrderEditUpdateShippingLineInput!","shippingLineId":"ID!"}],"orderInvoiceSend":["OrderInvoiceSendPayload",{"email":"EmailInput","id":"ID!"}],"orderMarkAsPaid":["OrderMarkAsPaidPayload",{"input":"OrderMarkAsPaidInput!"}],"orderOpen":["OrderOpenPayload",{"input":"OrderOpenInput!"}],"orderRiskAssessmentCreate":["OrderRiskAssessmentCreatePayload",{"orderRiskAssessmentInput":"OrderRiskAssessmentCreateInput!"}],"orderUpdate":["OrderUpdatePayload",{"input":"OrderInput!"}],"pageCreate":["PageCreatePayload",{"page":"PageCreateInput!"}],"pageDelete":["PageDeletePayload",{"id":"ID!"}],"pageUpdate":["PageUpdatePayload",{"id":"ID!","page":"PageUpdateInput!"}],"paymentCustomizationActivation":["PaymentCustomizationActivationPayload",{"enabled":"Boolean!","ids":"[ID!]!"}],"paymentCustomizationCreate":["PaymentCustomizationCreatePayload",{"paymentCustomization":"PaymentCustomizationInput!"}],"paymentCustomizationDelete":["PaymentCustomizationDeletePayload",{"id":"ID!"}],"paymentCustomizationUpdate":["PaymentCustomizationUpdatePayload",{"id":"ID!","paymentCustomization":"PaymentCustomizationInput!"}],"paymentInstrumentSendAddEmail":["PaymentInstrumentSendAddEmailPayload",{"email":"EmailInput","mandate":"PaymentInstrumentMandateInput!"}],"paymentReminderSend":["PaymentReminderSendPayload",{"paymentScheduleId":"ID!"}],"paymentScheduleCapture":["PaymentScheduleCapturePayload",{"paymentScheduleId":"ID!"}],"paymentTermsCreate":["PaymentTermsCreatePayload",{"paymentTermsAttributes":"PaymentTermsCreateInput!","referenceId":"ID!"}],"paymentTermsDelete":["PaymentTermsDeletePayload",{"input":"PaymentTermsDeleteInput!"}],"paymentTermsUpdate":["PaymentTermsUpdatePayload",{"input":"PaymentTermsUpdateInput!"}],"pointOfSaleDeviceAssignToCashDrawer":["PointOfSaleDeviceAssignToCashDrawerPayload",{"cashDrawerId":"ID!","pointOfSaleDeviceId":"ID!"}],"pointOfSaleDevicePaymentSessionAdjust":["PointOfSaleDevicePaymentSessionAdjustPayload",{"cash":"MoneyInput!","note":"String","pointOfSaleDevicePaymentSessionId":"ID!","reasonCodeId":"ID","staffMemberId":"ID!","time":"DateTime"}],"pointOfSaleDevicePaymentSessionClose":["PointOfSaleDevicePaymentSessionClosePayload",{"balance":"MoneyInput!","note":"String","pointOfSaleDevicePaymentSessionId":"ID!","reasonCodeId":"ID","staffMemberId":"ID!","time":"DateTime"}],"pointOfSaleDevicePaymentSessionCount":["PointOfSaleDevicePaymentSessionCountPayload",{"balance":"MoneyInput!","note":"String","pointOfSaleDevicePaymentSessionId":"ID!","reasonCodeId":"ID","staffMemberId":"ID!","time":"DateTime"}],"pointOfSaleDevicePaymentSessionOpen":["PointOfSaleDevicePaymentSessionOpenPayload",{"balance":"MoneyInput","note":"String","pointOfSaleDeviceId":"ID!","reasonCodeId":"ID","staffMemberId":"ID!","time":"DateTime"}],"previewInstall":["PreviewInstallPayload",{"storefrontGenerationPreviewUuid":"String!"}],"priceListCreate":["PriceListCreatePayload",{"input":"PriceListCreateInput!"}],"priceListDelete":["PriceListDeletePayload",{"id":"ID!"}],"priceListFixedPricesAdd":["PriceListFixedPricesAddPayload",{"priceListId":"ID!","prices":"[PriceListPriceInput!]!"}],"priceListFixedPricesByProductUpdate":["PriceListFixedPricesByProductUpdatePayload",{"priceListId":"ID!","pricesToAdd":"[PriceListProductPriceInput!]","pricesToDeleteByProductIds":"[ID!]"}],"priceListFixedPricesDelete":["PriceListFixedPricesDeletePayload",{"priceListId":"ID!","variantIds":"[ID!]!"}],"priceListFixedPricesUpdate":["PriceListFixedPricesUpdatePayload",{"priceListId":"ID!","pricesToAdd":"[PriceListPriceInput!]!","variantIdsToDelete":"[ID!]!"}],"priceListUpdate":["PriceListUpdatePayload",{"id":"ID!","input":"PriceListUpdateInput!"}],"privacyFeaturesDisable":["PrivacyFeaturesDisablePayload",{"featuresToDisable":"[PrivacyFeaturesEnum!]!"}],"productBundleCreate":["ProductBundleCreatePayload",{"input":"ProductBundleCreateInput!"}],"productBundleUpdate":["ProductBundleUpdatePayload",{"input":"ProductBundleUpdateInput!"}],"productChangeStatus":["ProductChangeStatusPayload",{"productId":"ID!","status":"ProductStatus!"}],"productCreate":["ProductCreatePayload",{"input":"ProductInput","media":"[CreateMediaInput!]","product":"ProductCreateInput"}],"productCreateMedia":["ProductCreateMediaPayload",{"media":"[CreateMediaInput!]!","productId":"ID!"}],"productDelete":["ProductDeletePayload",{"input":"ProductDeleteInput!","synchronous":"Boolean="}],"productDeleteMedia":["ProductDeleteMediaPayload",{"mediaIds":"[ID!]!","productId":"ID!"}],"productDuplicate":["ProductDuplicatePayload",{"includeImages":"Boolean=","includeTranslations":"Boolean=","newStatus":"ProductStatus","newTitle":"String!","productId":"ID!","synchronous":"Boolean="}],"productFeedCreate":["ProductFeedCreatePayload",{"input":"ProductFeedInput"}],"productFeedDelete":["ProductFeedDeletePayload",{"id":"ID!"}],"productFullSync":["ProductFullSyncPayload",{"beforeUpdatedAt":"DateTime","id":"ID!","updatedAtSince":"DateTime"}],"productJoinSellingPlanGroups":["ProductJoinSellingPlanGroupsPayload",{"id":"ID!","sellingPlanGroupIds":"[ID!]!"}],"productLeaveSellingPlanGroups":["ProductLeaveSellingPlanGroupsPayload",{"id":"ID!","sellingPlanGroupIds":"[ID!]!"}],"productOptionUpdate":["ProductOptionUpdatePayload",{"option":"OptionUpdateInput!","optionValuesToAdd":"[OptionValueCreateInput!]","optionValuesToDelete":"[ID!]","optionValuesToUpdate":"[OptionValueUpdateInput!]","productId":"ID!","variantStrategy":"ProductOptionUpdateVariantStrategy"}],"productOptionsCreate":["ProductOptionsCreatePayload",{"options":"[OptionCreateInput!]!","productId":"ID!","variantStrategy":"ProductOptionCreateVariantStrategy="}],"productOptionsDelete":["ProductOptionsDeletePayload",{"options":"[ID!]!","productId":"ID!","strategy":"ProductOptionDeleteStrategy="}],"productOptionsReorder":["ProductOptionsReorderPayload",{"options":"[OptionReorderInput!]!","productId":"ID!"}],"productPublish":["ProductPublishPayload",{"input":"ProductPublishInput!"}],"productReorderMedia":["ProductReorderMediaPayload",{"id":"ID!","moves":"[MoveInput!]!"}],"productSet":["ProductSetPayload",{"identifier":"ProductSetIdentifiers","input":"ProductSetInput!","synchronous":"Boolean="}],"productUnpublish":["ProductUnpublishPayload",{"input":"ProductUnpublishInput!"}],"productUpdate":["ProductUpdatePayload",{"identifier":"ProductUpdateIdentifiers","input":"ProductInput","media":"[CreateMediaInput!]","product":"ProductUpdateInput"}],"productUpdateMedia":["ProductUpdateMediaPayload",{"media":"[UpdateMediaInput!]!","productId":"ID!"}],"productVariantAppendMedia":["ProductVariantAppendMediaPayload",{"productId":"ID!","variantMedia":"[ProductVariantAppendMediaInput!]!"}],"productVariantDetachMedia":["ProductVariantDetachMediaPayload",{"productId":"ID!","variantMedia":"[ProductVariantDetachMediaInput!]!"}],"productVariantJoinSellingPlanGroups":["ProductVariantJoinSellingPlanGroupsPayload",{"id":"ID!","sellingPlanGroupIds":"[ID!]!"}],"productVariantLeaveSellingPlanGroups":["ProductVariantLeaveSellingPlanGroupsPayload",{"id":"ID!","sellingPlanGroupIds":"[ID!]!"}],"productVariantRelationshipBulkUpdate":["ProductVariantRelationshipBulkUpdatePayload",{"input":"[ProductVariantRelationshipUpdateInput!]!"}],"productVariantsBulkCreate":["ProductVariantsBulkCreatePayload",{"media":"[CreateMediaInput!]","productId":"ID!","strategy":"ProductVariantsBulkCreateStrategy=","variants":"[ProductVariantsBulkInput!]!"}],"productVariantsBulkDelete":["ProductVariantsBulkDeletePayload",{"productId":"ID!","variantsIds":"[ID!]!"}],"productVariantsBulkReorder":["ProductVariantsBulkReorderPayload",{"positions":"[ProductVariantPositionInput!]!","productId":"ID!"}],"productVariantsBulkUpdate":["ProductVariantsBulkUpdatePayload",{"allowPartialUpdates":"Boolean=","media":"[CreateMediaInput!]","productId":"ID!","variants":"[ProductVariantsBulkInput!]!"}],"pubSubServerPixelUpdate":["PubSubServerPixelUpdatePayload",{"pubSubProject":"String!","pubSubTopic":"String!"}],"pubSubWebhookSubscriptionCreate":["PubSubWebhookSubscriptionCreatePayload",{"topic":"WebhookSubscriptionTopic!","webhookSubscription":"PubSubWebhookSubscriptionInput!"}],"pubSubWebhookSubscriptionUpdate":["PubSubWebhookSubscriptionUpdatePayload",{"id":"ID!","webhookSubscription":"PubSubWebhookSubscriptionInput!"}],"publicationCreate":["PublicationCreatePayload",{"input":"PublicationCreateInput!"}],"publicationDelete":["PublicationDeletePayload",{"id":"ID!"}],"publicationUpdate":["PublicationUpdatePayload",{"id":"ID!","input":"PublicationUpdateInput!"}],"publishablePublish":["PublishablePublishPayload",{"id":"ID!","input":"[PublicationInput!]!"}],"publishablePublishToCurrentChannel":["PublishablePublishToCurrentChannelPayload",{"id":"ID!"}],"publishableUnpublish":["PublishableUnpublishPayload",{"id":"ID!","input":"[PublicationInput!]!"}],"publishableUnpublishToCurrentChannel":["PublishableUnpublishToCurrentChannelPayload",{"id":"ID!"}],"quantityPricingByVariantUpdate":["QuantityPricingByVariantUpdatePayload",{"input":"QuantityPricingByVariantUpdateInput!","priceListId":"ID!"}],"quantityRulesAdd":["QuantityRulesAddPayload",{"priceListId":"ID!","quantityRules":"[QuantityRuleInput!]!"}],"quantityRulesDelete":["QuantityRulesDeletePayload",{"priceListId":"ID!","variantIds":"[ID!]!"}],"refundCreate":["RefundCreatePayload",{"input":"RefundInput!"}],"removeFromReturn":["RemoveFromReturnPayload",{"exchangeLineItems":"[ExchangeLineItemRemoveFromReturnInput!]","returnId":"ID!","returnLineItems":"[ReturnLineItemRemoveFromReturnInput!]"}],"requestedOrderEditCreate":["RequestedOrderEditCreatePayload",{"input":"RequestedOrderEditCreateInput!"}],"requestedOrderEditDecline":["RequestedOrderEditDeclinePayload",{"input":"RequestedOrderEditDeclineInput!"}],"requestedOrderEditResolve":["RequestedOrderEditResolvePayload",{"input":"RequestedOrderEditResolveInput!"}],"returnApproveRequest":["ReturnApproveRequestPayload",{"input":"ReturnApproveRequestInput!"}],"returnCancel":["ReturnCancelPayload",{"id":"ID!","notifyCustomer":"Boolean="}],"returnClose":["ReturnClosePayload",{"id":"ID!"}],"returnCreate":["ReturnCreatePayload",{"returnInput":"ReturnInput!"}],"returnDeclineRequest":["ReturnDeclineRequestPayload",{"input":"ReturnDeclineRequestInput!"}],"returnLineItemRemoveFromReturn":["ReturnLineItemRemoveFromReturnPayload",{"returnId":"ID!","returnLineItems":"[ReturnLineItemRemoveFromReturnInput!]!"}],"returnProcess":["ReturnProcessPayload",{"input":"ReturnProcessInput!"}],"returnRefund":["ReturnRefundPayload",{"returnRefundInput":"ReturnRefundInput!"}],"returnReopen":["ReturnReopenPayload",{"id":"ID!"}],"returnRequest":["ReturnRequestPayload",{"input":"ReturnRequestInput!"}],"reverseDeliveryCreateWithShipping":["ReverseDeliveryCreateWithShippingPayload",{"labelInput":"ReverseDeliveryLabelInput=","notifyCustomer":"Boolean=","reverseDeliveryLineItems":"[ReverseDeliveryLineItemInput!]!","reverseFulfillmentOrderId":"ID!","trackingInput":"ReverseDeliveryTrackingInput="}],"reverseDeliveryShippingUpdate":["ReverseDeliveryShippingUpdatePayload",{"labelInput":"ReverseDeliveryLabelInput=","notifyCustomer":"Boolean=","reverseDeliveryId":"ID!","trackingInput":"ReverseDeliveryTrackingInput="}],"reverseFulfillmentOrderDispose":["ReverseFulfillmentOrderDisposePayload",{"dispositionInputs":"[ReverseFulfillmentOrderDisposeInput!]!"}],"savedSearchCreate":["SavedSearchCreatePayload",{"input":"SavedSearchCreateInput!"}],"savedSearchDelete":["SavedSearchDeletePayload",{"input":"SavedSearchDeleteInput!"}],"savedSearchUpdate":["SavedSearchUpdatePayload",{"input":"SavedSearchUpdateInput!"}],"scriptTagCreate":["ScriptTagCreatePayload",{"input":"ScriptTagInput!"}],"scriptTagDelete":["ScriptTagDeletePayload",{"id":"ID!"}],"scriptTagUpdate":["ScriptTagUpdatePayload",{"id":"ID!","input":"ScriptTagInput!"}],"segmentCreate":["SegmentCreatePayload",{"name":"String!","query":"String!"}],"segmentDelete":["SegmentDeletePayload",{"id":"ID!"}],"segmentUpdate":["SegmentUpdatePayload",{"id":"ID!","name":"String","query":"String"}],"sellingPlanGroupAddProductVariants":["SellingPlanGroupAddProductVariantsPayload",{"id":"ID!","productVariantIds":"[ID!]!"}],"sellingPlanGroupAddProducts":["SellingPlanGroupAddProductsPayload",{"id":"ID!","productIds":"[ID!]!"}],"sellingPlanGroupCreate":["SellingPlanGroupCreatePayload",{"input":"SellingPlanGroupInput!","resources":"SellingPlanGroupResourceInput"}],"sellingPlanGroupDelete":["SellingPlanGroupDeletePayload",{"id":"ID!"}],"sellingPlanGroupRemoveProductVariants":["SellingPlanGroupRemoveProductVariantsPayload",{"id":"ID!","productVariantIds":"[ID!]!"}],"sellingPlanGroupRemoveProducts":["SellingPlanGroupRemoveProductsPayload",{"id":"ID!","productIds":"[ID!]!"}],"sellingPlanGroupUpdate":["SellingPlanGroupUpdatePayload",{"id":"ID!","input":"SellingPlanGroupInput!"}],"serverPixelCreate":"ServerPixelCreatePayload","serverPixelDelete":"ServerPixelDeletePayload","shippingLabelPurchase":["ShippingLabelPurchasePayload",{"shippingLabelPurchase":"ShippingLabelPurchaseInput!"}],"shippingPackageDelete":["ShippingPackageDeletePayload",{"id":"ID!"}],"shippingPackageMakeDefault":["ShippingPackageMakeDefaultPayload",{"id":"ID!"}],"shippingPackageUpdate":["ShippingPackageUpdatePayload",{"id":"ID!","shippingPackage":"CustomShippingPackageInput!"}],"shopLocaleDisable":["ShopLocaleDisablePayload",{"locale":"String!"}],"shopLocaleEnable":["ShopLocaleEnablePayload",{"locale":"String!","marketWebPresenceIds":"[ID!]"}],"shopLocaleUpdate":["ShopLocaleUpdatePayload",{"locale":"String!","shopLocale":"ShopLocaleInput!"}],"shopPolicyUpdate":["ShopPolicyUpdatePayload",{"shopPolicy":"ShopPolicyInput!"}],"shopResourceFeedbackCreate":["ShopResourceFeedbackCreatePayload",{"input":"ResourceFeedbackCreateInput!"}],"shopifyPaymentsPayoutAlternateCurrencyCreate":["ShopifyPaymentsPayoutAlternateCurrencyCreatePayload",{"accountId":"ID","currency":"CurrencyCode!"}],"stagedUploadTargetGenerate":["StagedUploadTargetGeneratePayload",{"input":"StagedUploadTargetGenerateInput!"}],"stagedUploadTargetsGenerate":["StagedUploadTargetsGeneratePayload",{"input":"[StageImageInput!]!"}],"stagedUploadsCreate":["StagedUploadsCreatePayload",{"input":"[StagedUploadInput!]!"}],"standardMetafieldDefinitionEnable":["StandardMetafieldDefinitionEnablePayload",{"access":"StandardMetafieldDefinitionAccessInput","capabilities":"MetafieldCapabilityCreateInput","id":"ID","key":"String","namespace":"String","ownerType":"MetafieldOwnerType!","pin":"Boolean=","useAsCollectionCondition":"Boolean=","visibleToStorefrontApi":"Boolean="}],"standardMetaobjectDefinitionEnable":["StandardMetaobjectDefinitionEnablePayload",{"type":"String!"}],"storeCreditAccountCredit":["StoreCreditAccountCreditPayload",{"creditInput":"StoreCreditAccountCreditInput!","id":"ID!"}],"storeCreditAccountDebit":["StoreCreditAccountDebitPayload",{"debitInput":"StoreCreditAccountDebitInput!","id":"ID!"}],"storefrontAccessTokenCreate":["StorefrontAccessTokenCreatePayload",{"input":"StorefrontAccessTokenInput!"}],"storefrontAccessTokenDelete":["StorefrontAccessTokenDeletePayload",{"input":"StorefrontAccessTokenDeleteInput!"}],"subscriptionBillingAttemptCreate":["SubscriptionBillingAttemptCreatePayload",{"subscriptionBillingAttemptInput":"SubscriptionBillingAttemptInput!","subscriptionContractId":"ID!"}],"subscriptionBillingCycleBulkCharge":["SubscriptionBillingCycleBulkChargePayload",{"actor":"SubscriptionActor","billingAttemptExpectedDateRange":"SubscriptionBillingCyclesDateRangeSelector!","filters":"SubscriptionBillingCycleBulkFilters","inventoryPolicy":"SubscriptionBillingAttemptInventoryPolicy=","paymentProcessingPolicy":"SubscriptionBillingAttemptPaymentProcessingPolicy="}],"subscriptionBillingCycleBulkSearch":["SubscriptionBillingCycleBulkSearchPayload",{"billingAttemptExpectedDateRange":"SubscriptionBillingCyclesDateRangeSelector!","filters":"SubscriptionBillingCycleBulkFilters"}],"subscriptionBillingCycleCharge":["SubscriptionBillingCycleChargePayload",{"actor":"SubscriptionActor","billingCycleSelector":"SubscriptionBillingCycleSelector!","inventoryPolicy":"SubscriptionBillingAttemptInventoryPolicy=","paymentProcessingPolicy":"SubscriptionBillingAttemptPaymentProcessingPolicy","subscriptionContractId":"ID!"}],"subscriptionBillingCycleContractDraftCommit":["SubscriptionBillingCycleContractDraftCommitPayload",{"draftId":"ID!"}],"subscriptionBillingCycleContractDraftConcatenate":["SubscriptionBillingCycleContractDraftConcatenatePayload",{"concatenatedBillingCycleContracts":"[SubscriptionBillingCycleInput!]!","draftId":"ID!"}],"subscriptionBillingCycleContractEdit":["SubscriptionBillingCycleContractEditPayload",{"actor":"SubscriptionActor","billingCycleInput":"SubscriptionBillingCycleInput!"}],"subscriptionBillingCycleContractEditCalculate":["SubscriptionBillingCycleContractEditCalculatePayload",{"actor":"SubscriptionActor","billingCycleEditInput":"SubscriptionContractCalculationBillingCycleEditInput!","billingCycleSelector":"SubscriptionBillingCycleSelector!","contractId":"ID!"}],"subscriptionBillingCycleEditDelete":["SubscriptionBillingCycleEditDeletePayload",{"billingCycleInput":"SubscriptionBillingCycleInput!"}],"subscriptionBillingCycleEditsDelete":["SubscriptionBillingCycleEditsDeletePayload",{"contractId":"ID!","targetSelection":"SubscriptionBillingCyclesTargetSelection!"}],"subscriptionBillingCycleScheduleEdit":["SubscriptionBillingCycleScheduleEditPayload",{"billingCycleInput":"SubscriptionBillingCycleInput!","input":"SubscriptionBillingCycleScheduleEditInput!"}],"subscriptionBillingCycleSkip":["SubscriptionBillingCycleSkipPayload",{"billingCycleInput":"SubscriptionBillingCycleInput!"}],"subscriptionBillingCycleUnskip":["SubscriptionBillingCycleUnskipPayload",{"billingCycleInput":"SubscriptionBillingCycleInput!"}],"subscriptionContractActivate":["SubscriptionContractActivatePayload",{"actor":"SubscriptionActor","subscriptionContractId":"ID!"}],"subscriptionContractAtomicCreate":["SubscriptionContractAtomicCreatePayload",{"input":"SubscriptionContractAtomicCreateInput!"}],"subscriptionContractCalculationCommit":["SubscriptionContractCalculationCommitPayload",{"id":"ID!"}],"subscriptionContractCancel":["SubscriptionContractCancelPayload",{"actor":"SubscriptionActor","subscriptionContractId":"ID!"}],"subscriptionContractCreate":["SubscriptionContractCreatePayload",{"input":"SubscriptionContractCreateInput!"}],"subscriptionContractCreateCalculate":["SubscriptionContractCreateCalculatePayload",{"contractCreateInput":"SubscriptionContractCalculationContractCreateInput!"}],"subscriptionContractExpire":["SubscriptionContractExpirePayload",{"actor":"SubscriptionActor","subscriptionContractId":"ID!"}],"subscriptionContractFail":["SubscriptionContractFailPayload",{"actor":"SubscriptionActor","subscriptionContractId":"ID!"}],"subscriptionContractPause":["SubscriptionContractPausePayload",{"actor":"SubscriptionActor","subscriptionContractId":"ID!"}],"subscriptionContractProductChange":["SubscriptionContractProductChangePayload",{"actor":"SubscriptionActor","input":"SubscriptionContractProductChangeInput!","lineId":"ID!","subscriptionContractId":"ID!"}],"subscriptionContractSetNextBillingDate":["SubscriptionContractSetNextBillingDatePayload",{"contractId":"ID!","date":"DateTime!"}],"subscriptionContractUpdate":["SubscriptionContractUpdatePayload",{"actor":"SubscriptionActor","contractId":"ID!"}],"subscriptionContractUpdateCalculate":["SubscriptionContractUpdateCalculatePayload",{"actor":"SubscriptionActor","contractId":"ID!","contractUpdateInput":"SubscriptionContractCalculationContractUpdateInput!"}],"subscriptionDraftCommit":["SubscriptionDraftCommitPayload",{"draftId":"ID!"}],"subscriptionDraftDiscountAdd":["SubscriptionDraftDiscountAddPayload",{"draftId":"ID!","input":"SubscriptionManualDiscountInput!"}],"subscriptionDraftDiscountCodeApply":["SubscriptionDraftDiscountCodeApplyPayload",{"draftId":"ID!","redeemCode":"String!"}],"subscriptionDraftDiscountRemove":["SubscriptionDraftDiscountRemovePayload",{"discountId":"ID!","draftId":"ID!"}],"subscriptionDraftDiscountUpdate":["SubscriptionDraftDiscountUpdatePayload",{"discountId":"ID!","draftId":"ID!","input":"SubscriptionManualDiscountInput!"}],"subscriptionDraftFreeShippingDiscountAdd":["SubscriptionDraftFreeShippingDiscountAddPayload",{"draftId":"ID!","input":"SubscriptionFreeShippingDiscountInput!"}],"subscriptionDraftFreeShippingDiscountUpdate":["SubscriptionDraftFreeShippingDiscountUpdatePayload",{"discountId":"ID!","draftId":"ID!","input":"SubscriptionFreeShippingDiscountInput!"}],"subscriptionDraftLineAdd":["SubscriptionDraftLineAddPayload",{"draftId":"ID!","input":"SubscriptionLineInput!"}],"subscriptionDraftLineRemove":["SubscriptionDraftLineRemovePayload",{"draftId":"ID!","lineId":"ID!"}],"subscriptionDraftLineUpdate":["SubscriptionDraftLineUpdatePayload",{"draftId":"ID!","input":"SubscriptionLineUpdateInput!","lineId":"ID!"}],"subscriptionDraftUpdate":["SubscriptionDraftUpdatePayload",{"draftId":"ID!","input":"SubscriptionDraftInput!"}],"tagsAdd":["TagsAddPayload",{"id":"ID!","tags":"[String!]!"}],"tagsRemove":["TagsRemovePayload",{"id":"ID!","tags":"[String!]!"}],"taxAppConfigure":["TaxAppConfigurePayload",{"ready":"Boolean!"}],"taxSummaryCreate":["TaxSummaryCreatePayload",{"endTime":"DateTime","orderId":"ID","startTime":"DateTime"}],"themeCreate":["ThemeCreatePayload",{"name":"String","role":"ThemeRole=","source":"URL!"}],"themeDelete":["ThemeDeletePayload",{"id":"ID!"}],"themeDuplicate":["ThemeDuplicatePayload",{"id":"ID!","name":"String"}],"themeFilesCopy":["ThemeFilesCopyPayload",{"files":"[ThemeFilesCopyFileInput!]!","themeId":"ID!"}],"themeFilesDelete":["ThemeFilesDeletePayload",{"files":"[String!]!","themeId":"ID!"}],"themeFilesUpsert":["ThemeFilesUpsertPayload",{"files":"[OnlineStoreThemeFilesUpsertFileInput!]!","themeId":"ID!"}],"themePublish":["ThemePublishPayload",{"id":"ID!"}],"themeUpdate":["ThemeUpdatePayload",{"id":"ID!","input":"OnlineStoreThemeInput!"}],"transactionVoid":["TransactionVoidPayload",{"parentTransactionId":"ID!"}],"translationsRegister":["TranslationsRegisterPayload",{"resourceId":"ID!","translations":"[TranslationInput!]!"}],"translationsRemove":["TranslationsRemovePayload",{"locales":"[String!]!","marketIds":"[ID!]","resourceId":"ID!","translationKeys":"[String!]!"}],"urlRedirectBulkDeleteAll":"UrlRedirectBulkDeleteAllPayload","urlRedirectBulkDeleteByIds":["UrlRedirectBulkDeleteByIdsPayload",{"ids":"[ID!]!"}],"urlRedirectBulkDeleteBySavedSearch":["UrlRedirectBulkDeleteBySavedSearchPayload",{"savedSearchId":"ID!"}],"urlRedirectBulkDeleteBySearch":["UrlRedirectBulkDeleteBySearchPayload",{"search":"String!"}],"urlRedirectCreate":["UrlRedirectCreatePayload",{"urlRedirect":"UrlRedirectInput!"}],"urlRedirectDelete":["UrlRedirectDeletePayload",{"id":"ID!"}],"urlRedirectImportCreate":["UrlRedirectImportCreatePayload",{"url":"URL!"}],"urlRedirectImportSubmit":["UrlRedirectImportSubmitPayload",{"id":"ID!"}],"urlRedirectUpdate":["UrlRedirectUpdatePayload",{"id":"ID!","urlRedirect":"UrlRedirectInput!"}],"validationCreate":["ValidationCreatePayload",{"validation":"ValidationCreateInput!"}],"validationDelete":["ValidationDeletePayload",{"id":"ID!"}],"validationUpdate":["ValidationUpdatePayload",{"id":"ID!","validation":"ValidationUpdateInput!"}],"webPixelCreate":["WebPixelCreatePayload",{"webPixel":"WebPixelInput!"}],"webPixelDelete":["WebPixelDeletePayload",{"id":"ID!"}],"webPixelUpdate":["WebPixelUpdatePayload",{"id":"ID!","webPixel":"WebPixelInput!"}],"webPresenceCreate":["WebPresenceCreatePayload",{"input":"WebPresenceCreateInput!"}],"webPresenceDelete":["WebPresenceDeletePayload",{"id":"ID!"}],"webPresenceUpdate":["WebPresenceUpdatePayload",{"id":"ID!","input":"WebPresenceUpdateInput!"}],"webhookSubscriptionCreate":["WebhookSubscriptionCreatePayload",{"topic":"WebhookSubscriptionTopic!","webhookSubscription":"WebhookSubscriptionInput!"}],"webhookSubscriptionDelete":["WebhookSubscriptionDeletePayload",{"id":"ID!"}],"webhookSubscriptionUpdate":["WebhookSubscriptionUpdatePayload",{"id":"ID!","webhookSubscription":"WebhookSubscriptionInput!"}]},"d":{"abandonmentEmailStateUpdate":"Use `abandonmentUpdateActivitiesDeliveryStatuses` instead.","bulkOperationRunMutation(groupObjects)":"This argument has no effect on output order.","cartTransformCreate(functionId)":"Use `functionHandle` instead.","checkoutBrandingUpsert":"Use `checkoutAndAccountsConfigurationUpdate` instead.","collectionAddProducts":"Use `collectionUpdate` with inclusion.selectionsToAdd instead.","collectionAddProductsV2":"Use `collectionUpdate` with inclusion.selectionsToAdd instead.","collectionCreate(input)":"Use `collection` instead.","collectionPublish":"Use `publishablePublish` instead.","collectionRemoveProducts":"Use `collectionUpdate` with inclusions.selectionsToRemove instead.","collectionUnpublish":"Use `publishableUnpublish` instead.","collectionUpdate(input)":"This argument does not support new collection model features, such as multiple sources. Use `collection` to ensure compatibility with all collections.","companyLocationAssignTaxExemptions":"Use `companyLocationTaxSettingsUpdate` instead.","companyLocationCreateTaxRegistration":"Use `companyLocationTaxSettingsUpdate` instead.","companyLocationRevokeTaxExemptions":"Use `companyLocationTaxSettingsUpdate` instead.","companyLocationRevokeTaxRegistration":"Use `companyLocationTaxSettingsUpdate` instead.","deliveryShippingOriginAssign":"Single origin shipping mode is no longer supported.","draftOrderComplete(paymentPending)":"Create a draft with payment terms rather than marking the draft as pending.","draftOrderDuplicate(draftOrderId)":"Use `id` instead.","eventBridgeWebhookSubscriptionCreate":"Use `webhookSubscriptionCreate` instead.","eventBridgeWebhookSubscriptionUpdate":"Use `webhookSubscriptionUpdate` instead.","flowTriggerReceive(body)":"Use `payload` and `handle` to execute your Flow trigger.","fulfillmentConstraintRuleCreate(functionId)":"Use `functionHandle` instead.","fulfillmentCreateV2":"Use `fulfillmentCreate` instead.","fulfillmentServiceCreate(fulfillmentOrdersOptIn)":"Migration period ended. Defaults to `true`.","fulfillmentServiceUpdate(fulfillmentOrdersOptIn)":"Migration period has ended.","fulfillmentTrackingInfoUpdateV2":"Use `fulfillmentTrackingInfoUpdate` instead.","inventoryActivate(stockAtLegacyLocation)":"All fulfillment services now permit SKU sharing, so activation no longer depends on this argument. It's ignored and has no effect; stop passing it.","inventorySetOnHandQuantities":"Use `inventorySetQuantities` to set on_hand or available quantites instead.","marketCurrencySettingsUpdate":"Use `marketCreate` and `marketUpdate` for creating and updating\nmarket currency settings, respectively. Removed in API version 2027-01.","marketRegionDelete":"Use `marketUpdate` instead.","marketRegionsCreate":"This mutation is deprecated and will be removed in the future. Use `marketCreate` or `marketUpdate` instead.","marketRegionsDelete":"Use `marketUpdate` instead.","marketWebPresenceCreate":"Use `webPresenceCreate` instead.","marketWebPresenceDelete":"Use `webPresenceDelete` instead.","marketWebPresenceUpdate":"Use `webPresenceUpdate` instead.","marketingActivityCreateExternal":"Use `marketingActivityUpsertExternal` instead.","marketingEngagementCreate(channelHandle)":"Channel-level engagements are deprecated. Provide engagement metrics on a marketing activity using `marketingActivityId` or `remoteId` instead.","marketingEngagementsDelete":"Channel-level engagements are deprecated. Activity-level engagement data cannot be deleted directly; delete the MarketingActivity instead.","marketingEngagementsDelete(channelHandle)":"Channel-level engagements are deprecated. Activity-level engagement data cannot be deleted directly; delete the MarketingActivity instead.","marketingEngagementsDelete(deleteEngagementsForAllChannels)":"Channel-level engagements are deprecated. Activity-level engagement data cannot be deleted directly; delete the MarketingActivity instead.","orderCancel(refund)":"Use `refundMethod` instead.","orderEditRemoveLineItemDiscount":"Use `orderEditRemoveDiscount` instead.","orderEditSetQuantity(locationId)":"No longer supported.","productChangeStatus":"Use `productUpdate` instead.","productCreate(input)":"Use `product` instead.","productCreateMedia":"Use `productUpdate` or `productSet` instead.","productDeleteMedia":"Use `fileUpdate` instead.","productPublish":"Use `publishablePublish` instead.","productUnpublish":"Use `publishableUnpublish` instead.","productUpdate(input)":"Use `product` instead.","productUpdateMedia":"Use `fileUpdate` instead.","pubSubWebhookSubscriptionCreate":"Use `webhookSubscriptionCreate` instead.","pubSubWebhookSubscriptionUpdate":"Use `webhookSubscriptionUpdate` instead.","publishablePublishToCurrentChannel":"Use `publishablePublish` instead.","publishableUnpublishToCurrentChannel":"Use `publishableUnpublish` instead.","returnCancel(notifyCustomer)":"Not supported. This argument will be removed in a future version.","returnLineItemRemoveFromReturn":"Use `removeFromReturn` instead.","returnRefund":"Use `returnProcess` instead.","stagedUploadTargetGenerate":"Use `stagedUploadsCreate` instead.","stagedUploadTargetsGenerate":"Use `stagedUploadsCreate` instead.","standardMetafieldDefinitionEnable(useAsCollectionCondition)":"Use `capabilities.smartCollectionCondition` instead.","standardMetafieldDefinitionEnable(visibleToStorefrontApi)":"Use `access.storefront` instead.","subscriptionContractCreate":"Use [`subscriptionContractCreateCalculate`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/subscriptionContractCreateCalculate) instead.","subscriptionContractUpdate":"Use [`subscriptionContractUpdateCalculate`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/subscriptionContractUpdateCalculate) instead.","subscriptionDraftCommit":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftDiscountAdd":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftDiscountCodeApply":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftDiscountRemove":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftDiscountUpdate":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftFreeShippingDiscountAdd":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftFreeShippingDiscountUpdate":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftLineAdd":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftLineRemove":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftLineUpdate":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","subscriptionDraftUpdate":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead."}}}, +"MutationsStagedUploadTargetGenerateUploadParameter":{"o":{"f":{"name":"String!","value":"String!"}}}, +"Navigable":{"n":{"f":{"defaultCursor":"String!"},"t":["AbandonedCheckout","Article","Company","CompanyLocation","CustomerAccountAppExtensionPage","CustomerAccountNativePage","DraftOrder","Page","Product","ProductVariant"]}}, +"NavigationItem":{"o":{"f":{"id":"String!","title":"String!","url":"URL!"}}}, +"Node":{"n":{"f":{"id":"ID!"},"t":["AbandonedCheckout","AbandonedCheckoutLineItem","Abandonment","AddAllProductsOperation","AdditionalFee","AnalyticsAnnotation","AnalyticsTarget","App","AppCatalog","AppCredit","AppInstallation","AppPurchaseOneTime","AppRevenueAttributionRecord","AppSubscription","AppUsageRecord","Article","BasicEvent","Blog","BulkOperation","BusinessEntity","CalculatedOrder","CartTransform","CashDrawer","CashManagementCustomReasonCode","CashManagementDefaultReasonCode","CashManagementSystemReasonCode","CashTrackingAdjustment","CashTrackingSession","CatalogCsvOperation","Channel","ChannelDefinition","ChannelInformation","CheckoutAndAccountsConfiguration","CheckoutAndAccountsConfigurationOverride","CheckoutProfile","Collection","CollectionConditionsSource","CollectionSubCollectionsSource","Comment","CommentEvent","Company","CompanyAddress","CompanyContact","CompanyContactRole","CompanyContactRoleAssignment","CompanyLocation","CompanyLocationCatalog","CompanyLocationStaffMemberAssignment","ConsentPolicy","CurrencyExchangeAdjustment","Customer","CustomerAccountAppExtensionPage","CustomerAccountNativePage","CustomerPaymentMethod","CustomerSegmentMembersQuery","CustomerVisit","DeliveryCarrierService","DeliveryCondition","DeliveryCountry","DeliveryCustomization","DeliveryLocationGroup","DeliveryMethod","DeliveryMethodDefinition","DeliveryParticipant","DeliveryProfile","DeliveryProfileItem","DeliveryPromiseParticipant","DeliveryPromiseProvider","DeliveryProvince","DeliveryRateDefinition","DeliveryZone","DiscountAutomaticBxgy","DiscountAutomaticNode","DiscountCodeNode","DiscountNode","DiscountRedeemCodeBulkCreation","Domain","DraftOrder","DraftOrderLineItem","DraftOrderTag","Duty","ExchangeLineItem","ExchangeV2","ExternalVideo","Fulfillment","FulfillmentConstraintRule","FulfillmentEvent","FulfillmentHold","FulfillmentLineItem","FulfillmentOrder","FulfillmentOrderDestination","FulfillmentOrderLineItem","FulfillmentOrderMerchantRequest","GenericFile","GiftCard","GiftCardCashOutTransaction","GiftCardCreditTransaction","GiftCardDebitTransaction","IdentityProviderSubject","InventoryAdjustmentGroup","InventoryItem","InventoryItemMeasurement","InventoryLevel","InventoryPurchaseOrder","InventoryPurchaseOrderLineItem","InventoryQuantity","InventoryShipment","InventoryShipmentLineItem","InventoryTransfer","InventoryTransferLineItem","LineItem","LineItemGroup","Location","MailingAddress","Market","MarketCatalog","MarketRegionCountry","MarketRegionSubdivision","MarketRelationship","MarketWebPresence","MarketingActivity","MarketingEvent","MediaImage","Menu","Metafield","MetafieldDefinition","Metaobject","MetaobjectDefinition","Model3d","OnlineStoreTheme","Order","OrderAdjustment","OrderAttributionDefinition","OrderCancelJobResult","OrderCreateMandatePaymentJobResult","OrderDisputeSummary","OrderEditSession","OrderTransaction","Page","PaymentCustomization","PaymentMandate","PaymentSchedule","PaymentTerms","PaymentTermsTemplate","PointOfSaleDevice","PointOfSaleDevicePaymentSession","PriceList","Product","ProductBundleOperation","ProductDeleteOperation","ProductDuplicateOperation","ProductFeed","ProductOption","ProductOptionValue","ProductSetOperation","ProductTaxonomyNode","ProductVariant","ProductVariantComponent","Publication","PublicationResourceOperation","QuantityPriceBreak","Refund","RefundShippingLine","RequestedOrderEdit","RequestedOrderEditLineItem","Return","ReturnLineItem","ReturnPolicyProfile","ReturnReasonDefinition","ReturnableFulfillment","ReverseDelivery","ReverseDeliveryLineItem","ReverseFulfillmentOrder","ReverseFulfillmentOrderDisposition","ReverseFulfillmentOrderLineItem","Rollout","RolloutTreatment","SaleAdditionalFee","SavedSearch","ScriptTag","Segment","SellingPlan","SellingPlanGroup","ServerPixel","ShippingLabel","ShippingLabelPurchaseResult","Shop","ShopAddress","ShopPolicy","ShopifyPaymentsAccount","ShopifyPaymentsBalanceTransaction","ShopifyPaymentsBankAccount","ShopifyPaymentsDispute","ShopifyPaymentsDisputeEvidence","ShopifyPaymentsDisputeFileUpload","ShopifyPaymentsDisputeFulfillment","ShopifyPaymentsPayout","StaffMember","StandardMetafieldDefinitionTemplate","StoreCreditAccount","StoreCreditAccountCreditTransaction","StoreCreditAccountDebitRevertTransaction","StoreCreditAccountDebitTransaction","StorefrontAccessToken","SubscriptionBillingAttempt","SubscriptionContract","SubscriptionDraft","TaxonomyAttribute","TaxonomyCategory","TaxonomyChoiceListAttribute","TaxonomyMeasurementAttribute","TaxonomyValue","TenderTransaction","TransactionFee","UnverifiedReturnLineItem","UrlRedirect","UrlRedirectImport","Validation","Video","WebPixel","WebhookSubscription"]}}, +"NotificationUsage":{"e":["WEB","SMS"]}, +"ObjectDimensionsInput":{"i":{"height":"Float!","length":"Float!","unit":"LengthUnit!","width":"Float!"}}, +"OnlineStore":{"o":{"f":{"passwordProtection":"OnlineStorePasswordProtection!"}}}, +"OnlineStorePasswordProtection":{"o":{"f":{"enabled":"Boolean!"}}}, +"OnlineStorePreviewable":{"n":{"f":{"onlineStorePreviewUrl":"URL"},"t":["Product"]}}, +"OnlineStoreTheme":{"o":{"f":{"createdAt":"DateTime!","files":["OnlineStoreThemeFileConnection",{"after":"String","filenames":"[String!]","first":"Int="}],"id":"ID!","name":"String!","prefix":"String!","processing":"Boolean!","processingFailed":"Boolean!","role":"ThemeRole!","themeStoreId":"Int","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"updatedAt":"DateTime!"},"t":["HasPublishedTranslations","Node"]}}, +"OnlineStoreThemeConnection":{"o":{"f":{"edges":"[OnlineStoreThemeEdge!]!","nodes":"[OnlineStoreTheme!]!","pageInfo":"PageInfo!"}}}, +"OnlineStoreThemeEdge":{"o":{"f":{"cursor":"String!","node":"OnlineStoreTheme!"}}}, +"OnlineStoreThemeFile":{"o":{"f":{"body":"OnlineStoreThemeFileBody!","checksumMd5":"String","contentType":"String!","createdAt":"DateTime!","filename":"String!","size":"UnsignedInt64!","updatedAt":"DateTime!"}}}, +"OnlineStoreThemeFileBody":{"u":["OnlineStoreThemeFileBodyBase64","OnlineStoreThemeFileBodyText","OnlineStoreThemeFileBodyUrl"]}, +"OnlineStoreThemeFileBodyBase64":{"o":{"f":{"contentBase64":"String!"}}}, +"OnlineStoreThemeFileBodyInput":{"i":{"type":"OnlineStoreThemeFileBodyInputType!","value":"String!"}}, +"OnlineStoreThemeFileBodyInputType":{"e":["TEXT","BASE64","URL"]}, +"OnlineStoreThemeFileBodyText":{"o":{"f":{"content":"String!"}}}, +"OnlineStoreThemeFileBodyUrl":{"o":{"f":{"url":"URL!"}}}, +"OnlineStoreThemeFileConnection":{"o":{"f":{"edges":"[OnlineStoreThemeFileEdge!]!","nodes":"[OnlineStoreThemeFile!]!","pageInfo":"PageInfo!","userErrors":"[OnlineStoreThemeFileReadResult!]!"}}}, +"OnlineStoreThemeFileEdge":{"o":{"f":{"cursor":"String!","node":"OnlineStoreThemeFile!"}}}, +"OnlineStoreThemeFileOperationResult":{"o":{"f":{"checksumMd5":"String","createdAt":"DateTime!","filename":"String!","size":"UnsignedInt64!","updatedAt":"DateTime!"}}}, +"OnlineStoreThemeFileReadResult":{"o":{"f":{"code":"OnlineStoreThemeFileResultType!","filename":"String!"}}}, +"OnlineStoreThemeFileResultType":{"e":["SUCCESS","ERROR","CONFLICT","UNPROCESSABLE_ENTITY","BAD_REQUEST","TIMEOUT","NOT_FOUND"]}, +"OnlineStoreThemeFilesUpsertFileInput":{"i":{"body":"OnlineStoreThemeFileBodyInput!","filename":"String!"}}, +"OnlineStoreThemeFilesUserErrors":{"o":{"f":{"code":"OnlineStoreThemeFilesUserErrorsCode","field":"[String!]","filename":"String","message":"String!"},"t":["DisplayableError"]}}, +"OnlineStoreThemeFilesUserErrorsCode":{"e":["NOT_FOUND","LESS_THAN_OR_EQUAL_TO","THEME_FILES_CONFLICT","DUPLICATE_FILE_INPUT","ACCESS_DENIED","THEME_LIMITED_PLAN","THEME_CONTEXTUALIZATION_NOT_COMPATIBLE_WITH_CONDITION_TYPES","FILE_VALIDATION_ERROR","ERROR","THROTTLED"]}, +"OnlineStoreThemeInput":{"i":{"name":"String"}}, +"OptionAndValueInput":{"i":{"linkedMetafield":"LinkedMetafieldInput","name":"String!","optionId":"ID","values":"[String!]!"}}, +"OptionCreateInput":{"i":{"linkedMetafield":"LinkedMetafieldCreateInput","name":"String","position":"Int","values":"[OptionValueCreateInput!]"}}, +"OptionReorderInput":{"i":{"id":"ID","name":"String","values":"[OptionValueReorderInput!]"}}, +"OptionSetInput":{"i":{"id":"ID","linkedMetafield":"LinkedMetafieldCreateInput","name":"String","position":"Int","values":"[OptionValueSetInput!]"}}, +"OptionUpdateInput":{"i":{"id":"ID!","linkedMetafield":"LinkedMetafieldUpdateInput","name":"String","position":"Int"}}, +"OptionValueCreateInput":{"i":{"linkedMetafieldValue":"String","name":"String"}}, +"OptionValueReorderInput":{"i":{"id":"ID","name":"String"}}, +"OptionValueSetInput":{"i":{"id":"ID","name":"String"}}, +"OptionValueUpdateInput":{"i":{"id":"ID!","linkedMetafieldValue":"String","name":"String"}}, +"Order":{"o":{"f":{"additionalFees":"[AdditionalFee!]!","agreements":["SalesAgreementConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"alerts":"[ResourceAlert!]!","app":"OrderApp","attribution":"OrderAttribution","billingAddress":"MailingAddress","billingAddressMatchesShippingAddress":"Boolean!","canMarkAsPaid":"Boolean!","canNotifyCustomer":"Boolean!","cancelReason":"OrderCancelReason","cancellation":"OrderCancellation","cancelledAt":"DateTime","capturable":"Boolean!","cartDiscountAmount":"Money","cartDiscountAmountSet":"MoneyBag","cartToken":"String","channel":"Channel","channelInformation":"ChannelInformation","checkoutToken":"String","clientIp":"String","closed":"Boolean!","closedAt":"DateTime","confirmationNumber":"String","confirmed":"Boolean!","createdAt":"DateTime!","currencyCode":"CurrencyCode!","currentCartDiscountAmountSet":"MoneyBag!","currentShippingPriceSet":"MoneyBag!","currentSubtotalLineItemsQuantity":"Int!","currentSubtotalPriceSet":"MoneyBag!","currentTaxLines":"[TaxLine!]!","currentTotalAdditionalFeesSet":"MoneyBag","currentTotalDiscountsSet":"MoneyBag!","currentTotalDutiesSet":"MoneyBag","currentTotalPriceSet":"MoneyBag!","currentTotalTaxSet":"MoneyBag!","currentTotalWeight":"UnsignedInt64!","customAttributes":"[Attribute!]!","customer":"Customer","customerAcceptsMarketing":"Boolean!","customerJourney":"CustomerJourney","customerJourneySummary":"CustomerJourneySummary","customerLocale":"String","discountApplications":["DiscountApplicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"discountCode":"String","discountCodes":"[String!]!","displayAddress":"MailingAddress","displayFinancialStatus":"OrderDisplayFinancialStatus","displayFulfillmentStatus":"OrderDisplayFulfillmentStatus!","displayRequestedEditStatus":"OrderDisplayRequestedEditStatus!","disputes":"[OrderDisputeSummary!]!","dutiesIncluded":"Boolean!","edited":"Boolean!","email":"String","estimatedTaxes":"Boolean!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"exchangeV2s":["ExchangeV2Connection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"fulfillable":"Boolean!","fulfillmentOrders":["FulfillmentOrderConnection!",{"after":"String","before":"String","displayable":"Boolean=","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"fulfillments":["[Fulfillment!]!",{"first":"Int","query":"String"}],"fulfillmentsCount":"Count","fullyPaid":"Boolean!","hasTimelineComment":"Boolean!","id":"ID!","landingPageDisplayText":"String","landingPageUrl":"URL","legacyResourceId":"UnsignedInt64!","lineItems":["LineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"localizationExtensions":["LocalizationExtensionConnection!",{"after":"String","before":"String","countryCodes":"[CountryCode!]","first":"Int","last":"Int","purposes":"[LocalizationExtensionPurpose!]","reverse":"Boolean="}],"localizedFields":["LocalizedFieldConnection!",{"after":"String","before":"String","countryCodes":"[CountryCode!]","first":"Int","last":"Int","purposes":"[LocalizedFieldPurpose!]","reverse":"Boolean="}],"merchantBusinessEntity":"BusinessEntity!","merchantEditable":"Boolean!","merchantEditableErrors":"[String!]!","merchantOfRecordApp":"OrderApp","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","netPayment":"Money!","netPaymentSet":"MoneyBag!","nonFulfillableLineItems":["LineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"note":"String","number":"Int!","originalTotalAdditionalFeesSet":"MoneyBag","originalTotalDutiesSet":"MoneyBag","originalTotalPriceSet":"MoneyBag!","paymentCollectionDetails":"OrderPaymentCollectionDetails!","paymentGatewayNames":"[String!]!","paymentTerms":"PaymentTerms","phone":"String","physicalLocation":"Location","poNumber":"String","presentmentCurrencyCode":"CurrencyCode!","processedAt":"DateTime!","productNetwork":"Boolean!","publication":"Publication","purchasingEntity":"PurchasingEntity","referralCode":"String","referrerDisplayText":"String","referrerUrl":"URL","refundDiscrepancySet":"MoneyBag!","refundable":"Boolean!","refunds":["[Refund!]!",{"first":"Int"}],"registeredSourceUrl":"URL","requestedOrderEdits":["RequestedOrderEditConnection!",{"after":"String","before":"String","first":"Int","last":"Int"}],"requiresShipping":"Boolean!","restockable":"Boolean!","retailLocation":"Location","returnStatus":"OrderReturnStatus!","returns":["ReturnConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"risk":"OrderRiskSummary!","riskLevel":"OrderRiskLevel!","risks":["[OrderRisk!]!",{"first":"Int"}],"shippingAddress":"MailingAddress","shippingLine":"ShippingLine","shippingLines":["ShippingLineConnection!",{"after":"String","before":"String","first":"Int","includeRemovals":"Boolean=","last":"Int","reverse":"Boolean="}],"shopifyProtect":"ShopifyProtectOrderSummary","sourceIdentifier":"String","sourceName":"String","staffMember":"StaffMember","statusPageUrl":["URL!",{"audience":"Audience","notificationUsage":"NotificationUsage"}],"subtotalLineItemsQuantity":"Int!","subtotalPrice":"Money","subtotalPriceSet":"MoneyBag","suggestedRefund":["SuggestedRefund",{"refundDuties":"[RefundDutyInput!]","refundLineItems":"[RefundLineItemInput!]","refundMethodAllocation":"RefundMethodAllocation=","refundShipping":"Boolean","shippingAmount":"Money","suggestFullRefund":"Boolean="}],"tags":"[String!]!","taxExempt":"Boolean!","taxLines":"[TaxLine!]!","taxesIncluded":"Boolean!","test":"Boolean!","totalCapturable":"Money!","totalCapturableSet":"MoneyBag!","totalCashRoundingAdjustment":"CashRoundingAdjustment!","totalDiscounts":"Money","totalDiscountsSet":"MoneyBag","totalOutstandingSet":"MoneyBag!","totalPrice":"Money!","totalPriceSet":"MoneyBag!","totalReceived":"Money!","totalReceivedSet":"MoneyBag!","totalRefunded":"Money!","totalRefundedSet":"MoneyBag!","totalRefundedShippingSet":"MoneyBag!","totalShippingPrice":"Money!","totalShippingPriceSet":"MoneyBag!","totalTax":"Money","totalTaxSet":"MoneyBag","totalTipReceived":"MoneyV2!","totalTipReceivedSet":"MoneyBag!","totalWeight":"UnsignedInt64","transactions":["[OrderTransaction!]!",{"capturable":"Boolean","first":"Int","manuallyResolvable":"Boolean"}],"transactionsCount":"Count","unpaid":"Boolean!","updatedAt":"DateTime!"},"t":["CommentEventSubject","HasEvents","HasLocalizationExtensions","HasLocalizedFields","HasMetafieldDefinitions","HasMetafields","LegacyInteroperability","Node"],"d":{"cartDiscountAmount":"Use `cartDiscountAmountSet` instead.","channel":"Use `publication` instead.","channelInformation":"Use `attribution` instead.","customerJourney":"Use `customerJourneySummary` instead.","exchangeV2s":"Use `returns` instead.","landingPageDisplayText":"Use `customerJourneySummary.lastVisit.landingPageHtml` instead","landingPageUrl":"Use `customerJourneySummary.lastVisit.landingPage` instead","localizationExtensions":"This connection will be removed in a future version. Use `localizedFields` instead.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","netPayment":"Use `netPaymentSet` instead.","physicalLocation":"Use `fulfillmentOrders` to get the fulfillment location for the order","referralCode":"Use `customerJourneySummary.lastVisit.referralCode` instead","referrerDisplayText":"Use `customerJourneySummary.lastVisit.referralInfoHtml` instead","referrerUrl":"Use `customerJourneySummary.lastVisit.referrerUrl` instead","riskLevel":"This field is deprecated in favor of OrderRiskAssessment.riskLevel which allows for more granular risk levels, including PENDING and NONE.","risks":"This field is deprecated in favor of OrderRiskAssessment, which provides enhanced capabilities such as distinguishing risks from their provider.","subtotalPrice":"Use `subtotalPriceSet` instead.","totalCapturable":"Use `totalCapturableSet` instead.","totalDiscounts":"Use `totalDiscountsSet` instead.","totalPrice":"Use `totalPriceSet` instead.","totalReceived":"Use `totalReceivedSet` instead.","totalRefunded":"Use `totalRefundedSet` instead.","totalShippingPrice":"Use `totalShippingPriceSet` instead.","totalTax":"Use `totalTaxSet` instead.","totalTipReceived":"Use `totalTipReceivedSet` instead."}}}, +"OrderActionType":{"e":["ORDER","ORDER_EDIT","REFUND","RETURN","UNKNOWN"]}, +"OrderAdjustment":{"o":{"f":{"amountSet":"MoneyBag!","id":"ID!","reason":"OrderAdjustmentDiscrepancyReason","taxAmountSet":"MoneyBag!"},"t":["Node"]}}, +"OrderAdjustmentConnection":{"o":{"f":{"edges":"[OrderAdjustmentEdge!]!","nodes":"[OrderAdjustment!]!","pageInfo":"PageInfo!"}}}, +"OrderAdjustmentDiscrepancyReason":{"e":["RESTOCK","DAMAGE","CUSTOMER","REFUND_DISCREPANCY","FULL_RETURN_BALANCING_ADJUSTMENT","PENDING_REFUND_DISCREPANCY"]}, +"OrderAdjustmentEdge":{"o":{"f":{"cursor":"String!","node":"OrderAdjustment!"}}}, +"OrderAdjustmentInputDiscrepancyReason":{"e":["RESTOCK","DAMAGE","CUSTOMER","OTHER"]}, +"OrderAgreement":{"o":{"f":{"app":"App","happenedAt":"DateTime!","id":"ID!","order":"Order!","reason":"OrderActionType!","sales":["SaleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"user":"StaffMember"},"t":["SalesAgreement"]}}, +"OrderApp":{"o":{"f":{"icon":"Image!","id":"ID!","name":"String!"}}}, +"OrderAttribution":{"o":{"f":{"displayName":"String!","handle":"String!","icon":"String"}}}, +"OrderAttributionDefinition":{"o":{"f":{"displayName":"String!","handle":"String!","icon":"String","id":"ID!"},"t":["Node"]}}, +"OrderAttributionDefinitionConnection":{"o":{"f":{"edges":"[OrderAttributionDefinitionEdge!]!","nodes":"[OrderAttributionDefinition!]!","pageInfo":"PageInfo!"}}}, +"OrderAttributionDefinitionDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[OrderAttributionDefinitionDeleteUserError!]!"}}}, +"OrderAttributionDefinitionDeleteUserError":{"o":{"f":{"code":"OrderAttributionDefinitionDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderAttributionDefinitionDeleteUserErrorCode":{"e":["INVALID","NOT_FOUND"]}, +"OrderAttributionDefinitionEdge":{"o":{"f":{"cursor":"String!","node":"OrderAttributionDefinition!"}}}, +"OrderAttributionDefinitionUpsertInput":{"i":{"displayName":"String!","handle":"String!","icon":"String"}}, +"OrderAttributionDefinitionUpsertPayload":{"o":{"f":{"orderAttributionDefinition":"OrderAttributionDefinition","userErrors":"[OrderAttributionDefinitionUpsertUserError!]!"}}}, +"OrderAttributionDefinitionUpsertUserError":{"o":{"f":{"code":"OrderAttributionDefinitionUpsertUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderAttributionDefinitionUpsertUserErrorCode":{"e":["INVALID"]}, +"OrderCancelJobResult":{"o":{"f":{"done":"Boolean!","errors":"[OrderCancelUserError!]!","id":"ID!","order":"Order","status":"OrderCancelStatus!"},"t":["JobResult","Node"]}}, +"OrderCancelPayload":{"o":{"f":{"job":"Job","jobResult":"OrderCancelJobResult","orderCancelUserErrors":"[OrderCancelUserError!]!","userErrors":"[UserError!]!"},"d":{"userErrors":"Use `orderCancelUserErrors` instead."}}}, +"OrderCancelReason":{"e":["CUSTOMER","DECLINED","FRAUD","INVENTORY","STAFF","OTHER"]}, +"OrderCancelRefundMethodInput":{"i":{"f":{"originalPaymentMethodsRefund":"Boolean","storeCreditRefund":"OrderCancelStoreCreditRefundInput"},"o":true}}, +"OrderCancelStatus":{"e":["STARTED","SUCCEEDED","FAILED"]}, +"OrderCancelStoreCreditRefundInput":{"i":{"expiresAt":"DateTime"}}, +"OrderCancelUserError":{"o":{"f":{"code":"OrderCancelUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderCancelUserErrorCode":{"e":["NO_REFUND_PERMISSION","NO_REFUND_TO_STORE_CREDIT_PERMISSION","STORE_CREDIT_REFUND_EXPIRATION_IN_PAST","STORE_CREDIT_REFUND_MISSING_CUSTOMER","STORE_CREDIT_REFUND_B2B_NOT_SUPPORTED","NOT_FOUND","INVALID","INTERNAL_ERROR"]}, +"OrderCancellation":{"o":{"f":{"staffNote":"String"}}}, +"OrderCaptureInput":{"i":{"amount":"Money!","currency":"CurrencyCode","finalCapture":"Boolean","id":"ID!","parentTransactionId":"ID!"}}, +"OrderCapturePayload":{"o":{"f":{"transaction":"OrderTransaction","userErrors":"[UserError!]!"}}}, +"OrderCloseInput":{"i":{"id":"ID!"}}, +"OrderClosePayload":{"o":{"f":{"order":"Order","userErrors":"[UserError!]!"}}}, +"OrderConnection":{"o":{"f":{"edges":"[OrderEdge!]!","nodes":"[Order!]!","pageInfo":"PageInfo!"}}}, +"OrderCreateAssociateCustomerAttributesInput":{"i":{"email":"String","id":"ID"}}, +"OrderCreateCustomAttributeInput":{"i":{"key":"String!","value":"String!"}}, +"OrderCreateCustomerAddressInput":{"i":{"address1":"String","address2":"String","city":"String","company":"String","country":"String","firstName":"String","lastName":"String","phone":"String","province":"String","zip":"String"}}, +"OrderCreateCustomerInput":{"i":{"f":{"toAssociate":"OrderCreateAssociateCustomerAttributesInput","toUpsert":"OrderCreateUpsertCustomerAttributesInput"},"o":true}}, +"OrderCreateDiscountCodeInput":{"i":{"freeShippingDiscountCode":"OrderCreateFreeShippingDiscountCodeAttributesInput","itemFixedDiscountCode":"OrderCreateFixedDiscountCodeAttributesInput","itemPercentageDiscountCode":"OrderCreatePercentageDiscountCodeAttributesInput"}}, +"OrderCreateFinancialStatus":{"e":["PENDING","AUTHORIZED","PARTIALLY_PAID","PAID","PARTIALLY_REFUNDED","REFUNDED","VOIDED","EXPIRED"]}, +"OrderCreateFixedDiscountCodeAttributesInput":{"i":{"amountSet":"MoneyBagInput","code":"String!"}}, +"OrderCreateFreeShippingDiscountCodeAttributesInput":{"i":{"code":"String!"}}, +"OrderCreateFulfillmentInput":{"i":{"locationId":"ID!","notifyCustomer":"Boolean=","originAddress":"FulfillmentOriginAddressInput","shipmentStatus":"FulfillmentEventStatus","trackingCompany":"String","trackingNumber":"String","trackingNumbers":"[String!]"}}, +"OrderCreateFulfillmentStatus":{"e":["FULFILLED","PARTIAL","RESTOCKED"]}, +"OrderCreateInputsInventoryBehavior":{"e":["BYPASS","DECREMENT_IGNORING_POLICY","DECREMENT_OBEYING_POLICY"]}, +"OrderCreateLineItemInput":{"i":{"fulfillmentService":"String","giftCard":"Boolean=","priceSet":"MoneyBagInput","productId":"ID","properties":"[OrderCreateLineItemPropertyInput!]","quantity":"Int!","requiresShipping":"Boolean=","sku":"String","taxLines":"[OrderCreateTaxLineInput!]","taxable":"Boolean=","title":"String","variantId":"ID","variantTitle":"String","vendor":"String","weight":"WeightInput"}}, +"OrderCreateLineItemPropertyInput":{"i":{"name":"String!","value":"String!"}}, +"OrderCreateMandatePaymentJobResult":{"o":{"f":{"done":"Boolean!","errors":"[UserError!]!","id":"ID!","order":"Order","status":"OrderCreateMandatePaymentStatus!"},"t":["JobResult","Node"]}}, +"OrderCreateMandatePaymentPayload":{"o":{"f":{"job":"Job","jobResult":"OrderCreateMandatePaymentJobResult","paymentReferenceId":"String","userErrors":"[OrderCreateMandatePaymentUserError!]!"}}}, +"OrderCreateMandatePaymentStatus":{"e":["STARTED","SUCCEEDED","FAILED"]}, +"OrderCreateMandatePaymentUserError":{"o":{"f":{"code":"OrderCreateMandatePaymentUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderCreateMandatePaymentUserErrorCode":{"e":["ORDER_MANDATE_PAYMENT_ERROR_CODE"]}, +"OrderCreateManualPaymentOrderCreateManualPaymentError":{"o":{"f":{"code":"OrderCreateManualPaymentOrderCreateManualPaymentErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderCreateManualPaymentOrderCreateManualPaymentErrorCode":{"e":["ORDER_NOT_FOUND","AMOUNT_NOT_POSITIVE","GATEWAY_NOT_FOUND","AMOUNT_EXCEEDS_BALANCE","ORDER_IS_TEMPORARILY_UNAVAILABLE","PROCESSED_AT_INVALID","CURRENCY_MISMATCH"]}, +"OrderCreateManualPaymentPayload":{"o":{"f":{"order":"Order","userErrors":"[OrderCreateManualPaymentOrderCreateManualPaymentError!]!"}}}, +"OrderCreateOptionsInput":{"i":{"inventoryBehaviour":"OrderCreateInputsInventoryBehavior=","sendFulfillmentReceipt":"Boolean=","sendReceipt":"Boolean="}}, +"OrderCreateOrderInput":{"i":{"f":{"billingAddress":"MailingAddressInput","buyerAcceptsMarketing":"Boolean=","closedAt":"DateTime","companyLocationId":"ID","currency":"CurrencyCode","customAttributes":"[OrderCreateCustomAttributeInput!]","customer":"OrderCreateCustomerInput","customerId":"ID","discountCode":"OrderCreateDiscountCodeInput","email":"String","financialStatus":"OrderCreateFinancialStatus","fulfillment":"OrderCreateFulfillmentInput","fulfillmentStatus":"OrderCreateFulfillmentStatus","lineItems":"[OrderCreateLineItemInput!]","metafields":"[MetafieldInput!]","name":"String","note":"String","phone":"String","poNumber":"String","presentmentCurrency":"CurrencyCode","processedAt":"DateTime","referringSite":"URL","shippingAddress":"MailingAddressInput","shippingLines":"[OrderCreateShippingLineInput!]","sourceIdentifier":"String","sourceName":"String","sourceUrl":"URL","tags":"[String!]","taxLines":"[OrderCreateTaxLineInput!]","taxesIncluded":"Boolean=","test":"Boolean=","transactions":"[OrderCreateOrderTransactionInput!]","userId":"ID"},"d":{"customerId":"This is replaced by the `customer` field in a future version."}}}, +"OrderCreateOrderTransactionInput":{"i":{"amountSet":"MoneyBagInput!","authorizationCode":"String","deviceId":"ID","gateway":"String","giftCardId":"ID","kind":"OrderTransactionKind=","locationId":"ID","processedAt":"DateTime","receiptJson":"JSON","status":"OrderTransactionStatus=","test":"Boolean=","userId":"ID"}}, +"OrderCreatePayload":{"o":{"f":{"order":"Order","userErrors":"[OrderCreateUserError!]!"}}}, +"OrderCreatePercentageDiscountCodeAttributesInput":{"i":{"code":"String!","percentage":"Float"}}, +"OrderCreateShippingLineInput":{"i":{"code":"String","priceSet":"MoneyBagInput!","source":"String","taxLines":"[OrderCreateTaxLineInput!]","title":"String!"}}, +"OrderCreateTaxLineInput":{"i":{"channelLiable":"Boolean=","priceSet":"MoneyBagInput","rate":"Decimal!","title":"String!"}}, +"OrderCreateUpsertCustomerAttributesInput":{"i":{"addresses":"[OrderCreateCustomerAddressInput!]","email":"String","firstName":"String","id":"ID","lastName":"String","multipassIdentifier":"String","note":"String","phone":"String","tags":"[String!]","taxExempt":"Boolean"}}, +"OrderCreateUserError":{"o":{"f":{"code":"OrderCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderCreateUserErrorCode":{"e":["INVALID","FULFILLMENT_SERVICE_INVALID","INVENTORY_CLAIM_FAILED","PROCESSED_AT_INVALID","TAX_LINE_RATE_MISSING","REDUNDANT_CUSTOMER_FIELDS","SHOP_DORMANT"]}, +"OrderCustomerRemovePayload":{"o":{"f":{"order":"Order","userErrors":"[OrderCustomerRemoveUserError!]!"}}}, +"OrderCustomerRemoveUserError":{"o":{"f":{"code":"OrderCustomerRemoveUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderCustomerRemoveUserErrorCode":{"e":["NOT_FOUND","INVALID","NOT_SAVED"]}, +"OrderCustomerSetPayload":{"o":{"f":{"order":"Order","userErrors":"[OrderCustomerSetUserError!]!"}}}, +"OrderCustomerSetUserError":{"o":{"f":{"code":"OrderCustomerSetUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderCustomerSetUserErrorCode":{"e":["NOT_FOUND","INVALID","NOT_SAVED","NOT_PERMITTED"]}, +"OrderDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[OrderDeleteUserError!]!"}}}, +"OrderDeleteUserError":{"o":{"f":{"code":"OrderDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderDeleteUserErrorCode":{"e":["NOT_FOUND","INVALID"]}, +"OrderDisplayFinancialStatus":{"e":["PENDING","AUTHORIZED","PARTIALLY_PAID","PARTIALLY_REFUNDED","VOIDED","PAID","REFUNDED","EXPIRED"]}, +"OrderDisplayFulfillmentStatus":{"e":["UNFULFILLED","PARTIALLY_FULFILLED","FULFILLED","RESTOCKED","PENDING_FULFILLMENT","OPEN","IN_PROGRESS","ON_HOLD","SCHEDULED","REQUEST_DECLINED","FULFILLMENT_NOT_REQUIRED"]}, +"OrderDisplayRequestedEditStatus":{"e":["NONE","REQUESTED","RESOLVED","DECLINED"]}, +"OrderDisputeSummary":{"o":{"f":{"id":"ID!","initiatedAs":"DisputeType!","status":"DisputeStatus!"},"t":["Node"]}}, +"OrderEdge":{"o":{"f":{"cursor":"String!","node":"Order!"}}}, +"OrderEditAddCustomItemPayload":{"o":{"f":{"calculatedLineItem":"CalculatedLineItem","calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[UserError!]!"}}}, +"OrderEditAddLineItemDiscountPayload":{"o":{"f":{"addedDiscountStagedChange":"OrderStagedChangeAddLineItemDiscount","calculatedLineItem":"CalculatedLineItem","calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[UserError!]!"}}}, +"OrderEditAddShippingLineInput":{"i":{"price":"MoneyInput!","title":"String!"}}, +"OrderEditAddShippingLinePayload":{"o":{"f":{"calculatedOrder":"CalculatedOrder","calculatedShippingLine":"CalculatedShippingLine","orderEditSession":"OrderEditSession","userErrors":"[OrderEditAddShippingLineUserError!]!"}}}, +"OrderEditAddShippingLineUserError":{"o":{"f":{"code":"OrderEditAddShippingLineUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderEditAddShippingLineUserErrorCode":{"e":["INVALID"]}, +"OrderEditAddVariantPayload":{"o":{"f":{"calculatedLineItem":"CalculatedLineItem","calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[UserError!]!"}}}, +"OrderEditAgreement":{"o":{"f":{"app":"App","happenedAt":"DateTime!","id":"ID!","reason":"OrderActionType!","sales":["SaleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"user":"StaffMember"},"t":["SalesAgreement"]}}, +"OrderEditAppliedDiscountInput":{"i":{"description":"String","fixedValue":"MoneyInput","percentValue":"Float"}}, +"OrderEditBeginPayload":{"o":{"f":{"calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[UserError!]!"}}}, +"OrderEditCommitPayload":{"o":{"f":{"order":"Order","successMessages":"[String!]","userErrors":"[UserError!]!"}}}, +"OrderEditRemoveDiscountPayload":{"o":{"f":{"calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[OrderEditRemoveDiscountUserError!]!"}}}, +"OrderEditRemoveDiscountUserError":{"o":{"f":{"code":"OrderEditRemoveDiscountUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderEditRemoveDiscountUserErrorCode":{"e":["INVALID"]}, +"OrderEditRemoveLineItemDiscountPayload":{"o":{"f":{"calculatedLineItem":"CalculatedLineItem","calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[UserError!]!"}}}, +"OrderEditRemoveShippingLinePayload":{"o":{"f":{"calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[OrderEditRemoveShippingLineUserError!]!"}}}, +"OrderEditRemoveShippingLineUserError":{"o":{"f":{"code":"OrderEditRemoveShippingLineUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderEditRemoveShippingLineUserErrorCode":{"e":["INVALID"]}, +"OrderEditSession":{"o":{"f":{"id":"ID!"},"t":["Node"]}}, +"OrderEditSetQuantityPayload":{"o":{"f":{"calculatedLineItem":"CalculatedLineItem","calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[UserError!]!"}}}, +"OrderEditUpdateDiscountPayload":{"o":{"f":{"calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[OrderEditUpdateDiscountUserError!]!"}}}, +"OrderEditUpdateDiscountUserError":{"o":{"f":{"code":"OrderEditUpdateDiscountUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderEditUpdateDiscountUserErrorCode":{"e":["INVALID"]}, +"OrderEditUpdateShippingLineInput":{"i":{"price":"MoneyInput","title":"String"}}, +"OrderEditUpdateShippingLinePayload":{"o":{"f":{"calculatedOrder":"CalculatedOrder","orderEditSession":"OrderEditSession","userErrors":"[OrderEditUpdateShippingLineUserError!]!"}}}, +"OrderEditUpdateShippingLineUserError":{"o":{"f":{"code":"OrderEditUpdateShippingLineUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderEditUpdateShippingLineUserErrorCode":{"e":["INVALID"]}, +"OrderIdentifierInput":{"i":{"f":{"customId":"UniqueMetafieldValueInput","id":"ID"},"o":true}}, +"OrderInput":{"i":{"f":{"customAttributes":"[AttributeInput!]","email":"String","id":"ID!","localizationExtensions":"[LocalizationExtensionInput!]","localizedFields":"[LocalizedFieldInput!]","metafields":"[MetafieldInput!]","note":"String","phone":"String","poNumber":"String","shippingAddress":"MailingAddressInput","tags":"[String!]"},"d":{"localizationExtensions":"This field will be removed in a future version. Use `localizedFields` instead."}}}, +"OrderInvoiceSendPayload":{"o":{"f":{"order":"Order","userErrors":"[OrderInvoiceSendUserError!]!"}}}, +"OrderInvoiceSendUserError":{"o":{"f":{"code":"OrderInvoiceSendUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderInvoiceSendUserErrorCode":{"e":["ORDER_INVOICE_SEND_UNSUCCESSFUL"]}, +"OrderMarkAsPaidInput":{"i":{"id":"ID!"}}, +"OrderMarkAsPaidPayload":{"o":{"f":{"order":"Order","userErrors":"[UserError!]!"}}}, +"OrderOpenInput":{"i":{"id":"ID!"}}, +"OrderOpenPayload":{"o":{"f":{"order":"Order","userErrors":"[UserError!]!"}}}, +"OrderPaymentCollectionDetails":{"o":{"f":{"additionalPaymentCollectionUrl":"URL","vaultedPaymentMethods":"[PaymentMandate!]"}}}, +"OrderPaymentStatus":{"o":{"f":{"errorMessage":"String","paymentReferenceId":"String!","status":"OrderPaymentStatusResult!","transactions":"[OrderTransaction!]!","translatedErrorMessage":"String"}}}, +"OrderPaymentStatusResult":{"e":["SUCCESS","AUTHORIZED","VOIDED","REFUNDED","CAPTURED","PURCHASED","ERROR","PROCESSING","REDIRECT_REQUIRED","RETRYABLE","UNKNOWN","INITIATED","PENDING","PARTIAL_SUCCESS"]}, +"OrderReturnStatus":{"e":["IN_PROGRESS","INSPECTION_COMPLETE","NO_RETURN","RETURNED","RETURN_FAILED","RETURN_REQUESTED"]}, +"OrderRisk":{"o":{"f":{"display":"Boolean!","level":"OrderRiskLevel","message":"String"},"d":{"display":"This field is deprecated in favor of OrderRiskAssessment.facts.","level":"This field is deprecated in favor of OrderRiskAssessment.riskLevel which allows for more granular risk levels, including PENDING and NONE.","message":"This field is deprecated in favor of OrderRiskAssessment.facts."}}}, +"OrderRiskAssessment":{"o":{"f":{"facts":"[RiskFact!]!","provider":"App","riskLevel":"RiskAssessmentResult!"}}}, +"OrderRiskAssessmentCreateInput":{"i":{"facts":"[OrderRiskAssessmentFactInput!]!","orderId":"ID!","riskLevel":"RiskAssessmentResult!"}}, +"OrderRiskAssessmentCreatePayload":{"o":{"f":{"orderRiskAssessment":"OrderRiskAssessment","userErrors":"[OrderRiskAssessmentCreateUserError!]!"}}}, +"OrderRiskAssessmentCreateUserError":{"o":{"f":{"code":"OrderRiskAssessmentCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"OrderRiskAssessmentCreateUserErrorCode":{"e":["TOO_MANY_FACTS","ORDER_ALREADY_FULFILLED","INVALID","NOT_FOUND"]}, +"OrderRiskAssessmentFactInput":{"i":{"description":"String!","sentiment":"RiskFactSentiment!"}}, +"OrderRiskLevel":{"e":["LOW","MEDIUM","HIGH"]}, +"OrderRiskRecommendationResult":{"e":["CANCEL","INVESTIGATE","ACCEPT","NONE"]}, +"OrderRiskSummary":{"o":{"f":{"assessments":"[OrderRiskAssessment!]!","recommendation":"OrderRiskRecommendationResult!"}}}, +"OrderSortKeys":{"e":["CREATED_AT","CURRENT_TOTAL_PRICE","CUSTOMER_NAME","DESTINATION","FINANCIAL_STATUS","FULFILLMENT_STATUS","ID","ORDER_NUMBER","PO_NUMBER","PROCESSED_AT","RELEVANCE","TOTAL_ITEMS_QUANTITY","TOTAL_PRICE","UPDATED_AT"]}, +"OrderStagedChange":{"u":["OrderStagedChangeAddCustomItem","OrderStagedChangeAddLineItemDiscount","OrderStagedChangeAddShippingLine","OrderStagedChangeAddVariant","OrderStagedChangeDecrementItem","OrderStagedChangeIncrementItem","OrderStagedChangeRemoveDiscount","OrderStagedChangeRemoveShippingLine"]}, +"OrderStagedChangeAddCustomItem":{"o":{"f":{"originalUnitPrice":"MoneyV2!","quantity":"Int!","title":"String!"}}}, +"OrderStagedChangeAddLineItemDiscount":{"o":{"f":{"description":"String!","id":"ID!","value":"PricingValue!"}}}, +"OrderStagedChangeAddShippingLine":{"o":{"f":{"phone":"String","presentmentTitle":"String","price":"MoneyV2!","title":"String"}}}, +"OrderStagedChangeAddVariant":{"o":{"f":{"quantity":"Int!","variant":"ProductVariant!"}}}, +"OrderStagedChangeConnection":{"o":{"f":{"edges":"[OrderStagedChangeEdge!]!","nodes":"[OrderStagedChange!]!","pageInfo":"PageInfo!"}}}, +"OrderStagedChangeDecrementItem":{"o":{"f":{"delta":"Int!","lineItem":"LineItem!","restock":"Boolean!"}}}, +"OrderStagedChangeEdge":{"o":{"f":{"cursor":"String!","node":"OrderStagedChange!"}}}, +"OrderStagedChangeIncrementItem":{"o":{"f":{"delta":"Int!","lineItem":"LineItem!"}}}, +"OrderStagedChangeRemoveDiscount":{"o":{"f":{"discountApplication":"DiscountApplication!"}}}, +"OrderStagedChangeRemoveShippingLine":{"o":{"f":{"shippingLine":"ShippingLine!"}}}, +"OrderTransaction":{"o":{"f":{"accountNumber":"String","amount":"Money!","amountRoundingSet":"MoneyBag","amountSet":"MoneyBag!","amountV2":"MoneyV2!","authorizationCode":"String","authorizationExpiresAt":"DateTime","createdAt":"DateTime!","currencyExchangeAdjustment":"CurrencyExchangeAdjustment","device":"PointOfSaleDevice","errorCode":"OrderTransactionErrorCode","fees":"[TransactionFee!]!","formattedGateway":"String","gateway":"String","id":"ID!","kind":"OrderTransactionKind!","location":"Location","manualPaymentGateway":"Boolean!","manuallyCapturable":"Boolean!","maximumRefundable":"Money","maximumRefundableV2":"MoneyV2","multiCapturable":"Boolean!","order":"Order","parentTransaction":"OrderTransaction","paymentDetails":"PaymentDetails","paymentIcon":["Image",{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","scale":"Int="}],"paymentId":"String","paymentMethod":"PaymentMethods","processedAt":"DateTime","receiptJson":"JSON","settlementCurrency":"CurrencyCode","settlementCurrencyRate":"Decimal","shopifyPaymentsSet":"ShopifyPaymentsTransactionSet","status":"OrderTransactionStatus!","test":"Boolean!","totalUnsettled":"Money","totalUnsettledSet":"MoneyBag","totalUnsettledV2":"MoneyV2","user":"StaffMember"},"t":["Node"],"d":{"amount":"Use `amountSet` instead.","amountV2":"Use `amountSet` instead.","authorizationCode":"Use `paymentId` instead.","maximumRefundable":"Use `maximumRefundableV2` instead.","paymentIcon(crop)":"Use `Image.url(transform: { crop:})` instead.","paymentIcon(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","paymentIcon(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","paymentIcon(scale)":"Use `Image.url(transform: { scale:})` instead.","paymentMethod":"Use `paymentIcon` instead.","totalUnsettled":"Use `totalUnsettledSet` instead.","totalUnsettledV2":"Use `totalUnsettledSet` instead."}}}, +"OrderTransactionConnection":{"o":{"f":{"edges":"[OrderTransactionEdge!]!","nodes":"[OrderTransaction!]!","pageInfo":"PageInfo!"}}}, +"OrderTransactionEdge":{"o":{"f":{"cursor":"String!","node":"OrderTransaction!"}}}, +"OrderTransactionErrorCode":{"e":["INCORRECT_NUMBER","INVALID_NUMBER","INVALID_EXPIRY_DATE","INVALID_CVC","EXPIRED_CARD","INCORRECT_CVC","INCORRECT_ZIP","INCORRECT_ADDRESS","INCORRECT_PIN","CARD_DECLINED","PROCESSING_ERROR","CALL_ISSUER","PICK_UP_CARD","CONFIG_ERROR","TEST_MODE_LIVE_CARD","UNSUPPORTED_FEATURE","GENERIC_ERROR","INVALID_COUNTRY","INVALID_AMOUNT","PAYMENT_METHOD_UNAVAILABLE","AMAZON_PAYMENTS_INVALID_PAYMENT_METHOD","AMAZON_PAYMENTS_MAX_AMOUNT_CHARGED","AMAZON_PAYMENTS_MAX_AMOUNT_REFUNDED","AMAZON_PAYMENTS_MAX_AUTHORIZATIONS_CAPTURED","AMAZON_PAYMENTS_MAX_REFUNDS_PROCESSED","AMAZON_PAYMENTS_ORDER_REFERENCE_CANCELED","AMAZON_PAYMENTS_STALE","AMOUNT_TOO_LARGE","AMOUNT_TOO_SMALL","AUTHENTICATION_FAILED","AUTHENTICATION_REQUIRED","CANCELLED_PAYMENT","CARD_TESTING","DO_NOT_HONOR","FRAUD_SUSPECTED","INSUFFICIENT_FUNDS","INVALID_CURRENCY","INVALID_PAYMENT_METHOD","INVALID_PURCHASE_TYPE","MERCHANT_ACCOUNT_ERROR","MERCHANT_RULE","INSTRUMENT_DECLINED","PAYMENT_METHOD_UNSUPPORTED","PAYMENT_PROVIDER_ERROR","RETRY_DECLINED","TRANSACTION_LIMIT_EXCEEDED","AUTHORIZATION_EXPIRED"]}, +"OrderTransactionInput":{"i":{"amount":"Money!","gateway":"String!","kind":"OrderTransactionKind!","orderId":"ID!","parentId":"ID"}}, +"OrderTransactionKind":{"e":["SALE","CAPTURE","AUTHORIZATION","VOID","REFUND","CHANGE","EMV_AUTHORIZATION","SUGGESTED_REFUND"]}, +"OrderTransactionStatus":{"e":["SUCCESS","FAILURE","PENDING","ERROR","AWAITING_RESPONSE","UNKNOWN"]}, +"OrderUpdatePayload":{"o":{"f":{"order":"Order","userErrors":"[UserError!]!"}}}, +"PackageInfoInput":{"i":{"carrierPackage":"ShippingCarrierPackageInput","customPackage":"ShippingLabelPurchaseCustomPackageInput"}}, +"Page":{"o":{"f":{"body":"HTML!","bodySummary":"String!","createdAt":"DateTime!","defaultCursor":"String!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"handle":"String!","id":"ID!","isPublished":"Boolean!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"publishedAt":"DateTime","templateSuffix":"String","title":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"updatedAt":"DateTime!"},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","Navigable","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"PageConnection":{"o":{"f":{"edges":"[PageEdge!]!","nodes":"[Page!]!","pageInfo":"PageInfo!"}}}, +"PageCreateInput":{"i":{"body":"String","handle":"String","isPublished":"Boolean","metafields":"[MetafieldInput!]","publishDate":"DateTime","templateSuffix":"String","title":"String!"}}, +"PageCreatePayload":{"o":{"f":{"page":"Page","userErrors":"[PageCreateUserError!]!"}}}, +"PageCreateUserError":{"o":{"f":{"code":"PageCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PageCreateUserErrorCode":{"e":["INVALID_PUBLISH_DATE","BLANK","TOO_LONG","TOO_SHORT","TOO_BIG","TAKEN","INVALID","INVALID_VALUE","INVALID_TYPE"]}, +"PageDeletePayload":{"o":{"f":{"deletedPageId":"ID","userErrors":"[PageDeleteUserError!]!"}}}, +"PageDeleteUserError":{"o":{"f":{"code":"PageDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PageDeleteUserErrorCode":{"e":["NOT_FOUND"]}, +"PageEdge":{"o":{"f":{"cursor":"String!","node":"Page!"}}}, +"PageInfo":{"o":{"f":{"endCursor":"String","hasNextPage":"Boolean!","hasPreviousPage":"Boolean!","startCursor":"String"}}}, +"PageSortKeys":{"e":["ID","PUBLISHED_AT","TITLE","UPDATED_AT"]}, +"PageUpdateInput":{"i":{"body":"String","handle":"String","isPublished":"Boolean","metafields":"[MetafieldInput!]","publishDate":"DateTime","redirectNewHandle":"Boolean=","templateSuffix":"String","title":"String"}}, +"PageUpdatePayload":{"o":{"f":{"page":"Page","userErrors":"[PageUpdateUserError!]!"}}}, +"PageUpdateUserError":{"o":{"f":{"code":"PageUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PageUpdateUserErrorCode":{"e":["INVALID_PUBLISH_DATE","NOT_FOUND","BLANK","TOO_LONG","TOO_BIG","TAKEN","INVALID","INVALID_VALUE","INVALID_TYPE"]}, +"PaymentCustomization":{"o":{"f":{"enabled":"Boolean!","errorHistory":"FunctionsErrorHistory","functionId":"String!","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"shopifyFunction":"ShopifyFunction!","title":"String!"},"t":["HasMetafieldDefinitions","HasMetafields","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"PaymentCustomizationActivationPayload":{"o":{"f":{"ids":"[String!]","userErrors":"[PaymentCustomizationError!]!"}}}, +"PaymentCustomizationConnection":{"o":{"f":{"edges":"[PaymentCustomizationEdge!]!","nodes":"[PaymentCustomization!]!","pageInfo":"PageInfo!"}}}, +"PaymentCustomizationCreatePayload":{"o":{"f":{"paymentCustomization":"PaymentCustomization","userErrors":"[PaymentCustomizationError!]!"}}}, +"PaymentCustomizationDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[PaymentCustomizationError!]!"}}}, +"PaymentCustomizationEdge":{"o":{"f":{"cursor":"String!","node":"PaymentCustomization!"}}}, +"PaymentCustomizationError":{"o":{"f":{"code":"PaymentCustomizationErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PaymentCustomizationErrorCode":{"e":["CUSTOM_APP_FUNCTION_NOT_ELIGIBLE","FUNCTION_DOES_NOT_IMPLEMENT","FUNCTION_NOT_FOUND","FUNCTION_PENDING_DELETION","INVALID","PAYMENT_CUSTOMIZATION_NOT_FOUND","PAYMENT_CUSTOMIZATION_FUNCTION_NOT_ELIGIBLE","MAXIMUM_ACTIVE_PAYMENT_CUSTOMIZATIONS","REQUIRED_INPUT_FIELD","INVALID_METAFIELDS","MAXIMUM_PAYMENT_CUSTOMIZATIONS","FUNCTION_ID_CANNOT_BE_CHANGED","MISSING_FUNCTION_IDENTIFIER","MULTIPLE_FUNCTION_IDENTIFIERS"]}, +"PaymentCustomizationInput":{"i":{"f":{"enabled":"Boolean","functionHandle":"String","functionId":"String","metafields":"[MetafieldInput!]=","title":"String"},"d":{"functionId":"Use `functionHandle` instead."}}}, +"PaymentCustomizationUpdatePayload":{"o":{"f":{"paymentCustomization":"PaymentCustomization","userErrors":"[PaymentCustomizationError!]!"}}}, +"PaymentDetails":{"u":["CardPaymentDetails","LocalPaymentMethodsPaymentDetails","PaypalWalletPaymentDetails","ShopPayInstallmentsPaymentDetails"]}, +"PaymentInstrument":{"u":["BankAccount","VaultCreditCard","VaultPaypalBillingAgreement"]}, +"PaymentInstrumentMandateInput":{"i":{"resourceId":"String!","resourceType":"PaymentInstrumentMandateResourceType!"}}, +"PaymentInstrumentMandateResourceType":{"e":["SUBSCRIPTIONS","ORDERS","DRAFT_ORDERS"]}, +"PaymentInstrumentSendAddEmailPayload":{"o":{"f":{"customer":"Customer","userErrors":"[UserError!]!"}}}, +"PaymentMandate":{"o":{"f":{"id":"ID!","paymentInstrument":"PaymentInstrument!"},"t":["Node"]}}, +"PaymentMandateResource":{"o":{"f":{"id":"ID!","resourceId":"ID","resourceType":"MandateResourceType"}}}, +"PaymentMandateResourceConnection":{"o":{"f":{"edges":"[PaymentMandateResourceEdge!]!","nodes":"[PaymentMandateResource!]!","pageInfo":"PageInfo!"}}}, +"PaymentMandateResourceEdge":{"o":{"f":{"cursor":"String!","node":"PaymentMandateResource!"}}}, +"PaymentMethods":{"e":["VISA","MASTERCARD","DISCOVER","AMERICAN_EXPRESS","DINERS_CLUB","JCB","UNIONPAY","ELO","DANKORT","MAESTRO","FORBRUGSFORENINGEN","PAYPAL","BOGUS","BITCOIN","LITECOIN","DOGECOIN","INTERAC","EFTPOS","CARTES_BANCAIRES","BANCONTACT"]}, +"PaymentReminderSendPayload":{"o":{"f":{"success":"Boolean","userErrors":"[PaymentReminderSendUserError!]!"}}}, +"PaymentReminderSendUserError":{"o":{"f":{"code":"PaymentReminderSendUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PaymentReminderSendUserErrorCode":{"e":["PAYMENT_REMINDER_SEND_UNSUCCESSFUL"]}, +"PaymentSchedule":{"o":{"f":{"amount":"MoneyV2!","balanceDue":"MoneyV2!","completedAt":"DateTime","due":"Boolean!","dueAt":"DateTime","id":"ID!","issuedAt":"DateTime","paymentTerms":"PaymentTerms!","totalBalance":"MoneyV2!"},"t":["Node"],"d":{"amount":"Use `balanceDue`, `totalBalance`, or `Order.totalOutstandingSet` instead."}}}, +"PaymentScheduleCapturePayload":{"o":{"f":{"job":"Job","jobResult":"OrderCreateMandatePaymentJobResult","paymentReferenceId":"String","userErrors":"[PaymentScheduleCaptureUserError!]!"}}}, +"PaymentScheduleCaptureUserError":{"o":{"f":{"code":"PaymentScheduleCaptureUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PaymentScheduleCaptureUserErrorCode":{"e":["PAYMENT_SCHEDULE_CAPTURE_ERROR_CODE"]}, +"PaymentScheduleConnection":{"o":{"f":{"edges":"[PaymentScheduleEdge!]!","nodes":"[PaymentSchedule!]!","pageInfo":"PageInfo!"}}}, +"PaymentScheduleEdge":{"o":{"f":{"cursor":"String!","node":"PaymentSchedule!"}}}, +"PaymentScheduleInput":{"i":{"dueAt":"DateTime","issuedAt":"DateTime"}}, +"PaymentSettings":{"o":{"f":{"supportedDigitalWallets":"[DigitalWallet!]!"}}}, +"PaymentTerms":{"o":{"f":{"draftOrder":"DraftOrder","due":"Boolean!","dueInDays":"Int","id":"ID!","order":"Order","overdue":"Boolean!","paymentSchedules":["PaymentScheduleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"paymentTermsName":"String!","paymentTermsType":"PaymentTermsType!","translatedName":"String!"},"t":["Node"]}}, +"PaymentTermsCreateInput":{"i":{"paymentSchedules":"[PaymentScheduleInput!]","paymentTermsTemplateId":"ID!"}}, +"PaymentTermsCreatePayload":{"o":{"f":{"paymentTerms":"PaymentTerms","userErrors":"[PaymentTermsCreateUserError!]!"}}}, +"PaymentTermsCreateUserError":{"o":{"f":{"code":"PaymentTermsCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PaymentTermsCreateUserErrorCode":{"e":["PAYMENT_TERMS_CREATION_UNSUCCESSFUL"]}, +"PaymentTermsDeleteInput":{"i":{"paymentTermsId":"ID!"}}, +"PaymentTermsDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[PaymentTermsDeleteUserError!]!"}}}, +"PaymentTermsDeleteUserError":{"o":{"f":{"code":"PaymentTermsDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PaymentTermsDeleteUserErrorCode":{"e":["PAYMENT_TERMS_DELETE_UNSUCCESSFUL"]}, +"PaymentTermsInput":{"i":{"paymentSchedules":"[PaymentScheduleInput!]","paymentTermsTemplateId":"ID"}}, +"PaymentTermsTemplate":{"o":{"f":{"description":"String!","dueInDays":"Int","id":"ID!","name":"String!","paymentTermsType":"PaymentTermsType!","translatedName":"String!"},"t":["Node"]}}, +"PaymentTermsType":{"e":["RECEIPT","NET","FIXED","FULFILLMENT","UNKNOWN"]}, +"PaymentTermsUpdateInput":{"i":{"paymentTermsAttributes":"PaymentTermsInput!","paymentTermsId":"ID!"}}, +"PaymentTermsUpdatePayload":{"o":{"f":{"paymentTerms":"PaymentTerms","userErrors":"[PaymentTermsUpdateUserError!]!"}}}, +"PaymentTermsUpdateUserError":{"o":{"f":{"code":"PaymentTermsUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PaymentTermsUpdateUserErrorCode":{"e":["PAYMENT_TERMS_UPDATE_UNSUCCESSFUL"]}, +"PayoutSortKeys":{"e":["ADJUSTMENT_GROSS","ADVANCE_GROSS","AMOUNT","CHARGE_GROSS","DUTIES_GROSS","FEE_AMOUNT","ID","ISSUED_AT","REFUND_GROSS","SHIPPING_LABEL_GROSS","STATUS"]}, +"PaypalExpressSubscriptionsGatewayStatus":{"e":["ENABLED","DISABLED","PENDING"]}, +"PaypalWalletPaymentDetails":{"o":{"f":{"paymentMethodName":"String"},"t":["BasePaymentDetails"]}}, +"PickupInStoreLocation":{"o":{"f":{"code":"String!","distanceFromBuyer":"Distance","handle":"String!","instructions":"String!","locationId":"ID!","source":"String!","title":"String!"}}}, +"PointOfSaleDevice":{"o":{"f":{"activePaymentSession":"PointOfSaleDevicePaymentSession","cashDrawer":"CashDrawer","fiscalDeviceIdentifier":"String","id":"ID!"},"t":["Node"]}}, +"PointOfSaleDeviceAssignToCashDrawerPayload":{"o":{"f":{"pointOfSaleDevice":"PointOfSaleDevice","userErrors":"[PointOfSaleDeviceAssignToCashDrawerUserError!]!"}}}, +"PointOfSaleDeviceAssignToCashDrawerUserError":{"o":{"f":{"code":"PointOfSaleDeviceAssignToCashDrawerUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PointOfSaleDeviceAssignToCashDrawerUserErrorCode":{"e":["INTERNAL_ERROR","LOCATION_MISMATCH","CASH_DRAWER_NOT_FOUND","POINT_OF_SALE_DEVICE_NOT_FOUND"]}, +"PointOfSaleDeviceConnection":{"o":{"f":{"edges":"[PointOfSaleDeviceEdge!]!","nodes":"[PointOfSaleDevice!]!","pageInfo":"PageInfo!"}}}, +"PointOfSaleDeviceEdge":{"o":{"f":{"cursor":"String!","node":"PointOfSaleDevice!"}}}, +"PointOfSaleDevicePaymentSession":{"o":{"f":{"cashActivities":["CashActivityConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","staffMemberId":"ID"}],"cashCountedAtClose":"MoneyV2","cashCountedAtOpen":"MoneyV2!","cashDrawer":"CashDrawer!","closingAdjustment":"MoneyV2","closingBalance":"MoneyV2","closingNote":"String","closingStaffMember":"StaffMember","closingTime":"DateTime","currency":"String!","expectedCashAtClose":"MoneyV2","expectedCashAtOpen":"MoneyV2!","id":"ID!","location":"Location!","netCashSales":"MoneyV2!","netSales":"MoneyV2!","openingNote":"String","openingStaffMember":"StaffMember!","openingTime":"DateTime!","pointOfSaleDevice":"PointOfSaleDevice!","status":"PointOfSaleDevicePaymentSessionStatus!","totalAdjustments":"MoneyV2!","totalCashRefunds":"MoneyV2!","totalCashSales":"MoneyV2!","totalDiscrepancy":"MoneyV2!","totalRefunds":"MoneyV2!","totalSales":"MoneyV2!","totalsReady":"Boolean!"},"t":["Node"]}}, +"PointOfSaleDevicePaymentSessionAdjustPayload":{"o":{"f":{"pointOfSaleDevicePaymentSession":"PointOfSaleDevicePaymentSession","userErrors":"[UserError!]!"}}}, +"PointOfSaleDevicePaymentSessionClosePayload":{"o":{"f":{"pointOfSaleDevicePaymentSession":"PointOfSaleDevicePaymentSession","userErrors":"[PointOfSaleDevicePaymentSessionCloseUserError!]!"}}}, +"PointOfSaleDevicePaymentSessionCloseUserError":{"o":{"f":{"code":"PointOfSaleDevicePaymentSessionCloseUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PointOfSaleDevicePaymentSessionCloseUserErrorCode":{"e":["STAFF_MEMBER_NOT_FOUND","PAYMENT_SESSION_NOT_FOUND","SESSION_ALREADY_CLOSED","TIME_BEFORE_SESSION_OPEN","REASON_CODE_NOT_FOUND","CURRENCY_MISMATCH","NO_CASH_DRAWER_ASSOCIATED","FAILED_TO_CLOSE_SESSION"]}, +"PointOfSaleDevicePaymentSessionConnection":{"o":{"f":{"edges":"[PointOfSaleDevicePaymentSessionEdge!]!","nodes":"[PointOfSaleDevicePaymentSession!]!","pageInfo":"PageInfo!"}}}, +"PointOfSaleDevicePaymentSessionCountPayload":{"o":{"f":{"pointOfSaleDevicePaymentSession":"PointOfSaleDevicePaymentSession","userErrors":"[PointOfSaleDevicePaymentSessionCountUserError!]!"}}}, +"PointOfSaleDevicePaymentSessionCountUserError":{"o":{"f":{"code":"PointOfSaleDevicePaymentSessionCountUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PointOfSaleDevicePaymentSessionCountUserErrorCode":{"e":["STAFF_MEMBER_NOT_FOUND","PAYMENT_SESSION_NOT_FOUND","SESSION_ALREADY_CLOSED","TIME_BEFORE_SESSION_OPEN","REASON_CODE_NOT_FOUND","CURRENCY_MISMATCH","NO_CASH_DRAWER_ASSOCIATED","FAILED_TO_RECORD_COUNT"]}, +"PointOfSaleDevicePaymentSessionEdge":{"o":{"f":{"cursor":"String!","node":"PointOfSaleDevicePaymentSession!"}}}, +"PointOfSaleDevicePaymentSessionOpenPayload":{"o":{"f":{"pointOfSaleDevicePaymentSession":"PointOfSaleDevicePaymentSession","userErrors":"[PointOfSaleDevicePaymentSessionOpenUserError!]!"}}}, +"PointOfSaleDevicePaymentSessionOpenUserError":{"o":{"f":{"code":"PointOfSaleDevicePaymentSessionOpenUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PointOfSaleDevicePaymentSessionOpenUserErrorCode":{"e":["POINT_OF_SALE_DEVICE_NOT_FOUND","NO_CASH_DRAWER_ASSOCIATED","NOT_SAVED","ALREADY_OPEN","STAFF_MEMBER_NOT_FOUND","CURRENCY_MISMATCH","REASON_CODE_NOT_FOUND"]}, +"PointOfSaleDevicePaymentSessionSortKeys":{"e":["CLOSING_TIME","ID","OPENING_TIME"]}, +"PointOfSaleDevicePaymentSessionStatus":{"e":["OPEN","CLOSED"]}, +"PreferredRateSelectionInput":{"i":{"carrierCode":"String!","serviceCode":"String!"}}, +"PreparedFulfillmentOrderLineItemsInput":{"i":{"fulfillmentOrderId":"ID!"}}, +"PreviewInstallPayload":{"o":{"f":{"newTheme":"OnlineStoreTheme","userErrors":"[PreviewInstallUserError!]!"}}}, +"PreviewInstallUserError":{"o":{"f":{"code":"PreviewInstallUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PreviewInstallUserErrorCode":{"e":["INTERNAL_ERROR"]}, +"PriceCalculationType":{"e":["COMPONENTS_SUM","FIXED","NONE"]}, +"PriceInput":{"i":{"calculation":"PriceCalculationType","price":"Money"}}, +"PriceList":{"o":{"f":{"catalog":"Catalog","createdAt":"DateTime!","currency":"CurrencyCode!","fixedPricesCount":"Int!","id":"ID!","name":"String!","parent":"PriceListParent","prices":["PriceListPriceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","originType":"PriceListPriceOriginType","query":"String","reverse":"Boolean="}],"quantityRules":["QuantityRuleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","originType":"QuantityRuleOriginType","reverse":"Boolean="}]},"t":["Node"]}}, +"PriceListAdjustment":{"o":{"f":{"type":"PriceListAdjustmentType!","value":"Float!"}}}, +"PriceListAdjustmentInput":{"i":{"type":"PriceListAdjustmentType!","value":"Float!"}}, +"PriceListAdjustmentSettings":{"o":{"f":{"compareAtMode":"PriceListCompareAtMode!"}}}, +"PriceListAdjustmentSettingsInput":{"i":{"compareAtMode":"PriceListCompareAtMode!="}}, +"PriceListAdjustmentType":{"e":["PERCENTAGE_DECREASE","PERCENTAGE_INCREASE"]}, +"PriceListCompareAtMode":{"e":["ADJUSTED","NULLIFY"]}, +"PriceListConnection":{"o":{"f":{"edges":"[PriceListEdge!]!","nodes":"[PriceList!]!","pageInfo":"PageInfo!"}}}, +"PriceListCreateInput":{"i":{"catalogId":"ID","currency":"CurrencyCode!","name":"String!","parent":"PriceListParentCreateInput!"}}, +"PriceListCreatePayload":{"o":{"f":{"priceList":"PriceList","userErrors":"[PriceListUserError!]!"}}}, +"PriceListDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[PriceListUserError!]!"}}}, +"PriceListEdge":{"o":{"f":{"cursor":"String!","node":"PriceList!"}}}, +"PriceListFixedPricesAddPayload":{"o":{"f":{"prices":"[PriceListPrice!]","userErrors":"[PriceListPriceUserError!]!"}}}, +"PriceListFixedPricesByProductBulkUpdateUserError":{"o":{"f":{"code":"PriceListFixedPricesByProductBulkUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PriceListFixedPricesByProductBulkUpdateUserErrorCode":{"e":["NO_UPDATE_OPERATIONS_SPECIFIED","PRICES_TO_ADD_CURRENCY_MISMATCH","PRICE_LIST_DOES_NOT_EXIST","DUPLICATE_ID_IN_INPUT","ID_MUST_BE_MUTUALLY_EXCLUSIVE","PRODUCT_DOES_NOT_EXIST","PRICE_LIMIT_EXCEEDED","LOCAL_CURRENCY_GIFT_CARD_ISSUANCE_CURRENCY_MISMATCH","LOCAL_CURRENCY_GIFT_CARD_LIMIT_EXCEEDED"]}, +"PriceListFixedPricesByProductUpdatePayload":{"o":{"f":{"priceList":"PriceList","pricesToAddProducts":"[Product!]","pricesToDeleteProducts":"[Product!]","userErrors":"[PriceListFixedPricesByProductBulkUpdateUserError!]!"}}}, +"PriceListFixedPricesDeletePayload":{"o":{"f":{"deletedFixedPriceVariantIds":"[ID!]","userErrors":"[PriceListPriceUserError!]!"}}}, +"PriceListFixedPricesUpdatePayload":{"o":{"f":{"deletedFixedPriceVariantIds":"[ID!]","priceList":"PriceList","pricesAdded":"[PriceListPrice!]","userErrors":"[PriceListPriceUserError!]!"}}}, +"PriceListParent":{"o":{"f":{"adjustment":"PriceListAdjustment!","settings":"PriceListAdjustmentSettings!"}}}, +"PriceListParentCreateInput":{"i":{"adjustment":"PriceListAdjustmentInput!","settings":"PriceListAdjustmentSettingsInput"}}, +"PriceListParentUpdateInput":{"i":{"adjustment":"PriceListAdjustmentInput!","settings":"PriceListAdjustmentSettingsInput"}}, +"PriceListPrice":{"o":{"f":{"compareAtPrice":"MoneyV2","originType":"PriceListPriceOriginType!","price":"MoneyV2!","quantityPriceBreaks":["QuantityPriceBreakConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"QuantityPriceBreakSortKeys="}],"variant":"ProductVariant!"}}}, +"PriceListPriceConnection":{"o":{"f":{"edges":"[PriceListPriceEdge!]!","nodes":"[PriceListPrice!]!","pageInfo":"PageInfo!"}}}, +"PriceListPriceEdge":{"o":{"f":{"cursor":"String!","node":"PriceListPrice!"}}}, +"PriceListPriceInput":{"i":{"compareAtPrice":"MoneyInput","price":"MoneyInput!","variantId":"ID!"}}, +"PriceListPriceOriginType":{"e":["FIXED","RELATIVE"]}, +"PriceListPriceUserError":{"o":{"f":{"code":"PriceListPriceUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PriceListPriceUserErrorCode":{"e":["BLANK","PRICE_LIST_NOT_FOUND","PRICE_LIST_CURRENCY_MISMATCH","LOCAL_CURRENCY_GIFT_CARD_ISSUANCE_CURRENCY_MISMATCH","LOCAL_CURRENCY_GIFT_CARD_LIMIT_EXCEEDED","VARIANT_NOT_FOUND","PRICE_NOT_FIXED"]}, +"PriceListProductPriceInput":{"i":{"compareAtPrice":"MoneyInput","price":"MoneyInput!","productId":"ID!"}}, +"PriceListSortKeys":{"e":["ID","NAME"]}, +"PriceListUpdateInput":{"i":{"catalogId":"ID","currency":"CurrencyCode","name":"String","parent":"PriceListParentUpdateInput"}}, +"PriceListUpdatePayload":{"o":{"f":{"priceList":"PriceList","userErrors":"[PriceListUserError!]!"}}}, +"PriceListUserError":{"o":{"f":{"code":"PriceListUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PriceListUserErrorCode":{"e":["TAKEN","BLANK","INCLUSION","TOO_LONG","PRICE_LIST_NOT_FOUND","PRICE_LIST_LOCKED","CURRENCY_MARKET_MISMATCH","INVALID_ADJUSTMENT_VALUE","INVALID_ADJUSTMENT_MIN_VALUE","INVALID_ADJUSTMENT_MAX_VALUE","CATALOG_CONTEXT_DOES_NOT_SUPPORT_QUANTITY_RULES","CATALOG_CONTEXT_DOES_NOT_SUPPORT_QUANTITY_PRICE_BREAKS","CONTEXT_RULE_LIMIT_ONE_OPTION","CURRENCY_NOT_SUPPORTED","PRICE_LIST_NOT_ALLOWED_FOR_PRIMARY_MARKET","CATALOG_DOES_NOT_EXIST","CATALOG_MARKET_AND_PRICE_LIST_CURRENCY_MISMATCH","CATALOG_TAKEN","COUNTRY_PRICE_LIST_ASSIGNMENT","GENERIC_ERROR"]}, +"PricingAuditTrail":{"o":{"f":{"priceAdjustments":"[AuditTrailAdjustment!]!"}}}, +"PricingPercentageValue":{"o":{"f":{"percentage":"Float!"}}}, +"PricingValue":{"u":["MoneyV2","PricingPercentageValue"]}, +"PrivacyCountryCode":{"e":["AN","AC","AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NS","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TA","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW","XX"]}, +"PrivacyFeaturesDisablePayload":{"o":{"f":{"featuresDisabled":"[PrivacyFeaturesEnum!]","userErrors":"[PrivacyFeaturesDisableUserError!]!"}}}, +"PrivacyFeaturesDisableUserError":{"o":{"f":{"code":"PrivacyFeaturesDisableUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PrivacyFeaturesDisableUserErrorCode":{"e":["FAILED"]}, +"PrivacyFeaturesEnum":{"e":["COOKIE_BANNER","DATA_SALE_OPT_OUT_PAGE","PRIVACY_POLICY"]}, +"PrivacyPolicy":{"o":{"f":{"autoManaged":"Boolean!","supportedLocales":"[String!]!"}}}, +"PrivacySettings":{"o":{"f":{"banner":"CookieBanner","dataSaleOptOutPage":"DataSaleOptOutPage","privacyPolicy":"PrivacyPolicy"}}}, +"Product":{"o":{"f":{"availablePublicationsCount":"Count","bodyHtml":"String","bundleComponents":["ProductBundleComponentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"bundleConsolidatedOptions":"[ComponentizedProductsBundleConsolidatedOption!]","category":"TaxonomyCategory","collections":["CollectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CollectionSortKeys="}],"combinedListing":"CombinedListing","combinedListingRole":"CombinedListingsRole","compareAtPriceRange":"ProductCompareAtPriceRange","contextualPricing":["ProductContextualPricing!",{"context":"ContextualPricingContext!"}],"createdAt":"DateTime!","customProductType":"String","defaultCursor":"String!","description":["String!",{"truncateAt":"Int"}],"descriptionHtml":"HTML!","descriptionPlainSummary":"String!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"featuredImage":"Image","featuredMedia":"Media","feedback":"ResourceFeedback","giftCardSettings":"GiftCardProductSettings","giftCardTemplateSuffix":"String","handle":"String!","hasOnlyDefaultVariant":"Boolean!","hasOutOfStockVariants":"Boolean!","hasVariantsThatRequiresComponents":"Boolean!","id":"ID!","images":["ImageConnection!",{"after":"String","before":"String","crop":"CropRegion","first":"Int","last":"Int","maxHeight":"Int","maxWidth":"Int","reverse":"Boolean=","scale":"Int=","sortKey":"ProductImageSortKeys="}],"inCollection":["Boolean!",{"id":"ID!"}],"isGiftCard":"Boolean!","legacyResourceId":"UnsignedInt64!","media":["MediaConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"ProductMediaSortKeys="}],"mediaCount":"Count","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"onlineStorePreviewUrl":"URL","onlineStoreUrl":"URL","options":["[ProductOption!]!",{"first":"Int"}],"priceRange":"ProductPriceRange!","priceRangeV2":"ProductPriceRangeV2!","productCategory":"ProductCategory","productComponents":["ProductComponentTypeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productComponentsCount":"Count","productParents":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"productPublications":["ProductPublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productType":"String!","publicationCount":["Int!",{"onlyPublished":"Boolean="}],"publications":["ProductPublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"publishedAt":"DateTime","publishedInContext":["Boolean!",{"context":"ContextualPublicationContext!"}],"publishedOnChannel":["Boolean!",{"channelId":"ID!"}],"publishedOnCurrentChannel":"Boolean!","publishedOnCurrentPublication":"Boolean!","publishedOnPublication":["Boolean!",{"publicationId":"ID!"}],"requiresSellingPlan":"Boolean!","resourcePublicationOnCurrentPublication":"ResourcePublicationV2","resourcePublications":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"resourcePublicationsCount":["Count",{"onlyPublished":"Boolean="}],"resourcePublicationsV2":["ResourcePublicationV2Connection!",{"after":"String","before":"String","catalogType":"CatalogType","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"restrictedForResource":["RestrictedForResource",{"calculatedOrderId":"ID!"}],"sellingPlanGroupCount":"Int!","sellingPlanGroups":["SellingPlanGroupConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"sellingPlanGroupsCount":"Count","seo":"SEO!","standardizedProductType":"StandardizedProductType","status":"ProductStatus!","storefrontId":"StorefrontID!","tags":"[String!]!","templateSuffix":"String","title":"String!","totalInventory":"Int!","totalVariants":"Int!","tracksInventory":"Boolean!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"unpublishedChannels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"unpublishedPublications":["PublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"updatedAt":"DateTime!","variants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"ProductVariantSortKeys="}],"variantsCount":"Count","variantsInCollection":["ProductVariantConnection",{"after":"String","before":"String","collectionId":"ID!","first":"Int","last":"Int"}],"variantsInCollectionCount":["Count",{"collectionId":"ID!"}],"vendor":"String!"},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","LegacyInteroperability","Navigable","Node","OnlineStorePreviewable","Publishable"],"d":{"bodyHtml":"Use `descriptionHtml` instead.","customProductType":"Use `productType` instead.","descriptionPlainSummary":"Use `description` instead.","featuredImage":"Use `featuredMedia` instead.","images":"Use `media` instead.","images(crop)":"Use `Image.url(transform: { crop:})` instead.","images(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","images(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","images(scale)":"Use `Image.url(transform: { scale:})` instead.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","priceRange":"Use `priceRangeV2` instead.","productCategory":"Use `category` instead.","productPublications":"Use `resourcePublications` instead.","publicationCount":"Use `resourcePublicationsCount` instead.","publications":"Use `resourcePublications` instead.","publishedOnChannel":"Use `publishedOnPublication` instead.","publishedOnCurrentChannel":"Use `publishedOnCurrentPublication` instead.","publishedOnCurrentPublication":"Use `publishedOnPublication` instead.","resourcePublicationOnCurrentPublication":"Use `resourcePublications` instead.","sellingPlanGroupCount":"Use `sellingPlanGroupsCount` instead.","standardizedProductType":"Use `productCategory` instead.","storefrontId":"Use `id` instead.","totalVariants":"Use `variantsCount` instead.","unpublishedChannels":"Use `unpublishedPublications` instead."}}}, +"ProductBundleComponent":{"o":{"f":{"componentProduct":"Product!","componentVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"componentVariantsCount":"Count","optionSelections":"[ProductBundleComponentOptionSelection!]!","quantity":"Int","quantityOption":"ProductBundleComponentQuantityOption"}}}, +"ProductBundleComponentConnection":{"o":{"f":{"edges":"[ProductBundleComponentEdge!]!","nodes":"[ProductBundleComponent!]!","pageInfo":"PageInfo!"}}}, +"ProductBundleComponentEdge":{"o":{"f":{"cursor":"String!","node":"ProductBundleComponent!"}}}, +"ProductBundleComponentInput":{"i":{"optionSelections":"[ProductBundleComponentOptionSelectionInput!]!","productId":"ID!","quantity":"Int","quantityOption":"ProductBundleComponentQuantityOptionInput"}}, +"ProductBundleComponentOptionSelection":{"o":{"f":{"componentOption":"ProductOption!","parentOption":"ProductOption","values":"[ProductBundleComponentOptionSelectionValue!]!"}}}, +"ProductBundleComponentOptionSelectionInput":{"i":{"componentOptionId":"ID!","name":"String!","values":"[String!]!"}}, +"ProductBundleComponentOptionSelectionStatus":{"e":["SELECTED","DESELECTED","NEW","UNAVAILABLE"]}, +"ProductBundleComponentOptionSelectionValue":{"o":{"f":{"selectionStatus":"ProductBundleComponentOptionSelectionStatus!","value":"String!"}}}, +"ProductBundleComponentQuantityOption":{"o":{"f":{"name":"String!","parentOption":"ProductOption","values":"[ProductBundleComponentQuantityOptionValue!]!"}}}, +"ProductBundleComponentQuantityOptionInput":{"i":{"name":"String!","values":"[ProductBundleComponentQuantityOptionValueInput!]!"}}, +"ProductBundleComponentQuantityOptionValue":{"o":{"f":{"name":"String!","quantity":"Int!"}}}, +"ProductBundleComponentQuantityOptionValueInput":{"i":{"name":"String!","quantity":"Int!"}}, +"ProductBundleConsolidatedOptionComponentInput":{"i":{"componentOptionId":"ID","componentOptionValue":"String!"}}, +"ProductBundleConsolidatedOptionInput":{"i":{"optionName":"String!","optionSelections":"[ProductBundleConsolidatedOptionSelectionInput!]!"}}, +"ProductBundleConsolidatedOptionSelectionInput":{"i":{"components":"[ProductBundleConsolidatedOptionComponentInput!]!","optionValue":"String!"}}, +"ProductBundleCreateInput":{"i":{"components":"[ProductBundleComponentInput!]!","consolidatedOptions":"[ProductBundleConsolidatedOptionInput!]","title":"String!"}}, +"ProductBundleCreatePayload":{"o":{"f":{"productBundleOperation":"ProductBundleOperation","userErrors":"[UserError!]!"}}}, +"ProductBundleMutationUserError":{"o":{"f":{"code":"ProductBundleMutationUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductBundleMutationUserErrorCode":{"e":["GENERIC_ERROR","PRODUCT_DOES_NOT_EXIST","INVALID_INPUT","JOB_ERROR"]}, +"ProductBundleOperation":{"o":{"f":{"id":"ID!","product":"Product","status":"ProductOperationStatus!","userErrors":"[ProductBundleMutationUserError!]!"},"t":["Node","ProductOperation"]}}, +"ProductBundleUpdateInput":{"i":{"components":"[ProductBundleComponentInput!]","consolidatedOptions":"[ProductBundleConsolidatedOptionInput!]","productId":"ID!","title":"String"}}, +"ProductBundleUpdatePayload":{"o":{"f":{"productBundleOperation":"ProductBundleOperation","userErrors":"[UserError!]!"}}}, +"ProductCategory":{"o":{"f":{"productTaxonomyNode":"ProductTaxonomyNode"}}}, +"ProductChangeStatusPayload":{"o":{"f":{"product":"Product","userErrors":"[ProductChangeStatusUserError!]!"}}}, +"ProductChangeStatusUserError":{"o":{"f":{"code":"ProductChangeStatusUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductChangeStatusUserErrorCode":{"e":["PRODUCT_NOT_FOUND","COMBINED_LISTINGS_NOT_COMPATIBLE_WITH_SHOP"]}, +"ProductClaimOwnershipInput":{"i":{"bundles":"Boolean"}}, +"ProductCollectionSortKeys":{"e":["BEST_SELLING","COLLECTION_DEFAULT","CREATED","ID","MANUAL","PRICE","RELEVANCE","TITLE"]}, +"ProductCompareAtPriceRange":{"o":{"f":{"maxVariantCompareAtPrice":"MoneyV2!","minVariantCompareAtPrice":"MoneyV2!"}}}, +"ProductComponentType":{"o":{"f":{"componentVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"componentVariantsCount":"Count","nonComponentVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"nonComponentVariantsCount":"Count","product":"Product!"}}}, +"ProductComponentTypeConnection":{"o":{"f":{"edges":"[ProductComponentTypeEdge!]!","nodes":"[ProductComponentType!]!","pageInfo":"PageInfo!"}}}, +"ProductComponentTypeEdge":{"o":{"f":{"cursor":"String!","node":"ProductComponentType!"}}}, +"ProductConnection":{"o":{"f":{"edges":"[ProductEdge!]!","nodes":"[Product!]!","pageInfo":"PageInfo!"}}}, +"ProductContextualPricing":{"o":{"f":{"fixedQuantityRulesCount":"Int!","maxVariantPricing":"ProductVariantContextualPricing","minVariantPricing":"ProductVariantContextualPricing","priceRange":"ProductPriceRangeV2!"}}}, +"ProductCreateInput":{"i":{"category":"ID","claimOwnership":"ProductClaimOwnershipInput","collectionsToJoin":"[ID!]","combinedListingRole":"CombinedListingsRole","descriptionHtml":"String","giftCard":"Boolean","giftCardTemplateSuffix":"String","handle":"String","metafields":"[MetafieldInput!]","productOptions":"[OptionCreateInput!]","productType":"String","requiresSellingPlan":"Boolean","seo":"SEOInput","status":"ProductStatus","tags":"[String!]","templateSuffix":"String","title":"String","vendor":"String"}}, +"ProductCreateMediaPayload":{"o":{"f":{"media":"[Media!]","mediaUserErrors":"[MediaUserError!]!","product":"Product","userErrors":"[UserError!]!"},"d":{"userErrors":"Use `mediaUserErrors` instead."}}}, +"ProductCreatePayload":{"o":{"f":{"product":"Product","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"ProductDeleteInput":{"i":{"id":"ID!"}}, +"ProductDeleteMediaPayload":{"o":{"f":{"deletedMediaIds":"[ID!]","deletedProductImageIds":"[ID!]","mediaUserErrors":"[MediaUserError!]!","product":"Product","userErrors":"[UserError!]!"},"d":{"userErrors":"Use `mediaUserErrors` instead."}}}, +"ProductDeleteOperation":{"o":{"f":{"deletedProductId":"ID","id":"ID!","product":"Product","status":"ProductOperationStatus!","userErrors":"[UserError!]!"},"t":["Node","ProductOperation"]}}, +"ProductDeletePayload":{"o":{"f":{"deletedProductId":"ID","productDeleteOperation":"ProductDeleteOperation","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"ProductDiscountsWithTagsOnSameCartLineInput":{"i":{"add":"[String!]","remove":"[String!]"}}, +"ProductDuplicateJob":{"o":{"f":{"done":"Boolean!","id":"ID!"}}}, +"ProductDuplicateOperation":{"o":{"f":{"id":"ID!","newProduct":"Product","product":"Product","status":"ProductOperationStatus!","userErrors":"[UserError!]!"},"t":["Node","ProductOperation"]}}, +"ProductDuplicatePayload":{"o":{"f":{"imageJob":"Job","newProduct":"Product","productDuplicateOperation":"ProductDuplicateOperation","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"ProductEdge":{"o":{"f":{"cursor":"String!","node":"Product!"}}}, +"ProductFeed":{"o":{"f":{"channelId":"ID!","country":"CountryCode","id":"ID!","language":"LanguageCode","status":"ProductFeedStatus!"},"t":["Node"]}}, +"ProductFeedConnection":{"o":{"f":{"edges":"[ProductFeedEdge!]!","nodes":"[ProductFeed!]!","pageInfo":"PageInfo!"}}}, +"ProductFeedCreatePayload":{"o":{"f":{"productFeed":"ProductFeed","userErrors":"[ProductFeedCreateUserError!]!"}}}, +"ProductFeedCreateUserError":{"o":{"f":{"code":"ProductFeedCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductFeedCreateUserErrorCode":{"e":["INVALID","TAKEN"]}, +"ProductFeedDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[ProductFeedDeleteUserError!]!"}}}, +"ProductFeedDeleteUserError":{"o":{"f":{"code":"ProductFeedDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductFeedDeleteUserErrorCode":{"e":["INVALID"]}, +"ProductFeedEdge":{"o":{"f":{"cursor":"String!","node":"ProductFeed!"}}}, +"ProductFeedInput":{"i":{"channelId":"ID","country":"CountryCode!","language":"LanguageCode!"}}, +"ProductFeedStatus":{"e":["ACTIVE","INACTIVE"]}, +"ProductFullSyncPayload":{"o":{"f":{"id":"ID","userErrors":"[ProductFullSyncUserError!]!"}}}, +"ProductFullSyncUserError":{"o":{"f":{"code":"ProductFullSyncUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductFullSyncUserErrorCode":{"e":["INVALID"]}, +"ProductIdentifierInput":{"i":{"f":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"},"o":true}}, +"ProductImageSortKeys":{"e":["CREATED_AT","ID","POSITION"]}, +"ProductInput":{"i":{"f":{"category":"ID","claimOwnership":"ProductClaimOwnershipInput","collectionsToJoin":"[ID!]","collectionsToLeave":"[ID!]","combinedListingRole":"CombinedListingsRole","descriptionHtml":"String","giftCard":"Boolean","giftCardTemplateSuffix":"String","handle":"String","id":"ID","metafields":"[MetafieldInput!]","productOptions":"[OptionCreateInput!]","productPublications":"[ProductPublicationInput!]","productType":"String","publications":"[ProductPublicationInput!]","publishDate":"DateTime","publishOn":"DateTime","published":"Boolean","publishedAt":"DateTime","redirectNewHandle":"Boolean","requiresSellingPlan":"Boolean","seo":"SEOInput","status":"ProductStatus","tags":"[String!]","templateSuffix":"String","title":"String","vendor":"String"},"d":{"productPublications":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead.","publications":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead.","publishDate":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead.","publishOn":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead.","published":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead.","publishedAt":"Use [`PublishablePublish`](https://shopify.dev/docs/api/admin-graphql/latest/mutations/publishablePublish)\ninstead."}}}, +"ProductJoinSellingPlanGroupsPayload":{"o":{"f":{"product":"Product","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"ProductLeaveSellingPlanGroupsPayload":{"o":{"f":{"product":"Product","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"ProductMediaSortKeys":{"e":["ID","POSITION"]}, +"ProductOperation":{"n":{"f":{"product":"Product","status":"ProductOperationStatus!"},"t":["ProductBundleOperation","ProductDeleteOperation","ProductDuplicateOperation","ProductSetOperation"]}}, +"ProductOperationStatus":{"e":["CREATED","ACTIVE","COMPLETE"]}, +"ProductOption":{"o":{"f":{"createdAt":"DateTime!","id":"ID!","linkedMetafield":"LinkedMetafield","name":"String!","optionValues":"[ProductOptionValue!]!","position":"Int!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"values":"[String!]!"},"t":["HasPublishedTranslations","Node"]}}, +"ProductOptionCreateVariantStrategy":{"e":["LEAVE_AS_IS","CREATE"]}, +"ProductOptionDeleteStrategy":{"e":["DEFAULT","POSITION","NON_DESTRUCTIVE"]}, +"ProductOptionUpdatePayload":{"o":{"f":{"product":"Product","userErrors":"[ProductOptionUpdateUserError!]!"}}}, +"ProductOptionUpdateUserError":{"o":{"f":{"code":"ProductOptionUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductOptionUpdateUserErrorCode":{"e":["PRODUCT_DOES_NOT_EXIST","PRODUCT_SUSPENDED","OPTION_DOES_NOT_EXIST","OPTION_ALREADY_EXISTS","INVALID_POSITION","INVALID_NAME","OPTION_VALUES_OVER_LIMIT","OPTION_VALUE_DOES_NOT_EXIST","OPTION_VALUE_ALREADY_EXISTS","OPTION_VALUE_HAS_VARIANTS","CANNOT_DELETE_ALL_OPTION_VALUES_IN_OPTION","CANNOT_LEAVE_OPTIONS_WITHOUT_VARIANTS","NO_KEY_ON_CREATE","KEY_MISSING_IN_INPUT","DUPLICATED_OPTION_VALUE","OPTION_NAME_TOO_LONG","OPTION_VALUE_NAME_TOO_LONG","OPTION_VALUE_CONFLICTING_OPERATION","CANNOT_CREATE_VARIANTS_ABOVE_LIMIT","CANNOT_COMBINE_LINKED_AND_NONLINKED_OPTION_VALUES","INVALID_METAFIELD_VALUE_FOR_LINKED_OPTION","DUPLICATE_LINKED_OPTION","OPTION_LINKED_METAFIELD_ALREADY_TAKEN","LINKED_OPTION_UPDATE_MISSING_VALUES","LINKED_OPTIONS_NOT_SUPPORTED_FOR_SHOP","LINKED_METAFIELD_DEFINITION_NOT_FOUND","CANNOT_MAKE_CHANGES_IF_VARIANT_IS_MISSING_REQUIRED_SKU","UNSUPPORTED_COMBINED_LISTING_PARENT_OPERATION","CANNOT_DELETE_VARIANT_WITHOUT_PERMISSION","TOO_MANY_VARIANTS_CREATED"]}, +"ProductOptionUpdateVariantStrategy":{"e":["LEAVE_AS_IS","MANAGE"]}, +"ProductOptionValue":{"o":{"f":{"hasVariants":"Boolean!","id":"ID!","linkedMetafieldValue":"String","name":"String!","swatch":"ProductOptionValueSwatch","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}]},"t":["HasPublishedTranslations","Node"]}}, +"ProductOptionValueSwatch":{"o":{"f":{"color":"Color","image":"MediaImage"}}}, +"ProductOptionsCreatePayload":{"o":{"f":{"product":"Product","userErrors":"[ProductOptionsCreateUserError!]!"}}}, +"ProductOptionsCreateUserError":{"o":{"f":{"code":"ProductOptionsCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductOptionsCreateUserErrorCode":{"e":["OPTION_ALREADY_EXISTS","OPTIONS_OVER_LIMIT","OPTION_VALUES_OVER_LIMIT","INVALID_NAME","PRODUCT_SUSPENDED","NEW_OPTION_WITHOUT_VALUE_FOR_EXISTING_VARIANTS","DUPLICATED_OPTION_NAME","DUPLICATED_OPTION_VALUE","OPTION_NAME_MISSING","OPTION_VALUES_MISSING","OPTION_VALUE_NAME_TOO_LONG","OPTION_NAME_TOO_LONG","POSITION_OUT_OF_BOUNDS","OPTION_POSITION_MISSING","PRODUCT_DOES_NOT_EXIST","LINKED_METAFIELD_DEFINITION_NOT_FOUND","INVALID_METAFIELD_VALUE_FOR_LINKED_OPTION","MISSING_METAFIELD_VALUES_FOR_LINKED_OPTION","CANNOT_COMBINE_LINKED_METAFIELD_AND_OPTION_VALUES","DUPLICATE_LINKED_OPTION","OPTION_LINKED_METAFIELD_ALREADY_TAKEN","LINKED_OPTIONS_NOT_SUPPORTED_FOR_SHOP","CANNOT_MAKE_CHANGES_IF_VARIANT_IS_MISSING_REQUIRED_SKU","UNSUPPORTED_COMBINED_LISTING_PARENT_OPERATION","LINKED_METAFIELD_VALUE_WITHOUT_LINKED_OPTION","TOO_MANY_VARIANTS_CREATED"]}, +"ProductOptionsDeletePayload":{"o":{"f":{"deletedOptionsIds":"[ID!]","product":"Product","userErrors":"[ProductOptionsDeleteUserError!]!"}}}, +"ProductOptionsDeleteUserError":{"o":{"f":{"code":"ProductOptionsDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductOptionsDeleteUserErrorCode":{"e":["PRODUCT_DOES_NOT_EXIST","PRODUCT_SUSPENDED","OPTION_DOES_NOT_EXIST","OPTIONS_DO_NOT_BELONG_TO_THE_SAME_PRODUCT","CANNOT_DELETE_OPTION_WITH_MULTIPLE_VALUES","CANNOT_USE_NON_DESTRUCTIVE_STRATEGY","CANNOT_MAKE_CHANGES_IF_VARIANT_IS_MISSING_REQUIRED_SKU","UNSUPPORTED_COMBINED_LISTING_PARENT_OPERATION","CANNOT_DELETE_VARIANT_WITHOUT_PERMISSION"]}, +"ProductOptionsReorderPayload":{"o":{"f":{"product":"Product","userErrors":"[ProductOptionsReorderUserError!]!"}}}, +"ProductOptionsReorderUserError":{"o":{"f":{"code":"ProductOptionsReorderUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductOptionsReorderUserErrorCode":{"e":["OPTION_NAME_DOES_NOT_EXIST","OPTION_VALUE_DOES_NOT_EXIST","OPTION_ID_DOES_NOT_EXIST","OPTION_VALUE_ID_DOES_NOT_EXIST","DUPLICATED_OPTION_NAME","DUPLICATED_OPTION_VALUE","MISSING_OPTION_NAME","MISSING_OPTION_VALUE","PRODUCT_DOES_NOT_EXIST","PRODUCT_SUSPENDED","NO_KEY_ON_REORDER","MIXING_ID_AND_NAME_KEYS_IS_NOT_ALLOWED","CANNOT_MAKE_CHANGES_IF_VARIANT_IS_MISSING_REQUIRED_SKU"]}, +"ProductPriceRange":{"o":{"f":{"maxVariantPrice":"MoneyV2!","minVariantPrice":"MoneyV2!"}}}, +"ProductPriceRangeV2":{"o":{"f":{"maxVariantPrice":"MoneyV2!","minVariantPrice":"MoneyV2!"}}}, +"ProductPublication":{"o":{"f":{"channel":"Channel!","isPublished":"Boolean!","product":"Product!","publishDate":"DateTime"}}}, +"ProductPublicationConnection":{"o":{"f":{"edges":"[ProductPublicationEdge!]!","nodes":"[ProductPublication!]!","pageInfo":"PageInfo!"}}}, +"ProductPublicationEdge":{"o":{"f":{"cursor":"String!","node":"ProductPublication!"}}}, +"ProductPublicationInput":{"i":{"f":{"channelHandle":"String","channelId":"ID","publicationId":"ID","publishDate":"DateTime"},"d":{"channelHandle":"Use publicationId instead.","channelId":"Use publicationId instead."}}}, +"ProductPublishInput":{"i":{"id":"ID!","productPublications":"[ProductPublicationInput!]!"}}, +"ProductPublishPayload":{"o":{"f":{"product":"Product","productPublications":"[ProductPublication!]","shop":"Shop!","userErrors":"[UserError!]!"},"d":{"productPublications":"Use Product.publications instead."}}}, +"ProductReorderMediaPayload":{"o":{"f":{"job":"Job","mediaUserErrors":"[MediaUserError!]!","userErrors":"[UserError!]!"},"d":{"userErrors":"Use `mediaUserErrors` instead."}}}, +"ProductResourceFeedback":{"o":{"f":{"channel":"Channel","feedbackGeneratedAt":"DateTime!","messages":"[String!]!","productId":"ID!","productUpdatedAt":"DateTime!","state":"ResourceFeedbackState!"}}}, +"ProductResourceFeedbackInput":{"i":{"channelId":"ID","feedbackGeneratedAt":"DateTime!","messages":"[String!]","productId":"ID!","productUpdatedAt":"DateTime!","state":"ResourceFeedbackState!"}}, +"ProductSale":{"o":{"f":{"actionType":"SaleActionType!","id":"ID!","lineItem":"LineItem!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"ProductSetIdentifiers":{"i":{"f":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"},"o":true}}, +"ProductSetInput":{"i":{"f":{"category":"ID","claimOwnership":"ProductClaimOwnershipInput","collections":"[ID!]","combinedListingRole":"CombinedListingsRole","descriptionHtml":"String","files":"[FileSetInput!]","giftCard":"Boolean","giftCardTemplateSuffix":"String","handle":"String","id":"ID","metafields":"[MetafieldInput!]","productOptions":"[OptionSetInput!]","productType":"String","redirectNewHandle":"Boolean","requiresSellingPlan":"Boolean","seo":"SEOInput","status":"ProductStatus","tags":"[String!]","templateSuffix":"String","title":"String","variants":"[ProductVariantSetInput!]","vendor":"String"},"d":{"id":"Use `identifier` instead to get the product's ID"}}}, +"ProductSetInventoryInput":{"i":{"locationId":"ID!","name":"String!","quantity":"Int!"}}, +"ProductSetOperation":{"o":{"f":{"id":"ID!","product":"Product","status":"ProductOperationStatus!","userErrors":"[ProductSetUserError!]!"},"t":["Node","ProductOperation"]}}, +"ProductSetPayload":{"o":{"f":{"product":"Product","productSetOperation":"ProductSetOperation","userErrors":"[ProductSetUserError!]!"}}}, +"ProductSetUserError":{"o":{"f":{"code":"ProductSetUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductSetUserErrorCode":{"e":["ID_NOT_ALLOWED","MISSING_FIELD_REQUIRED","INPUT_MISMATCH","NOT_FOUND","METAFIELD_MISMATCH","GENERIC_ERROR","INVALID_METAFIELD","INVALID_VARIANT","PRODUCT_DOES_NOT_EXIST","PRODUCT_SUSPENDED","PRODUCT_VARIANT_DOES_NOT_EXIST","OPTION_DOES_NOT_EXIST","OPTION_VALUE_DOES_NOT_EXIST","OPTIONS_OVER_LIMIT","OPTION_VALUES_OVER_LIMIT","OPTION_VALUES_MISSING","DUPLICATED_OPTION_NAME","DUPLICATED_OPTION_VALUE","VARIANTS_OVER_LIMIT","PRODUCT_OPTIONS_INPUT_MISSING","VARIANTS_INPUT_MISSING","GIFT_CARDS_NOT_ACTIVATED","GIFT_CARD_ATTRIBUTE_CANNOT_BE_CHANGED","INVALID_PRODUCT","INVALID_INPUT","JOB_ERROR","CAPABILITY_VIOLATION","CANNOT_COMBINE_LINKED_AND_NONLINKED_OPTION_VALUES","INVALID_METAFIELD_VALUE_FOR_LINKED_OPTION","DUPLICATE_LINKED_OPTION","DUPLICATED_METAFIELD_VALUE","LINKED_OPTIONS_NOT_SUPPORTED_FOR_SHOP","LINKED_METAFIELD_DEFINITION_NOT_FOUND","DUPLICATED_VALUE","HANDLE_NOT_UNIQUE","INCOMPATIBLE_BARCODE_FIELDS","BLANK_BARCODE_VALUE","TOO_MANY_BARCODES","BARCODE_VALUE_TOO_LONG","DUPLICATE_BARCODE_VALUE","INVALID_BARCODE_TYPE","INVALID_BARCODE_SEPARATORS","INVALID_BARCODE_LENGTH","INVALID_BARCODE_PREFIX","INVALID_BARCODE_CHARACTERS","BARCODE_CHECKSUM_VALIDATION_FAILED","INVENTORY_QUANTITIES_LIMIT_EXCEEDED"]}, +"ProductSortKeys":{"e":["CREATED_AT","ID","INVENTORY_TOTAL","PRODUCT_TYPE","PUBLISHED_AT","RELEVANCE","TITLE","UPDATED_AT","VENDOR"]}, +"ProductStatus":{"e":["ACTIVE","ARCHIVED","DRAFT","UNLISTED"]}, +"ProductTaxonomyNode":{"o":{"f":{"fullName":"String!","id":"ID!","isLeaf":"Boolean!","isRoot":"Boolean!","name":"String!"},"t":["Node"]}}, +"ProductUnpublishInput":{"i":{"id":"ID!","productPublications":"[ProductPublicationInput!]!"}}, +"ProductUnpublishPayload":{"o":{"f":{"product":"Product","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"ProductUpdateIdentifiers":{"i":{"f":{"customId":"UniqueMetafieldValueInput","handle":"String","id":"ID"},"o":true}}, +"ProductUpdateInput":{"i":{"category":"ID","collectionsToJoin":"[ID!]","collectionsToLeave":"[ID!]","deleteConflictingConstrainedMetafields":"Boolean=","descriptionHtml":"String","giftCardTemplateSuffix":"String","handle":"String","id":"ID","metafields":"[MetafieldInput!]","productType":"String","redirectNewHandle":"Boolean","requiresSellingPlan":"Boolean","seo":"SEOInput","status":"ProductStatus","tags":"[String!]","templateSuffix":"String","title":"String","vendor":"String"}}, +"ProductUpdateMediaPayload":{"o":{"f":{"media":"[Media!]","mediaUserErrors":"[MediaUserError!]!","product":"Product","userErrors":"[UserError!]!"},"d":{"userErrors":"Use `mediaUserErrors` instead."}}}, +"ProductUpdatePayload":{"o":{"f":{"product":"Product","userErrors":"[UserError!]!"}}}, +"ProductVariant":{"o":{"f":{"availableForSale":"Boolean!","availablePublicationsCount":"Count","barcode":"String","barcodes":["ProductVariantBarcodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int"}],"compareAtPrice":"Money","contextualPricing":["ProductVariantContextualPricing!",{"context":"ContextualPricingContext!"}],"createdAt":"DateTime!","defaultCursor":"String!","deliveryProfile":"DeliveryProfile","displayName":"String!","events":["EventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"id":"ID!","image":["Image",{"crop":"CropRegion","maxHeight":"Int","maxWidth":"Int","scale":"Int="}],"inventoryItem":"InventoryItem!","inventoryPolicy":"ProductVariantInventoryPolicy!","inventoryQuantity":"Int","legacyResourceId":"UnsignedInt64!","media":["MediaConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"position":"Int!","presentmentPrices":["ProductVariantPricePairConnection!",{"after":"String","before":"String","first":"Int","last":"Int","presentmentCurrencies":"[CurrencyCode!]","reverse":"Boolean="}],"price":"Money!","product":"Product!","productParents":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"productVariantComponents":["ProductVariantComponentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"publicationCount":["Int!",{"onlyPublished":"Boolean="}],"publishedOnChannel":["Boolean!",{"channelId":"ID!"}],"publishedOnCurrentChannel":"Boolean!","publishedOnCurrentPublication":"Boolean!","publishedOnPublication":["Boolean!",{"publicationId":"ID!"}],"requiresComponents":"Boolean!","resourcePublications":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"resourcePublicationsCount":["Count",{"onlyPublished":"Boolean="}],"resourcePublicationsV2":["ResourcePublicationV2Connection!",{"after":"String","before":"String","catalogType":"CatalogType","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"selectedOptions":"[SelectedOption!]!","sellableOnlineQuantity":"Int!","sellingPlanGroupCount":"Int!","sellingPlanGroups":["SellingPlanGroupConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"sellingPlanGroupsCount":"Count","showUnitPrice":"Boolean!","sku":"String","storefrontId":"StorefrontID!","taxCode":"String","taxable":"Boolean!","title":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"unitPrice":"MoneyV2","unitPriceMeasurement":"UnitPriceMeasurement","unpublishedChannels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"unpublishedPublications":["PublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"updatedAt":"DateTime!"},"t":["HasEvents","HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","LegacyInteroperability","Navigable","Node","Publishable"],"d":{"barcode":"Use `barcodes` instead.","image":"Use `media` instead.","image(crop)":"Use `Image.url(transform: { crop:})` instead.","image(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","image(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","image(scale)":"Use `Image.url(transform: { scale:})` instead.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","presentmentPrices":"Use `contextualPricing` instead.","publicationCount":"Use `resourcePublicationsCount` instead.","publishedOnChannel":"Use `publishedOnPublication` instead.","publishedOnCurrentChannel":"Use `publishedOnCurrentPublication` instead.","publishedOnCurrentPublication":"Use `publishedOnPublication` instead.","sellingPlanGroupCount":"Use `sellingPlanGroupsCount` instead.","storefrontId":"Use `id` instead.","taxCode":"This field should no longer be used in new integrations. This field will not be available in future API versions.","unpublishedChannels":"Use `unpublishedPublications` instead."}}}, +"ProductVariantAppendMediaInput":{"i":{"mediaIds":"[ID!]!","variantId":"ID!"}}, +"ProductVariantAppendMediaPayload":{"o":{"f":{"product":"Product","productVariants":"[ProductVariant!]","userErrors":"[MediaUserError!]!"}}}, +"ProductVariantBarcode":{"o":{"f":{"type":"BarcodeType","value":"String!"}}}, +"ProductVariantBarcodeConnection":{"o":{"f":{"edges":"[ProductVariantBarcodeEdge!]!","nodes":"[ProductVariantBarcode!]!","pageInfo":"PageInfo!"}}}, +"ProductVariantBarcodeEdge":{"o":{"f":{"cursor":"String!","node":"ProductVariantBarcode!"}}}, +"ProductVariantComponent":{"o":{"f":{"id":"ID!","productVariant":"ProductVariant!","quantity":"Int!"},"t":["Node"]}}, +"ProductVariantComponentConnection":{"o":{"f":{"edges":"[ProductVariantComponentEdge!]!","nodes":"[ProductVariantComponent!]!","pageInfo":"PageInfo!"}}}, +"ProductVariantComponentEdge":{"o":{"f":{"cursor":"String!","node":"ProductVariantComponent!"}}}, +"ProductVariantConnection":{"o":{"f":{"edges":"[ProductVariantEdge!]!","nodes":"[ProductVariant!]!","pageInfo":"PageInfo!"}}}, +"ProductVariantContextualPricing":{"o":{"f":{"auditTrail":"PricingAuditTrail!","compareAtPrice":"MoneyV2","price":"MoneyV2!","quantityPriceBreaks":["QuantityPriceBreakConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"QuantityPriceBreakSortKeys="}],"quantityRule":"QuantityRule!","unitPrice":"MoneyV2"}}}, +"ProductVariantDetachMediaInput":{"i":{"mediaIds":"[ID!]!","variantId":"ID!"}}, +"ProductVariantDetachMediaPayload":{"o":{"f":{"product":"Product","productVariants":"[ProductVariant!]","userErrors":"[MediaUserError!]!"}}}, +"ProductVariantEdge":{"o":{"f":{"cursor":"String!","node":"ProductVariant!"}}}, +"ProductVariantGroupRelationshipInput":{"i":{"id":"ID!","quantity":"Int!"}}, +"ProductVariantIdentifierInput":{"i":{"f":{"customId":"UniqueMetafieldValueInput","id":"ID"},"o":true}}, +"ProductVariantInventoryPolicy":{"e":["DENY","CONTINUE"]}, +"ProductVariantJoinSellingPlanGroupsPayload":{"o":{"f":{"productVariant":"ProductVariant","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"ProductVariantLeaveSellingPlanGroupsPayload":{"o":{"f":{"productVariant":"ProductVariant","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"ProductVariantPositionInput":{"i":{"id":"ID!","position":"Int!"}}, +"ProductVariantPricePair":{"o":{"f":{"compareAtPrice":"MoneyV2","price":"MoneyV2!"}}}, +"ProductVariantPricePairConnection":{"o":{"f":{"edges":"[ProductVariantPricePairEdge!]!","nodes":"[ProductVariantPricePair!]!","pageInfo":"PageInfo!"}}}, +"ProductVariantPricePairEdge":{"o":{"f":{"cursor":"String!","node":"ProductVariantPricePair!"}}}, +"ProductVariantRelationshipBulkUpdatePayload":{"o":{"f":{"parentProductVariants":"[ProductVariant!]","userErrors":"[ProductVariantRelationshipBulkUpdateUserError!]!"}}}, +"ProductVariantRelationshipBulkUpdateUserError":{"o":{"f":{"code":"ProductVariantRelationshipBulkUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductVariantRelationshipBulkUpdateUserErrorCode":{"e":["PARENT_REQUIRED","FAILED_TO_CREATE","PRODUCT_VARIANTS_NOT_FOUND","CIRCULAR_REFERENCE","NESTED_PARENT_PRODUCT_VARIANT","INVALID_QUANTITY","DUPLICATE_PRODUCT_VARIANT_RELATIONSHIP","EXCEEDED_PRODUCT_VARIANT_RELATIONSHIP_LIMIT","PRODUCT_VARIANT_RELATIONSHIP_TYPE_CONFLICT","UNEXPECTED_ERROR","FAILED_TO_REMOVE","MUST_SPECIFY_COMPONENTS","FAILED_TO_UPDATE","FAILED_TO_UPDATE_PARENT_PRODUCT_VARIANT_PRICE","UPDATE_PARENT_VARIANT_PRICE_REQUIRED","PRODUCT_VARIANTS_NOT_COMPONENTS","PRODUCT_EXPANDER_APP_OWNERSHIP_ALREADY_EXISTS","UNSUPPORTED_MULTIPACK_RELATIONSHIP","PARENT_PRODUCT_VARIANT_CANNOT_BE_GIFT_CARD","PARENT_PRODUCT_VARIANT_CANNOT_REQUIRE_SELLING_PLAN","PARENT_PRODUCT_VARIANT_CANNOT_BE_COMBINED_LISTING","CHILD_PRODUCT_VARIANT_CANNOT_BE_COMBINED_LISTING"]}, +"ProductVariantRelationshipUpdateInput":{"i":{"parentProductId":"ID","parentProductVariantId":"ID","priceInput":"PriceInput=","productVariantRelationshipsToCreate":"[ProductVariantGroupRelationshipInput!]=","productVariantRelationshipsToRemove":"[ID!]=","productVariantRelationshipsToUpdate":"[ProductVariantGroupRelationshipInput!]=","removeAllProductVariantRelationships":"Boolean="}}, +"ProductVariantSetInput":{"i":{"f":{"barcode":"String","barcodes":"[BarcodeInput!]","compareAtPrice":"Money","file":"FileSetInput","id":"ID","inventoryItem":"InventoryItemInput","inventoryPolicy":"ProductVariantInventoryPolicy","inventoryQuantities":"[ProductSetInventoryInput!]","metafields":"[MetafieldInput!]","optionValues":"[VariantOptionValueInput!]!","position":"Int","price":"Money","published":"Boolean","requiresComponents":"Boolean","showUnitPrice":"Boolean","sku":"String","taxCode":"String","taxable":"Boolean","unitPriceMeasurement":"UnitPriceMeasurementInput"},"d":{"barcode":"Use `barcodes` instead."}}}, +"ProductVariantSortKeys":{"e":["FULL_TITLE","ID","INVENTORY_LEVELS_AVAILABLE","INVENTORY_MANAGEMENT","INVENTORY_POLICY","INVENTORY_QUANTITY","NAME","POPULAR","POSITION","RELEVANCE","SKU","TITLE"]}, +"ProductVariantsBulkCreatePayload":{"o":{"f":{"product":"Product","productVariants":"[ProductVariant!]","userErrors":"[ProductVariantsBulkCreateUserError!]!"}}}, +"ProductVariantsBulkCreateStrategy":{"e":["DEFAULT","REMOVE_STANDALONE_VARIANT","PRESERVE_STANDALONE_VARIANT"]}, +"ProductVariantsBulkCreateUserError":{"o":{"f":{"code":"ProductVariantsBulkCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductVariantsBulkCreateUserErrorCode":{"e":["INVALID_INPUT","PRODUCT_DOES_NOT_EXIST","NO_KEY_ON_CREATE","VARIANT_ALREADY_EXISTS","PRODUCT_SUSPENDED","GREATER_THAN_OR_EQUAL_TO","LOCAL_CURRENCY_GIFT_CARD_PRICE_MUST_BE_ZERO","NEED_TO_ADD_OPTION_VALUES","OPTION_VALUES_FOR_NUMBER_OF_UNKNOWN_OPTIONS","TOO_MANY_INVENTORY_LOCATIONS","SUBSCRIPTION_VIOLATION","VARIANT_ALREADY_EXISTS_CHANGE_OPTION_VALUE","TRACKED_VARIANT_LOCATION_NOT_FOUND","MUST_BE_FOR_THIS_PRODUCT","NOT_DEFINED_FOR_SHOP","INVALID","NEGATIVE_PRICE_VALUE","UNSUPPORTED_COMBINED_LISTING_PARENT_OPERATION","CANNOT_SET_NAME_FOR_LINKED_OPTION_VALUE","INVENTORY_QUANTITIES_LIMIT_EXCEEDED","INCOMPATIBLE_BARCODE_FIELDS","BLANK_BARCODE_VALUE","TOO_MANY_BARCODES","BARCODE_VALUE_TOO_LONG","DUPLICATE_BARCODE_VALUE","INVALID_BARCODE_TYPE","INVALID_BARCODE_SEPARATORS","INVALID_BARCODE_LENGTH","INVALID_BARCODE_PREFIX","INVALID_BARCODE_CHARACTERS","BARCODE_CHECKSUM_VALIDATION_FAILED"]}, +"ProductVariantsBulkDeletePayload":{"o":{"f":{"product":"Product","userErrors":"[ProductVariantsBulkDeleteUserError!]!"}}}, +"ProductVariantsBulkDeleteUserError":{"o":{"f":{"code":"ProductVariantsBulkDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductVariantsBulkDeleteUserErrorCode":{"e":["PRODUCT_DOES_NOT_EXIST","PRODUCT_SUSPENDED","CANNOT_DELETE_LAST_VARIANT","AT_LEAST_ONE_VARIANT_DOES_NOT_BELONG_TO_THE_PRODUCT","UNSUPPORTED_COMBINED_LISTING_PARENT_OPERATION"]}, +"ProductVariantsBulkInput":{"i":{"f":{"barcode":"String","barcodes":"[BarcodeInput!]","compareAtPrice":"Money","id":"ID","inventoryItem":"InventoryItemInput","inventoryPolicy":"ProductVariantInventoryPolicy","inventoryQuantities":"[InventoryLevelInput!]","mediaId":"ID","mediaSrc":"[String!]","metafields":"[MetafieldInput!]","optionValues":"[VariantOptionValueInput!]","price":"Money","published":"Boolean","quantityAdjustments":"[InventoryAdjustmentInput!]","requiresComponents":"Boolean","showUnitPrice":"Boolean","taxCode":"String","taxable":"Boolean","unitPriceMeasurement":"UnitPriceMeasurementInput"},"d":{"barcode":"Use `barcodes` instead."}}}, +"ProductVariantsBulkReorderPayload":{"o":{"f":{"product":"Product","userErrors":"[ProductVariantsBulkReorderUserError!]!"}}}, +"ProductVariantsBulkReorderUserError":{"o":{"f":{"code":"ProductVariantsBulkReorderUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductVariantsBulkReorderUserErrorCode":{"e":["PRODUCT_DOES_NOT_EXIST","MISSING_VARIANT","INVALID_POSITION","DUPLICATED_VARIANT_ID","GENERIC_ERROR"]}, +"ProductVariantsBulkUpdatePayload":{"o":{"f":{"product":"Product","productVariants":"[ProductVariant!]","userErrors":"[ProductVariantsBulkUpdateUserError!]!"}}}, +"ProductVariantsBulkUpdateUserError":{"o":{"f":{"code":"ProductVariantsBulkUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ProductVariantsBulkUpdateUserErrorCode":{"e":["INVALID_INPUT","CANNOT_SPECIFY_BOTH","MUST_SPECIFY_ONE_OF_PAIR","OPTION_VALUE_NAME_TOO_LONG","PRODUCT_DOES_NOT_EXIST","PRODUCT_VARIANT_ID_MISSING","PRODUCT_VARIANT_DOES_NOT_EXIST","OPTION_DOES_NOT_EXIST","OPTION_VALUE_DOES_NOT_EXIST","MUST_BE_FOR_THIS_PRODUCT","NOT_DEFINED_FOR_SHOP","PRODUCT_SUSPENDED","NO_INVENTORY_QUANTITIES_ON_VARIANTS_UPDATE","VARIANT_ALREADY_EXISTS","GREATER_THAN_OR_EQUAL_TO","NEED_TO_ADD_OPTION_VALUES","OPTION_VALUES_FOR_NUMBER_OF_UNKNOWN_OPTIONS","SUBSCRIPTION_VIOLATION","NO_INVENTORY_QUANTITES_DURING_UPDATE","NEGATIVE_PRICE_VALUE","LOCAL_CURRENCY_GIFT_CARD_PRICE_MUST_BE_ZERO","BLANK","TOO_SHORT","TOO_LONG","INVALID_VALUE","CANNOT_SET_NAME_FOR_LINKED_OPTION_VALUE","UNSUPPORTED_COMBINED_LISTING_PARENT_OPERATION","INVENTORY_QUANTITIES_LIMIT_EXCEEDED","INCOMPATIBLE_BARCODE_FIELDS","BLANK_BARCODE_VALUE","TOO_MANY_BARCODES","BARCODE_VALUE_TOO_LONG","DUPLICATE_BARCODE_VALUE","INVALID_BARCODE_TYPE","INVALID_BARCODE_SEPARATORS","INVALID_BARCODE_LENGTH","INVALID_BARCODE_PREFIX","INVALID_BARCODE_CHARACTERS","BARCODE_CHECKSUM_VALIDATION_FAILED"]}, +"ProfileItemSortKeys":{"e":["CREATED_AT","ID","INVENTORY_TOTAL","PRODUCT_TYPE","PUBLISHED_AT","RELEVANCE","TITLE","UPDATED_AT","VENDOR"]}, +"PubSubServerPixelUpdatePayload":{"o":{"f":{"serverPixel":"ServerPixel","userErrors":"[ErrorsServerPixelUserError!]!"}}}, +"PubSubWebhookSubscriptionCreatePayload":{"o":{"f":{"userErrors":"[PubSubWebhookSubscriptionCreateUserError!]!","webhookSubscription":"WebhookSubscription"}}}, +"PubSubWebhookSubscriptionCreateUserError":{"o":{"f":{"code":"PubSubWebhookSubscriptionCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PubSubWebhookSubscriptionCreateUserErrorCode":{"e":["INVALID_PARAMETERS","TAKEN"]}, +"PubSubWebhookSubscriptionInput":{"i":{"filter":"String","format":"WebhookSubscriptionFormat","includeFields":"[String!]","metafieldNamespaces":"[String!]","metafields":"[HasMetafieldsMetafieldIdentifierInput!]","name":"String","pubSubProject":"String!","pubSubTopic":"String!"}}, +"PubSubWebhookSubscriptionUpdatePayload":{"o":{"f":{"userErrors":"[PubSubWebhookSubscriptionUpdateUserError!]!","webhookSubscription":"WebhookSubscription"}}}, +"PubSubWebhookSubscriptionUpdateUserError":{"o":{"f":{"code":"PubSubWebhookSubscriptionUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PubSubWebhookSubscriptionUpdateUserErrorCode":{"e":["INVALID_PARAMETERS","TAKEN"]}, +"Publication":{"o":{"f":{"app":"App!","autoPublish":"Boolean!","catalog":"Catalog","channels":["ChannelConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collectionPublicationsV3":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collections":["CollectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"hasCollection":["Boolean!",{"id":"ID!"}],"id":"ID!","includedProducts":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"ProductSortKeys="}],"includedProductsCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"name":"String!","operation":"PublicationOperation","productPublicationsV3":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"ProductSortKeys="}],"supportsFuturePublishing":"Boolean!"},"t":["Node"],"d":{"app":"Use [AppCatalog.apps](https://shopify.dev/api/admin-graphql/unstable/objects/AppCatalog#connection-appcatalog-apps) instead.","name":"Use [Catalog.title](https://shopify.dev/api/admin-graphql/unstable/interfaces/Catalog#field-catalog-title) instead."}}}, +"PublicationConnection":{"o":{"f":{"edges":"[PublicationEdge!]!","nodes":"[Publication!]!","pageInfo":"PageInfo!"}}}, +"PublicationCreateInput":{"i":{"autoPublish":"Boolean=","catalogId":"ID","defaultState":"PublicationCreateInputPublicationDefaultState="}}, +"PublicationCreateInputPublicationDefaultState":{"e":["EMPTY","ALL_PRODUCTS"]}, +"PublicationCreatePayload":{"o":{"f":{"publication":"Publication","userErrors":"[PublicationUserError!]!"}}}, +"PublicationDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[PublicationUserError!]!"}}}, +"PublicationEdge":{"o":{"f":{"cursor":"String!","node":"Publication!"}}}, +"PublicationInput":{"i":{"f":{"channelId":"ID","publicationId":"ID","publishDate":"DateTime"},"d":{"channelId":"Use publicationId instead."}}}, +"PublicationOperation":{"u":["AddAllProductsOperation","CatalogCsvOperation","PublicationResourceOperation"]}, +"PublicationResourceOperation":{"o":{"f":{"id":"ID!","processedRowCount":"Int","rowCount":"RowCount","status":"ResourceOperationStatus!"},"t":["Node","ResourceOperation"]}}, +"PublicationUpdateInput":{"i":{"autoPublish":"Boolean","publishablesToAdd":"[ID!]=","publishablesToRemove":"[ID!]="}}, +"PublicationUpdatePayload":{"o":{"f":{"publication":"Publication","userErrors":"[PublicationUserError!]!"}}}, +"PublicationUserError":{"o":{"f":{"code":"PublicationUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"PublicationUserErrorCode":{"e":["UNSUPPORTED_PUBLICATION_ACTION","PUBLICATION_NOT_FOUND","PUBLICATION_LOCKED","UNSUPPORTED_PUBLISHABLE_TYPE","INVALID_PUBLISHABLE_ID","MARKET_NOT_FOUND","CATALOG_NOT_FOUND","CANNOT_MODIFY_APP_CATALOG_PUBLICATION","CANNOT_MODIFY_MARKET_CATALOG_PUBLICATION","CANNOT_MODIFY_APP_CATALOG","CANNOT_MODIFY_MARKET_CATALOG","INVALID","TAKEN","TOO_LONG","TOO_SHORT","BLANK","PRODUCT_TYPE_INCOMPATIBLE_WITH_CATALOG_TYPE","PUBLICATION_UPDATE_LIMIT_EXCEEDED","CANNOT_COMBINE_PRODUCTS_AND_VARIANTS","VARIANTS_BELONG_TO_MULTIPLE_PRODUCTS","PRODUCT_LOCK_ERROR","VARIANT_PUBLISHING_UNSUPPORTED_PRODUCT_TYPE"]}, +"Publishable":{"n":{"f":{"availablePublicationsCount":"Count","publicationCount":["Int!",{"onlyPublished":"Boolean="}],"publishedOnChannel":["Boolean!",{"channelId":"ID!"}],"publishedOnCurrentChannel":"Boolean!","publishedOnCurrentPublication":"Boolean!","publishedOnPublication":["Boolean!",{"publicationId":"ID!"}],"resourcePublications":["ResourcePublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"resourcePublicationsCount":["Count",{"onlyPublished":"Boolean="}],"resourcePublicationsV2":["ResourcePublicationV2Connection!",{"after":"String","before":"String","catalogType":"CatalogType","first":"Int","last":"Int","onlyPublished":"Boolean=","reverse":"Boolean="}],"unpublishedChannels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"unpublishedPublications":["PublicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["Collection","Product","ProductVariant"],"d":{"publicationCount":"Use `resourcePublicationsCount` instead.","publishedOnChannel":"Use `publishedOnPublication` instead.","publishedOnCurrentChannel":"Use `publishedOnCurrentPublication` instead.","publishedOnCurrentPublication":"Use `publishedOnPublication` instead.","unpublishedChannels":"Use `unpublishedPublications` instead."}}}, +"PublishablePublishPayload":{"o":{"f":{"publishable":"Publishable","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"PublishablePublishToCurrentChannelPayload":{"o":{"f":{"publishable":"Publishable","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"PublishableUnpublishPayload":{"o":{"f":{"publishable":"Publishable","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"PublishableUnpublishToCurrentChannelPayload":{"o":{"f":{"publishable":"Publishable","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"PurchaseOrderLineItemSortKeys":{"e":["ID"]}, +"PurchasingCompany":{"o":{"f":{"company":"Company!","contact":"CompanyContact","location":"CompanyLocation!"}}}, +"PurchasingCompanyInput":{"i":{"companyContactId":"ID!","companyId":"ID!","companyLocationId":"ID!"}}, +"PurchasingEntity":{"u":["Customer","PurchasingCompany"]}, +"PurchasingEntityInput":{"i":{"customerId":"ID","purchasingCompany":"PurchasingCompanyInput"}}, +"QuantityPriceBreak":{"o":{"f":{"id":"ID!","minimumQuantity":"Int!","price":"MoneyV2!","priceList":"PriceList!","variant":"ProductVariant!"},"t":["Node"]}}, +"QuantityPriceBreakConnection":{"o":{"f":{"edges":"[QuantityPriceBreakEdge!]!","nodes":"[QuantityPriceBreak!]!","pageInfo":"PageInfo!"}}}, +"QuantityPriceBreakEdge":{"o":{"f":{"cursor":"String!","node":"QuantityPriceBreak!"}}}, +"QuantityPriceBreakInput":{"i":{"minimumQuantity":"Int!","price":"MoneyInput!","variantId":"ID!"}}, +"QuantityPriceBreakSortKeys":{"e":["ID","MINIMUM_QUANTITY"]}, +"QuantityPricingByVariantUpdateInput":{"i":{"pricesToAdd":"[PriceListPriceInput!]!","pricesToDeleteByVariantId":"[ID!]!","quantityPriceBreaksToAdd":"[QuantityPriceBreakInput!]!","quantityPriceBreaksToDelete":"[ID!]!","quantityPriceBreaksToDeleteByVariantId":"[ID!]","quantityRulesToAdd":"[QuantityRuleInput!]!","quantityRulesToDeleteByVariantId":"[ID!]!"}}, +"QuantityPricingByVariantUpdatePayload":{"o":{"f":{"productVariants":"[ProductVariant!]","userErrors":"[QuantityPricingByVariantUserError!]!"}}}, +"QuantityPricingByVariantUserError":{"o":{"f":{"code":"QuantityPricingByVariantUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"QuantityPricingByVariantUserErrorCode":{"e":["BLANK","PRICE_LIST_NOT_FOUND","GENERIC_ERROR","QUANTITY_PRICE_BREAK_ADD_INVALID","QUANTITY_PRICE_BREAK_ADD_PRICE_LIST_PRICE_NOT_FOUND","QUANTITY_PRICE_BREAK_ADD_LIMIT_EXCEEDED","QUANTITY_PRICE_BREAK_ADD_CURRENCY_MISMATCH","QUANTITY_PRICE_BREAK_ADD_FAILED_TO_SAVE","QUANTITY_PRICE_BREAK_ADD_MIN_LOWER_THAN_QUANTITY_RULES_MIN","QUANTITY_PRICE_BREAK_ADD_MIN_HIGHER_THAN_QUANTITY_RULES_MAX","QUANTITY_PRICE_BREAK_ADD_MIN_NOT_A_MULTIPLE_OF_QUANTITY_RULES_INCREMENT","QUANTITY_PRICE_BREAK_ADD_VARIANT_NOT_FOUND","QUANTITY_PRICE_BREAK_ADD_DUPLICATE_INPUT_FOR_VARIANT_AND_MIN","QUANTITY_PRICE_BREAK_DELETE_NOT_FOUND","QUANTITY_PRICE_BREAK_DELETE_FAILED","QUANTITY_RULE_ADD_VARIANT_NOT_FOUND","QUANTITY_RULE_ADD_MIN_HIGHER_THAN_QUANTITY_PRICE_BREAK_MIN","QUANTITY_RULE_ADD_MAX_LOWER_THAN_QUANTITY_PRICE_BREAK_MIN","QUANTITY_RULE_ADD_INCREMENT_NOT_A_MULTIPLE_OF_QUANTITY_PRICE_BREAK_MIN","QUANTITY_RULE_ADD_CATALOG_CONTEXT_NOT_SUPPORTED","QUANTITY_RULE_ADD_INCREMENT_IS_GREATER_THAN_MINIMUM","QUANTITY_RULE_ADD_MINIMUM_NOT_A_MULTIPLE_OF_INCREMENT","QUANTITY_RULE_ADD_MAXIMUM_NOT_A_MULTIPLE_OF_INCREMENT","QUANTITY_RULE_ADD_MINIMUM_GREATER_THAN_MAXIMUM","QUANTITY_RULE_ADD_INCREMENT_IS_LESS_THAN_ONE","QUANTITY_RULE_ADD_MINIMUM_IS_LESS_THAN_ONE","QUANTITY_RULE_ADD_MAXIMUM_IS_LESS_THAN_ONE","QUANTITY_RULE_ADD_DUPLICATE_INPUT_FOR_VARIANT","QUANTITY_RULE_DELETE_RULE_NOT_FOUND","QUANTITY_RULE_DELETE_VARIANT_NOT_FOUND","PRICE_ADD_CURRENCY_MISMATCH","PRICE_ADD_VARIANT_NOT_FOUND","PRICE_ADD_DUPLICATE_INPUT_FOR_VARIANT","PRICE_ADD_LOCAL_CURRENCY_GIFT_CARD_ISSUANCE_CURRENCY_MISMATCH","PRICE_ADD_LOCAL_CURRENCY_GIFT_CARD_LIMIT_EXCEEDED","PRICE_DELETE_PRICE_NOT_FIXED","PRICE_DELETE_VARIANT_NOT_FOUND","QUANTITY_PRICE_BREAK_DELETE_BY_VARIANT_ID_VARIANT_NOT_FOUND"]}, +"QuantityRule":{"o":{"f":{"increment":"Int!","isDefault":"Boolean!","maximum":"Int","minimum":"Int!","originType":"QuantityRuleOriginType!","productVariant":"ProductVariant!"}}}, +"QuantityRuleConnection":{"o":{"f":{"edges":"[QuantityRuleEdge!]!","nodes":"[QuantityRule!]!","pageInfo":"PageInfo!"}}}, +"QuantityRuleEdge":{"o":{"f":{"cursor":"String!","node":"QuantityRule!"}}}, +"QuantityRuleInput":{"i":{"increment":"Int!","maximum":"Int=","minimum":"Int!","variantId":"ID!"}}, +"QuantityRuleOriginType":{"e":["FIXED","RELATIVE"]}, +"QuantityRuleUserError":{"o":{"f":{"code":"QuantityRuleUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"QuantityRuleUserErrorCode":{"e":["BLANK","PRODUCT_VARIANT_DOES_NOT_EXIST","PRICE_LIST_DOES_NOT_EXIST","VARIANT_QUANTITY_RULE_DOES_NOT_EXIST","MINIMUM_IS_GREATER_THAN_MAXIMUM","MINIMUM_IS_HIGHER_THAN_QUANTITY_PRICE_BREAK_MINIMUM","MAXIMUM_IS_LOWER_THAN_QUANTITY_PRICE_BREAK_MINIMUM","INCREMENT_NOT_A_MULTIPLE_OF_QUANTITY_PRICE_BREAK_MINIMUM","INCREMENT_IS_GREATER_THAN_MINIMUM","GREATER_THAN_OR_EQUAL_TO","MAXIMUM_NOT_MULTIPLE_OF_INCREMENT","MINIMUM_NOT_MULTIPLE_OF_INCREMENT","CATALOG_CONTEXT_DOES_NOT_SUPPORT_QUANTITY_RULES","DUPLICATE_INPUT_FOR_VARIANT","GENERIC_ERROR"]}, +"QuantityRulesAddPayload":{"o":{"f":{"quantityRules":"[QuantityRule!]","userErrors":"[QuantityRuleUserError!]!"}}}, +"QuantityRulesDeletePayload":{"o":{"f":{"deletedQuantityRulesVariantIds":"[ID!]","userErrors":"[QuantityRuleUserError!]!"}}}, +"QueryRoot":{"o":{"f":{"abandonedCheckouts":["AbandonedCheckoutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"AbandonedCheckoutSortKeys="}],"abandonedCheckoutsCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"abandonment":["Abandonment",{"id":"ID!"}],"abandonmentByAbandonedCheckoutId":["Abandonment",{"abandonedCheckoutId":"ID!"}],"analyticsTargets":["AnalyticsTargetConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"AnalyticsTargetSortKeys="}],"app":["App",{"id":"ID"}],"appByHandle":["App",{"handle":"String!"}],"appByKey":["App",{"apiKey":"String!"}],"appDiscountType":["AppDiscountType",{"functionId":"String!"}],"appDiscountTypes":"[AppDiscountType!]!","appDiscountTypesNodes":["AppDiscountTypeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"appInstallation":["AppInstallation",{"id":"ID"}],"appInstallations":["AppInstallationConnection!",{"after":"String","before":"String","category":"AppInstallationCategory","first":"Int","last":"Int","privacy":"AppInstallationPrivacy=","reverse":"Boolean=","sortKey":"AppInstallationSortKeys="}],"article":["Article",{"id":"ID!"}],"articleAuthors":["ArticleAuthorConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"articleTags":["[String!]!",{"limit":"Int!","sort":"ArticleTagSort="}],"articles":["ArticleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"ArticleSortKeys="}],"assignedFulfillmentOrders":["FulfillmentOrderConnection!",{"after":"String","assignmentStatus":"FulfillmentOrderAssignmentStatus","before":"String","first":"Int","last":"Int","locationIds":"[ID!]","reverse":"Boolean=","sortKey":"FulfillmentOrderSortKeys="}],"automaticDiscount":["DiscountAutomatic",{"id":"ID!"}],"automaticDiscountNode":["DiscountAutomaticNode",{"id":"ID!"}],"automaticDiscountNodes":["DiscountAutomaticNodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"AutomaticDiscountSortKeys="}],"automaticDiscountSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"automaticDiscounts":["DiscountAutomaticConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"AutomaticDiscountSortKeys="}],"availableBackupRegions":"[MarketRegion!]!","availableCarrierServices":"[DeliveryCarrierServiceAndLocations!]!","availableLocales":"[Locale!]!","backupRegion":"MarketRegion!","blog":["Blog",{"id":"ID!"}],"blogs":["BlogConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"BlogSortKeys="}],"blogsCount":["Count",{"limit":"Int=","query":"String"}],"bulkOperation":["BulkOperation",{"id":"ID!"}],"bulkOperations":["BulkOperationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"BulkOperationsSortKeys="}],"businessEntities":"[BusinessEntity!]!","businessEntity":["BusinessEntity",{"id":"ID"}],"carrierService":["DeliveryCarrierService",{"id":"ID!"}],"carrierServices":["DeliveryCarrierServiceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CarrierServiceSortKeys="}],"cartTransforms":["CartTransformConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"cashDrawer":["CashDrawer",{"id":"ID!"}],"cashDrawers":["CashDrawerConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String"}],"cashManagementLocationSummary":["CashManagementSummary!",{"endDate":"Date!","locationId":"ID!","startDate":"Date!"}],"cashManagementReasonCodes":["CashManagementReasonCodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"cashManagementShopSummary":["CashManagementSummary!",{"currencyCode":"CurrencyCode!","endDate":"Date!","startDate":"Date!"}],"cashTrackingSession":["CashTrackingSession",{"id":"ID!"}],"cashTrackingSessions":["CashTrackingSessionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CashTrackingSessionsSortKeys="}],"catalog":["Catalog",{"id":"ID!"}],"catalogOperations":"[ResourceOperation!]!","catalogs":["CatalogConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CatalogSortKeys=","type":"CatalogType="}],"catalogsCount":["Count",{"limit":"Int=","query":"String","type":"CatalogType="}],"channel":["Channel",{"id":"ID!"}],"channelByHandle":["Channel",{"handle":"String!"}],"channels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"checkoutAndAccountsConfiguration":["CheckoutAndAccountsConfiguration",{"id":"ID!"}],"checkoutAndAccountsConfigurations":["CheckoutAndAccountsConfigurationConnection",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CheckoutAndAccountsConfigurationsGraphQLSortKeys="}],"checkoutBranding":["CheckoutBranding",{"checkoutProfileId":"ID!"}],"checkoutProfile":["CheckoutProfile",{"id":"ID!"}],"checkoutProfiles":["CheckoutProfileConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CheckoutProfileSortKeys="}],"codeDiscountNode":["DiscountCodeNode",{"id":"ID!"}],"codeDiscountNodeByCode":["DiscountCodeNode",{"code":"String!"}],"codeDiscountNodes":["DiscountCodeNodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"CodeDiscountSortKeys="}],"codeDiscountSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collection":["Collection",{"id":"ID!"}],"collectionByHandle":["Collection",{"handle":"String!"}],"collectionByIdentifier":["Collection",{"identifier":"CollectionIdentifierInput!"}],"collectionConditionMetafieldDefinitions":"[CollectionConditionMetafieldDefinitionInterface!]!","collectionConditionsSources":["CollectionConditionsSourceConnection!",{"after":"String","appId":"ID!","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collectionConditionsSourcesByApp":["CollectionConditionsSourcesByAppConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collectionRulesConditions":"[CollectionRuleConditions!]!","collectionSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"collections":["CollectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"CollectionSortKeys="}],"collectionsCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"comment":["Comment",{"id":"ID!"}],"comments":["CommentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CommentSortKeys="}],"companies":["CompanyConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanySortKeys="}],"companiesCount":["Count",{"limit":"Int="}],"company":["Company",{"id":"ID!"}],"companyContact":["CompanyContact",{"id":"ID!"}],"companyContactRole":["CompanyContactRole",{"id":"ID!"}],"companyLocation":["CompanyLocation",{"id":"ID!"}],"companyLocations":["CompanyLocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CompanyLocationSortKeys="}],"consentPolicy":["[ConsentPolicy!]!",{"consentRequired":"Boolean","countryCode":"PrivacyCountryCode","dataSaleOptOutRequired":"Boolean","id":"ID","regionCode":"String"}],"consentPolicyRegions":"[ConsentPolicyRegion!]!","currentAppInstallation":"AppInstallation!","currentBulkOperation":["BulkOperation",{"type":"BulkOperationType="}],"currentStaffMember":"StaffMember","customer":["Customer",{"id":"ID!"}],"customerAccountPage":["CustomerAccountPage",{"id":"ID!"}],"customerAccountPages":["CustomerAccountPageConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"customerByIdentifier":["Customer",{"identifier":"CustomerIdentifierInput!"}],"customerMergeJobStatus":["CustomerMergeRequest",{"jobId":"ID!"}],"customerMergePreview":["CustomerMergePreview!",{"customerOneId":"ID!","customerTwoId":"ID!","overrideFields":"CustomerMergeOverrideFields"}],"customerPaymentMethod":["CustomerPaymentMethod",{"id":"ID!","showRevoked":"Boolean="}],"customerSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CustomerSavedSearchSortKeys="}],"customerSegmentMembers":["CustomerSegmentMemberConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","queryId":"ID","reverse":"Boolean=","segmentId":"ID","sortKey":"String","timezone":"String"}],"customerSegmentMembersQuery":["CustomerSegmentMembersQuery",{"id":"ID!"}],"customerSegmentMembership":["SegmentMembershipResponse!",{"customerId":"ID!","segmentIds":"[ID!]!"}],"customers":["CustomerConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CustomerSortKeys="}],"customersCount":["Count",{"limit":"Int=","query":"String"}],"deletionEvents":["DeletionEventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"DeletionEventSortKeys=","subjectTypes":"[DeletionEventSubjectType!]"}],"deliveryCustomization":["DeliveryCustomization",{"id":"ID!"}],"deliveryCustomizations":["DeliveryCustomizationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"deliveryProfile":["DeliveryProfile",{"id":"ID!"}],"deliveryProfiles":["DeliveryProfileConnection!",{"after":"String","before":"String","first":"Int","last":"Int","merchantOwnedOnly":"Boolean","reverse":"Boolean="}],"deliveryPromiseParticipants":["DeliveryPromiseParticipantConnection",{"after":"String","before":"String","brandedPromiseHandle":"String!","first":"Int","last":"Int","ownerIds":"[ID!]","reverse":"Boolean="}],"deliveryPromiseProvider":["DeliveryPromiseProvider",{"locationId":"ID!"}],"deliveryPromiseSettings":"DeliveryPromiseSetting!","discountCodesCount":["Count",{"limit":"Int=","query":"String"}],"discountNode":["DiscountNode",{"id":"ID!"}],"discountNodes":["DiscountNodeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"DiscountSortKeys="}],"discountNodesCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"discountRedeemCodeBulkCreation":["DiscountRedeemCodeBulkCreation",{"id":"ID!"}],"discountRedeemCodeSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"DiscountCodeSortKeys="}],"discountTags":["StringConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"DiscountTagSortKeys="}],"dispute":["ShopifyPaymentsDispute",{"id":"ID!"}],"disputeEvidence":["ShopifyPaymentsDisputeEvidence",{"id":"ID!"}],"disputes":["ShopifyPaymentsDisputeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"domain":["Domain",{"id":"ID!"}],"draftOrder":["DraftOrder",{"id":"ID!"}],"draftOrderAvailableDeliveryOptions":["DraftOrderAvailableDeliveryOptions!",{"input":"DraftOrderAvailableDeliveryOptionsInput!","localPickupCount":"Int","localPickupFrom":"Int","search":"String","sessionToken":"String"}],"draftOrderSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"draftOrderTag":["DraftOrderTag",{"id":"ID!"}],"draftOrders":["DraftOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"DraftOrderSortKeys="}],"draftOrdersCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"event":["Event",{"id":"ID!"}],"events":["EventConnection",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"EventSortKeys="}],"eventsCount":["Count",{"query":"String"}],"fileSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"files":["FileConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"FileSortKeys="}],"financeAppAccessPolicy":"FinanceAppAccessPolicy!","financeKycInformation":"FinanceKycInformation","fulfillment":["Fulfillment",{"id":"ID!"}],"fulfillmentConstraintRules":"[FulfillmentConstraintRule!]!","fulfillmentOrder":["FulfillmentOrder",{"id":"ID!"}],"fulfillmentOrders":["FulfillmentOrderConnection!",{"after":"String","before":"String","first":"Int","includeClosed":"Boolean=","last":"Int","query":"String","reverse":"Boolean=","sortKey":"FulfillmentOrderSortKeys="}],"fulfillmentService":["FulfillmentService",{"id":"ID!"}],"giftCard":["GiftCard",{"id":"ID!"}],"giftCardConfiguration":"GiftCardConfiguration!","giftCards":["GiftCardConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"GiftCardSortKeys="}],"giftCardsCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"inventoryItem":["InventoryItem",{"id":"ID!"}],"inventoryItems":["InventoryItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"inventoryLevel":["InventoryLevel",{"id":"ID!"}],"inventoryProperties":"InventoryProperties!","inventoryPurchaseOrder":["InventoryPurchaseOrder",{"id":"ID!"}],"inventoryPurchaseOrders":["InventoryPurchaseOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String"}],"inventoryShipment":["InventoryShipment",{"id":"ID!"}],"inventoryShipments":["InventoryShipmentConnection",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","sortKey":"InventoryShipmentSortKeys="}],"inventoryTransfer":["InventoryTransfer",{"id":"ID!"}],"inventoryTransfers":["InventoryTransferConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"TransferSortKeys="}],"job":["Job",{"id":"ID!"}],"location":["Location",{"id":"ID"}],"locationByIdentifier":["Location",{"identifier":"LocationIdentifierInput!"}],"locations":["LocationConnection!",{"after":"String","before":"String","first":"Int","includeInactive":"Boolean=","includeLegacy":"Boolean=","last":"Int","query":"String","reverse":"Boolean=","sortKey":"LocationSortKeys="}],"locationsAvailableForDeliveryProfiles":"[Location!]","locationsAvailableForDeliveryProfilesConnection":["LocationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"locationsCount":["Count",{"limit":"Int=","query":"String"}],"manualHoldsFulfillmentOrders":["FulfillmentOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"market":["Market",{"id":"ID!"}],"marketByGeography":["Market",{"countryCode":"CountryCode!"}],"marketLocalizableResource":["MarketLocalizableResource",{"resourceId":"ID!"}],"marketLocalizableResources":["MarketLocalizableResourceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","resourceType":"MarketLocalizableResourceType!","reverse":"Boolean="}],"marketLocalizableResourcesByIds":["MarketLocalizableResourceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","resourceIds":"[ID!]!","reverse":"Boolean="}],"marketRelationships":["MarketRelationshipConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"marketRelationshipsStatus":"MarketRelationshipsStatus!","marketingActivities":["MarketingActivityConnection!",{"after":"String","before":"String","first":"Int","last":"Int","marketingActivityIds":"[ID!]=","query":"String","remoteIds":"[String!]=","reverse":"Boolean=","savedSearchId":"ID","sortKey":"MarketingActivitySortKeys=","utm":"UTMInput"}],"marketingActivity":["MarketingActivity",{"id":"ID!"}],"marketingEvent":["MarketingEvent",{"id":"ID!"}],"marketingEvents":["MarketingEventConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"MarketingEventSortKeys="}],"markets":["MarketConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"MarketsSortKeys=","type":"MarketType="}],"marketsResolvedValues":["MarketsResolvedValues!",{"buyerSignal":"BuyerSignalInput!"}],"menu":["Menu",{"id":"ID!"}],"menus":["MenuConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"MenuSortKeys="}],"metafieldDefinition":["MetafieldDefinition",{"id":"ID","identifier":"MetafieldDefinitionIdentifierInput"}],"metafieldDefinitionTypes":"[MetafieldDefinitionType!]!","metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","constraintStatus":"MetafieldDefinitionConstraintStatus","constraintSubtype":"MetafieldDefinitionConstraintSubtypeIdentifier","first":"Int","key":"String","last":"Int","namespace":"String","ownerType":"MetafieldOwnerType!","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metaobject":["Metaobject",{"id":"ID!"}],"metaobjectByHandle":["Metaobject",{"handle":"MetaobjectHandleInput!"}],"metaobjectDefinition":["MetaobjectDefinition",{"id":"ID!"}],"metaobjectDefinitionByType":["MetaobjectDefinition",{"type":"String!"}],"metaobjectDefinitions":["MetaobjectDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"metaobjects":["MetaobjectConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"String","type":"String!"}],"mobilePlatformApplication":["MobilePlatformApplication",{"id":"ID!"}],"mobilePlatformApplications":["MobilePlatformApplicationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"node":["Node",{"id":"ID!"}],"nodes":["[Node]!",{"ids":"[ID!]!"}],"onlineStore":"OnlineStore!","order":["Order",{"id":"ID!"}],"orderAttributionDefinitions":["OrderAttributionDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"orderByIdentifier":["Order",{"identifier":"OrderIdentifierInput!"}],"orderEditSession":["OrderEditSession",{"id":"ID!"}],"orderPaymentStatus":["OrderPaymentStatus",{"orderId":"ID!","paymentReferenceId":"String!"}],"orderSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"OrderSortKeys="}],"ordersCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"page":["Page",{"id":"ID!"}],"pages":["PageConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"PageSortKeys="}],"pagesCount":["Count",{"limit":"Int="}],"paymentCustomization":["PaymentCustomization",{"id":"ID!"}],"paymentCustomizations":["PaymentCustomizationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"paymentTermsTemplates":["[PaymentTermsTemplate!]!",{"paymentTermsType":"PaymentTermsType"}],"pendingOrdersCount":"Count","pointOfSaleDevice":["PointOfSaleDevice",{"id":"ID!"}],"pointOfSaleDevicePaymentSession":["PointOfSaleDevicePaymentSession",{"id":"ID!"}],"pointOfSaleDevicePaymentSessions":["PointOfSaleDevicePaymentSessionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"PointOfSaleDevicePaymentSessionSortKeys="}],"priceList":["PriceList",{"id":"ID!"}],"priceLists":["PriceListConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"PriceListSortKeys="}],"primaryMarket":"Market!","privacySettings":"PrivacySettings!","product":["Product",{"id":"ID!"}],"productByHandle":["Product",{"handle":"String!"}],"productByIdentifier":["Product",{"identifier":"ProductIdentifierInput!"}],"productDuplicateJob":["ProductDuplicateJob!",{"id":"ID!"}],"productFeed":["ProductFeed",{"id":"ID!"}],"productFeeds":["ProductFeedConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productOperation":["ProductOperation",{"id":"ID!"}],"productResourceFeedback":["ProductResourceFeedback",{"channelId":"ID","id":"ID!"}],"productSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productTags":["StringConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productTypes":["StringConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productVariant":["ProductVariant",{"id":"ID!"}],"productVariantByIdentifier":["ProductVariant",{"identifier":"ProductVariantIdentifierInput!"}],"productVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"ProductVariantSortKeys="}],"productVariantsCount":["Count",{"limit":"Int=","query":"String"}],"productVendors":["StringConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"ProductSortKeys="}],"productsCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"publicApiVersions":"[ApiVersion!]!","publication":["Publication",{"id":"ID!"}],"publications":["PublicationConnection!",{"after":"String","before":"String","catalogType":"CatalogType","first":"Int","last":"Int","reverse":"Boolean="}],"publicationsCount":["Count",{"catalogType":"CatalogType","limit":"Int="}],"publishedProductsCount":["Count",{"limit":"Int=","publicationId":"ID!"}],"refund":["Refund",{"id":"ID!"}],"requestedOrderEditCalculate":["CalculatedRequestedOrderEdit",{"input":"CalculateRequestedOrderEditInput!"}],"return":["Return",{"id":"ID!"}],"returnCalculate":["CalculatedReturn",{"input":"CalculateReturnInput!"}],"returnPolicyProfile":["ReturnPolicyProfile",{"id":"ID!"}],"returnPolicyProfiles":["ReturnPolicyProfileConnection!",{"after":"String","before":"String","default":"Boolean","first":"Int","last":"Int","reverse":"Boolean="}],"returnReasonDefinitions":["ReturnReasonDefinitionConnection!",{"after":"String","before":"String","first":"Int","handles":"[String!]","ids":"[ID!]","last":"Int","query":"String","reverse":"Boolean=","sortKey":"ReturnReasonDefinitionSortKeys="}],"returnableFulfillment":["ReturnableFulfillment",{"id":"ID!"}],"returnableFulfillments":["ReturnableFulfillmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","orderId":"ID!","reverse":"Boolean="}],"reverseDelivery":["ReverseDelivery",{"id":"ID!"}],"reverseFulfillmentOrder":["ReverseFulfillmentOrder",{"id":"ID!"}],"rollout":["Rollout",{"id":"ID!"}],"rollouts":["RolloutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"RolloutSortKeys="}],"scriptTag":["ScriptTag",{"id":"ID!"}],"scriptTags":["ScriptTagConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","src":"URL"}],"segment":["Segment",{"id":"ID!"}],"segmentFilterSuggestions":["SegmentFilterConnection!",{"after":"String","first":"Int!","search":"String!"}],"segmentFilters":["SegmentFilterConnection!",{"after":"String","before":"String","first":"Int","last":"Int"}],"segmentMigrations":["SegmentMigrationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","savedSearchId":"ID"}],"segmentValueSuggestions":["SegmentValueConnection!",{"after":"String","before":"String","filterQueryName":"String","first":"Int","functionParameterQueryName":"String","last":"Int","search":"String!"}],"segments":["SegmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"SegmentSortKeys="}],"segmentsCount":["Count",{"limit":"Int="}],"sellingPlanGroup":["SellingPlanGroup",{"id":"ID!"}],"sellingPlanGroups":["SellingPlanGroupConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"SellingPlanGroupSortKeys="}],"serverPixel":"ServerPixel","shippingLabel":["ShippingLabel",{"id":"ID!"}],"shop":"Shop!","shopBillingPreferences":"ShopBillingPreferences!","shopLocales":["[ShopLocale!]!",{"published":"Boolean="}],"shopPayPaymentRequestReceipt":["ShopPayPaymentRequestReceipt",{"token":"String!"}],"shopPayPaymentRequestReceipts":["ShopPayPaymentRequestReceiptConnection",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"ShopPayPaymentRequestReceiptsSortKeys="}],"shopifyFunction":["ShopifyFunction",{"id":"String!"}],"shopifyFunctions":["ShopifyFunctionConnection!",{"after":"String","apiType":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","useCreationUi":"Boolean"}],"shopifyPaymentsAccount":"ShopifyPaymentsAccount","shopifyqlQuery":["ShopifyqlQueryResponse",{"query":"String!"}],"staffMember":["StaffMember",{"id":"ID"}],"staffMembers":["StaffMemberConnection",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"StaffMembersSortKeys="}],"standardMetafieldDefinitionTemplates":["StandardMetafieldDefinitionTemplateConnection!",{"after":"String","before":"String","constraintStatus":"MetafieldDefinitionConstraintStatus","constraintSubtype":"MetafieldDefinitionConstraintSubtypeIdentifier","excludeActivated":"Boolean=","first":"Int","last":"Int","reverse":"Boolean="}],"storeCreditAccount":["StoreCreditAccount",{"id":"ID!"}],"storeCreditConfiguration":"StoreCreditConfiguration!","subscriptionBillingAttempt":["SubscriptionBillingAttempt",{"id":"ID!"}],"subscriptionBillingAttempts":["SubscriptionBillingAttemptConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"SubscriptionBillingAttemptsSortKeys="}],"subscriptionBillingCycle":["SubscriptionBillingCycle",{"billingCycleInput":"SubscriptionBillingCycleInput!"}],"subscriptionBillingCycleBulkResults":["SubscriptionBillingCycleConnection!",{"after":"String","before":"String","first":"Int","jobId":"ID!","last":"Int","reverse":"Boolean="}],"subscriptionBillingCycles":["SubscriptionBillingCycleConnection!",{"after":"String","before":"String","billingCyclesDateRangeSelector":"SubscriptionBillingCyclesDateRangeSelector","billingCyclesIndexRangeSelector":"SubscriptionBillingCyclesIndexRangeSelector","contractId":"ID!","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"SubscriptionBillingCyclesSortKeys="}],"subscriptionContract":["SubscriptionContract",{"id":"ID!"}],"subscriptionContractCalculation":["SubscriptionContractCalculation",{"id":"ID!"}],"subscriptionContracts":["SubscriptionContractConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"SubscriptionContractsSortKeys="}],"subscriptionDraft":["SubscriptionDraft",{"id":"ID!"}],"taxonomy":"Taxonomy","tenderTransactions":["TenderTransactionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"theme":["OnlineStoreTheme",{"id":"ID!"}],"themes":["OnlineStoreThemeConnection",{"after":"String","before":"String","first":"Int","last":"Int","names":"[String!]","reverse":"Boolean=","roles":"[ThemeRole!]"}],"translatableResource":["TranslatableResource",{"resourceId":"ID!"}],"translatableResources":["TranslatableResourceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","resourceType":"TranslatableResourceType!","reverse":"Boolean="}],"translatableResourcesByIds":["TranslatableResourceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","resourceIds":"[ID!]!","reverse":"Boolean="}],"urlRedirect":["UrlRedirect",{"id":"ID!"}],"urlRedirectImport":["UrlRedirectImport",{"id":"ID!"}],"urlRedirectSavedSearches":["SavedSearchConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"urlRedirects":["UrlRedirectConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"UrlRedirectSortKeys="}],"urlRedirectsCount":["Count",{"limit":"Int=","query":"String","savedSearchId":"ID"}],"validation":["Validation",{"id":"ID!"}],"validations":["ValidationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"ValidationSortKeys="}],"webPixel":["WebPixel",{"id":"ID"}],"webPresences":["MarketWebPresenceConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"webhookSubscription":["WebhookSubscription",{"id":"ID!"}],"webhookSubscriptions":["WebhookSubscriptionConnection!",{"after":"String","before":"String","callbackUrl":"URL","first":"Int","format":"WebhookSubscriptionFormat","last":"Int","query":"String","reverse":"Boolean=","sortKey":"WebhookSubscriptionSortKeys=","topics":"[WebhookSubscriptionTopic!]","uri":"String"}],"webhookSubscriptionsCount":["Count",{"limit":"Int=","query":"String"}]},"d":{"automaticDiscount":"Use `automaticDiscountNode` instead.","automaticDiscountNode":"Use `discountNode` instead.","automaticDiscountNodes":"Use `discountNodes` instead.","automaticDiscounts":"Use `automaticDiscountNodes` instead. This will be removed in 2027-01.","checkoutBranding":"Use `checkoutAndAccountsConfiguration` instead.","checkoutProfile":"Use `checkoutAndAccountsConfiguration` instead.","checkoutProfiles":"Use `checkoutAndAccountsConfigurations` instead.","codeDiscountNode":"Use `discountNode` instead.","codeDiscountNodes":"Use `discountNodes` instead.","collectionByHandle":"Use `collectionByIdentifier` instead.","collectionRulesConditions":"Use `CollectionSourceInclusionCondition*` and `CollectionSourceExclusionCondition*` types instead.","currentBulkOperation":"Use `bulkOperations` with status filter instead.","customerSavedSearches":"Use `segments` instead.","deletionEvents":"Use `events` instead.","locationsAvailableForDeliveryProfiles":"Use `locationsAvailableForDeliveryProfilesConnection` instead.","marketByGeography":"This `market_by_geography` field will be removed in a future version of the API.","metafieldDefinition(id)":"This field will be removed in a future version. Use the identifier input instead.","primaryMarket":"Use `backupRegion` instead.","productByHandle":"Use `productByIdentifier` instead.","segmentMigrations":"Use the migrated segment ID and query `segment` directly.","subscriptionDraft":"Use the [SubscriptionContractCalculation API](https://shopify.dev/docs/apps/build/purchase-options/subscriptions/contracts/migrate-to-subscription-calculation-api) instead.","webhookSubscriptions(callbackUrl)":"Use `uri` instead."}}}, +"Refund":{"o":{"f":{"createdAt":"DateTime","duties":"[RefundDuty!]","id":"ID!","legacyResourceId":"UnsignedInt64!","note":"String","order":"Order!","orderAdjustments":["OrderAdjustmentConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"processedAt":"DateTime!","refundLineItems":["RefundLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"refundShippingLines":["RefundShippingLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"return":"Return","staffMember":"StaffMember","totalRefunded":"MoneyV2!","totalRefundedSet":"MoneyBag!","transactions":["OrderTransactionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"updatedAt":"DateTime!"},"t":["LegacyInteroperability","Node"],"d":{"totalRefunded":"Use `totalRefundedSet` instead."}}}, +"RefundAgreement":{"o":{"f":{"app":"App","happenedAt":"DateTime!","id":"ID!","reason":"OrderActionType!","refund":"Refund!","sales":["SaleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"user":"StaffMember"},"t":["SalesAgreement"]}}, +"RefundConnection":{"o":{"f":{"edges":"[RefundEdge!]!","nodes":"[Refund!]!","pageInfo":"PageInfo!"}}}, +"RefundCreatePayload":{"o":{"f":{"order":"Order","refund":"Refund","userErrors":"[UserError!]!"}}}, +"RefundDuty":{"o":{"f":{"amountSet":"MoneyBag!","originalDuty":"Duty"}}}, +"RefundDutyInput":{"i":{"dutyId":"ID!","refundType":"RefundDutyRefundType"}}, +"RefundDutyRefundType":{"e":["PROPORTIONAL","FULL"]}, +"RefundEdge":{"o":{"f":{"cursor":"String!","node":"Refund!"}}}, +"RefundInput":{"i":{"allowOverRefunding":"Boolean=","currency":"CurrencyCode","discrepancyReason":"OrderAdjustmentInputDiscrepancyReason","note":"String","notify":"Boolean","orderId":"ID!","processedAt":"DateTime","refundDuties":"[RefundDutyInput!]","refundLineItems":"[RefundLineItemInput!]","refundMethods":"[RefundMethodInput!]=","shipping":"ShippingRefundInput","transactions":"[OrderTransactionInput!]"}}, +"RefundLineItem":{"o":{"f":{"id":"ID","lineItem":"LineItem!","location":"Location","price":"Money!","priceSet":"MoneyBag!","quantity":"Int!","restockType":"RefundLineItemRestockType!","restocked":"Boolean!","subtotal":"Money!","subtotalSet":"MoneyBag!","totalTax":"Money!","totalTaxSet":"MoneyBag!"},"d":{"price":"Use `priceSet` instead.","subtotal":"Use `subtotalSet` instead.","totalTax":"Use `totalTaxSet` instead."}}}, +"RefundLineItemConnection":{"o":{"f":{"edges":"[RefundLineItemEdge!]!","nodes":"[RefundLineItem!]!","pageInfo":"PageInfo!"}}}, +"RefundLineItemEdge":{"o":{"f":{"cursor":"String!","node":"RefundLineItem!"}}}, +"RefundLineItemInput":{"i":{"lineItemId":"ID!","locationId":"ID","quantity":"Int!","restockType":"RefundLineItemRestockType"}}, +"RefundLineItemRestockType":{"e":["RETURN","CANCEL","LEGACY_RESTOCK","NO_RESTOCK"]}, +"RefundMethodAllocation":{"e":["ORIGINAL_PAYMENT_METHODS","STORE_CREDIT"]}, +"RefundMethodInput":{"i":{"f":{"storeCreditRefund":"StoreCreditRefundInput"},"o":true}}, +"RefundReturnOutcome":{"o":{"f":{"amount":"MoneyBag!","suggestedRefundMethods":"[SuggestedRefundMethod!]!","suggestedTransactions":"[SuggestedOrderTransaction!]!"}}}, +"RefundShippingInput":{"i":{"fullRefund":"Boolean=","shippingRefundAmount":"MoneyInput"}}, +"RefundShippingLine":{"o":{"f":{"id":"ID!","shippingLine":"ShippingLine!","subtotalAmountSet":"MoneyBag!","taxAmountSet":"MoneyBag!"},"t":["Node"]}}, +"RefundShippingLineConnection":{"o":{"f":{"edges":"[RefundShippingLineEdge!]!","nodes":"[RefundShippingLine!]!","pageInfo":"PageInfo!"}}}, +"RefundShippingLineEdge":{"o":{"f":{"cursor":"String!","node":"RefundShippingLine!"}}}, +"RegionsCondition":{"o":{"f":{"applicationLevel":"MarketConditionApplicationType","regions":["MarketRegionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"RemoteAuthorizeNetCustomerPaymentProfileInput":{"i":{"customerPaymentProfileId":"String!","customerProfileId":"String!"}}, +"RemoteBraintreePaymentMethodInput":{"i":{"customerId":"String!","paymentMethodToken":"String!"}}, +"RemoteStripePaymentMethodInput":{"i":{"customerId":"String!","paymentMethodId":"String!"}}, +"RemoveFromReturnPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"RequestedOrderEdit":{"o":{"f":{"createdAt":"DateTime!","id":"ID!","lineItems":"RequestedOrderEditLineItems!","order":"Order!","requestDeclinedAt":"DateTime","requestResolvedAt":"DateTime","requestedAt":"DateTime!","status":"RequestedOrderEditStatus!","updatedAt":"DateTime!"},"t":["Node"]}}, +"RequestedOrderEditConnection":{"o":{"f":{"edges":"[RequestedOrderEditEdge!]!","nodes":"[RequestedOrderEdit!]!","pageInfo":"PageInfo!"}}}, +"RequestedOrderEditCreateInput":{"i":{"lineItems":"RequestedOrderEditLineItemsInput!","orderId":"ID!"}}, +"RequestedOrderEditCreatePayload":{"o":{"f":{"requestedOrderEdit":"RequestedOrderEdit","userErrors":"[RequestedOrderEditCreateUserError!]!"}}}, +"RequestedOrderEditCreateUserError":{"o":{"f":{"code":"RequestedOrderEditCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"RequestedOrderEditCreateUserErrorCode":{"e":["NOT_FOUND","INVALID","INTERNAL_ERROR","BLANK"]}, +"RequestedOrderEditDeclineInput":{"i":{"declineNote":"String","id":"ID!"}}, +"RequestedOrderEditDeclinePayload":{"o":{"f":{"requestedOrderEdit":"RequestedOrderEdit","userErrors":"[RequestedOrderEditDeclineUserError!]!"}}}, +"RequestedOrderEditDeclineUserError":{"o":{"f":{"code":"RequestedOrderEditDeclineUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"RequestedOrderEditDeclineUserErrorCode":{"e":["NOT_FOUND","INVALID"]}, +"RequestedOrderEditEdge":{"o":{"f":{"cursor":"String!","node":"RequestedOrderEdit!"}}}, +"RequestedOrderEditFinancialSummary":{"o":{"f":{"editOrderLevelDiscountSubtotalSet":"MoneyBag!","editSubtotalBeforeTargetAllDiscountsSet":"MoneyBag!","editSubtotalSet":"MoneyBag!","editSubtotalWithCartDiscountSet":"MoneyBag!","editTotalSet":"MoneyBag!","editTotalTaxSet":"MoneyBag!"}}}, +"RequestedOrderEditLineItem":{"o":{"f":{"id":"ID!","lineItem":"LineItem!","quantity":"Int!","resolvedQuantity":"Int!"},"t":["Node"]}}, +"RequestedOrderEditLineItemConnection":{"o":{"f":{"edges":"[RequestedOrderEditLineItemEdge!]!","nodes":"[RequestedOrderEditLineItem!]!","pageInfo":"PageInfo!"}}}, +"RequestedOrderEditLineItemEdge":{"o":{"f":{"cursor":"String!","node":"RequestedOrderEditLineItem!"}}}, +"RequestedOrderEditLineItemRemovalInput":{"i":{"lineItemId":"ID!","quantity":"Int!"}}, +"RequestedOrderEditLineItems":{"o":{"f":{"removals":["RequestedOrderEditLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int"}]}}}, +"RequestedOrderEditLineItemsInput":{"i":{"removals":"[RequestedOrderEditLineItemRemovalInput!]!"}}, +"RequestedOrderEditResolveInput":{"i":{"id":"ID!"}}, +"RequestedOrderEditResolvePayload":{"o":{"f":{"requestedOrderEdit":"RequestedOrderEdit","userErrors":"[RequestedOrderEditResolveUserError!]!"}}}, +"RequestedOrderEditResolveUserError":{"o":{"f":{"code":"RequestedOrderEditResolveUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"RequestedOrderEditResolveUserErrorCode":{"e":["NOT_FOUND","INVALID"]}, +"RequestedOrderEditStatus":{"e":["REQUESTED","RESOLVED","DECLINED"]}, +"ResolvedPriceInclusivity":{"o":{"f":{"dutiesIncluded":"Boolean!","taxesIncluded":"Boolean!"}}}, +"ResourceAlert":{"o":{"f":{"actions":"[ResourceAlertAction!]!","content":"HTML!","dismissibleHandle":"String","icon":"ResourceAlertIcon","severity":"ResourceAlertSeverity!","title":"String!"}}}, +"ResourceAlertAction":{"o":{"f":{"primary":"Boolean!","show":"String","title":"String!","url":"URL!"}}}, +"ResourceAlertIcon":{"e":["CHECKMARK_CIRCLE","INFORMATION_CIRCLE"]}, +"ResourceAlertSeverity":{"e":{"v":["DEFAULT","INFO","WARNING","SUCCESS","CRITICAL","ERROR"],"d":{"ERROR":"`ERROR` severity is being deprecated in favour of `WARNING` or `CRITICAL` instead."}}}, +"ResourceFeedback":{"o":{"f":{"appFeedback":"[AppFeedback!]!","details":"[AppFeedback!]!","summary":"String!"},"d":{"appFeedback":"Use `details` instead."}}}, +"ResourceFeedbackCreateInput":{"i":{"channelId":"ID","feedbackGeneratedAt":"DateTime!","messages":"[String!]","state":"ResourceFeedbackState!"}}, +"ResourceFeedbackState":{"e":["ACCEPTED","REQUIRES_ACTION"]}, +"ResourceOperation":{"n":{"f":{"id":"ID!","processedRowCount":"Int","rowCount":"RowCount","status":"ResourceOperationStatus!"},"t":["AddAllProductsOperation","CatalogCsvOperation","PublicationResourceOperation"]}}, +"ResourceOperationStatus":{"e":["CREATED","ACTIVE","COMPLETE"]}, +"ResourcePublication":{"o":{"f":{"channel":"Channel!","isPublished":"Boolean!","publication":"Publication!","publishDate":"DateTime!","publishable":"Publishable!"},"d":{"channel":"Use `publication` instead."}}}, +"ResourcePublicationConnection":{"o":{"f":{"edges":"[ResourcePublicationEdge!]!","nodes":"[ResourcePublication!]!","pageInfo":"PageInfo!"}}}, +"ResourcePublicationEdge":{"o":{"f":{"cursor":"String!","node":"ResourcePublication!"}}}, +"ResourcePublicationV2":{"o":{"f":{"isPublished":"Boolean!","publication":"Publication!","publishDate":"DateTime","publishable":"Publishable!"}}}, +"ResourcePublicationV2Connection":{"o":{"f":{"edges":"[ResourcePublicationV2Edge!]!","nodes":"[ResourcePublicationV2!]!","pageInfo":"PageInfo!"}}}, +"ResourcePublicationV2Edge":{"o":{"f":{"cursor":"String!","node":"ResourcePublicationV2!"}}}, +"RestockingFee":{"o":{"f":{"amountSet":"MoneyBag!","id":"ID!","percentage":"Float!"},"t":["Fee"]}}, +"RestockingFeeInput":{"i":{"percentage":"Float!"}}, +"RestrictedForResource":{"o":{"f":{"restricted":"Boolean!","restrictedReason":"String!"}}}, +"Return":{"o":{"f":{"closedAt":"DateTime","createdAt":"DateTime!","decline":"ReturnDecline","exchangeLineItems":["ExchangeLineItemConnection!",{"after":"String","before":"String","first":"Int","includeRemovedItems":"Boolean=","last":"Int","processingStatus":"ReturnProcessingStatusFilterInput","reverse":"Boolean="}],"id":"ID!","name":"String!","order":"Order!","refunds":["RefundConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"requestApprovedAt":"DateTime","returnLineItems":["ReturnLineItemTypeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","processingStatus":"ReturnProcessingStatusFilterInput","reverse":"Boolean="}],"returnShippingFees":"[ReturnShippingFee!]!","reverseFulfillmentOrders":["ReverseFulfillmentOrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"staffMember":"StaffMember","status":"ReturnStatus!","suggestedFinancialOutcome":["SuggestedReturnFinancialOutcome",{"exchangeLineItems":"[SuggestedOutcomeExchangeLineItemInput!]!","refundDuties":"[RefundDutyInput!]","refundMethodAllocation":"RefundMethodAllocation=","refundShipping":"RefundShippingInput","returnLineItems":"[SuggestedOutcomeReturnLineItemInput!]!","tipLineId":"ID"}],"suggestedRefund":["SuggestedReturnRefund",{"refundDuties":"[RefundDutyInput!]","refundShipping":"RefundShippingInput","returnRefundLineItems":"[ReturnRefundLineItemInput!]!"}],"totalQuantity":"Int!","transactions":["OrderTransactionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["Node"],"d":{"suggestedRefund":"Use `suggestedFinancialOutcome` instead."}}}, +"ReturnAgreement":{"o":{"f":{"app":"App","happenedAt":"DateTime!","id":"ID!","reason":"OrderActionType!","return":"Return!","sales":["SaleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"user":"StaffMember"},"t":["SalesAgreement"]}}, +"ReturnApproveRequestInput":{"i":{"f":{"id":"ID!","notifyCustomer":"Boolean=","unprocessed":"Boolean="},"d":{"unprocessed":"This field is temporary to support the transition to Returns Processing APIs."}}}, +"ReturnApproveRequestPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnCancelPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnClosePayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnConnection":{"o":{"f":{"edges":"[ReturnEdge!]!","nodes":"[Return!]!","pageInfo":"PageInfo!"}}}, +"ReturnCreatePayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnDecline":{"o":{"f":{"note":"String","reason":"ReturnDeclineReason!"}}}, +"ReturnDeclineReason":{"e":["RETURN_PERIOD_ENDED","FINAL_SALE","OTHER"]}, +"ReturnDeclineRequestInput":{"i":{"declineNote":"String","declineReason":"ReturnDeclineReason!","id":"ID!","notifyCustomer":"Boolean="}}, +"ReturnDeclineRequestPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnEdge":{"o":{"f":{"cursor":"String!","node":"Return!"}}}, +"ReturnErrorCode":{"e":["INTERNAL_ERROR","TOO_MANY_ARGUMENTS","BLANK","EQUAL_TO","GREATER_THAN","GREATER_THAN_OR_EQUAL_TO","INCLUSION","INVALID","LESS_THAN","LESS_THAN_OR_EQUAL_TO","NOT_A_NUMBER","PRESENT","TAKEN","TOO_BIG","TOO_LONG","TOO_SHORT","WRONG_LENGTH","ALREADY_EXISTS","CREATION_FAILED","FEATURE_NOT_ENABLED","INCOMPATIBLE_WITH_STANDARD_POLICY","INVALID_STATE","MISSING_PERMISSION","NOTIFICATION_FAILED","NOT_EDITABLE","NOT_FOUND"]}, +"ReturnInput":{"i":{"f":{"exchangeLineItems":"[ExchangeLineItemInput!]","notifyCustomer":"Boolean=","orderId":"ID!","requestedAt":"DateTime","returnLineItems":"[ReturnLineItemInput!]!","returnShippingFee":"ReturnShippingFeeInput","unprocessed":"Boolean="},"d":{"notifyCustomer":"This field is no longer supported and any value provided to it is currently ignored.","unprocessed":"This field is temporary to support the transition to Returns Processing APIs."}}}, +"ReturnLineItem":{"o":{"f":{"customerNote":"String","fulfillmentLineItem":"FulfillmentLineItem!","id":"ID!","processableQuantity":"Int!","processedQuantity":"Int!","quantity":"Int!","refundableQuantity":"Int!","refundedQuantity":"Int!","restockingFee":"RestockingFee","returnReason":"ReturnReason!","returnReasonDefinition":"ReturnReasonDefinition","returnReasonNote":"String!","totalWeight":"Weight","unprocessedQuantity":"Int!","withCodeDiscountedTotalPriceSet":"MoneyBag!"},"t":["Node","ReturnLineItemType"],"d":{"returnReason":"Use `returnReasonDefinition` instead. This field will be removed in the future."}}}, +"ReturnLineItemInput":{"i":{"f":{"fulfillmentLineItemId":"ID!","quantity":"Int!","restockingFee":"RestockingFeeInput","returnReason":"ReturnReason","returnReasonDefinitionId":"ID","returnReasonNote":"String="},"d":{"returnReason":"Use `returnReasonDefinitionId` instead. This field will be removed in the future."}}}, +"ReturnLineItemRemoveFromReturnInput":{"i":{"quantity":"Int!","returnLineItemId":"ID!"}}, +"ReturnLineItemRemoveFromReturnPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnLineItemType":{"n":{"f":{"customerNote":"String","id":"ID!","processableQuantity":"Int!","processedQuantity":"Int!","quantity":"Int!","refundableQuantity":"Int!","refundedQuantity":"Int!","returnReason":"ReturnReason!","returnReasonDefinition":"ReturnReasonDefinition","returnReasonNote":"String!","unprocessedQuantity":"Int!"},"t":["ReturnLineItem","UnverifiedReturnLineItem"],"d":{"returnReason":"Use `returnReasonDefinition` instead. This field will be removed in the future."}}}, +"ReturnLineItemTypeConnection":{"o":{"f":{"edges":"[ReturnLineItemTypeEdge!]!","nodes":"[ReturnLineItemType!]!","pageInfo":"PageInfo!"}}}, +"ReturnLineItemTypeEdge":{"o":{"f":{"cursor":"String!","node":"ReturnLineItemType!"}}}, +"ReturnOutcomeFinancialTransfer":{"u":["InvoiceReturnOutcome","RefundReturnOutcome"]}, +"ReturnPoliciesEditRules":{"o":{"f":{"canAcceptEdits":"Boolean!","editWindowMinutes":"Int"}}}, +"ReturnPoliciesReturnRules":{"o":{"f":{"canAcceptReturns":"Boolean!","extendWindowToBusinessDay":"Boolean","returnWindowDays":"Int","returnWindowStartingFrom":"ReturnPoliciesReturnWindowStartingFrom"}}}, +"ReturnPoliciesReturnWindowStartingFrom":{"e":["ITEM_DELIVERY_DATE","LAST_ITEM_DELIVERY_DATE"]}, +"ReturnPolicyProfile":{"o":{"f":{"default":"Boolean!","editRules":"ReturnPoliciesEditRules","id":"ID!","markets":"[Market!]!","name":"String","returnRules":"ReturnPoliciesReturnRules","updatedAt":"DateTime"},"t":["Node"]}}, +"ReturnPolicyProfileConnection":{"o":{"f":{"edges":"[ReturnPolicyProfileEdge!]!","nodes":"[ReturnPolicyProfile!]!","pageInfo":"PageInfo!"}}}, +"ReturnPolicyProfileEdge":{"o":{"f":{"cursor":"String!","node":"ReturnPolicyProfile!"}}}, +"ReturnProcessExchangeLineItemInput":{"i":{"id":"ID!","quantity":"Int!"}}, +"ReturnProcessFinancialTransferInput":{"i":{"f":{"issueRefund":"ReturnProcessRefundInput"},"o":true}}, +"ReturnProcessInput":{"i":{"exchangeLineItems":"[ReturnProcessExchangeLineItemInput!]=","financialTransfer":"ReturnProcessFinancialTransferInput","note":"String","notifyCustomer":"Boolean=","refundDuties":"[RefundDutyInput!]=","refundShipping":"RefundShippingInput","returnId":"ID!","returnLineItems":"[ReturnProcessReturnLineItemInput!]=","tipLineId":"ID"}}, +"ReturnProcessPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnProcessRefundInput":{"i":{"allowOverRefunding":"Boolean=","orderTransactions":"[ReturnRefundOrderTransactionInput!]!","refundMethods":"[RefundMethodInput!]="}}, +"ReturnProcessReturnLineItemInput":{"i":{"dispositions":"[ReverseFulfillmentOrderDisposeInput!]","id":"ID!","quantity":"Int!"}}, +"ReturnProcessingStatusFilterInput":{"e":["PROCESSED","PROCESSABLE"]}, +"ReturnReason":{"e":["SIZE_TOO_SMALL","SIZE_TOO_LARGE","UNWANTED","NOT_AS_DESCRIBED","WRONG_ITEM","DEFECTIVE","STYLE","COLOR","OTHER","UNKNOWN"]}, +"ReturnReasonDefinition":{"o":{"f":{"deleted":"Boolean!","handle":"String!","id":"ID!","name":"String!"},"t":["Node"]}}, +"ReturnReasonDefinitionConnection":{"o":{"f":{"edges":"[ReturnReasonDefinitionEdge!]!","nodes":"[ReturnReasonDefinition!]!","pageInfo":"PageInfo!"}}}, +"ReturnReasonDefinitionEdge":{"o":{"f":{"cursor":"String!","node":"ReturnReasonDefinition!"}}}, +"ReturnReasonDefinitionSortKeys":{"e":["HANDLE","ID","NAME"]}, +"ReturnRefundInput":{"i":{"notifyCustomer":"Boolean=","orderTransactions":"[ReturnRefundOrderTransactionInput!]=","refundDuties":"[RefundDutyInput!]","refundShipping":"RefundShippingInput","returnId":"ID!","returnRefundLineItems":"[ReturnRefundLineItemInput!]!"}}, +"ReturnRefundLineItemInput":{"i":{"quantity":"Int!","returnLineItemId":"ID!"}}, +"ReturnRefundOrderTransactionInput":{"i":{"parentId":"ID!","transactionAmount":"MoneyInput!"}}, +"ReturnRefundPayload":{"o":{"f":{"refund":"Refund","userErrors":"[ReturnUserError!]!"}}}, +"ReturnReopenPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnRequestInput":{"i":{"orderId":"ID!","returnLineItems":"[ReturnRequestLineItemInput!]!","returnShippingFee":"ReturnShippingFeeInput"}}, +"ReturnRequestLineItemInput":{"i":{"f":{"customerNote":"String","fulfillmentLineItemId":"ID!","quantity":"Int!","restockingFee":"RestockingFeeInput","returnReason":"ReturnReason","returnReasonDefinitionId":"ID"},"d":{"returnReason":"Use `returnReasonDefinitionId` instead. This field will be removed in the future."}}}, +"ReturnRequestPayload":{"o":{"f":{"return":"Return","userErrors":"[ReturnUserError!]!"}}}, +"ReturnShippingFee":{"o":{"f":{"amountSet":"MoneyBag!","finalizedTaxAmountSet":"MoneyBag","id":"ID!"},"t":["Fee"]}}, +"ReturnShippingFeeInput":{"i":{"amount":"MoneyInput!"}}, +"ReturnStatus":{"e":["CANCELED","CLOSED","OPEN","REQUESTED","DECLINED"]}, +"ReturnUserError":{"o":{"f":{"code":"ReturnErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ReturnableFulfillment":{"o":{"f":{"fulfillment":"Fulfillment!","id":"ID!","returnableFulfillmentLineItems":["ReturnableFulfillmentLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["Node"]}}, +"ReturnableFulfillmentConnection":{"o":{"f":{"edges":"[ReturnableFulfillmentEdge!]!","nodes":"[ReturnableFulfillment!]!","pageInfo":"PageInfo!"}}}, +"ReturnableFulfillmentEdge":{"o":{"f":{"cursor":"String!","node":"ReturnableFulfillment!"}}}, +"ReturnableFulfillmentLineItem":{"o":{"f":{"fulfillmentLineItem":"FulfillmentLineItem!","quantity":"Int!"}}}, +"ReturnableFulfillmentLineItemConnection":{"o":{"f":{"edges":"[ReturnableFulfillmentLineItemEdge!]!","nodes":"[ReturnableFulfillmentLineItem!]!","pageInfo":"PageInfo!"}}}, +"ReturnableFulfillmentLineItemEdge":{"o":{"f":{"cursor":"String!","node":"ReturnableFulfillmentLineItem!"}}}, +"ReverseDelivery":{"o":{"f":{"deliverable":"ReverseDeliveryDeliverable","id":"ID!","reverseDeliveryLineItems":["ReverseDeliveryLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"reverseFulfillmentOrder":"ReverseFulfillmentOrder!"},"t":["Node"]}}, +"ReverseDeliveryConnection":{"o":{"f":{"edges":"[ReverseDeliveryEdge!]!","nodes":"[ReverseDelivery!]!","pageInfo":"PageInfo!"}}}, +"ReverseDeliveryCreateWithShippingPayload":{"o":{"f":{"reverseDelivery":"ReverseDelivery","userErrors":"[ReturnUserError!]!"}}}, +"ReverseDeliveryDeliverable":{"u":["ReverseDeliveryShippingDeliverable"]}, +"ReverseDeliveryEdge":{"o":{"f":{"cursor":"String!","node":"ReverseDelivery!"}}}, +"ReverseDeliveryLabelInput":{"i":{"fileUrl":"URL!"}}, +"ReverseDeliveryLabelV2":{"o":{"f":{"createdAt":"DateTime!","publicFileUrl":"URL","updatedAt":"DateTime!"}}}, +"ReverseDeliveryLineItem":{"o":{"f":{"dispositions":"[ReverseFulfillmentOrderDisposition!]!","id":"ID!","quantity":"Int!","reverseFulfillmentOrderLineItem":"ReverseFulfillmentOrderLineItem!"},"t":["Node"]}}, +"ReverseDeliveryLineItemConnection":{"o":{"f":{"edges":"[ReverseDeliveryLineItemEdge!]!","nodes":"[ReverseDeliveryLineItem!]!","pageInfo":"PageInfo!"}}}, +"ReverseDeliveryLineItemEdge":{"o":{"f":{"cursor":"String!","node":"ReverseDeliveryLineItem!"}}}, +"ReverseDeliveryLineItemInput":{"i":{"quantity":"Int!","reverseFulfillmentOrderLineItemId":"ID!"}}, +"ReverseDeliveryShippingDeliverable":{"o":{"f":{"label":"ReverseDeliveryLabelV2","tracking":"ReverseDeliveryTrackingV2"}}}, +"ReverseDeliveryShippingUpdatePayload":{"o":{"f":{"reverseDelivery":"ReverseDelivery","userErrors":"[ReturnUserError!]!"}}}, +"ReverseDeliveryTrackingInput":{"i":{"number":"String","url":"URL"}}, +"ReverseDeliveryTrackingV2":{"o":{"f":{"carrierName":"String","number":"String","url":"URL"}}}, +"ReverseFulfillmentOrder":{"o":{"f":{"id":"ID!","lineItems":["ReverseFulfillmentOrderLineItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"order":"Order","reverseDeliveries":["ReverseDeliveryConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"status":"ReverseFulfillmentOrderStatus!","thirdPartyConfirmation":"ReverseFulfillmentOrderThirdPartyConfirmation"},"t":["Node"]}}, +"ReverseFulfillmentOrderConnection":{"o":{"f":{"edges":"[ReverseFulfillmentOrderEdge!]!","nodes":"[ReverseFulfillmentOrder!]!","pageInfo":"PageInfo!"}}}, +"ReverseFulfillmentOrderDisposeInput":{"i":{"dispositionType":"ReverseFulfillmentOrderDispositionType!","locationId":"ID","quantity":"Int!","reverseFulfillmentOrderLineItemId":"ID!"}}, +"ReverseFulfillmentOrderDisposePayload":{"o":{"f":{"reverseFulfillmentOrderLineItems":"[ReverseFulfillmentOrderLineItem!]","userErrors":"[ReturnUserError!]!"}}}, +"ReverseFulfillmentOrderDisposition":{"o":{"f":{"createdAt":"DateTime!","id":"ID!","location":"Location","quantity":"Int!","type":"ReverseFulfillmentOrderDispositionType!"},"t":["Node"]}}, +"ReverseFulfillmentOrderDispositionType":{"e":["RESTOCKED","PROCESSING_REQUIRED","NOT_RESTOCKED","MISSING"]}, +"ReverseFulfillmentOrderEdge":{"o":{"f":{"cursor":"String!","node":"ReverseFulfillmentOrder!"}}}, +"ReverseFulfillmentOrderLineItem":{"o":{"f":{"dispositions":"[ReverseFulfillmentOrderDisposition!]!","fulfillmentLineItem":"FulfillmentLineItem","id":"ID!","totalQuantity":"Int!"},"t":["Node"]}}, +"ReverseFulfillmentOrderLineItemConnection":{"o":{"f":{"edges":"[ReverseFulfillmentOrderLineItemEdge!]!","nodes":"[ReverseFulfillmentOrderLineItem!]!","pageInfo":"PageInfo!"}}}, +"ReverseFulfillmentOrderLineItemEdge":{"o":{"f":{"cursor":"String!","node":"ReverseFulfillmentOrderLineItem!"}}}, +"ReverseFulfillmentOrderStatus":{"e":["CANCELED","CLOSED","OPEN"]}, +"ReverseFulfillmentOrderThirdPartyConfirmation":{"o":{"f":{"status":"ReverseFulfillmentOrderThirdPartyConfirmationStatus!"}}}, +"ReverseFulfillmentOrderThirdPartyConfirmationStatus":{"e":["ACCEPTED","CANCEL_ACCEPTED","CANCEL_REJECTED","PENDING_ACCEPTANCE","PENDING_CANCELATION","REJECTED"]}, +"RiskAssessmentResult":{"e":["HIGH","MEDIUM","LOW","NONE","PENDING"]}, +"RiskFact":{"o":{"f":{"description":"String!","sentiment":"RiskFactSentiment!"}}}, +"RiskFactSentiment":{"e":["POSITIVE","NEUTRAL","NEGATIVE"]}, +"Rollout":{"o":{"f":{"archivedAt":"DateTime","concludedAt":"DateTime","createdAt":"DateTime!","effectiveTrafficAllocation":"Float!","id":"ID!","name":"String!","schedule":"RolloutSchedule","startedAt":"DateTime","status":"RolloutStatus!","trafficAllocation":"Int!","treatments":"[RolloutTreatment!]!","updatedAt":"DateTime!"},"t":["Node"]}}, +"RolloutCatalogActivateChange":{"o":{"f":{"catalog":"Catalog","id":"ID!"},"t":["RolloutCatalogChange","RolloutChange"]}}, +"RolloutCatalogChange":{"n":{"f":{"catalog":"Catalog","id":"ID!"},"t":["RolloutCatalogActivateChange","RolloutCatalogDraftChange"]}}, +"RolloutCatalogDraftChange":{"o":{"f":{"catalog":"Catalog","id":"ID!"},"t":["RolloutCatalogChange","RolloutChange"]}}, +"RolloutChange":{"n":{"f":{"id":"ID!"},"t":["RolloutCatalogActivateChange","RolloutCatalogDraftChange","RolloutCheckoutAndAccountsConfigurationPublishChange","RolloutDiscountActivateChange","RolloutDiscountExpireChange","RolloutThemePublishChange"]}}, +"RolloutChangeConnection":{"o":{"f":{"edges":"[RolloutChangeEdge!]!","nodes":"[RolloutChange!]!","pageInfo":"PageInfo!"}}}, +"RolloutChangeEdge":{"o":{"f":{"cursor":"String!","node":"RolloutChange!"}}}, +"RolloutCheckoutAndAccountsConfigurationChange":{"n":{"f":{"checkoutAndAccountsConfiguration":"CheckoutAndAccountsConfiguration","id":"ID!"},"t":["RolloutCheckoutAndAccountsConfigurationPublishChange"]}}, +"RolloutCheckoutAndAccountsConfigurationPublishChange":{"o":{"f":{"checkoutAndAccountsConfiguration":"CheckoutAndAccountsConfiguration","id":"ID!"},"t":["RolloutChange","RolloutCheckoutAndAccountsConfigurationChange"]}}, +"RolloutConnection":{"o":{"f":{"edges":"[RolloutEdge!]!","nodes":"[Rollout!]!","pageInfo":"PageInfo!"}}}, +"RolloutDiscountActivateChange":{"o":{"f":{"discount":"DiscountNode","id":"ID!"},"t":["RolloutChange","RolloutDiscountChange"]}}, +"RolloutDiscountChange":{"n":{"f":{"discount":"DiscountNode","id":"ID!"},"t":["RolloutDiscountActivateChange","RolloutDiscountExpireChange"]}}, +"RolloutDiscountExpireChange":{"o":{"f":{"discount":"DiscountNode","id":"ID!"},"t":["RolloutChange","RolloutDiscountChange"]}}, +"RolloutEdge":{"o":{"f":{"cursor":"String!","node":"Rollout!"}}}, +"RolloutSchedule":{"o":{"f":{"activateAt":"DateTime!","concludeAt":"DateTime"}}}, +"RolloutSortKeys":{"e":["ID","NAME","CREATED_AT","UPDATED_AT"]}, +"RolloutStatus":{"e":["DRAFT","SCHEDULED","PAUSED","ACTIVE","CONCLUDED","ARCHIVED"]}, +"RolloutThemeChange":{"n":{"f":{"id":"ID!","theme":"OnlineStoreTheme"},"t":["RolloutThemePublishChange"]}}, +"RolloutThemePublishChange":{"o":{"f":{"id":"ID!","theme":"OnlineStoreTheme"},"t":["RolloutChange","RolloutThemeChange"]}}, +"RolloutTreatment":{"o":{"f":{"changes":["RolloutChangeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"id":"ID!","rollout":"Rollout","split":"Int!"},"t":["Node"]}}, +"RowCount":{"o":{"f":{"count":"Int!","exceedsMax":"Boolean!"}}}, +"SEO":{"o":{"f":{"description":"String","title":"String"}}}, +"SEOInput":{"i":{"description":"String","title":"String"}}, +"Sale":{"n":{"f":{"actionType":"SaleActionType!","id":"ID!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["AdditionalFeeSale","AdjustmentSale","DutySale","FeeSale","GiftCardSale","ProductSale","ShippingLineSale","TipSale","UnknownSale"]}}, +"SaleActionType":{"e":["ORDER","RETURN","UPDATE","UNKNOWN"]}, +"SaleAdditionalFee":{"o":{"f":{"id":"ID!","name":"String!","price":"MoneyBag!","taxLines":"[TaxLine!]!"},"t":["Node"]}}, +"SaleConnection":{"o":{"f":{"edges":"[SaleEdge!]!","nodes":"[Sale!]!","pageInfo":"PageInfo!"}}}, +"SaleEdge":{"o":{"f":{"cursor":"String!","node":"Sale!"}}}, +"SaleLineType":{"e":["PRODUCT","TIP","GIFT_CARD","SHIPPING","DUTY","ADDITIONAL_FEE","FEE","UNKNOWN","ADJUSTMENT"]}, +"SaleTax":{"o":{"f":{"amount":"MoneyBag!","id":"ID!","taxLine":"TaxLine!"}}}, +"SalesAgreement":{"n":{"f":{"app":"App","happenedAt":"DateTime!","id":"ID!","reason":"OrderActionType!","sales":["SaleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"user":"StaffMember"},"t":["OrderAgreement","OrderEditAgreement","RefundAgreement","ReturnAgreement"]}}, +"SalesAgreementConnection":{"o":{"f":{"edges":"[SalesAgreementEdge!]!","nodes":"[SalesAgreement!]!","pageInfo":"PageInfo!"}}}, +"SalesAgreementEdge":{"o":{"f":{"cursor":"String!","node":"SalesAgreement!"}}}, +"SavedSearch":{"o":{"f":{"filters":"[SearchFilter!]!","id":"ID!","legacyResourceId":"UnsignedInt64!","name":"String!","query":"String!","resourceType":"SearchResultType!","searchTerms":"String!"},"t":["LegacyInteroperability","Node"]}}, +"SavedSearchConnection":{"o":{"f":{"edges":"[SavedSearchEdge!]!","nodes":"[SavedSearch!]!","pageInfo":"PageInfo!"}}}, +"SavedSearchCreateInput":{"i":{"name":"String!","query":"String!","resourceType":"SearchResultType!"}}, +"SavedSearchCreatePayload":{"o":{"f":{"savedSearch":"SavedSearch","userErrors":"[UserError!]!"}}}, +"SavedSearchDeleteInput":{"i":{"id":"ID!"}}, +"SavedSearchDeletePayload":{"o":{"f":{"deletedSavedSearchId":"ID","shop":"Shop!","userErrors":"[UserError!]!"}}}, +"SavedSearchEdge":{"o":{"f":{"cursor":"String!","node":"SavedSearch!"}}}, +"SavedSearchUpdateInput":{"i":{"id":"ID!","name":"String","query":"String"}}, +"SavedSearchUpdatePayload":{"o":{"f":{"savedSearch":"SavedSearch","userErrors":"[UserError!]!"}}}, +"ScheduledChangeSortKeys":{"e":["EXPECTED_AT","ID"]}, +"ScriptDiscountApplication":{"o":{"f":{"allocationMethod":"DiscountApplicationAllocationMethod!","description":"String!","index":"Int!","targetSelection":"DiscountApplicationTargetSelection!","targetType":"DiscountApplicationTargetType!","title":"String!","value":"PricingValue!"},"t":["DiscountApplication"],"d":{"description":"Use `title` instead."}}}, +"ScriptTag":{"o":{"f":{"cache":"Boolean!","createdAt":"DateTime!","displayScope":"ScriptTagDisplayScope!","id":"ID!","legacyResourceId":"UnsignedInt64!","src":"URL!","updatedAt":"DateTime!"},"t":["LegacyInteroperability","Node"]}}, +"ScriptTagConnection":{"o":{"f":{"edges":"[ScriptTagEdge!]!","nodes":"[ScriptTag!]!","pageInfo":"PageInfo!"}}}, +"ScriptTagCreatePayload":{"o":{"f":{"scriptTag":"ScriptTag","userErrors":"[UserError!]!"}}}, +"ScriptTagDeletePayload":{"o":{"f":{"deletedScriptTagId":"ID","userErrors":"[UserError!]!"}}}, +"ScriptTagDisplayScope":{"e":{"v":["ALL","ORDER_STATUS","ONLINE_STORE"],"d":{"ALL":"`ALL` is deprecated. Use `ONLINE_STORE` instead.","ORDER_STATUS":"`ORDER_STATUS` is deprecated and unavailable as a mutation input."}}}, +"ScriptTagEdge":{"o":{"f":{"cursor":"String!","node":"ScriptTag!"}}}, +"ScriptTagInput":{"i":{"cache":"Boolean=","displayScope":"ScriptTagDisplayScope","src":"URL"}}, +"ScriptTagUpdatePayload":{"o":{"f":{"scriptTag":"ScriptTag","userErrors":"[UserError!]!"}}}, +"SearchFilter":{"o":{"f":{"key":"String!","value":"String!"}}}, +"SearchFilterOptions":{"o":{"f":{"productAvailability":"[FilterOption!]!"}}}, +"SearchResult":{"o":{"f":{"description":"String","image":"Image","reference":"Node!","title":"String!","url":"URL!"}}}, +"SearchResultConnection":{"o":{"f":{"edges":"[SearchResultEdge!]!","pageInfo":"PageInfo!","resultsAfterCount":"Int!"},"d":{"resultsAfterCount":"The provided information is not accurate."}}}, +"SearchResultEdge":{"o":{"f":{"cursor":"String!","node":"SearchResult!"}}}, +"SearchResultType":{"e":["CUSTOMER","DRAFT_ORDER","INVENTORY_TRANSFER","PRODUCT","COLLECTION","FILE","PAGE","BLOG","ARTICLE","URL_REDIRECT","PRICE_RULE","DISCOUNT_REDEEM_CODE","ORDER","BALANCE_TRANSACTION"]}, +"Segment":{"o":{"f":{"creationDate":"DateTime!","id":"ID!","lastEditDate":"DateTime!","name":"String!","query":"String!"},"t":["Node"]}}, +"SegmentAssociationFilter":{"o":{"f":{"localizedName":"String!","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentFilter"]}}, +"SegmentAttributeStatistics":{"o":{"f":{"average":"Float!","sum":"Float!"}}}, +"SegmentBooleanFilter":{"o":{"f":{"localizedName":"String!","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentFilter"]}}, +"SegmentConnection":{"o":{"f":{"edges":"[SegmentEdge!]!","nodes":"[Segment!]!","pageInfo":"PageInfo!"}}}, +"SegmentCreatePayload":{"o":{"f":{"segment":"Segment","userErrors":"[UserError!]!"}}}, +"SegmentDateFilter":{"o":{"f":{"localizedName":"String!","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentFilter"]}}, +"SegmentDeletePayload":{"o":{"f":{"deletedSegmentId":"ID","userErrors":"[UserError!]!"}}}, +"SegmentEdge":{"o":{"f":{"cursor":"String!","node":"Segment!"}}}, +"SegmentEnumFilter":{"o":{"f":{"localizedName":"String!","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentFilter"]}}, +"SegmentEventFilter":{"o":{"f":{"localizedName":"String!","multiValue":"Boolean!","parameters":"[SegmentEventFilterParameter!]!","queryName":"String!","returnValueType":"String!"},"t":["SegmentFilter"]}}, +"SegmentEventFilterParameter":{"o":{"f":{"acceptsMultipleValues":"Boolean!","localizedDescription":"String!","localizedName":"String!","maxRange":"Float","minRange":"Float","optional":"Boolean!","parameterType":"String!","queryName":"String!"}}}, +"SegmentFilter":{"n":{"f":{"localizedName":"String!","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentAssociationFilter","SegmentBooleanFilter","SegmentDateFilter","SegmentEnumFilter","SegmentEventFilter","SegmentFloatFilter","SegmentIntegerFilter","SegmentStringFilter"]}}, +"SegmentFilterConnection":{"o":{"f":{"edges":"[SegmentFilterEdge!]!","nodes":"[SegmentFilter!]!","pageInfo":"PageInfo!"}}}, +"SegmentFilterEdge":{"o":{"f":{"cursor":"String!","node":"SegmentFilter!"}}}, +"SegmentFloatFilter":{"o":{"f":{"localizedName":"String!","maxRange":"Float","minRange":"Float","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentFilter"]}}, +"SegmentIntegerFilter":{"o":{"f":{"localizedName":"String!","maxRange":"Float","minRange":"Float","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentFilter"]}}, +"SegmentMembership":{"o":{"f":{"isMember":"Boolean!","segmentId":"ID!"}}}, +"SegmentMembershipResponse":{"o":{"f":{"memberships":"[SegmentMembership!]!"}}}, +"SegmentMigration":{"o":{"f":{"id":"ID!","savedSearchId":"ID!","segmentId":"ID"}}}, +"SegmentMigrationConnection":{"o":{"f":{"edges":"[SegmentMigrationEdge!]!","nodes":"[SegmentMigration!]!","pageInfo":"PageInfo!"}}}, +"SegmentMigrationEdge":{"o":{"f":{"cursor":"String!","node":"SegmentMigration!"}}}, +"SegmentSortKeys":{"e":["CREATION_DATE","ID","LAST_EDIT_DATE","RELEVANCE"]}, +"SegmentStatistics":{"o":{"f":{"attributeStatistics":["SegmentAttributeStatistics!",{"attributeName":"String!"}]}}}, +"SegmentStringFilter":{"o":{"f":{"localizedName":"String!","multiValue":"Boolean!","queryName":"String!"},"t":["SegmentFilter"]}}, +"SegmentUpdatePayload":{"o":{"f":{"segment":"Segment","userErrors":"[UserError!]!"}}}, +"SegmentValue":{"o":{"f":{"localizedValue":"String!","queryName":"String!"}}}, +"SegmentValueConnection":{"o":{"f":{"edges":"[SegmentValueEdge!]!","nodes":"[SegmentValue!]!","pageInfo":"PageInfo!"}}}, +"SegmentValueEdge":{"o":{"f":{"cursor":"String!","node":"SegmentValue!"}}}, +"SelectedOption":{"o":{"f":{"name":"String!","optionValue":"ProductOptionValue!","value":"String!"}}}, +"SelectedVariantOptionInput":{"i":{"linkedMetafieldValue":"String","name":"String!","value":"String!"}}, +"SellingPlan":{"o":{"f":{"billingPolicy":"SellingPlanBillingPolicy!","category":"SellingPlanCategory","createdAt":"DateTime!","deliveryPolicy":"SellingPlanDeliveryPolicy!","description":"String","id":"ID!","inventoryPolicy":"SellingPlanInventoryPolicy","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"name":"String!","options":"[String!]!","position":"Int","pricingPolicies":"[SellingPlanPricingPolicy!]!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}]},"t":["HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"SellingPlanAnchor":{"o":{"f":{"cutoffDay":"Int","day":"Int!","month":"Int","type":"SellingPlanAnchorType!"}}}, +"SellingPlanAnchorInput":{"i":{"cutoffDay":"Int","day":"Int","month":"Int","type":"SellingPlanAnchorType"}}, +"SellingPlanAnchorType":{"e":["WEEKDAY","MONTHDAY","YEARDAY"]}, +"SellingPlanBillingPolicy":{"u":["SellingPlanFixedBillingPolicy","SellingPlanRecurringBillingPolicy"]}, +"SellingPlanBillingPolicyInput":{"i":{"fixed":"SellingPlanFixedBillingPolicyInput","recurring":"SellingPlanRecurringBillingPolicyInput"}}, +"SellingPlanCategory":{"e":["OTHER","PRE_ORDER","SUBSCRIPTION","TRY_BEFORE_YOU_BUY"]}, +"SellingPlanCheckoutCharge":{"o":{"f":{"type":"SellingPlanCheckoutChargeType!","value":"SellingPlanCheckoutChargeValue!"}}}, +"SellingPlanCheckoutChargeInput":{"i":{"type":"SellingPlanCheckoutChargeType","value":"SellingPlanCheckoutChargeValueInput"}}, +"SellingPlanCheckoutChargePercentageValue":{"o":{"f":{"percentage":"Float!"}}}, +"SellingPlanCheckoutChargeType":{"e":["PERCENTAGE","PRICE"]}, +"SellingPlanCheckoutChargeValue":{"u":["MoneyV2","SellingPlanCheckoutChargePercentageValue"]}, +"SellingPlanCheckoutChargeValueInput":{"i":{"fixedValue":"Decimal","percentage":"Float"}}, +"SellingPlanConnection":{"o":{"f":{"edges":"[SellingPlanEdge!]!","nodes":"[SellingPlan!]!","pageInfo":"PageInfo!"}}}, +"SellingPlanDeliveryPolicy":{"u":["SellingPlanFixedDeliveryPolicy","SellingPlanRecurringDeliveryPolicy"]}, +"SellingPlanDeliveryPolicyInput":{"i":{"fixed":"SellingPlanFixedDeliveryPolicyInput","recurring":"SellingPlanRecurringDeliveryPolicyInput"}}, +"SellingPlanEdge":{"o":{"f":{"cursor":"String!","node":"SellingPlan!"}}}, +"SellingPlanFixedBillingPolicy":{"o":{"f":{"checkoutCharge":"SellingPlanCheckoutCharge!","remainingBalanceChargeExactTime":"DateTime","remainingBalanceChargeTimeAfterCheckout":"String","remainingBalanceChargeTrigger":"SellingPlanRemainingBalanceChargeTrigger!"}}}, +"SellingPlanFixedBillingPolicyInput":{"i":{"checkoutCharge":"SellingPlanCheckoutChargeInput","remainingBalanceChargeExactTime":"DateTime","remainingBalanceChargeTimeAfterCheckout":"String","remainingBalanceChargeTrigger":"SellingPlanRemainingBalanceChargeTrigger"}}, +"SellingPlanFixedDeliveryPolicy":{"o":{"f":{"anchors":"[SellingPlanAnchor!]!","cutoff":"Int","fulfillmentExactTime":"DateTime","fulfillmentTrigger":"SellingPlanFulfillmentTrigger!","intent":"SellingPlanFixedDeliveryPolicyIntent!","preAnchorBehavior":"SellingPlanFixedDeliveryPolicyPreAnchorBehavior!"}}}, +"SellingPlanFixedDeliveryPolicyInput":{"i":{"anchors":"[SellingPlanAnchorInput!]","cutoff":"Int","fulfillmentExactTime":"DateTime","fulfillmentTrigger":"SellingPlanFulfillmentTrigger","intent":"SellingPlanFixedDeliveryPolicyIntent","preAnchorBehavior":"SellingPlanFixedDeliveryPolicyPreAnchorBehavior"}}, +"SellingPlanFixedDeliveryPolicyIntent":{"e":["FULFILLMENT_BEGIN"]}, +"SellingPlanFixedDeliveryPolicyPreAnchorBehavior":{"e":["ASAP","NEXT"]}, +"SellingPlanFixedPricingPolicy":{"o":{"f":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType!","adjustmentValue":"SellingPlanPricingPolicyAdjustmentValue!","createdAt":"DateTime!"},"t":["SellingPlanPricingPolicyBase"]}}, +"SellingPlanFixedPricingPolicyInput":{"i":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType","adjustmentValue":"SellingPlanPricingPolicyValueInput","id":"ID"}}, +"SellingPlanFulfillmentTrigger":{"e":["ANCHOR","ASAP","EXACT_TIME","UNKNOWN"]}, +"SellingPlanGroup":{"o":{"f":{"appId":"String","appliesToProduct":["Boolean!",{"productId":"ID!"}],"appliesToProductVariant":["Boolean!",{"productVariantId":"ID!"}],"appliesToProductVariants":["Boolean!",{"productId":"ID!"}],"createdAt":"DateTime!","description":"String","id":"ID!","merchantCode":"String!","name":"String!","options":"[String!]!","position":"Int","productVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","productId":"ID","reverse":"Boolean="}],"productVariantsCount":["Count",{"productId":"ID"}],"products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"productsCount":"Count","sellingPlans":["SellingPlanConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"summary":"String","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}]},"t":["HasPublishedTranslations","Node"]}}, +"SellingPlanGroupAddProductVariantsPayload":{"o":{"f":{"sellingPlanGroup":"SellingPlanGroup","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"SellingPlanGroupAddProductsPayload":{"o":{"f":{"sellingPlanGroup":"SellingPlanGroup","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"SellingPlanGroupConnection":{"o":{"f":{"edges":"[SellingPlanGroupEdge!]!","nodes":"[SellingPlanGroup!]!","pageInfo":"PageInfo!"}}}, +"SellingPlanGroupCreatePayload":{"o":{"f":{"sellingPlanGroup":"SellingPlanGroup","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"SellingPlanGroupDeletePayload":{"o":{"f":{"deletedSellingPlanGroupId":"ID","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"SellingPlanGroupEdge":{"o":{"f":{"cursor":"String!","node":"SellingPlanGroup!"}}}, +"SellingPlanGroupInput":{"i":{"appId":"String","description":"String","merchantCode":"String","name":"String","options":"[String!]","position":"Int","sellingPlansToCreate":"[SellingPlanInput!]","sellingPlansToDelete":"[ID!]","sellingPlansToUpdate":"[SellingPlanInput!]"}}, +"SellingPlanGroupRemoveProductVariantsPayload":{"o":{"f":{"removedProductVariantIds":"[ID!]","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"SellingPlanGroupRemoveProductsPayload":{"o":{"f":{"removedProductIds":"[ID!]","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"SellingPlanGroupResourceInput":{"i":{"productIds":"[ID!]","productVariantIds":"[ID!]"}}, +"SellingPlanGroupSortKeys":{"e":["CREATED_AT","ID","NAME","UPDATED_AT"]}, +"SellingPlanGroupUpdatePayload":{"o":{"f":{"deletedSellingPlanIds":"[ID!]","sellingPlanGroup":"SellingPlanGroup","userErrors":"[SellingPlanGroupUserError!]!"}}}, +"SellingPlanGroupUserError":{"o":{"f":{"code":"SellingPlanGroupUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SellingPlanGroupUserErrorCode":{"e":["BLANK","EQUAL_TO","GREATER_THAN","GREATER_THAN_OR_EQUAL_TO","INCLUSION","INVALID","LESS_THAN","LESS_THAN_OR_EQUAL_TO","NOT_A_NUMBER","NOT_FOUND","PRESENT","TAKEN","TOO_BIG","TOO_LONG","TOO_SHORT","WRONG_LENGTH","SELLING_PLAN_COUNT_UPPER_BOUND","SELLING_PLAN_COUNT_LOWER_BOUND","SELLING_PLAN_MAX_CYCLES_MUST_BE_GREATER_THAN_MIN_CYCLES","SELLING_PLAN_BILLING_AND_DELIVERY_POLICY_ANCHORS_MUST_BE_EQUAL","SELLING_PLAN_BILLING_CYCLE_MUST_BE_A_MULTIPLE_OF_DELIVERY_CYCLE","SELLING_PLAN_PRICING_POLICIES_MUST_CONTAIN_A_FIXED_PRICING_POLICY","SELLING_PLAN_MISSING_OPTION2_LABEL_ON_PARENT_GROUP","SELLING_PLAN_MISSING_OPTION3_LABEL_ON_PARENT_GROUP","SELLING_PLAN_OPTION2_REQUIRED_AS_DEFINED_ON_PARENT_GROUP","SELLING_PLAN_OPTION3_REQUIRED_AS_DEFINED_ON_PARENT_GROUP","SELLING_PLAN_PRICING_POLICIES_LIMIT","RESOURCE_LIST_CONTAINS_INVALID_IDS","RESOURCE_LIST_IS_EMPTY","PRODUCT_VARIANT_DOES_NOT_EXIST","PRODUCT_DOES_NOT_EXIST","GROUP_DOES_NOT_EXIST","GROUP_COULD_NOT_BE_DELETED","ERROR_ADDING_RESOURCE_TO_GROUP","SELLING_PLAN_DELIVERY_POLICY_MISSING","SELLING_PLAN_BILLING_POLICY_MISSING","PLAN_DOES_NOT_EXIST","PLAN_ID_MUST_BE_SPECIFIED_TO_UPDATE","ONLY_NEED_ONE_BILLING_POLICY_TYPE","ONLY_NEED_ONE_DELIVERY_POLICY_TYPE","ONLY_NEED_ONE_PRICING_POLICY_TYPE","BILLING_AND_DELIVERY_POLICY_TYPES_MUST_BE_THE_SAME","ONLY_NEED_ONE_PRICING_POLICY_VALUE","PRICING_POLICY_ADJUSTMENT_VALUE_AND_TYPE_MUST_MATCH","SELLING_PLAN_DUPLICATE_NAME","SELLING_PLAN_DUPLICATE_OPTIONS","SELLING_PLAN_FIXED_PRICING_POLICIES_LIMIT","REMAINING_BALANCE_CHARGE_EXACT_TIME_REQUIRED","CHECKOUT_CHARGE_VALUE_AND_TYPE_MUST_MATCH","ONLY_NEED_ONE_CHECKOUT_CHARGE_VALUE","REMAINING_BALANCE_CHARGE_EXACT_TIME_NOT_ALLOWED","REMAINING_BALANCE_CHARGE_TIME_AFTER_CHECKOUT_MUST_BE_GREATER_THAN_ZERO","REMAINING_BALANCE_CHARGE_TRIGGER_ON_FULL_CHECKOUT","REMAINING_BALANCE_CHARGE_TRIGGER_NO_REMAINING_BALANCE_ON_PARTIAL_PERCENTAGE_CHECKOUT_CHARGE","REMAINING_BALANCE_CHARGE_TRIGGER_NO_REMAINING_BALANCE_ON_PRICE_CHECKOUT_CHARGE","FULFILLMENT_EXACT_TIME_REQUIRED","FULFILLMENT_EXACT_TIME_NOT_ALLOWED","SELLING_PLAN_ANCHORS_NOT_ALLOWED","SELLING_PLAN_ANCHORS_REQUIRED","MUST_HAVE_EXACTLY_ONE_ANCHOR","ONLY_ONE_OF_FIXED_OR_RECURRING_BILLING","ONLY_ONE_OF_FIXED_OR_RECURRING_DELIVERY","BILLING_POLICY_INTERVAL_TOO_LARGE","DELIVERY_POLICY_INTERVAL_TOO_LARGE","INVALID_INPUT"]}, +"SellingPlanInput":{"i":{"billingPolicy":"SellingPlanBillingPolicyInput","category":"SellingPlanCategory","deliveryPolicy":"SellingPlanDeliveryPolicyInput","description":"String","id":"ID","inventoryPolicy":"SellingPlanInventoryPolicyInput","metafields":"[MetafieldInput!]","name":"String","options":"[String!]","position":"Int","pricingPolicies":"[SellingPlanPricingPolicyInput!]"}}, +"SellingPlanInterval":{"e":["DAY","WEEK","MONTH","YEAR"]}, +"SellingPlanInventoryPolicy":{"o":{"f":{"reserve":"SellingPlanReserve!"}}}, +"SellingPlanInventoryPolicyInput":{"i":{"reserve":"SellingPlanReserve"}}, +"SellingPlanPricingPolicy":{"u":["SellingPlanFixedPricingPolicy","SellingPlanRecurringPricingPolicy"]}, +"SellingPlanPricingPolicyAdjustmentType":{"e":["PERCENTAGE","FIXED_AMOUNT","PRICE"]}, +"SellingPlanPricingPolicyAdjustmentValue":{"u":["MoneyV2","SellingPlanPricingPolicyPercentageValue"]}, +"SellingPlanPricingPolicyBase":{"n":{"f":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType!","adjustmentValue":"SellingPlanPricingPolicyAdjustmentValue!"},"t":["SellingPlanFixedPricingPolicy","SellingPlanRecurringPricingPolicy"]}}, +"SellingPlanPricingPolicyInput":{"i":{"fixed":"SellingPlanFixedPricingPolicyInput","recurring":"SellingPlanRecurringPricingPolicyInput"}}, +"SellingPlanPricingPolicyPercentageValue":{"o":{"f":{"percentage":"Float!"}}}, +"SellingPlanPricingPolicyValueInput":{"i":{"fixedValue":"Decimal","percentage":"Float"}}, +"SellingPlanRecurringBillingPolicy":{"o":{"f":{"anchors":"[SellingPlanAnchor!]!","createdAt":"DateTime!","interval":"SellingPlanInterval!","intervalCount":"Int!","maxCycles":"Int","minCycles":"Int"}}}, +"SellingPlanRecurringBillingPolicyInput":{"i":{"anchors":"[SellingPlanAnchorInput!]","interval":"SellingPlanInterval","intervalCount":"Int","maxCycles":"Int","minCycles":"Int"}}, +"SellingPlanRecurringDeliveryPolicy":{"o":{"f":{"anchors":"[SellingPlanAnchor!]!","createdAt":"DateTime!","cutoff":"Int","intent":"SellingPlanRecurringDeliveryPolicyIntent!","interval":"SellingPlanInterval!","intervalCount":"Int!","preAnchorBehavior":"SellingPlanRecurringDeliveryPolicyPreAnchorBehavior!"}}}, +"SellingPlanRecurringDeliveryPolicyInput":{"i":{"anchors":"[SellingPlanAnchorInput!]","cutoff":"Int","intent":"SellingPlanRecurringDeliveryPolicyIntent","interval":"SellingPlanInterval","intervalCount":"Int","preAnchorBehavior":"SellingPlanRecurringDeliveryPolicyPreAnchorBehavior"}}, +"SellingPlanRecurringDeliveryPolicyIntent":{"e":["FULFILLMENT_BEGIN"]}, +"SellingPlanRecurringDeliveryPolicyPreAnchorBehavior":{"e":["ASAP","NEXT"]}, +"SellingPlanRecurringPricingPolicy":{"o":{"f":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType!","adjustmentValue":"SellingPlanPricingPolicyAdjustmentValue!","afterCycle":"Int","createdAt":"DateTime!"},"t":["SellingPlanPricingPolicyBase"]}}, +"SellingPlanRecurringPricingPolicyInput":{"i":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType","adjustmentValue":"SellingPlanPricingPolicyValueInput","afterCycle":"Int!","id":"ID"}}, +"SellingPlanRemainingBalanceChargeTrigger":{"e":["NO_REMAINING_BALANCE","EXACT_TIME","TIME_AFTER_CHECKOUT","ON_FULFILLMENT"]}, +"SellingPlanReserve":{"e":["ON_FULFILLMENT","ON_SALE"]}, +"ServerPixel":{"o":{"f":{"id":"ID!","status":"ServerPixelStatus","webhookEndpointAddress":"String"},"t":["Node"]}}, +"ServerPixelCreatePayload":{"o":{"f":{"serverPixel":"ServerPixel","userErrors":"[ErrorsServerPixelUserError!]!"}}}, +"ServerPixelDeletePayload":{"o":{"f":{"deletedServerPixelId":"ID","userErrors":"[ErrorsServerPixelUserError!]!"}}}, +"ServerPixelStatus":{"e":["CONNECTED","DISCONNECTED_UNCONFIGURED","DISCONNECTED_CONFIGURED"]}, +"ShipmentLineItemSortKeys":{"e":["ID"]}, +"ShippingCarrierPackageInput":{"i":{"carrierCode":"String!","carrierPackageCode":"String!","name":"String"}}, +"ShippingConfiguration":{"o":{"f":{"isEnabled":"Boolean!","optionDefinitions":["DeliveryOptionDefinitionConnection!",{"active":"Boolean","after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"optionDefinitionsCount":["Count!",{"active":"Boolean"}]}}}, +"ShippingConfigurationCreateInput":{"i":{"isEnabled":"Boolean!","optionDefinitions":"[DeliveryOptionDefinitionCreateInput!]"}}, +"ShippingConfigurationUpdateInput":{"i":{"isEnabled":"Boolean","optionDefinitionsToCreate":"[DeliveryOptionDefinitionCreateInput!]","optionDefinitionsToDelete":"[ID!]","optionDefinitionsToUpdate":"[DeliveryOptionDefinitionUpdateInput!]"}}, +"ShippingDiscountClass":{"e":["SHIPPING"]}, +"ShippingDocumentType":{"e":["LABEL","CUSTOMS_FORM"]}, +"ShippingEnumsFileFormat":{"e":["PDF","ZPL"]}, +"ShippingLabel":{"o":{"f":{"cancellable":"Boolean!","id":"ID!","location":"Location","printed":"Boolean!","shippingDocuments":"[ShippingObjectsShippingDocument!]!","trackingInfo":"FulfillmentTrackingInfo"},"t":["Node"]}}, +"ShippingLabelPurchaseCustomPackageInput":{"i":{"dimensions":"ObjectDimensionsInput!","type":"ShippingPackageType=","weight":"WeightInput!"}}, +"ShippingLabelPurchaseError":{"o":{"f":{"code":"ShippingLabelPurchaseErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ShippingLabelPurchaseErrorCode":{"e":["JOB_NOT_ENQUEUED","PURCHASE_IN_PROGRESS","PURCHASE_LABEL_VALIDATION_ERROR","KILL_SWITCH","CARRIER_NOT_AVAILABLE","DISABLED_SHIPPING_ACCOUNT","CONNECTION_ERROR","TRANSIENT_ERROR","PERMANENT_ERROR","UNKNOWN_ERROR"]}, +"ShippingLabelPurchaseInput":{"i":{"fulfillmentOrderId":"ID!","notifyCustomer":"Boolean=","originAddress":"MailingAddressInput","packageInfo":"PackageInfoInput","preferredRateSelection":"PreferredRateSelectionInput","shippingDatetime":"DateTime!","totalWeight":"WeightInput"}}, +"ShippingLabelPurchasePayload":{"o":{"f":{"shippingLabelPurchaseResult":"ShippingLabelPurchaseResult","userErrors":"[ShippingLabelPurchaseUserError!]!"}}}, +"ShippingLabelPurchaseResult":{"o":{"f":{"done":"Boolean!","errors":"[ShippingLabelPurchaseError!]!","id":"ID!","shippingLabels":"[ShippingLabel!]!","status":"ShippingLabelPurchaseResultStatus!"},"t":["JobResult","Node"]}}, +"ShippingLabelPurchaseResultStatus":{"e":["PENDING_PURCHASE","PURCHASE_FAILED","PURCHASED"]}, +"ShippingLabelPurchaseUserError":{"o":{"f":{"code":"ShippingLabelPurchaseUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ShippingLabelPurchaseUserErrorCode":{"e":["NOT_FOUND","TOTAL_WEIGHT_ZERO","SHIPPING_DATE_IN_THE_PAST","MISSING_SHIPPING_RATE","MISSING_SHIPPING_DATE","MISSING_INSURANCE_COVERAGE_AMOUNT","MISSING_INSURANCE_COVERAGE_CURRENCY","INVALID_PACKAGE_DIMENSIONS","MISSING_HS_CODE","MISSING_COUNTRY_OF_ORIGIN","AT_LEAST_1_ITEM_REQUIRED","PHONE_NUMBER_NOT_FULLY_QUALIFIED_ORIGIN","PHONE_NUMBER_NOT_FULLY_QUALIFIED_DESTINATION","ADAPTIVE_SHIPPING_STATE_INVALID","FULFILLMENT_ORDER_INVALID","KILL_SWITCH","PURCHASE_FAILED","RATES_NOT_FOUND","TERMS_OF_SERVICE_NOT_ACCEPTED","CARRIER_NOT_SUPPORTED","ACCESS_DENIED","PACKAGE_CARRIER_MISMATCH","PICKUP_POINT_NOT_SUPPORTED"]}, +"ShippingLine":{"o":{"f":{"carrierIdentifier":"String","code":"String","createdAt":"DateTime!","currentDiscountedPriceSet":"MoneyBag!","custom":"Boolean!","deliveryCategory":"String","discountAllocations":"[DiscountAllocation!]!","discountedPrice":"MoneyV2!","discountedPriceSet":"MoneyBag!","id":"ID","isRemoved":"Boolean!","originalPrice":"MoneyV2!","originalPriceSet":"MoneyBag!","phone":"String","price":"Money!","requestedFulfillmentService":"FulfillmentService","shippingRateHandle":"String","source":"String","taxLines":"[TaxLine!]!","title":"String!"},"d":{"discountedPrice":"Use `discountedPriceSet` instead.","originalPrice":"Use `originalPriceSet` instead.","price":"Use `originalPriceSet` instead.","requestedFulfillmentService":"requestedFulfillmentService is no longer in use. Order routing does not use the requestedFulfillmentService during order and fulfillment order creation."}}}, +"ShippingLineConnection":{"o":{"f":{"edges":"[ShippingLineEdge!]!","nodes":"[ShippingLine!]!","pageInfo":"PageInfo!"}}}, +"ShippingLineEdge":{"o":{"f":{"cursor":"String!","node":"ShippingLine!"}}}, +"ShippingLineInput":{"i":{"f":{"price":"Money","priceWithCurrency":"MoneyInput","shippingRateHandle":"String","title":"String"},"d":{"price":"`priceWithCurrency` should be used instead, where currencies can be specified."}}}, +"ShippingLineSale":{"o":{"f":{"actionType":"SaleActionType!","id":"ID!","lineType":"SaleLineType!","quantity":"Int","shippingLine":"ShippingLine","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"ShippingObjectsShippingDocument":{"o":{"f":{"documentType":"ShippingDocumentType!","format":"ShippingEnumsFileFormat","printedAt":"DateTime","shippingLabelId":"ID!","url":"URL"}}}, +"ShippingPackageDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[UserError!]!"}}}, +"ShippingPackageMakeDefaultPayload":{"o":{"f":{"userErrors":"[UserError!]!"}}}, +"ShippingPackageType":{"e":["BOX","FLAT_RATE","ENVELOPE","SOFT_PACK"]}, +"ShippingPackageUpdatePayload":{"o":{"f":{"userErrors":"[UserError!]!"}}}, +"ShippingRate":{"o":{"f":{"handle":"String!","price":"MoneyV2!","title":"String!"}}}, +"ShippingRefund":{"o":{"f":{"amount":"Money!","amountSet":"MoneyBag!","maximumRefundable":"Money!","maximumRefundableSet":"MoneyBag!","tax":"Money!","taxSet":"MoneyBag!"},"d":{"amount":"Use `amountSet` instead.","maximumRefundable":"Use `maximumRefundableSet` instead.","tax":"Use `taxSet` instead."}}}, +"ShippingRefundInput":{"i":{"amount":"Money","fullRefund":"Boolean"}}, +"Shop":{"o":{"f":{"accountOwner":"StaffMember!","alerts":"[ShopAlert!]!","allProductCategories":"[ProductCategory!]!","allProductCategoriesList":"[TaxonomyCategory!]!","analyticsAnnotations":["AnalyticsAnnotationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"AnalyticsAnnotationSortKeys="}],"analyticsToken":"String!","assignedFulfillmentOrders":["FulfillmentOrderConnection!",{"after":"String","assignmentStatus":"FulfillmentOrderAssignmentStatus","before":"String","first":"Int","last":"Int","locationIds":"[ID!]","reverse":"Boolean=","sortKey":"FulfillmentOrderSortKeys="}],"availableChannelApps":["AppConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"billingAddress":"ShopAddress!","channelDefinitionsForInstalledChannels":"[AvailableChannelDefinitionsByChannel!]!","channels":["ChannelConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"checkoutApiSupported":"Boolean!","collections":["CollectionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"CollectionSortKeys="}],"contactEmail":"String!","countriesInShippingZones":"CountriesInShippingZones!","createdAt":"DateTime!","currencyCode":"CurrencyCode!","currencyFormats":"CurrencyFormats!","currencySettings":["CurrencySettingConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"customerAccounts":"ShopCustomerAccountsSetting!","customerAccountsV2":"CustomerAccountsV2!","customerTags":["StringConnection!",{"first":"Int!"}],"customers":["CustomerConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"CustomerSortKeys="}],"description":"String","domains":"[Domain!]!","draftOrderTags":["StringConnection!",{"first":"Int!"}],"email":"String!","enabledPresentmentCurrencies":"[CurrencyCode!]!","entitlements":"EntitlementsType!","features":"ShopFeatures!","fulfillmentOrders":["FulfillmentOrderConnection!",{"after":"String","before":"String","first":"Int","includeClosed":"Boolean=","last":"Int","query":"String","reverse":"Boolean=","sortKey":"FulfillmentOrderSortKeys="}],"fulfillmentServices":"[FulfillmentService!]!","ianaTimezone":"String!","id":"ID!","inventoryItems":["InventoryItemConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"limitedPendingOrderCount":"LimitedPendingOrderCount!","locations":["LocationConnection!",{"after":"String","before":"String","first":"Int","includeInactive":"Boolean=","includeLegacy":"Boolean=","last":"Int","query":"String","reverse":"Boolean=","sortKey":"LocationSortKeys="}],"marketingSmsConsentEnabledAtCheckout":"Boolean!","merchantApprovalSignals":"MerchantApprovalSignals","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"myshopifyDomain":"String!","name":"String!","navigationSettings":"[NavigationItem!]!","orderNumberFormatPrefix":"String!","orderNumberFormatSuffix":"String!","orderTags":["StringConnection!",{"first":"Int!","sort":"ShopTagSort="}],"orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"OrderSortKeys="}],"paymentSettings":"PaymentSettings!","plan":"ShopPlan!","primaryDomain":"Domain!","productImages":["ImageConnection!",{"after":"String","before":"String","crop":"CropRegion","first":"Int","last":"Int","maxHeight":"Int","maxWidth":"Int","reverse":"Boolean=","scale":"Int=","sortKey":"ProductImageSortKeys="}],"productTags":["StringConnection!",{"first":"Int!"}],"productTypes":["StringConnection!",{"first":"Int!"}],"productVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"ProductVariantSortKeys="}],"productVendors":["StringConnection!",{"first":"Int!"}],"products":["ProductConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"ProductSortKeys="}],"publicationCount":"Int!","resourceLimits":"ShopResourceLimits!","richTextEditorUrl":"URL!","search":["SearchResultConnection!",{"after":"String","first":"Int!","query":"String!","types":"[SearchResultType!]"}],"searchFilters":"SearchFilterOptions!","setupRequired":"Boolean!","shipsToCountries":"[CountryCode!]!","shopAddress":"ShopAddress!","shopOwnerName":"String!","shopPolicies":"[ShopPolicy!]!","staffMembers":["StaffMemberConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"storefrontAccessTokens":["StorefrontAccessTokenConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"storefrontUrl":"URL!","taxShipping":"Boolean!","taxesIncluded":"Boolean!","timezoneAbbreviation":"String!","timezoneOffset":"String!","timezoneOffsetMinutes":"Int!","transactionalSmsDisabled":"Boolean!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"unitSystem":"UnitSystem!","updatedAt":"DateTime!","url":"URL!","weightUnit":"WeightUnit!"},"t":["HasMetafieldDefinitions","HasMetafields","HasPublishedTranslations","Node"],"d":{"allProductCategories":"Use `allProductCategoriesList` instead.","analyticsToken":"Not supported anymore.","assignedFulfillmentOrders":"Use `QueryRoot.assignedFulfillmentOrders` instead. Details: https://shopify.dev/changelog/moving-the-shop-assignedfulfillmentorders-connection-to-queryroot","billingAddress":"Use `shopAddress` instead.","channelDefinitionsForInstalledChannels":"Use [`QueryRoot.orderAttributionDefinitions`](https://shopify.dev/docs/api/admin-graphql/latest/queries/orderAttributionDefinitions) and select `id`, `handle`, `displayName`, and `icon` instead.","channels":"Use `QueryRoot.channels` instead.","collections":"Use `QueryRoot.collections` instead.","customers":"Use `QueryRoot.customers` instead.","domains":"Use `domainsPaginated` instead.","fulfillmentOrders":"Use `QueryRoot.fulfillmentOrders` instead.","inventoryItems":"Use `QueryRoot.inventoryItems` instead.","limitedPendingOrderCount":"Use `QueryRoot.pendingOrdersCount` instead.","locations":"Use `QueryRoot.locations` instead.","metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead.","orders":"Use `QueryRoot.orders` instead.","productImages":"Use `files` instead. See [filesQuery](https://shopify.dev/docs/api/admin-graphql/latest/queries/files) and its [query](https://shopify.dev/docs/api/admin-graphql/latest/queries/files#argument-query) argument for more information.","productImages(crop)":"Use `Image.url(transform: { crop:})` instead.","productImages(maxHeight)":"Use `Image.url(transform: { maxHeight:})` instead.","productImages(maxWidth)":"Use `Image.url(transform: { maxWidth:})` instead.","productImages(scale)":"Use `Image.url(transform: { scale:})` instead.","productTags":"Use `QueryRoot.productTags` instead.","productTypes":"Use `QueryRoot.productTypes` instead.","productVariants":"Use `QueryRoot.productVariants` instead.","productVendors":"Use `QueryRoot.productVendors` instead.","products":"Use `QueryRoot.products`.","publicationCount":"Use `QueryRoot.publicationsCount` instead.","staffMembers":"Use `QueryRoot.staffMembers` instead.","storefrontUrl":"Use `url` instead."}}}, +"ShopAddress":{"o":{"f":{"address1":"String","address2":"String","city":"String","company":"String","coordinatesValidated":"Boolean!","country":"String","countryCode":"String","countryCodeV2":"CountryCode","firstName":"String","formatted":["[String!]!",{"withCompany":"Boolean="}],"formattedArea":"String","id":"ID!","lastName":"String","latitude":"Float","longitude":"Float","name":"String","phone":"String","province":"String","provinceCode":"String","zip":"String"},"t":["Node"],"d":{"countryCode":"Use `countryCodeV2` instead.","firstName":"Always null in this context.","lastName":"Always null in this context.","name":"Always null in this context."}}}, +"ShopAlert":{"o":{"f":{"action":"ShopAlertAction!","description":"String!"}}}, +"ShopAlertAction":{"o":{"f":{"title":"String!","url":"URL!"}}}, +"ShopBillingPreferences":{"o":{"f":{"currency":"CurrencyCode!"}}}, +"ShopBranding":{"e":["SHOPIFY_GOLD","SHOPIFY_PLUS","ROGERS","SHOPIFY"]}, +"ShopCustomerAccountsSetting":{"e":["REQUIRED","OPTIONAL","DISABLED"]}, +"ShopFeatures":{"o":{"f":{"avalaraAvatax":"Boolean!","branding":"ShopBranding!","bundles":"BundlesFeature!","buyerExperienceDepositEnabled":"Boolean!","captcha":"Boolean!","captchaExternalDomains":"Boolean!","cartTransform":"CartTransformFeature!","deliveryProfiles":"Boolean!","directConnectionCatalogAssignmentEnabled":"Boolean!","dynamicRemarketing":"Boolean!","eligibleForSubscriptionMigration":"Boolean!","eligibleForSubscriptions":"Boolean!","giftCards":"Boolean!","harmonizedSystemCode":"Boolean!","internationalDomains":"Boolean!","internationalPriceOverrides":"Boolean!","internationalPriceRules":"Boolean!","legacySubscriptionGatewayEnabled":"Boolean!","liveView":"Boolean!","marketDrivenShipping":"Boolean!","onboardingVisual":"Boolean!","paypalExpressSubscriptionGatewayStatus":"PaypalExpressSubscriptionsGatewayStatus!","reports":"Boolean!","sellsSubscriptions":"Boolean!","shopifyPlus":"Boolean!","showMetrics":"Boolean!","storefront":"Boolean!","subCountryMarketsEnabled":"Boolean!","unifiedMarkets":"Boolean!","usingShopifyBalance":"Boolean!"},"d":{"captchaExternalDomains":"No longer required for external domains","deliveryProfiles":"Delivery profiles are now 100% enabled across Shopify.","internationalDomains":"All shops have international domains through Shopify Markets.","internationalPriceOverrides":"Use the `markets` field on `EntitlementsType`.\nEach market entitlement has a `catalogs` field that indicates\nwhether the shop's markets have access to catalogs and price overrides.","internationalPriceRules":"Use the `markets` field on `EntitlementsType`.\nEach market entitlement has a `catalogs` field that indicates\nwhether the shop's markets have access to catalogs and price overrides.","onboardingVisual":"No longer supported.","shopifyPlus":"Use Shop.plan.shopifyPlus instead.","unifiedMarkets":"Unified Markets is enabled for all shops. Remove checks against this field."}}}, +"ShopLocale":{"o":{"f":{"locale":"String!","marketWebPresences":"[MarketWebPresence!]!","name":"String!","primary":"Boolean!","published":"Boolean!"}}}, +"ShopLocaleDisablePayload":{"o":{"f":{"locale":"String","userErrors":"[UserError!]!"}}}, +"ShopLocaleEnablePayload":{"o":{"f":{"shopLocale":"ShopLocale","userErrors":"[UserError!]!"}}}, +"ShopLocaleInput":{"i":{"marketWebPresenceIds":"[ID!]","published":"Boolean"}}, +"ShopLocaleUpdatePayload":{"o":{"f":{"shopLocale":"ShopLocale","userErrors":"[UserError!]!"}}}, +"ShopPayInstallmentsPaymentDetails":{"o":{"f":{"paymentMethodName":"String"},"t":["BasePaymentDetails"]}}, +"ShopPayPaymentRequest":{"o":{"f":{"discounts":"[ShopPayPaymentRequestDiscount!]","lineItems":"[ShopPayPaymentRequestLineItem!]!","presentmentCurrency":"CurrencyCode!","selectedDeliveryMethodType":"ShopPayPaymentRequestDeliveryMethodType!","shippingAddress":"ShopPayPaymentRequestContactField","shippingLines":"[ShopPayPaymentRequestShippingLine!]!","subtotal":"MoneyV2!","total":"MoneyV2!","totalShippingPrice":"ShopPayPaymentRequestTotalShippingPrice","totalTax":"MoneyV2"}}}, +"ShopPayPaymentRequestContactField":{"o":{"f":{"address1":"String!","address2":"String","city":"String!","companyName":"String","countryCode":"String!","email":"String","firstName":"String!","lastName":"String!","phone":"String","postalCode":"String","provinceCode":"String"}}}, +"ShopPayPaymentRequestDeliveryMethodType":{"e":["SHIPPING","PICKUP"]}, +"ShopPayPaymentRequestDiscount":{"o":{"f":{"amount":"MoneyV2!","label":"String!"}}}, +"ShopPayPaymentRequestImage":{"o":{"f":{"alt":"String","url":"String!"}}}, +"ShopPayPaymentRequestLineItem":{"o":{"f":{"finalItemPrice":"MoneyV2!","finalLinePrice":"MoneyV2!","image":"ShopPayPaymentRequestImage","itemDiscounts":"[ShopPayPaymentRequestDiscount!]","label":"String!","lineDiscounts":"[ShopPayPaymentRequestDiscount!]","originalItemPrice":"MoneyV2","originalLinePrice":"MoneyV2","quantity":"Int!","requiresShipping":"Boolean","sku":"String"}}}, +"ShopPayPaymentRequestReceipt":{"o":{"f":{"createdAt":"DateTime!","order":"Order","paymentRequest":"ShopPayPaymentRequest!","processingStatus":"ShopPayPaymentRequestReceiptProcessingStatus!","sourceIdentifier":"String!","token":"String!"}}}, +"ShopPayPaymentRequestReceiptConnection":{"o":{"f":{"edges":"[ShopPayPaymentRequestReceiptEdge!]!","nodes":"[ShopPayPaymentRequestReceipt!]!","pageInfo":"PageInfo!"}}}, +"ShopPayPaymentRequestReceiptEdge":{"o":{"f":{"cursor":"String!","node":"ShopPayPaymentRequestReceipt!"}}}, +"ShopPayPaymentRequestReceiptProcessingStatus":{"o":{"f":{"errorCode":"ShopPayPaymentRequestReceiptProcessingStatusErrorCode","message":"String","state":"ShopPayPaymentRequestReceiptProcessingStatusState!"}}}, +"ShopPayPaymentRequestReceiptProcessingStatusErrorCode":{"e":["INCORRECT_NUMBER","INVALID_NUMBER","INVALID_EXPIRY_DATE","INVALID_CVC","EXPIRED_CARD","INCORRECT_CVC","INCORRECT_ZIP","INCORRECT_ADDRESS","INCORRECT_PIN","AMOUNT_TOO_SMALL","CARD_DECLINED","PROCESSING_ERROR","CALL_ISSUER","THREE_D_SECURE_FAILED","FRAUD_SUSPECTED","PICK_UP_CARD","CONFIG_ERROR","TEST_MODE_LIVE_CARD","UNSUPPORTED_FEATURE","CVV_ATTEMPTS_EXCEEDED","GENERIC_ERROR","INVALID_COUNTRY","INVALID_AMOUNT","PAYMENT_METHOD_UNAVAILABLE"]}, +"ShopPayPaymentRequestReceiptProcessingStatusState":{"e":["READY","PROCESSING","FAILED","COMPLETED","ACTION_REQUIRED"]}, +"ShopPayPaymentRequestReceiptsSortKeys":{"e":["CREATED_AT","ID"]}, +"ShopPayPaymentRequestShippingLine":{"o":{"f":{"amount":"MoneyV2!","code":"String!","label":"String!"}}}, +"ShopPayPaymentRequestTotalShippingPrice":{"o":{"f":{"discounts":"[ShopPayPaymentRequestDiscount!]!","finalTotal":"MoneyV2!","originalTotal":"MoneyV2"}}}, +"ShopPlan":{"o":{"f":{"displayName":"String!","partnerDevelopment":"Boolean!","publicDisplayName":"String!","shopifyPlus":"Boolean!"},"d":{"displayName":"Use `publicDisplayName` instead."}}}, +"ShopPolicy":{"o":{"f":{"body":"HTML!","createdAt":"DateTime!","id":"ID!","title":"String!","translations":["[Translation!]!",{"locale":"String!","marketId":"ID"}],"type":"ShopPolicyType!","updatedAt":"DateTime!","url":"URL!"},"t":["HasPublishedTranslations","Node"]}}, +"ShopPolicyErrorCode":{"e":["TOO_BIG"]}, +"ShopPolicyInput":{"i":{"body":"String!","type":"ShopPolicyType!"}}, +"ShopPolicyType":{"e":["REFUND_POLICY","SHIPPING_POLICY","PRIVACY_POLICY","TERMS_OF_SERVICE","TERMS_OF_SALE","LEGAL_NOTICE","SUBSCRIPTION_POLICY","CONTACT_INFORMATION"]}, +"ShopPolicyUpdatePayload":{"o":{"f":{"shopPolicy":"ShopPolicy","userErrors":"[ShopPolicyUserError!]!"}}}, +"ShopPolicyUserError":{"o":{"f":{"code":"ShopPolicyErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ShopResourceFeedbackCreatePayload":{"o":{"f":{"feedback":"AppFeedback","userErrors":"[ShopResourceFeedbackCreateUserError!]!"}}}, +"ShopResourceFeedbackCreateUserError":{"o":{"f":{"code":"ShopResourceFeedbackCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ShopResourceFeedbackCreateUserErrorCode":{"e":["OUTDATED_FEEDBACK","FEEDBACK_DATE_IN_FUTURE","INVALID","BLANK","PRESENT","NOT_FOUND"]}, +"ShopResourceLimits":{"o":{"f":{"locationLimit":"Int!","maxProductOptions":"Int!","maxProductVariants":"Int!","redirectLimitReached":"Boolean!"}}}, +"ShopTagSort":{"e":["ALPHABETICAL","POPULAR"]}, +"ShopifyFunction":{"o":{"f":{"apiType":"String!","apiVersion":"String!","app":"App!","appBridge":"FunctionsAppBridge!","appKey":"String!","description":"String","handle":"String!","id":"String!","inputQuery":"String","title":"String!","useCreationUi":"Boolean!"}}}, +"ShopifyFunctionConnection":{"o":{"f":{"edges":"[ShopifyFunctionEdge!]!","nodes":"[ShopifyFunction!]!","pageInfo":"PageInfo!"}}}, +"ShopifyFunctionEdge":{"o":{"f":{"cursor":"String!","node":"ShopifyFunction!"}}}, +"ShopifyPaymentsAccount":{"o":{"f":{"accountOpenerName":"String","activated":"Boolean!","balance":"[MoneyV2!]!","balanceTransactions":["ShopifyPaymentsBalanceTransactionConnection!",{"after":"String","before":"String","first":"Int","hideTransfers":"Boolean=","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"BalanceTransactionSortKeys="}],"bankAccounts":["ShopifyPaymentsBankAccountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"chargeStatementDescriptor":"String","chargeStatementDescriptors":"ShopifyPaymentsChargeStatementDescriptor","country":"String!","defaultCurrency":"CurrencyCode!","disputes":["ShopifyPaymentsDisputeConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean="}],"id":"ID!","onboardable":"Boolean!","payoutSchedule":"ShopifyPaymentsPayoutSchedule!","payoutStatementDescriptor":"String","payouts":["ShopifyPaymentsPayoutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"PayoutSortKeys=","transactionType":"ShopifyPaymentsPayoutTransactionType"}]},"t":["Node"],"d":{"chargeStatementDescriptor":"Use `chargeStatementDescriptors` instead."}}}, +"ShopifyPaymentsAddressBasic":{"o":{"f":{"addressLine1":"String","addressLine2":"String","city":"String","country":"String","postalCode":"String","zone":"String"}}}, +"ShopifyPaymentsAdjustmentOrder":{"o":{"f":{"amount":"MoneyV2!","fees":"MoneyV2!","link":"URL!","name":"String!","net":"MoneyV2!","orderTransactionId":"BigInt!"}}}, +"ShopifyPaymentsAssociatedOrder":{"o":{"f":{"id":"ID!","name":"String!"}}}, +"ShopifyPaymentsBalanceTransaction":{"o":{"f":{"adjustmentReason":"String","adjustmentsOrders":"[ShopifyPaymentsAdjustmentOrder!]!","amount":"MoneyV2!","associatedOrder":"ShopifyPaymentsAssociatedOrder","associatedPayout":"ShopifyPaymentsBalanceTransactionAssociatedPayout!","fee":"MoneyV2!","id":"ID!","net":"MoneyV2!","sourceId":"BigInt","sourceOrderTransactionId":"BigInt","sourceType":"ShopifyPaymentsSourceType","test":"Boolean!","transactionDate":"DateTime!","type":"ShopifyPaymentsTransactionType!"},"t":["Node"]}}, +"ShopifyPaymentsBalanceTransactionAssociatedPayout":{"o":{"f":{"id":"ID","status":"ShopifyPaymentsBalanceTransactionPayoutStatus"}}}, +"ShopifyPaymentsBalanceTransactionConnection":{"o":{"f":{"edges":"[ShopifyPaymentsBalanceTransactionEdge!]!","nodes":"[ShopifyPaymentsBalanceTransaction!]!","pageInfo":"PageInfo!"}}}, +"ShopifyPaymentsBalanceTransactionEdge":{"o":{"f":{"cursor":"String!","node":"ShopifyPaymentsBalanceTransaction!"}}}, +"ShopifyPaymentsBalanceTransactionPayoutStatus":{"e":{"v":["SCHEDULED","IN_TRANSIT","PAID","FAILED","CANCELED","PENDING","ACTION_REQUIRED"],"d":{"IN_TRANSIT":"Use `SCHEDULED` instead."}}}, +"ShopifyPaymentsBankAccount":{"o":{"f":{"accountNumberLastDigits":"String!","bankName":"String","country":"CountryCode!","createdAt":"DateTime!","currency":"CurrencyCode!","id":"ID!","payouts":["ShopifyPaymentsPayoutConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","savedSearchId":"ID","sortKey":"PayoutSortKeys=","transactionType":"ShopifyPaymentsPayoutTransactionType"}],"status":"ShopifyPaymentsBankAccountStatus!"},"t":["Node"]}}, +"ShopifyPaymentsBankAccountConnection":{"o":{"f":{"edges":"[ShopifyPaymentsBankAccountEdge!]!","nodes":"[ShopifyPaymentsBankAccount!]!","pageInfo":"PageInfo!"}}}, +"ShopifyPaymentsBankAccountEdge":{"o":{"f":{"cursor":"String!","node":"ShopifyPaymentsBankAccount!"}}}, +"ShopifyPaymentsBankAccountStatus":{"e":["NEW","VALIDATED","VERIFIED","ERRORED"]}, +"ShopifyPaymentsBusinessType":{"e":["CORPORATION","GOVERNMENT","INCORPORATED_PARTNERSHIP","INDIVIDUAL","LLC","NON_PROFIT","NON_PROFIT_INCORPORATED","NON_PROFIT_UNINCORPORATED","NON_PROFIT_UNINCORPORATED_ASSOCIATION","NON_PROFIT_REGISTERED_CHARITY","PARTNERSHIP","PRIVATE_CORPORATION","PUBLIC_COMPANY","PUBLIC_CORPORATION","SOLE_PROP","UNINCORPORATED_PARTNERSHIP","PRIVATE_MULTI_MEMBER_LLC","PRIVATE_SINGLE_MEMBER_LLC","PRIVATE_UNINCORPORATED_ASSOCIATION","PRIVATE_PARTNERSHIP","PUBLIC_PARTNERSHIP","FREE_ZONE_ESTABLISHMENT","FREE_ZONE_LLC","SOLE_ESTABLISHMENT","NOT_SET"]}, +"ShopifyPaymentsChargeStatementDescriptor":{"n":{"f":{"default":"String","prefix":"String!"},"t":["ShopifyPaymentsDefaultChargeStatementDescriptor","ShopifyPaymentsJpChargeStatementDescriptor"]}}, +"ShopifyPaymentsDefaultChargeStatementDescriptor":{"o":{"f":{"default":"String","prefix":"String!"},"t":["ShopifyPaymentsChargeStatementDescriptor"]}}, +"ShopifyPaymentsDispute":{"o":{"f":{"amount":"MoneyV2!","disputeEvidence":"ShopifyPaymentsDisputeEvidence!","evidenceDueBy":"DateTime","evidenceSentOn":"DateTime","finalizedOn":"DateTime","id":"ID!","initiatedAt":"DateTime!","legacyResourceId":"UnsignedInt64!","order":"Order","reasonDetails":"ShopifyPaymentsDisputeReasonDetails!","status":"DisputeStatus!","type":"DisputeType!"},"t":["LegacyInteroperability","Node"]}}, +"ShopifyPaymentsDisputeConnection":{"o":{"f":{"edges":"[ShopifyPaymentsDisputeEdge!]!","nodes":"[ShopifyPaymentsDispute!]!","pageInfo":"PageInfo!"}}}, +"ShopifyPaymentsDisputeEdge":{"o":{"f":{"cursor":"String!","node":"ShopifyPaymentsDispute!"}}}, +"ShopifyPaymentsDisputeEvidence":{"o":{"f":{"accessActivityLog":"String","billingAddress":"MailingAddress","cancellationPolicyDisclosure":"String","cancellationPolicyFile":"ShopifyPaymentsDisputeFileUpload","cancellationRebuttal":"String","customerCommunicationFile":"ShopifyPaymentsDisputeFileUpload","customerEmailAddress":"String","customerFirstName":"String","customerLastName":"String","customerPurchaseIp":"String","dispute":"ShopifyPaymentsDispute!","disputeFileUploads":"[ShopifyPaymentsDisputeFileUpload!]!","fulfillments":"[ShopifyPaymentsDisputeFulfillment!]!","id":"ID!","productDescription":"String","refundPolicyDisclosure":"String","refundPolicyFile":"ShopifyPaymentsDisputeFileUpload","refundRefusalExplanation":"String","serviceDocumentationFile":"ShopifyPaymentsDisputeFileUpload","shippingAddress":"MailingAddress","shippingDocumentationFile":"ShopifyPaymentsDisputeFileUpload","submitted":"Boolean!","uncategorizedFile":"ShopifyPaymentsDisputeFileUpload","uncategorizedText":"String"},"t":["Node"]}}, +"ShopifyPaymentsDisputeEvidenceFileType":{"e":["CUSTOMER_COMMUNICATION_FILE","REFUND_POLICY_FILE","CANCELLATION_POLICY_FILE","UNCATEGORIZED_FILE","SHIPPING_DOCUMENTATION_FILE","SERVICE_DOCUMENTATION_FILE","RESPONSE_SUMMARY_FILE"]}, +"ShopifyPaymentsDisputeEvidenceUpdateInput":{"i":{"f":{"accessActivityLog":"String","cancellationPolicyDisclosure":"String","cancellationPolicyFile":"ShopifyPaymentsDisputeFileUploadUpdateInput","cancellationRebuttal":"String","customerCommunicationFile":"ShopifyPaymentsDisputeFileUploadUpdateInput","customerEmailAddress":"String","customerFirstName":"String","customerLastName":"String","refundPolicyDisclosure":"String","refundPolicyFile":"ShopifyPaymentsDisputeFileUploadUpdateInput","refundRefusalExplanation":"String","serviceDocumentationFile":"ShopifyPaymentsDisputeFileUploadUpdateInput","shippingAddress":"MailingAddressInput","shippingDocumentationFile":"ShopifyPaymentsDisputeFileUploadUpdateInput","submitEvidence":"Boolean=","uncategorizedFile":"ShopifyPaymentsDisputeFileUploadUpdateInput","uncategorizedText":"String"},"d":{"submitEvidence":"Dispute evidence can't be submitted through the API. Submissions go directly to the bank and are final, so merchants must confirm them in the Shopify admin."}}}, +"ShopifyPaymentsDisputeFileUpload":{"o":{"f":{"disputeEvidenceType":"ShopifyPaymentsDisputeEvidenceFileType","fileSize":"Int!","fileType":"String!","id":"ID!","originalFileName":"String","url":"URL!"},"t":["Node"]}}, +"ShopifyPaymentsDisputeFileUploadUpdateInput":{"i":{"destroy":"Boolean=","id":"ID!"}}, +"ShopifyPaymentsDisputeFulfillment":{"o":{"f":{"id":"ID!","shippingCarrier":"String","shippingDate":"Date","shippingTrackingNumber":"String"},"t":["Node"]}}, +"ShopifyPaymentsDisputeReason":{"e":["FRAUDULENT","GENERAL","UNRECOGNIZED","DUPLICATE","SUBSCRIPTION_CANCELLED","PRODUCT_UNACCEPTABLE","PRODUCT_NOT_RECEIVED","CREDIT_NOT_PROCESSED","INCORRECT_ACCOUNT_DETAILS","INSUFFICIENT_FUNDS","BANK_CANNOT_PROCESS","DEBIT_NOT_AUTHORIZED","CUSTOMER_INITIATED","NONCOMPLIANT"]}, +"ShopifyPaymentsDisputeReasonDetails":{"o":{"f":{"networkReasonCode":"String","reason":"ShopifyPaymentsDisputeReason!"}}}, +"ShopifyPaymentsExtendedAuthorization":{"o":{"f":{"extendedAuthorizationExpiresAt":"DateTime!","standardAuthorizationExpiresAt":"DateTime!"}}}, +"ShopifyPaymentsJpChargeStatementDescriptor":{"o":{"f":{"default":"String","kana":"String","kanji":"String","prefix":"String!"},"t":["ShopifyPaymentsChargeStatementDescriptor"],"d":{"kana":"This field is deprecated and will be removed in a future release.","kanji":"This field is deprecated and will be removed in a future release."}}}, +"ShopifyPaymentsMerchantCategoryCode":{"o":{"f":{"category":"String!","categoryLabel":"String!","code":"Int!","id":"Int!","subcategoryLabel":"String!"}}}, +"ShopifyPaymentsPayout":{"o":{"f":{"bankAccount":"ShopifyPaymentsBankAccount","businessEntity":"BusinessEntity!","externalTraceId":"String","gross":"MoneyV2!","id":"ID!","issuedAt":"DateTime!","legacyResourceId":"UnsignedInt64!","net":"MoneyV2!","status":"ShopifyPaymentsPayoutStatus!","summary":"ShopifyPaymentsPayoutSummary!","transactionType":"ShopifyPaymentsPayoutTransactionType!"},"t":["LegacyInteroperability","Node"],"d":{"bankAccount":"Use `destinationAccount` instead.","gross":"Use `net` instead."}}}, +"ShopifyPaymentsPayoutAlternateCurrencyCreatePayload":{"o":{"f":{"payout":"ShopifyPaymentsToolingProviderPayout","success":"Boolean","userErrors":"[ShopifyPaymentsPayoutAlternateCurrencyCreateUserError!]!"}}}, +"ShopifyPaymentsPayoutAlternateCurrencyCreateUserError":{"o":{"f":{"code":"ShopifyPaymentsPayoutAlternateCurrencyCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ShopifyPaymentsPayoutAlternateCurrencyCreateUserErrorCode":{"e":["MISSING_PROVIDER_ACCOUNT","ALTERNATE_CURRENCY_PAYOUT_FAILED_STRIPE_ERROR","UNKNOWN_CORE_ERROR","ALTERNATE_CURRENCY_PAYOUT_FAILED_NO_ELIGIBLE_BALANCE"]}, +"ShopifyPaymentsPayoutConnection":{"o":{"f":{"edges":"[ShopifyPaymentsPayoutEdge!]!","nodes":"[ShopifyPaymentsPayout!]!","pageInfo":"PageInfo!"}}}, +"ShopifyPaymentsPayoutEdge":{"o":{"f":{"cursor":"String!","node":"ShopifyPaymentsPayout!"}}}, +"ShopifyPaymentsPayoutInterval":{"e":["DAILY","WEEKLY","MONTHLY","MANUAL"]}, +"ShopifyPaymentsPayoutSchedule":{"o":{"f":{"interval":"ShopifyPaymentsPayoutInterval!","monthlyAnchor":"Int","weeklyAnchor":"DayOfTheWeek"}}}, +"ShopifyPaymentsPayoutStatus":{"e":{"v":["SCHEDULED","IN_TRANSIT","PAID","FAILED","CANCELED"],"d":{"IN_TRANSIT":"Use `SCHEDULED` instead."}}}, +"ShopifyPaymentsPayoutSummary":{"o":{"f":{"adjustmentsFee":"MoneyV2!","adjustmentsGross":"MoneyV2!","advanceFees":"MoneyV2!","advanceGross":"MoneyV2!","chargesFee":"MoneyV2!","chargesGross":"MoneyV2!","refundsFee":"MoneyV2!","refundsFeeGross":"MoneyV2!","reservedFundsFee":"MoneyV2!","reservedFundsGross":"MoneyV2!","retriedPayoutsFee":"MoneyV2!","retriedPayoutsGross":"MoneyV2!","usdcRebateCreditAmount":"MoneyV2!"}}}, +"ShopifyPaymentsPayoutTransactionType":{"e":["DEPOSIT","WITHDRAWAL"]}, +"ShopifyPaymentsRefundSet":{"o":{"f":{"acquirerReferenceNumber":"String"}}}, +"ShopifyPaymentsSourceType":{"e":["ADJUSTMENT_REVERSAL","CHARGE","REFUND","SYSTEM_ADJUSTMENT","DISPUTE","ADJUSTMENT","TRANSFER"]}, +"ShopifyPaymentsTaxIdentification":{"o":{"f":{"taxIdentificationType":"ShopifyPaymentsTaxIdentificationType!","value":"String!"}}}, +"ShopifyPaymentsTaxIdentificationType":{"e":["SSN_LAST4_DIGITS","FULL_SSN","EIN"]}, +"ShopifyPaymentsToolingProviderPayout":{"o":{"f":{"amount":"MoneyV2!","arrivalDate":"DateTime","createdAt":"DateTime","currency":"String!","remoteId":"String!"}}}, +"ShopifyPaymentsTransactionSet":{"o":{"f":{"extendedAuthorizationSet":"ShopifyPaymentsExtendedAuthorization","refundSet":"ShopifyPaymentsRefundSet"}}}, +"ShopifyPaymentsTransactionType":{"e":["ACH_BANK_FAILURE_DEBIT_FEE","ACH_BANK_FAILURE_DEBIT_REVERSAL_FEE","ADS_PUBLISHER_CREDIT","ADS_PUBLISHER_CREDIT_REVERSAL","CHARGEBACK_PROTECTION_CREDIT","CHARGEBACK_PROTECTION_CREDIT_REVERSAL","CHARGEBACK_PROTECTION_DEBIT","CHARGEBACK_PROTECTION_DEBIT_REVERSAL","COLLECTIONS_CREDIT","COLLECTIONS_CREDIT_REVERSAL","PROMOTION_CREDIT","PROMOTION_CREDIT_REVERSAL","ANOMALY_CREDIT","ANOMALY_CREDIT_REVERSAL","ANOMALY_DEBIT","ANOMALY_DEBIT_REVERSAL","VAT_REFUND_CREDIT","VAT_REFUND_CREDIT_REVERSAL","CHANNEL_CREDIT","CHANNEL_CREDIT_REVERSAL","CHANNEL_TRANSFER_CREDIT","CHANNEL_TRANSFER_CREDIT_REVERSAL","CHANNEL_TRANSFER_DEBIT","CHANNEL_TRANSFER_DEBIT_REVERSAL","CHANNEL_PROMOTION_CREDIT","CHANNEL_PROMOTION_CREDIT_REVERSAL","MARKETPLACE_FEE_CREDIT","MARKETPLACE_FEE_CREDIT_REVERSAL","MERCHANT_GOODWILL_CREDIT","MERCHANT_GOODWILL_CREDIT_REVERSAL","TAX_ADJUSTMENT_DEBIT","TAX_ADJUSTMENT_DEBIT_REVERSAL","TAX_ADJUSTMENT_CREDIT","TAX_ADJUSTMENT_CREDIT_REVERSAL","BILLING_DEBIT","BILLING_DEBIT_REVERSAL","SHOP_CASH_CREDIT","SHOP_CASH_CREDIT_REVERSAL","SHOP_CASH_BILLING_DEBIT","SHOP_CASH_BILLING_DEBIT_REVERSAL","SHOP_CASH_REFUND_DEBIT","SHOP_CASH_REFUND_DEBIT_REVERSAL","SHOP_CASH_CAMPAIGN_BILLING_DEBIT","SHOP_CASH_CAMPAIGN_BILLING_DEBIT_REVERSAL","SHOP_CASH_CAMPAIGN_BILLING_CREDIT","SHOP_CASH_CAMPAIGN_BILLING_CREDIT_REVERSAL","SELLER_PROTECTION_CREDIT","SELLER_PROTECTION_CREDIT_REVERSAL","SHOPIFY_COLLECTIVE_DEBIT","SHOPIFY_COLLECTIVE_DEBIT_REVERSAL","SHOPIFY_COLLECTIVE_CREDIT","SHOPIFY_COLLECTIVE_CREDIT_REVERSAL","LENDING_DEBIT","LENDING_DEBIT_REVERSAL","LENDING_CREDIT","LENDING_CREDIT_REVERSAL","LENDING_CAPITAL_REMITTANCE","LENDING_CAPITAL_REMITTANCE_REVERSAL","LENDING_CREDIT_REMITTANCE","LENDING_CREDIT_REMITTANCE_REVERSAL","LENDING_CAPITAL_REFUND","LENDING_CAPITAL_REFUND_REVERSAL","LENDING_CREDIT_REFUND","LENDING_CREDIT_REFUND_REVERSAL","BALANCE_TRANSFER_INBOUND","BALANCE_TRANSFER_OUTBOUND","MARKETS_PRO_CREDIT","CUSTOMS_DUTY_ADJUSTMENT","IMPORT_TAX_ADJUSTMENT","SHIPPING_LABEL_ADJUSTMENT","SHIPPING_LABEL_ADJUSTMENT_BASE","SHIPPING_LABEL_ADJUSTMENT_SURCHARGE","SHIPPING_RETURN_TO_ORIGIN_ADJUSTMENT","SHIPPING_OTHER_CARRIER_CHARGE_ADJUSTMENT","CHARGE_ADJUSTMENT","REFUND_ADJUSTMENT","CHARGEBACK_FEE","CHARGEBACK_FEE_REFUND","TRANSFER","TRANSFER_FAILURE","TRANSFER_CANCEL","RESERVED_FUNDS_WITHDRAWAL","RESERVED_FUNDS_REVERSAL","RISK_REVERSAL","RISK_WITHDRAWAL","REFERRAL_FEE","REFERRAL_FEE_TAX","MERCHANT_TO_MERCHANT_DEBIT","MERCHANT_TO_MERCHANT_DEBIT_REVERSAL","MERCHANT_TO_MERCHANT_CREDIT","MERCHANT_TO_MERCHANT_CREDIT_REVERSAL","SHOPIFY_SOURCE_DEBIT","SHOPIFY_SOURCE_DEBIT_REVERSAL","SHOPIFY_SOURCE_CREDIT","SHOPIFY_SOURCE_CREDIT_REVERSAL","CHARGE","REFUND","REFUND_FAILURE","APPLICATION_FEE_REFUND","ADJUSTMENT","DISPUTE_WITHDRAWAL","DISPUTE_REVERSAL","SHIPPING_LABEL","CUSTOMS_DUTY","IMPORT_TAX","CHARGEBACK_HOLD","CHARGEBACK_HOLD_RELEASE","CURRENCY_CONVERSION","RESERVED_FUNDS","STRIPE_FEE","TRANSFER_REFUND","ADVANCE","ADVANCE_FUNDING","IMPORT_TAX_REFUND"]}, +"ShopifyProtectEligibilityStatus":{"e":["PENDING","ELIGIBLE","NOT_ELIGIBLE"]}, +"ShopifyProtectOrderEligibility":{"o":{"f":{"status":"ShopifyProtectEligibilityStatus!"}}}, +"ShopifyProtectOrderSummary":{"o":{"f":{"eligibility":"ShopifyProtectOrderEligibility!","status":"ShopifyProtectStatus!"}}}, +"ShopifyProtectStatus":{"e":["PENDING","ACTIVE","INACTIVE","PROTECTED","NOT_PROTECTED"]}, +"ShopifyqlColumnOrigin":{"e":["UNSPECIFIED","REQUESTED","GENERATED"]}, +"ShopifyqlDynamicColumnMetadata":{"o":{"f":{"aggregatedBy":"[String!]!","comparisonReference":"String","originalColumnName":"String","type":"ShopifyqlDynamicColumnType!"}}}, +"ShopifyqlDynamicColumnType":{"e":["UNSPECIFIED","TOTALS","COMPARISON","PERCENT_CHANGE","COMPARISON_TOTALS","BENCHMARKS","BENCHMARK_TOTALS","CUMULATIVE","COMPARISON_CUMULATIVE","ATTRIBUTION","ATTRIBUTION_TOTALS","ATTRIBUTION_COMPARISON","ATTRIBUTION_PERCENT_CHANGE","ATTRIBUTION_COMPARISON_TOTALS","ATTRIBUTION_CUMULATIVE","ATTRIBUTION_COMPARISON_CUMULATIVE","ROLLOUT_RESULTS","PERCENT_OF_TOTAL"]}, +"ShopifyqlNullCellTranslation":{"o":{"f":{"columnName":"String!","displayText":"String!"}}}, +"ShopifyqlQueryResponse":{"o":{"f":{"analyticsTargets":"[AnalyticsTarget!]!","parseErrors":"[String!]!","parseWarnings":"[String!]!","tableData":"ShopifyqlTableData"}}}, +"ShopifyqlRowMetadata":{"o":{"f":{"nullCellTranslations":"[ShopifyqlNullCellTranslation!]!","rawResourceIds":"[[String!]!]!","topNRemainderColumnNames":"[String!]!"}}}, +"ShopifyqlTableData":{"o":{"f":{"columns":"[ShopifyqlTableDataColumn!]!","rowMetadata":"[ShopifyqlRowMetadata!]!","rows":"JSON!"}}}, +"ShopifyqlTableDataColumn":{"o":{"f":{"columnOrigin":"ShopifyqlColumnOrigin!","dataType":"ColumnDataType!","displayName":"String!","dynamicColumnMetadata":"ShopifyqlDynamicColumnMetadata","name":"String!","shortDisplayName":"String","subType":"ColumnDataType"}}}, +"StaffMember":{"o":{"f":{"accountType":"AccountType","active":"Boolean!","avatar":["Image!",{"fallback":"StaffMemberDefaultImage=","maxHeight":"Int","maxWidth":"Int"}],"email":"String!","exists":"Boolean!","firstName":"String","id":"ID!","initials":"[String!]","isShopOwner":"Boolean!","lastName":"String","locale":"String!","name":"String!","phone":"String","privateData":"StaffMemberPrivateData!"},"t":["Node"],"d":{"avatar(maxHeight)":"Use `maxHeight` argument on `image` instead.","avatar(maxWidth)":"Use `maxWidth` on argument `image` instead."}}}, +"StaffMemberConnection":{"o":{"f":{"edges":"[StaffMemberEdge!]!","nodes":"[StaffMember!]!","pageInfo":"PageInfo!"}}}, +"StaffMemberDefaultImage":{"e":["DEFAULT","TRANSPARENT","NOT_FOUND"]}, +"StaffMemberEdge":{"o":{"f":{"cursor":"String!","node":"StaffMember!"}}}, +"StaffMemberPermission":{"e":{"v":["APPLICATIONS","CHANNELS","CREATE_AND_EDIT_CUSTOMERS","CREATE_AND_EDIT_GIFT_CARDS","CUSTOMERS","DASHBOARD","DEACTIVATE_GIFT_CARDS","DELETE_CUSTOMERS","DOMAINS","DRAFT_ORDERS","EDIT_ORDERS","ERASE_CUSTOMER_DATA","EXPORT_CUSTOMERS","EXPORT_GIFT_CARDS","FULL","GIFT_CARDS","LINKS","LOCATIONS","VIEW_MARKETS","CREATE_AND_EDIT_MARKETS","DELETE_MARKETS","MARKETING","MARKETING_SECTION","MERGE_CUSTOMERS","ORDERS","OVERVIEWS","PAGES","PAY_ORDERS_BY_VAULTED_CARD","PREFERENCES","PRODUCTS","REPORTS","REQUEST_CUSTOMER_DATA","THEMES","TRANSLATIONS"],"d":{"FULL":"Use the list of the staff member's explicit permissions returned in the `StaffMember.permissions.userPermissions` field instead of `full` permission.","TRANSLATIONS":"Unused."}}}, +"StaffMemberPrivateData":{"o":{"f":{"accountSettingsUrl":"URL!","createdAt":"DateTime!","permissions":"[StaffMemberPermission!]!"},"d":{"permissions":"There's no alternative field to use instead."}}}, +"StaffMembersSortKeys":{"e":["EMAIL","FIRST_NAME","ID","LAST_NAME"]}, +"StageImageInput":{"i":{"filename":"String!","httpMethod":"StagedUploadHttpMethodType=","mimeType":"String!","resource":"StagedUploadTargetGenerateUploadResource!"}}, +"StagedMediaUploadTarget":{"o":{"f":{"parameters":"[StagedUploadParameter!]!","resourceUrl":"URL","url":"URL"}}}, +"StagedUploadHttpMethodType":{"e":["POST","PUT"]}, +"StagedUploadInput":{"i":{"fileSize":"UnsignedInt64","filename":"String!","httpMethod":"StagedUploadHttpMethodType=","mimeType":"String!","resource":"StagedUploadTargetGenerateUploadResource!"}}, +"StagedUploadParameter":{"o":{"f":{"name":"String!","value":"String!"}}}, +"StagedUploadTarget":{"o":{"f":{"parameters":"[ImageUploadParameter!]!","url":"String!"}}}, +"StagedUploadTargetGenerateInput":{"i":{"fileSize":"UnsignedInt64","filename":"String!","httpMethod":"StagedUploadHttpMethodType=","mimeType":"String!","resource":"StagedUploadTargetGenerateUploadResource!"}}, +"StagedUploadTargetGeneratePayload":{"o":{"f":{"parameters":"[MutationsStagedUploadTargetGenerateUploadParameter!]!","url":"String!","userErrors":"[UserError!]!"}}}, +"StagedUploadTargetGenerateUploadResource":{"e":{"v":["COLLECTION_IMAGE","FILE","IMAGE","MODEL_3D","PRODUCT_IMAGE","SHOP_IMAGE","VIDEO","BULK_MUTATION_VARIABLES","RETURN_LABEL","URL_REDIRECT_IMPORT","DISPUTE_FILE_UPLOAD"],"d":{"PRODUCT_IMAGE":"Use IMAGE instead. This resource type will be removed in a future version."}}}, +"StagedUploadTargetsGeneratePayload":{"o":{"f":{"urls":"[StagedUploadTarget!]","userErrors":"[UserError!]!"}}}, +"StagedUploadsCreatePayload":{"o":{"f":{"stagedTargets":"[StagedMediaUploadTarget!]","userErrors":"[UserError!]!"}}}, +"StandardMetafieldDefinitionAccessInput":{"i":{"admin":"MetafieldAdminAccessInput","customerAccount":"MetafieldCustomerAccountAccessInput","storefront":"MetafieldStorefrontAccessInput"}}, +"StandardMetafieldDefinitionEnablePayload":{"o":{"f":{"createdDefinition":"MetafieldDefinition","userErrors":"[StandardMetafieldDefinitionEnableUserError!]!"}}}, +"StandardMetafieldDefinitionEnableUserError":{"o":{"f":{"code":"StandardMetafieldDefinitionEnableUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"StandardMetafieldDefinitionEnableUserErrorCode":{"e":["INVALID","TAKEN","TEMPLATE_NOT_FOUND","LIMIT_EXCEEDED","UNSTRUCTURED_ALREADY_EXISTS","TYPE_NOT_ALLOWED_FOR_CONDITIONS","INVALID_CAPABILITY","CAPABILITY_CANNOT_BE_DISABLED","OWNER_TYPE_LIMIT_EXCEEDED_FOR_USE_AS_ADMIN_FILTERS","INVALID_STANDARD_METAOBJECT","UNSUPPORTED_PINNING","ADMIN_ACCESS_INPUT_NOT_ALLOWED","INVALID_INPUT_COMBINATION"]}, +"StandardMetafieldDefinitionTemplate":{"o":{"f":{"description":"String","id":"ID!","key":"String!","name":"String!","namespace":"String!","ownerTypes":"[MetafieldOwnerType!]!","type":"MetafieldDefinitionType!","validations":"[MetafieldDefinitionValidation!]!","visibleToStorefrontApi":"Boolean!"},"t":["Node"]}}, +"StandardMetafieldDefinitionTemplateConnection":{"o":{"f":{"edges":"[StandardMetafieldDefinitionTemplateEdge!]!","nodes":"[StandardMetafieldDefinitionTemplate!]!","pageInfo":"PageInfo!"}}}, +"StandardMetafieldDefinitionTemplateEdge":{"o":{"f":{"cursor":"String!","node":"StandardMetafieldDefinitionTemplate!"}}}, +"StandardMetaobjectCapabilityTemplate":{"o":{"f":{"capabilityType":"MetaobjectCapabilityType!"}}}, +"StandardMetaobjectDefinitionEnablePayload":{"o":{"f":{"metaobjectDefinition":"MetaobjectDefinition","userErrors":"[MetaobjectUserError!]!"}}}, +"StandardMetaobjectDefinitionFieldTemplate":{"o":{"f":{"description":"String","key":"String!","name":"String!","required":"Boolean!","type":"MetafieldDefinitionType!","validations":"[MetafieldDefinitionValidation!]!","visibleToStorefrontApi":"Boolean!"},"d":{"visibleToStorefrontApi":"Access control at the metaobject field definition level is deprecated and will be removed in 2027-01. Use the access field on the definition instead."}}}, +"StandardMetaobjectDefinitionTemplate":{"o":{"f":{"access":"MetaobjectAccess!","description":"String","displayNameKey":"String","enabledCapabilities":"[StandardMetaobjectCapabilityTemplate!]!","fieldDefinitions":"[StandardMetaobjectDefinitionFieldTemplate!]!","name":"String!","type":"String!"}}}, +"StandardizedProductType":{"o":{"f":{"productTaxonomyNode":"ProductTaxonomyNode"}}}, +"StoreCreditAccount":{"o":{"f":{"balance":"MoneyV2!","id":"ID!","owner":"HasStoreCreditAccounts!","transactions":["StoreCreditAccountTransactionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"TransactionSortKeys="}]},"t":["Node"]}}, +"StoreCreditAccountConnection":{"o":{"f":{"edges":"[StoreCreditAccountEdge!]!","nodes":"[StoreCreditAccount!]!","pageInfo":"PageInfo!"}}}, +"StoreCreditAccountCreditInput":{"i":{"creditAmount":"MoneyInput!","expiresAt":"DateTime","notify":"Boolean="}}, +"StoreCreditAccountCreditPayload":{"o":{"f":{"storeCreditAccountTransaction":"StoreCreditAccountCreditTransaction","userErrors":"[StoreCreditAccountCreditUserError!]!"}}}, +"StoreCreditAccountCreditTransaction":{"o":{"f":{"account":"StoreCreditAccount!","amount":"MoneyV2!","balanceAfterTransaction":"MoneyV2!","createdAt":"DateTime!","event":"StoreCreditSystemEvent!","expiresAt":"DateTime","id":"ID!","origin":"StoreCreditAccountTransactionOrigin","remainingAmount":"MoneyV2!"},"t":["Node","StoreCreditAccountTransaction"]}}, +"StoreCreditAccountCreditUserError":{"o":{"f":{"code":"StoreCreditAccountCreditUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"StoreCreditAccountCreditUserErrorCode":{"e":["ACCOUNT_NOT_FOUND","OWNER_NOT_FOUND","NEGATIVE_OR_ZERO_AMOUNT","MISMATCHING_CURRENCY","EXPIRES_AT_IN_PAST","CREDIT_LIMIT_EXCEEDED","UNSUPPORTED_CURRENCY"]}, +"StoreCreditAccountDebitInput":{"i":{"debitAmount":"MoneyInput!"}}, +"StoreCreditAccountDebitPayload":{"o":{"f":{"storeCreditAccountTransaction":"StoreCreditAccountDebitTransaction","userErrors":"[StoreCreditAccountDebitUserError!]!"}}}, +"StoreCreditAccountDebitRevertTransaction":{"o":{"f":{"account":"StoreCreditAccount!","amount":"MoneyV2!","balanceAfterTransaction":"MoneyV2!","createdAt":"DateTime!","debitTransaction":"StoreCreditAccountDebitTransaction!","event":"StoreCreditSystemEvent!","id":"ID!","origin":"StoreCreditAccountTransactionOrigin"},"t":["Node","StoreCreditAccountTransaction"]}}, +"StoreCreditAccountDebitTransaction":{"o":{"f":{"account":"StoreCreditAccount!","amount":"MoneyV2!","balanceAfterTransaction":"MoneyV2!","createdAt":"DateTime!","event":"StoreCreditSystemEvent!","id":"ID!","origin":"StoreCreditAccountTransactionOrigin"},"t":["Node","StoreCreditAccountTransaction"]}}, +"StoreCreditAccountDebitUserError":{"o":{"f":{"code":"StoreCreditAccountDebitUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"StoreCreditAccountDebitUserErrorCode":{"e":["ACCOUNT_NOT_FOUND","NEGATIVE_OR_ZERO_AMOUNT","INSUFFICIENT_FUNDS","MISMATCHING_CURRENCY"]}, +"StoreCreditAccountEdge":{"o":{"f":{"cursor":"String!","node":"StoreCreditAccount!"}}}, +"StoreCreditAccountExpirationTransaction":{"o":{"f":{"account":"StoreCreditAccount!","amount":"MoneyV2!","balanceAfterTransaction":"MoneyV2!","createdAt":"DateTime!","creditTransaction":"StoreCreditAccountCreditTransaction!","event":"StoreCreditSystemEvent!","origin":"StoreCreditAccountTransactionOrigin"},"t":["StoreCreditAccountTransaction"]}}, +"StoreCreditAccountTransaction":{"n":{"f":{"account":"StoreCreditAccount!","amount":"MoneyV2!","balanceAfterTransaction":"MoneyV2!","createdAt":"DateTime!","event":"StoreCreditSystemEvent!","origin":"StoreCreditAccountTransactionOrigin"},"t":["StoreCreditAccountCreditTransaction","StoreCreditAccountDebitRevertTransaction","StoreCreditAccountDebitTransaction","StoreCreditAccountExpirationTransaction"]}}, +"StoreCreditAccountTransactionConnection":{"o":{"f":{"edges":"[StoreCreditAccountTransactionEdge!]!","nodes":"[StoreCreditAccountTransaction!]!","pageInfo":"PageInfo!"}}}, +"StoreCreditAccountTransactionEdge":{"o":{"f":{"cursor":"String!","node":"StoreCreditAccountTransaction!"}}}, +"StoreCreditAccountTransactionOrigin":{"u":["OrderTransaction"]}, +"StoreCreditConfiguration":{"o":{"f":{"storeCreditEnabled":"Boolean!"}}}, +"StoreCreditRefundInput":{"i":{"amount":"MoneyInput!","expiresAt":"DateTime"}}, +"StoreCreditSystemEvent":{"e":["ADJUSTMENT","ORDER_PAYMENT","ORDER_REFUND","PAYMENT_FAILURE","PAYMENT_RETURNED","ORDER_CANCELLATION","TAX_FINALIZATION","RECURRING_PAYMENT"]}, +"StorefrontAccessToken":{"o":{"f":{"accessScopes":"[AccessScope!]!","accessToken":"String!","createdAt":"DateTime!","id":"ID!","title":"String!","updatedAt":"DateTime!"},"t":["Node"]}}, +"StorefrontAccessTokenConnection":{"o":{"f":{"edges":"[StorefrontAccessTokenEdge!]!","nodes":"[StorefrontAccessToken!]!","pageInfo":"PageInfo!"}}}, +"StorefrontAccessTokenCreatePayload":{"o":{"f":{"shop":"Shop!","storefrontAccessToken":"StorefrontAccessToken","userErrors":"[UserError!]!"}}}, +"StorefrontAccessTokenDeleteInput":{"i":{"id":"ID!"}}, +"StorefrontAccessTokenDeletePayload":{"o":{"f":{"deletedStorefrontAccessTokenId":"ID","userErrors":"[UserError!]!"}}}, +"StorefrontAccessTokenEdge":{"o":{"f":{"cursor":"String!","node":"StorefrontAccessToken!"}}}, +"StorefrontAccessTokenInput":{"i":{"title":"String!"}}, +"StorefrontID":"s", +"String":"s", +"StringConnection":{"o":{"f":{"edges":"[StringEdge!]!","nodes":"[String!]!","pageInfo":"PageInfo!"}}}, +"StringEdge":{"o":{"f":{"cursor":"String!","node":"String!"}}}, +"SubCollectionIneligibleReason":{"e":["INVALID_COLLECTION_REFERENCE","SELF_REFERENCE","CHAIN_REFERENCE"]}, +"SubscriptionActor":{"e":["CUSTOMER","MERCHANT","PARTNER"]}, +"SubscriptionAppliedCodeDiscount":{"o":{"f":{"id":"ID!","redeemCode":"String!","rejectionReason":"SubscriptionDiscountRejectionReason"}}}, +"SubscriptionAtomicLineInput":{"i":{"discounts":"[SubscriptionAtomicManualDiscountInput!]","line":"SubscriptionLineInput!"}}, +"SubscriptionAtomicManualDiscountInput":{"i":{"recurringCycleLimit":"Int","title":"String","value":"SubscriptionManualDiscountValueInput"}}, +"SubscriptionBillingAttempt":{"o":{"f":{"completedAt":"DateTime","createdAt":"DateTime!","errorCode":"SubscriptionBillingAttemptErrorCode","errorMessage":"String","id":"ID!","idempotencyKey":"String!","nextActionUrl":"URL","order":"Order","originTime":"DateTime","paymentGroupId":"String","paymentSessionId":"String","processingError":"SubscriptionBillingAttemptProcessingError","ready":"Boolean!","respectInventoryPolicy":"Boolean!","state":"SubscriptionBillingAttemptState!","subscriptionContract":"SubscriptionContract!","transactions":["OrderTransactionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["Node"],"d":{"errorCode":"Use `state` instead.","errorMessage":"Use `state` instead.","nextActionUrl":"Use `state` instead.","order":"Use `state` instead.","processingError":"Use `state` instead.","ready":"Use `state` instead."}}}, +"SubscriptionBillingAttemptAction":{"u":["SubscriptionBillingAttemptPaymentChallenge"]}, +"SubscriptionBillingAttemptActionRequiredState":{"o":{"f":{"action":"SubscriptionBillingAttemptAction!"}}}, +"SubscriptionBillingAttemptConnection":{"o":{"f":{"edges":"[SubscriptionBillingAttemptEdge!]!","nodes":"[SubscriptionBillingAttempt!]!","pageInfo":"PageInfo!"}}}, +"SubscriptionBillingAttemptCreatePayload":{"o":{"f":{"subscriptionBillingAttempt":"SubscriptionBillingAttempt","userErrors":"[BillingAttemptUserError!]!"}}}, +"SubscriptionBillingAttemptEdge":{"o":{"f":{"cursor":"String!","node":"SubscriptionBillingAttempt!"}}}, +"SubscriptionBillingAttemptError":{"u":["SubscriptionBillingAttemptGeneralError","SubscriptionBillingAttemptInventoryError","SubscriptionBillingAttemptPaymentError","SubscriptionBillingAttemptUnexpectedError"]}, +"SubscriptionBillingAttemptErrorCode":{"e":["PAYMENT_METHOD_NOT_FOUND","PAYMENT_PROVIDER_IS_NOT_ENABLED","INVALID_PAYMENT_METHOD","UNEXPECTED_ERROR","EXPIRED_PAYMENT_METHOD","PAYMENT_METHOD_DECLINED","AUTHENTICATION_ERROR","TEST_MODE","BUYER_CANCELED_PAYMENT_METHOD","CUSTOMER_NOT_FOUND","CUSTOMER_INVALID","INVALID_SHIPPING_ADDRESS","INVALID_CUSTOMER_BILLING_AGREEMENT","INVOICE_ALREADY_PAID","PAYMENT_METHOD_INCOMPATIBLE_WITH_GATEWAY_CONFIG","AMOUNT_TOO_SMALL","AMOUNT_TOO_LARGE","MERCHANT_ACCOUNT_ERROR","INVENTORY_ALLOCATIONS_NOT_FOUND","INSUFFICIENT_INVENTORY","TRANSIENT_ERROR","INSUFFICIENT_FUNDS","PURCHASE_TYPE_NOT_SUPPORTED","PAYPAL_ERROR_GENERAL","CARD_NUMBER_INCORRECT","FRAUD_SUSPECTED","NON_TEST_ORDER_LIMIT_REACHED","FREE_GIFT_CARD_NOT_ALLOWED","PAYMENT_METHOD_NOT_SPECIFIED","INVALID_BILLING_ADDRESS","AUTHENTICATION_FAILED","AUTHENTICATION_REQUIRED","CALL_ISSUER","CARD_DECLINED","CONFIRMATION_REJECTED","DO_NOT_HONOR","MERCHANT_RULE","OFF_SESSION_REJECTED","RETRY_DECLINED","TRANSACTION_LIMIT_EXCEEDED","INCORRECT_ZIP","INVALID_AMOUNT","INVALID_CURRENCY","INVALID_CVC","INVALID_NUMBER","PAYMENT_METHOD_UNSUPPORTED","INCORRECT_ADDRESS","INCORRECT_CVC","INCORRECT_NUMBER","INCORRECT_PIN","EXPIRED_CARD","INVALID_EXPIRY_DATE","EXPIRED_BUYER_ACTION","PROCESSING_ERROR","PAYMENT_PROVIDER_ERROR","GENERIC_ERROR","CANCELLED_PAYMENT","INVALID_PURCHASE_TYPE","INVALID_REQUEST"]}, +"SubscriptionBillingAttemptFailedState":{"o":{"f":{"error":"SubscriptionBillingAttemptError!"}}}, +"SubscriptionBillingAttemptGeneralError":{"o":{"f":{"code":"SubscriptionBillingAttemptGeneralErrorCode!"}}}, +"SubscriptionBillingAttemptGeneralErrorCode":{"e":["NON_TEST_ORDER_LIMIT_REACHED","FREE_GIFT_CARD_NOT_ALLOWED","CUSTOMER_NOT_FOUND","CUSTOMER_INVALID","INVALID_BILLING_ADDRESS","MERCHANT_ACCOUNT_ERROR","PAYMENT_METHOD_NOT_FOUND","PAYMENT_METHOD_NOT_SPECIFIED","PAYMENT_METHOD_INCOMPATIBLE_WITH_GATEWAY_CONFIG","PAYMENT_PROVIDER_IS_NOT_ENABLED"]}, +"SubscriptionBillingAttemptGenericError":{"o":{"f":{"code":"SubscriptionBillingAttemptErrorCode!","message":"String!"},"t":["SubscriptionBillingAttemptProcessingError"]}}, +"SubscriptionBillingAttemptInput":{"i":{"actor":"SubscriptionActor","billingCycleSelector":"SubscriptionBillingCycleSelector","idempotencyKey":"String!","inventoryPolicy":"SubscriptionBillingAttemptInventoryPolicy=","originTime":"DateTime","paymentProcessingPolicy":"SubscriptionBillingAttemptPaymentProcessingPolicy="}}, +"SubscriptionBillingAttemptInsufficientStockProductVariantsError":{"o":{"f":{"code":"SubscriptionBillingAttemptErrorCode!","insufficientStockProductVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"message":"String!"},"t":["SubscriptionBillingAttemptProcessingError"]}}, +"SubscriptionBillingAttemptInventoryError":{"o":{"f":{"code":"SubscriptionBillingAttemptInventoryErrorCode!","insufficientStockProductVariants":["ProductVariantConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"SubscriptionBillingAttemptInventoryErrorCode":{"e":["INSUFFICIENT_INVENTORY","INVENTORY_ALLOCATIONS_NOT_FOUND"]}, +"SubscriptionBillingAttemptInventoryPolicy":{"e":["PRODUCT_VARIANT_INVENTORY_POLICY","ALLOW_OVERSELLING"]}, +"SubscriptionBillingAttemptOutOfStockProductVariantsError":{"o":{"f":{"code":"SubscriptionBillingAttemptErrorCode!","message":"String!","outOfStockProductVariants":["ProductVariantConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]},"t":["SubscriptionBillingAttemptProcessingError"],"d":{"outOfStockProductVariants":"Use `subscriptionBillingAttemptInsufficientStockProductVariantsError` type instead."}}}, +"SubscriptionBillingAttemptPaymentChallenge":{"o":{"f":{"nextActionUrl":"URL!","status":"SubscriptionBillingAttemptPaymentChallengeStatus!"}}}, +"SubscriptionBillingAttemptPaymentChallengeStatus":{"e":["OFF_SESSION_REJECTED","ON_SESSION_CHALLENGED"]}, +"SubscriptionBillingAttemptPaymentError":{"o":{"f":{"code":"SubscriptionBillingAttemptPaymentErrorCode!"}}}, +"SubscriptionBillingAttemptPaymentErrorCode":{"e":["PAYMENT_METHOD_DECLINED","EXPIRED_PAYMENT_METHOD","INSUFFICIENT_FUNDS","AUTHENTICATION_ERROR","INVALID_PAYMENT_METHOD","BUYER_CANCELED_PAYMENT_METHOD","INVALID_CUSTOMER_BILLING_AGREEMENT","AMOUNT_TOO_SMALL","AMOUNT_TOO_LARGE","CARD_NUMBER_INCORRECT","FRAUD_SUSPECTED","INVOICE_ALREADY_PAID","TEST_MODE","PAYPAL_ERROR_GENERAL","INVALID_SHIPPING_ADDRESS","TRANSIENT_ERROR","PURCHASE_TYPE_NOT_SUPPORTED","AUTHENTICATION_FAILED","AUTHENTICATION_REQUIRED","CALL_ISSUER","CARD_DECLINED","CONFIRMATION_REJECTED","DO_NOT_HONOR","MERCHANT_RULE","OFF_SESSION_REJECTED","RETRY_DECLINED","TRANSACTION_LIMIT_EXCEEDED","INCORRECT_ZIP","INVALID_AMOUNT","INVALID_CURRENCY","INVALID_CVC","INVALID_NUMBER","PAYMENT_METHOD_UNSUPPORTED","PAYMENT_PROVIDER_ERROR","INCORRECT_ADDRESS","INCORRECT_CVC","INCORRECT_NUMBER","INCORRECT_PIN","EXPIRED_CARD","INVALID_EXPIRY_DATE","EXPIRED_BUYER_ACTION","PROCESSING_ERROR","GENERIC_ERROR","CANCELLED_PAYMENT","INVALID_PURCHASE_TYPE","INVALID_REQUEST"]}, +"SubscriptionBillingAttemptPaymentProcessingPolicy":{"e":["FAIL_UNLESS_VALID_PAYMENT_METHOD","SKIP_PAYMENT_AND_CREATE_UNPAID_ORDER"]}, +"SubscriptionBillingAttemptPendingState":{"o":{"f":{"processing":"Boolean!"}}}, +"SubscriptionBillingAttemptProcessingError":{"n":{"f":{"code":"SubscriptionBillingAttemptErrorCode!","message":"String!"},"t":["SubscriptionBillingAttemptGenericError","SubscriptionBillingAttemptInsufficientStockProductVariantsError","SubscriptionBillingAttemptOutOfStockProductVariantsError"]}}, +"SubscriptionBillingAttemptState":{"u":["SubscriptionBillingAttemptActionRequiredState","SubscriptionBillingAttemptFailedState","SubscriptionBillingAttemptPendingState","SubscriptionBillingAttemptSuccessState"]}, +"SubscriptionBillingAttemptSuccessState":{"o":{"f":{"order":"Order"}}}, +"SubscriptionBillingAttemptUnexpectedError":{"o":{"f":{"message":"String!"}}}, +"SubscriptionBillingAttemptsSortKeys":{"e":["CREATED_AT","ID"]}, +"SubscriptionBillingCycle":{"o":{"f":{"billingAttemptExpectedDate":"DateTime!","billingAttempts":["SubscriptionBillingAttemptConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"cycleEndAt":"DateTime!","cycleIndex":"Int!","cycleStartAt":"DateTime!","edited":"Boolean!","editedContract":"SubscriptionBillingCycleEditedContract","skipped":"Boolean!","sourceContract":"SubscriptionContract!","status":"SubscriptionBillingCycleBillingCycleStatus!"}}}, +"SubscriptionBillingCycleBillingAttemptStatus":{"e":["HAS_ATTEMPT","NO_ATTEMPT","ANY"]}, +"SubscriptionBillingCycleBillingCycleStatus":{"e":["BILLED","UNBILLED"]}, +"SubscriptionBillingCycleBulkChargePayload":{"o":{"f":{"job":"Job","userErrors":"[SubscriptionBillingCycleBulkUserError!]!"}}}, +"SubscriptionBillingCycleBulkFilters":{"i":{"billingAttemptStatus":"SubscriptionBillingCycleBillingAttemptStatus=","billingCycleStatus":"[SubscriptionBillingCycleBillingCycleStatus!]","contractStatus":"[SubscriptionContractSubscriptionStatus!]"}}, +"SubscriptionBillingCycleBulkSearchPayload":{"o":{"f":{"job":"Job","userErrors":"[SubscriptionBillingCycleBulkUserError!]!"}}}, +"SubscriptionBillingCycleBulkUserError":{"o":{"f":{"code":"SubscriptionBillingCycleBulkUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionBillingCycleBulkUserErrorCode":{"e":["INVALID","BLANK","END_DATE_IN_THE_FUTURE","INVALID_DATE_RANGE","START_DATE_BEFORE_END_DATE"]}, +"SubscriptionBillingCycleChargePayload":{"o":{"f":{"subscriptionBillingAttempt":"SubscriptionBillingAttempt","userErrors":"[BillingAttemptUserError!]!"}}}, +"SubscriptionBillingCycleConnection":{"o":{"f":{"edges":"[SubscriptionBillingCycleEdge!]!","nodes":"[SubscriptionBillingCycle!]!","pageInfo":"PageInfo!"}}}, +"SubscriptionBillingCycleContractDraftCommitPayload":{"o":{"f":{"contract":"SubscriptionBillingCycleEditedContract","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionBillingCycleContractDraftConcatenatePayload":{"o":{"f":{"draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionBillingCycleContractEditCalculatePayload":{"o":{"f":{"subscriptionContractCalculation":"SubscriptionContractCalculation","userErrors":"[SubscriptionBillingCycleContractEditCalculateUserError!]!"}}}, +"SubscriptionBillingCycleContractEditCalculateUserError":{"o":{"f":{"code":"SubscriptionBillingCycleContractEditCalculateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionBillingCycleContractEditCalculateUserErrorCode":{"e":["INVALID"]}, +"SubscriptionBillingCycleContractEditPayload":{"o":{"f":{"draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionBillingCycleEdge":{"o":{"f":{"cursor":"String!","node":"SubscriptionBillingCycle!"}}}, +"SubscriptionBillingCycleEditDeletePayload":{"o":{"f":{"billingCycles":"[SubscriptionBillingCycle!]","userErrors":"[SubscriptionBillingCycleUserError!]!"}}}, +"SubscriptionBillingCycleEditedContract":{"o":{"f":{"app":"App","appAdminUrl":"URL","billingCycles":["SubscriptionBillingCycleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"SubscriptionBillingCyclesSortKeys="}],"createdAt":"DateTime!","currencyCode":"CurrencyCode!","customAttributes":"[Attribute!]!","customer":"Customer","customerPaymentMethod":["CustomerPaymentMethod",{"showRevoked":"Boolean="}],"deliveryMethod":"SubscriptionDeliveryMethod","deliveryPrice":"MoneyV2!","discounts":["SubscriptionManualDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"groupedLines":["SubscriptionGroupedLineConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"latestCommittedProjectedOrderTotals":"SubscriptionContractCalculationProjectedOrderTotals","lineCount":"Int!","lines":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"linesCount":"Count","note":"String","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"updatedAt":"DateTime!"},"t":["SubscriptionContractBase"],"d":{"lineCount":"Use `linesCount` instead."}}}, +"SubscriptionBillingCycleEditsDeletePayload":{"o":{"f":{"billingCycles":"[SubscriptionBillingCycle!]","userErrors":"[SubscriptionBillingCycleUserError!]!"}}}, +"SubscriptionBillingCycleErrorCode":{"e":["INVALID","CYCLE_NOT_FOUND","NO_CYCLE_EDITS","INVALID_CYCLE_INDEX","INVALID_DATE","EMPTY_BILLING_CYCLE_EDIT_SCHEDULE_INPUT","BILLING_DATE_SET_ON_SKIPPED","OUT_OF_BOUNDS","UPCOMING_CYCLE_LIMIT_EXCEEDED","CYCLE_INDEX_OUT_OF_RANGE","CYCLE_START_DATE_OUT_OF_RANGE","INCOMPLETE_BILLING_ATTEMPTS"]}, +"SubscriptionBillingCycleInput":{"i":{"contractId":"ID!","selector":"SubscriptionBillingCycleSelector!"}}, +"SubscriptionBillingCycleScheduleEditInput":{"i":{"billingDate":"DateTime","reason":"SubscriptionBillingCycleScheduleEditInputScheduleEditReason!","skip":"Boolean"}}, +"SubscriptionBillingCycleScheduleEditInputScheduleEditReason":{"e":["BUYER_INITIATED","MERCHANT_INITIATED","DEV_INITIATED"]}, +"SubscriptionBillingCycleScheduleEditPayload":{"o":{"f":{"billingCycle":"SubscriptionBillingCycle","userErrors":"[SubscriptionBillingCycleUserError!]!"}}}, +"SubscriptionBillingCycleSelector":{"i":{"date":"DateTime","index":"Int"}}, +"SubscriptionBillingCycleSkipPayload":{"o":{"f":{"billingCycle":"SubscriptionBillingCycle","userErrors":"[SubscriptionBillingCycleSkipUserError!]!"}}}, +"SubscriptionBillingCycleSkipUserError":{"o":{"f":{"code":"SubscriptionBillingCycleSkipUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionBillingCycleSkipUserErrorCode":{"e":["INVALID"]}, +"SubscriptionBillingCycleUnskipPayload":{"o":{"f":{"billingCycle":"SubscriptionBillingCycle","userErrors":"[SubscriptionBillingCycleUnskipUserError!]!"}}}, +"SubscriptionBillingCycleUnskipUserError":{"o":{"f":{"code":"SubscriptionBillingCycleUnskipUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionBillingCycleUnskipUserErrorCode":{"e":["INVALID"]}, +"SubscriptionBillingCycleUserError":{"o":{"f":{"code":"SubscriptionBillingCycleErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionBillingCyclesDateRangeSelector":{"i":{"endDate":"DateTime!","startDate":"DateTime!"}}, +"SubscriptionBillingCyclesIndexRangeSelector":{"i":{"endIndex":"Int!","startIndex":"Int!"}}, +"SubscriptionBillingCyclesSortKeys":{"e":["CYCLE_INDEX","ID"]}, +"SubscriptionBillingCyclesTargetSelection":{"e":["ALL"]}, +"SubscriptionBillingPolicy":{"o":{"f":{"anchors":"[SellingPlanAnchor!]!","cadence":"SubscriptionContractCalculationCadence!","interval":"SellingPlanInterval!","intervalCount":"Int!","maxCycles":"Int","minCycles":"Int"}}}, +"SubscriptionBillingPolicyInput":{"i":{"anchors":"[SellingPlanAnchorInput!]=","interval":"SellingPlanInterval!","intervalCount":"Int!","maxCycles":"Int","minCycles":"Int"}}, +"SubscriptionCalculatedContract":{"o":{"f":{"billingPolicy":"SubscriptionBillingPolicy!","currencyCode":"CurrencyCode!","customAttributes":"[Attribute!]!","customer":"Customer!","customerPaymentMethod":["CustomerPaymentMethod",{"showRevoked":"Boolean="}],"deliveryMethod":"SubscriptionDeliveryMethod","deliveryPolicy":"SubscriptionDeliveryPolicy!","deliveryPrice":"MoneyV2!","discounts":["SubscriptionManualDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"groupedLines":["SubscriptionGroupedLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"lines":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"note":"String"}}}, +"SubscriptionCommittedContract":{"u":["SubscriptionBillingCycleEditedContract","SubscriptionContract"]}, +"SubscriptionContract":{"o":{"f":{"app":"App","appAdminUrl":"URL","billingAttempts":["SubscriptionBillingAttemptConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"billingPolicy":"SubscriptionBillingPolicy!","createdAt":"DateTime!","currencyCode":"CurrencyCode!","customAttributes":"[Attribute!]!","customer":"Customer","customerPaymentMethod":["CustomerPaymentMethod",{"showRevoked":"Boolean="}],"deliveryMethod":"SubscriptionDeliveryMethod","deliveryPolicy":"SubscriptionDeliveryPolicy!","deliveryPrice":"MoneyV2!","discounts":["SubscriptionManualDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"groupedLines":["SubscriptionGroupedLineConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"id":"ID!","lastBillingAttemptErrorType":"SubscriptionContractLastBillingErrorType","lastPaymentStatus":"SubscriptionContractLastPaymentStatus","latestCommittedProjectedOrderTotals":"SubscriptionContractCalculationProjectedOrderTotals","lineCount":"Int!","lines":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"linesCount":"Count","nextBillingDate":"DateTime","note":"String","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"originOrder":"Order","revisionId":"UnsignedInt64!","status":"SubscriptionContractSubscriptionStatus!","updatedAt":"DateTime!"},"t":["Node","SubscriptionContractBase"],"d":{"lineCount":"Use `linesCount` instead."}}}, +"SubscriptionContractActivatePayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionContractStatusUpdateUserError!]!"}}}, +"SubscriptionContractAtomicCreateInput":{"i":{"actor":"SubscriptionActor","contract":"SubscriptionDraftInput!","currencyCode":"CurrencyCode!","customerId":"ID!","discountCodes":"[String!]=","lines":"[SubscriptionAtomicLineInput!]!","nextBillingDate":"DateTime!"}}, +"SubscriptionContractAtomicCreatePayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionContractBase":{"n":{"f":{"app":"App","appAdminUrl":"URL","currencyCode":"CurrencyCode!","customAttributes":"[Attribute!]!","customer":"Customer","customerPaymentMethod":["CustomerPaymentMethod",{"showRevoked":"Boolean="}],"deliveryMethod":"SubscriptionDeliveryMethod","deliveryPrice":"MoneyV2!","discounts":["SubscriptionManualDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"groupedLines":["SubscriptionGroupedLineConnection",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"lineCount":"Int!","lines":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"linesCount":"Count","note":"String","orders":["OrderConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"updatedAt":"DateTime!"},"t":["SubscriptionBillingCycleEditedContract","SubscriptionContract"],"d":{"lineCount":"Use `linesCount` instead."}}}, +"SubscriptionContractCalculation":{"u":["SubscriptionContractCalculationFailure","SubscriptionContractCalculationPending","SubscriptionContractCalculationSuccess"]}, +"SubscriptionContractCalculationAnchorInput":{"i":{"f":{"monthday":"SubscriptionContractCalculationMonthdayAnchorInput","weekday":"SubscriptionContractCalculationWeekdayAnchorInput","yearday":"SubscriptionContractCalculationYeardayAnchorInput"},"o":true}}, +"SubscriptionContractCalculationAppManagedBillingConfigInput":{"i":{"maxCycles":"Int","minCycles":"Int"}}, +"SubscriptionContractCalculationAppManagedPricingPolicyInput":{"i":{"basePrice":"MoneyInput!","cyclePriceAdjustments":"[SubscriptionContractCalculationCyclePriceAdjustmentInput!]!"}}, +"SubscriptionContractCalculationBillingCycleEditInput":{"i":{"customAttributes":"[AttributeInput!]","deliveryMethod":"SubscriptionContractCalculationDeliveryMethodInput","discountCodes":"[SubscriptionContractCalculationDiscountCodeInput!]!=","lines":"[SubscriptionContractCalculationLineInput!]","manualDiscounts":"[SubscriptionContractCalculationManualDiscountInput!]","note":"String","withMerchandiseCustomizations":"Boolean!"}}, +"SubscriptionContractCalculationBillingPolicyInput":{"i":{"anchors":"[SubscriptionContractCalculationAnchorInput!]!=","cadence":"SubscriptionContractCalculationCadenceInput!"}}, +"SubscriptionContractCalculationCadence":{"o":{"f":{"count":"Int!","unit":"SubscriptionContractCalculationCadenceUnit!"}}}, +"SubscriptionContractCalculationCadenceInput":{"i":{"count":"Int!","unit":"SubscriptionContractCalculationCadenceUnit!"}}, +"SubscriptionContractCalculationCadenceUnit":{"e":["DAY","WEEK","MONTH","YEAR"]}, +"SubscriptionContractCalculationCommitPayload":{"o":{"f":{"contract":"SubscriptionCommittedContract","userErrors":"[SubscriptionContractCalculationCommitUserError!]!"}}}, +"SubscriptionContractCalculationCommitUserError":{"o":{"f":{"code":"SubscriptionContractCalculationCommitUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionContractCalculationCommitUserErrorCode":{"e":["INVALID","NOT_READY_TO_COMMIT","DISCOVERY_CALCULATION_NOT_COMMITTABLE","CALCULATION_NOT_FOUND","STALE_CONTRACT","INVALID_BILLING_DATE","CONTRACT_TERMINATED"]}, +"SubscriptionContractCalculationComponentLineInput":{"i":{"f":{"productVariantLine":"SubscriptionContractCalculationProductVariantLineInput"},"o":true}}, +"SubscriptionContractCalculationContractCreateInput":{"i":{"actor":"SubscriptionActor","appManagedBillingConfig":"SubscriptionContractCalculationAppManagedBillingConfigInput","billingPolicy":"SubscriptionContractCalculationBillingPolicyInput!","currencyCode":"CurrencyCode!","customAttributes":"[AttributeInput!]!=","customerId":"ID!","deliveryMethod":"SubscriptionContractCalculationDeliveryMethodInput!","deliveryPolicy":"SubscriptionContractCalculationDeliveryPolicyInput!","discountCodes":"[SubscriptionContractCalculationDiscountCodeInput!]!=","lines":"[SubscriptionContractCalculationLineInput!]!","manualDiscounts":"[SubscriptionContractCalculationManualDiscountInput!]!","note":"String","paymentMethod":"SubscriptionContractCalculationPaymentMethodInput!","withMerchandiseCustomizations":"Boolean!"}}, +"SubscriptionContractCalculationContractUpdateInput":{"i":{"appManagedBillingConfig":"SubscriptionContractCalculationAppManagedBillingConfigInput","billingPolicy":"SubscriptionContractCalculationBillingPolicyInput","customAttributes":"[AttributeInput!]","deliveryMethod":"SubscriptionContractCalculationDeliveryMethodInput","deliveryPolicy":"SubscriptionContractCalculationDeliveryPolicyInput","discountCodes":"[SubscriptionContractCalculationDiscountCodeInput!]!=","lines":"[SubscriptionContractCalculationLineInput!]","manualDiscounts":"[SubscriptionContractCalculationManualDiscountInput!]","note":"String","paymentMethod":"SubscriptionContractCalculationPaymentMethodInput","withMerchandiseCustomizations":"Boolean!"}}, +"SubscriptionContractCalculationCustomLineInput":{"i":{"appManagedPricingPolicy":"SubscriptionContractCalculationAppManagedPricingPolicyInput","customAttributes":"[AttributeInput!]!=","discounts":"[SubscriptionContractCalculationLineDiscountInput!]!","id":"ID","originSellingPlanId":"ID","price":"MoneyInput!","quantity":"Int!","requiresShipping":"Boolean!","sellingPlanName":"String","sku":"String","taxable":"Boolean!","title":"String!","variantTitle":"String","weight":"WeightInput"}}, +"SubscriptionContractCalculationCustomerPaymentMethodInput":{"i":{"id":"ID!"}}, +"SubscriptionContractCalculationCyclePriceAdjustmentInput":{"i":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType!","adjustmentValue":"SellingPlanPricingPolicyValueInput!","afterCycle":"Int!","computedPrice":"MoneyInput!"}}, +"SubscriptionContractCalculationDeliveryDiscountInput":{"i":{"id":"ID","recurringCycleLimit":"Int!","title":"String!","value":"SubscriptionContractCalculationDiscountValueInput!"}}, +"SubscriptionContractCalculationDeliveryMethodInput":{"i":{"f":{"fetchAvailableDeliveryOptions":"SubscriptionContractCalculationFetchDeliveryOptionsInput","localDelivery":"SubscriptionContractCalculationDeliveryMethodLocalDeliveryInput","none":"Boolean","pickup":"SubscriptionContractCalculationDeliveryMethodPickupInput","shipping":"SubscriptionContractCalculationDeliveryMethodShippingInput"},"o":true}}, +"SubscriptionContractCalculationDeliveryMethodLocalDeliveryInput":{"i":{"address":"MailingAddressInput!","code":"String","deliveryPrice":"MoneyInput!","description":"String","instructions":"String","phone":"String!","presentmentTitle":"String","title":"String"}}, +"SubscriptionContractCalculationDeliveryMethodPickupInput":{"i":{"code":"String","deliveryPrice":"MoneyInput!","description":"String","locationId":"ID!","presentmentTitle":"String","title":"String"}}, +"SubscriptionContractCalculationDeliveryMethodShippingInput":{"i":{"address":"MailingAddressInput!","carrierServiceId":"ID","code":"String","deliveryPrice":"MoneyInput!","description":"String","presentmentTitle":"String","title":"String"}}, +"SubscriptionContractCalculationDeliveryOption":{"u":["SubscriptionContractCalculationLocalDeliveryOption","SubscriptionContractCalculationPickupOption","SubscriptionContractCalculationShippingOption"]}, +"SubscriptionContractCalculationDeliveryPolicyInput":{"i":{"anchors":"[SubscriptionContractCalculationAnchorInput!]!=","multiFulfillment":"SubscriptionContractCalculationMultipleFulfillmentConfigInput"}}, +"SubscriptionContractCalculationDiagnostic":{"o":{"f":{"code":"SubscriptionContractCalculationDiagnosticCode!","field":"[String!]","message":"String"}}}, +"SubscriptionContractCalculationDiagnosticCode":{"e":["INVALID","MERCHANDISE_NOT_FOUND","DELIVERY_ADDRESS_INVALID","CURRENCY_NOT_SUPPORTED","DELIVERY_NO_LOCATION_SHIPS_TO_ADDRESS","DELIVERY_PICKUP_LOCATION_UNAVAILABLE","PAYMENT_METHOD_NOT_FOUND","CUSTOM_VALIDATION","DELIVERY_METHOD_REQUIRED","DELIVERY_METHOD_UNUSED","CUSTOMER_CONTACT_METHOD_REQUIRED","BUNDLE_REQUIRES_MERCHANDISE_CUSTOMIZATIONS","MERCHANDISE_GIFT_CARD_INVALID","DISCOUNT_CODE_NOT_APPLIED","CALCULATION_TIMEOUT","LINE_PRICE_ADJUSTED_FOR_FULFILLMENTS","PROCESSING_ERROR"]}, +"SubscriptionContractCalculationDiscountCodeInput":{"i":{"redeemCode":"String!"}}, +"SubscriptionContractCalculationDiscountFixedAmountInput":{"i":{"amount":"MoneyInput!","appliesOnEachItem":"Boolean!"}}, +"SubscriptionContractCalculationDiscountValueInput":{"i":{"f":{"fixedAmount":"SubscriptionContractCalculationDiscountFixedAmountInput","percentage":"Int"},"o":true}}, +"SubscriptionContractCalculationFailure":{"o":{"f":{"errors":"[SubscriptionContractCalculationDiagnostic!]!","id":"ID!"}}}, +"SubscriptionContractCalculationFetchDeliveryOptionsInput":{"i":{"address":"MailingAddressInput!","withDeliveryCustomizations":"Boolean="}}, +"SubscriptionContractCalculationLineDiscountInput":{"i":{"id":"ID","recurringCycleLimit":"Int!","title":"String!","value":"SubscriptionContractCalculationDiscountValueInput!"}}, +"SubscriptionContractCalculationLineInput":{"i":{"f":{"customLine":"SubscriptionContractCalculationCustomLineInput","productVariantLine":"SubscriptionContractCalculationProductVariantLineInput","productVariantParentLine":"SubscriptionContractCalculationProductVariantParentLineInput"},"o":true}}, +"SubscriptionContractCalculationLocalDeliveryOption":{"o":{"f":{"code":"String!","description":"String","phoneRequired":"Boolean!","presentmentTitle":"String","price":"MoneyV2!","title":"String!"}}}, +"SubscriptionContractCalculationManualDiscountInput":{"i":{"f":{"deliveryDiscount":"SubscriptionContractCalculationDeliveryDiscountInput","orderDiscount":"SubscriptionContractCalculationOrderDiscountInput"},"o":true}}, +"SubscriptionContractCalculationMonthdayAnchorInput":{"i":{"dayOfMonth":"Int!"}}, +"SubscriptionContractCalculationMultipleFulfillmentConfig":{"o":{"f":{"cadence":"SubscriptionContractCalculationCadence!","numberOfFulfillments":"Int!"}}}, +"SubscriptionContractCalculationMultipleFulfillmentConfigInput":{"i":{"cadence":"SubscriptionContractCalculationCadenceInput!","numberOfFulfillments":"Int!"}}, +"SubscriptionContractCalculationOrderDiscountInput":{"i":{"id":"ID","recurringCycleLimit":"Int!","title":"String!","value":"SubscriptionContractCalculationDiscountValueInput!"}}, +"SubscriptionContractCalculationPaymentMethodInput":{"i":{"f":{"customerPaymentMethod":"SubscriptionContractCalculationCustomerPaymentMethodInput","none":"Boolean"},"o":true}}, +"SubscriptionContractCalculationPending":{"o":{"f":{"id":"ID!"}}}, +"SubscriptionContractCalculationPickupOption":{"o":{"f":{"code":"String!","description":"String","location":"Location!","phoneRequired":"Boolean!","pickupTime":"String","presentmentTitle":"String","price":"MoneyV2!","title":"String!"}}}, +"SubscriptionContractCalculationProductVariantLineInput":{"i":{"appManagedPricingPolicy":"SubscriptionContractCalculationAppManagedPricingPolicyInput","customAttributes":"[AttributeInput!]!=","discounts":"[SubscriptionContractCalculationLineDiscountInput!]!","id":"ID","originSellingPlanId":"ID","priceOverride":"MoneyInput","productVariantId":"ID!","quantity":"Int!","sellingPlanName":"String"}}, +"SubscriptionContractCalculationProductVariantParentLineInput":{"i":{"components":"[SubscriptionContractCalculationComponentLineInput!]!","customAttributes":"[AttributeInput!]!=","id":"ID","productVariantId":"ID!","quantity":"Int!"}}, +"SubscriptionContractCalculationProjectedOrderTotals":{"o":{"f":{"subtotal":"MoneyV2!","total":"MoneyV2!","totalDelivery":"MoneyV2!","totalDeliveryDiscounts":"MoneyV2!","totalMerchandiseDiscounts":"MoneyV2!","totalTax":"MoneyV2!"}}}, +"SubscriptionContractCalculationShippingOption":{"o":{"f":{"code":"String!","description":"String","phoneRequired":"Boolean!","presentmentTitle":"String","price":"MoneyV2!","title":"String!"}}}, +"SubscriptionContractCalculationSuccess":{"o":{"f":{"calculatedContract":"SubscriptionCalculatedContract!","deliveryOptions":"[SubscriptionContractCalculationDeliveryOption!]!","id":"ID!","projectedOrderTotals":"SubscriptionContractCalculationProjectedOrderTotals","warnings":"[SubscriptionContractCalculationDiagnostic!]!","withMerchandiseCustomizations":"Boolean!"}}}, +"SubscriptionContractCalculationWeekdayAnchorInput":{"i":{"dayOfWeek":"DayOfTheWeek!"}}, +"SubscriptionContractCalculationYeardayAnchorInput":{"i":{"dayOfMonth":"Int!","month":"Int!"}}, +"SubscriptionContractCancelPayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionContractStatusUpdateUserError!]!"}}}, +"SubscriptionContractConnection":{"o":{"f":{"edges":"[SubscriptionContractEdge!]!","nodes":"[SubscriptionContract!]!","pageInfo":"PageInfo!"}}}, +"SubscriptionContractCreateCalculatePayload":{"o":{"f":{"subscriptionContractCalculation":"SubscriptionContractCalculation","userErrors":"[SubscriptionContractCreateCalculateUserError!]!"}}}, +"SubscriptionContractCreateCalculateUserError":{"o":{"f":{"code":"SubscriptionContractCreateCalculateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionContractCreateCalculateUserErrorCode":{"e":["INVALID"]}, +"SubscriptionContractCreateInput":{"i":{"actor":"SubscriptionActor","contract":"SubscriptionDraftInput!","currencyCode":"CurrencyCode!","customerId":"ID!","nextBillingDate":"DateTime!"}}, +"SubscriptionContractCreatePayload":{"o":{"f":{"draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionContractEdge":{"o":{"f":{"cursor":"String!","node":"SubscriptionContract!"}}}, +"SubscriptionContractErrorCode":{"e":["INVALID"]}, +"SubscriptionContractExpirePayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionContractStatusUpdateUserError!]!"}}}, +"SubscriptionContractFailPayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionContractStatusUpdateUserError!]!"}}}, +"SubscriptionContractLastBillingErrorType":{"e":["PAYMENT_ERROR","CUSTOMER_ERROR","INVENTORY_ERROR","OTHER"]}, +"SubscriptionContractLastPaymentStatus":{"e":["SUCCEEDED","FAILED"]}, +"SubscriptionContractPausePayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionContractStatusUpdateUserError!]!"}}}, +"SubscriptionContractProductChangeInput":{"i":{"currentPrice":"Decimal","productVariantId":"ID"}}, +"SubscriptionContractProductChangePayload":{"o":{"f":{"contract":"SubscriptionContract","lineUpdated":"SubscriptionLine","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionContractSetNextBillingDatePayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionContractUserError!]!"}}}, +"SubscriptionContractStatusUpdateErrorCode":{"e":["INVALID","CONTRACT_TERMINATED"]}, +"SubscriptionContractStatusUpdateUserError":{"o":{"f":{"code":"SubscriptionContractStatusUpdateErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionContractSubscriptionStatus":{"e":["ACTIVE","PAUSED","CANCELLED","EXPIRED","FAILED"]}, +"SubscriptionContractUpdateCalculatePayload":{"o":{"f":{"subscriptionContractCalculation":"SubscriptionContractCalculation","userErrors":"[SubscriptionContractUpdateCalculateUserError!]!"}}}, +"SubscriptionContractUpdateCalculateUserError":{"o":{"f":{"code":"SubscriptionContractUpdateCalculateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionContractUpdateCalculateUserErrorCode":{"e":["INVALID","CONTRACT_TERMINATED","CONTRACT_HAS_FUTURE_EDITS"]}, +"SubscriptionContractUpdatePayload":{"o":{"f":{"draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionContractUserError":{"o":{"f":{"code":"SubscriptionContractErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionContractsSortKeys":{"e":["CREATED_AT","ID","STATUS","UPDATED_AT"]}, +"SubscriptionCyclePriceAdjustment":{"o":{"f":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType!","adjustmentValue":"SellingPlanPricingPolicyAdjustmentValue!","afterCycle":"Int!","computedPrice":"MoneyV2!"}}}, +"SubscriptionDeliveryMethod":{"u":["SubscriptionDeliveryMethodLocalDelivery","SubscriptionDeliveryMethodPickup","SubscriptionDeliveryMethodShipping"]}, +"SubscriptionDeliveryMethodInput":{"i":{"localDelivery":"SubscriptionDeliveryMethodLocalDeliveryInput","pickup":"SubscriptionDeliveryMethodPickupInput","shipping":"SubscriptionDeliveryMethodShippingInput"}}, +"SubscriptionDeliveryMethodLocalDelivery":{"o":{"f":{"address":"MailingAddress!","localDeliveryOption":"SubscriptionDeliveryMethodLocalDeliveryOption!"}}}, +"SubscriptionDeliveryMethodLocalDeliveryInput":{"i":{"address":"MailingAddressInput","localDeliveryOption":"SubscriptionDeliveryMethodLocalDeliveryOptionInput"}}, +"SubscriptionDeliveryMethodLocalDeliveryOption":{"o":{"f":{"code":"String","description":"String","instructions":"String","phone":"String!","presentmentTitle":"String","title":"String"}}}, +"SubscriptionDeliveryMethodLocalDeliveryOptionInput":{"i":{"code":"String","description":"String","instructions":"String","phone":"String!","presentmentTitle":"String","title":"String"}}, +"SubscriptionDeliveryMethodPickup":{"o":{"f":{"pickupOption":"SubscriptionDeliveryMethodPickupOption!"}}}, +"SubscriptionDeliveryMethodPickupInput":{"i":{"pickupOption":"SubscriptionDeliveryMethodPickupOptionInput"}}, +"SubscriptionDeliveryMethodPickupOption":{"o":{"f":{"code":"String","description":"String","location":"Location!","presentmentTitle":"String","title":"String"}}}, +"SubscriptionDeliveryMethodPickupOptionInput":{"i":{"code":"String","description":"String","locationId":"ID!","presentmentTitle":"String","title":"String"}}, +"SubscriptionDeliveryMethodShipping":{"o":{"f":{"address":"MailingAddress!","shippingOption":"SubscriptionDeliveryMethodShippingOption!"}}}, +"SubscriptionDeliveryMethodShippingInput":{"i":{"address":"MailingAddressInput","shippingOption":"SubscriptionDeliveryMethodShippingOptionInput"}}, +"SubscriptionDeliveryMethodShippingOption":{"o":{"f":{"carrierService":"DeliveryCarrierService","code":"String","description":"String","presentmentTitle":"String","title":"String"},"d":{"carrierService":"This field has never been implemented."}}}, +"SubscriptionDeliveryMethodShippingOptionInput":{"i":{"carrierServiceId":"ID","code":"String","description":"String","presentmentTitle":"String","title":"String"}}, +"SubscriptionDeliveryOption":{"u":["SubscriptionLocalDeliveryOption","SubscriptionPickupOption","SubscriptionShippingOption"]}, +"SubscriptionDeliveryOptionResult":{"u":["SubscriptionDeliveryOptionResultFailure","SubscriptionDeliveryOptionResultSuccess"]}, +"SubscriptionDeliveryOptionResultFailure":{"o":{"f":{"message":"String"}}}, +"SubscriptionDeliveryOptionResultSuccess":{"o":{"f":{"deliveryOptions":"[SubscriptionDeliveryOption!]!"}}}, +"SubscriptionDeliveryPolicy":{"o":{"f":{"anchors":"[SellingPlanAnchor!]!","interval":"SellingPlanInterval!","intervalCount":"Int!","multiFulfillment":"SubscriptionContractCalculationMultipleFulfillmentConfig"}}}, +"SubscriptionDeliveryPolicyInput":{"i":{"anchors":"[SellingPlanAnchorInput!]=","interval":"SellingPlanInterval!","intervalCount":"Int!"}}, +"SubscriptionDiscount":{"u":["SubscriptionAppliedCodeDiscount","SubscriptionManualDiscount"]}, +"SubscriptionDiscountAllocation":{"o":{"f":{"amount":"MoneyV2!","discount":"SubscriptionDiscount!"}}}, +"SubscriptionDiscountConnection":{"o":{"f":{"edges":"[SubscriptionDiscountEdge!]!","nodes":"[SubscriptionDiscount!]!","pageInfo":"PageInfo!"}}}, +"SubscriptionDiscountEdge":{"o":{"f":{"cursor":"String!","node":"SubscriptionDiscount!"}}}, +"SubscriptionDiscountEntitledLines":{"o":{"f":{"all":"Boolean!","lines":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}]}}}, +"SubscriptionDiscountFixedAmountValue":{"o":{"f":{"amount":"MoneyV2!","appliesOnEachItem":"Boolean!"}}}, +"SubscriptionDiscountPercentageValue":{"o":{"f":{"percentage":"Int!"}}}, +"SubscriptionDiscountRejectionReason":{"e":["NOT_FOUND","NO_ENTITLED_LINE_ITEMS","QUANTITY_NOT_IN_RANGE","PURCHASE_NOT_IN_RANGE","CUSTOMER_NOT_ELIGIBLE","USAGE_LIMIT_REACHED","CUSTOMER_USAGE_LIMIT_REACHED","CURRENTLY_INACTIVE","NO_ENTITLED_SHIPPING_LINES","INCOMPATIBLE_PURCHASE_TYPE","INTERNAL_ERROR"]}, +"SubscriptionDiscountValue":{"u":["SubscriptionDiscountFixedAmountValue","SubscriptionDiscountPercentageValue"]}, +"SubscriptionDraft":{"o":{"f":{"billingCycle":"SubscriptionBillingCycle","billingPolicy":"SubscriptionBillingPolicy!","concatenatedBillingCycles":["SubscriptionBillingCycleConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean=","sortKey":"SubscriptionBillingCyclesSortKeys="}],"currencyCode":"CurrencyCode!","customAttributes":"[Attribute!]!","customer":"Customer!","customerPaymentMethod":["CustomerPaymentMethod",{"showRevoked":"Boolean="}],"deliveryMethod":"SubscriptionDeliveryMethod","deliveryOptions":["SubscriptionDeliveryOptionResult",{"deliveryAddress":"MailingAddressInput"}],"deliveryPolicy":"SubscriptionDeliveryPolicy!","deliveryPrice":"MoneyV2","discounts":["SubscriptionDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"discountsAdded":["SubscriptionDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"discountsRemoved":["SubscriptionDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"discountsUpdated":["SubscriptionDiscountConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"id":"ID!","lines":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"linesAdded":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"linesRemoved":["SubscriptionLineConnection!",{"after":"String","before":"String","first":"Int","last":"Int","reverse":"Boolean="}],"nextBillingDate":"DateTime","note":"String","originalContract":"SubscriptionContract","shippingOptions":["SubscriptionShippingOptionResult",{"deliveryAddress":"MailingAddressInput"}],"status":"SubscriptionContractSubscriptionStatus"},"t":["Node"],"d":{"shippingOptions":"Use `deliveryOptions` instead."}}}, +"SubscriptionDraftCommitPayload":{"o":{"f":{"contract":"SubscriptionContract","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftDiscountAddPayload":{"o":{"f":{"discountAdded":"SubscriptionManualDiscount","draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftDiscountCodeApplyPayload":{"o":{"f":{"appliedDiscount":"SubscriptionAppliedCodeDiscount","draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftDiscountRemovePayload":{"o":{"f":{"discountRemoved":"SubscriptionDiscount","draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftDiscountUpdatePayload":{"o":{"f":{"discountUpdated":"SubscriptionManualDiscount","draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftErrorCode":{"e":["ALREADY_REMOVED","PRESENCE","COMMITTED","NOT_IN_RANGE","NOT_AN_INTEGER","SELLING_PLAN_MAX_CYCLES_MUST_BE_GREATER_THAN_MIN_CYCLES","DELIVERY_MUST_BE_MULTIPLE_OF_BILLING","INVALID_BILLING_DATE","INVALID_NOTE_LENGTH","INVALID_LINES","NO_ENTITLED_LINES","CUSTOMER_DOES_NOT_EXIST","CUSTOMER_MISMATCH","DELIVERY_METHOD_REQUIRED","MISSING_LOCAL_DELIVERY_OPTIONS","CYCLE_DISCOUNTS_UNIQUE_AFTER_CYCLE","INVALID_ADJUSTMENT_TYPE","INVALID_ADJUSTMENT_VALUE","STALE_CONTRACT","TOO_MANY_LINES","TOO_MANY_DISCOUNTS","CURRENCY_NOT_ENABLED","HAS_FUTURE_EDITS","BILLING_CYCLE_PRESENT","BILLING_CYCLE_ABSENT","BILLING_CYCLE_CONTRACT_DRAFT_DELIVERY_POLICY_INVALID","BILLING_CYCLE_CONTRACT_DRAFT_BILLING_POLICY_INVALID","CONCATENATION_BILLING_CYCLE_CONTRACT_DRAFT_REQUIRED","CONCATENATION_UNCOMMITTED_CONTRACT_DRAFT","DUPLICATE_CONCATENATED_CONTRACTS","UPCOMING_CYCLE_LIMIT_EXCEEDED","CYCLE_INDEX_OUT_OF_RANGE","CYCLE_START_DATE_OUT_OF_RANGE","CYCLE_SELECTOR_VALIDATE_ONE_OF","EXCEEDED_MAX_CONCATENATED_CONTRACTS","CUSTOMER_REDACTED","MISSING_CUSTOMER_PAYMENT_METHOD","INVALID","BLANK","GREATER_THAN","GREATER_THAN_OR_EQUAL_TO","LESS_THAN","LESS_THAN_OR_EQUAL_TO","TOO_LONG","TOO_SHORT"]}, +"SubscriptionDraftFreeShippingDiscountAddPayload":{"o":{"f":{"discountAdded":"SubscriptionManualDiscount","draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftFreeShippingDiscountUpdatePayload":{"o":{"f":{"discountUpdated":"SubscriptionManualDiscount","draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftInput":{"i":{"billingPolicy":"SubscriptionBillingPolicyInput","customAttributes":"[AttributeInput!]","deliveryMethod":"SubscriptionDeliveryMethodInput","deliveryPolicy":"SubscriptionDeliveryPolicyInput","deliveryPrice":"Decimal","nextBillingDate":"DateTime","note":"String","paymentMethodId":"ID","status":"SubscriptionContractSubscriptionStatus"}}, +"SubscriptionDraftLineAddPayload":{"o":{"f":{"draft":"SubscriptionDraft","lineAdded":"SubscriptionLine","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftLineRemovePayload":{"o":{"f":{"discountsUpdated":"[SubscriptionManualDiscount!]","draft":"SubscriptionDraft","lineRemoved":"SubscriptionLine","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftLineUpdatePayload":{"o":{"f":{"draft":"SubscriptionDraft","lineUpdated":"SubscriptionLine","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftUpdatePayload":{"o":{"f":{"draft":"SubscriptionDraft","userErrors":"[SubscriptionDraftUserError!]!"}}}, +"SubscriptionDraftUserError":{"o":{"f":{"code":"SubscriptionDraftErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"SubscriptionFreeShippingDiscountInput":{"i":{"recurringCycleLimit":"Int","title":"String"}}, +"SubscriptionGroupedLine":{"u":["SubscriptionLine","SubscriptionParentLine"]}, +"SubscriptionGroupedLineConnection":{"o":{"f":{"edges":"[SubscriptionGroupedLineEdge!]!","nodes":"[SubscriptionGroupedLine!]!","pageInfo":"PageInfo!"}}}, +"SubscriptionGroupedLineEdge":{"o":{"f":{"cursor":"String!","node":"SubscriptionGroupedLine!"}}}, +"SubscriptionLine":{"o":{"f":{"concatenatedOriginContract":"SubscriptionContract","currentPrice":"MoneyV2!","customAttributes":"[Attribute!]!","discountAllocations":"[SubscriptionDiscountAllocation!]!","id":"ID!","lineDiscountedPrice":"MoneyV2!","pricingPolicy":"SubscriptionPricingPolicy","productId":"ID","quantity":"Int!","requiresShipping":"Boolean!","sellingPlanId":"ID","sellingPlanName":"String","sku":"String","taxable":"Boolean!","title":"String!","variantId":"ID","variantImage":"Image","variantTitle":"String","weight":"Weight"}}}, +"SubscriptionLineConnection":{"o":{"f":{"edges":"[SubscriptionLineEdge!]!","nodes":"[SubscriptionLine!]!","pageInfo":"PageInfo!"}}}, +"SubscriptionLineEdge":{"o":{"f":{"cursor":"String!","node":"SubscriptionLine!"}}}, +"SubscriptionLineInput":{"i":{"currentPrice":"Decimal!","customAttributes":"[AttributeInput!]","pricingPolicy":"SubscriptionPricingPolicyInput","productVariantId":"ID!","quantity":"Int!","sellingPlanId":"ID","sellingPlanName":"String"}}, +"SubscriptionLineUpdateInput":{"i":{"currentPrice":"Decimal","customAttributes":"[AttributeInput!]","pricingPolicy":"SubscriptionPricingPolicyInput","productVariantId":"ID","quantity":"Int","sellingPlanId":"ID","sellingPlanName":"String"}}, +"SubscriptionLocalDeliveryOption":{"o":{"f":{"code":"String!","description":"String","phoneRequired":"Boolean!","presentmentTitle":"String","price":"MoneyV2","title":"String!"}}}, +"SubscriptionManualDiscount":{"o":{"f":{"entitledLines":"SubscriptionDiscountEntitledLines!","id":"ID!","recurringCycleLimit":"Int","rejectionReason":"SubscriptionDiscountRejectionReason","targetType":"DiscountTargetType!","title":"String","type":"DiscountType!","usageCount":"Int!","value":"SubscriptionDiscountValue!"}}}, +"SubscriptionManualDiscountConnection":{"o":{"f":{"edges":"[SubscriptionManualDiscountEdge!]!","nodes":"[SubscriptionManualDiscount!]!","pageInfo":"PageInfo!"}}}, +"SubscriptionManualDiscountEdge":{"o":{"f":{"cursor":"String!","node":"SubscriptionManualDiscount!"}}}, +"SubscriptionManualDiscountEntitledLinesInput":{"i":{"all":"Boolean","lines":"SubscriptionManualDiscountLinesInput"}}, +"SubscriptionManualDiscountFixedAmountInput":{"i":{"amount":"Float","appliesOnEachItem":"Boolean"}}, +"SubscriptionManualDiscountInput":{"i":{"entitledLines":"SubscriptionManualDiscountEntitledLinesInput","recurringCycleLimit":"Int","title":"String","value":"SubscriptionManualDiscountValueInput"}}, +"SubscriptionManualDiscountLinesInput":{"i":{"add":"[ID!]","remove":"[ID!]"}}, +"SubscriptionManualDiscountValueInput":{"i":{"fixedAmount":"SubscriptionManualDiscountFixedAmountInput","percentage":"Int"}}, +"SubscriptionParentLine":{"o":{"f":{"bundledBy":"App","components":"[SubscriptionLine!]!","customAttributes":"[Attribute!]!","id":"ID!","presentmentTitle":"String","productId":"ID","quantity":"Int!","sourceType":"String","title":"String!","variantId":"ID"}}}, +"SubscriptionPickupOption":{"o":{"f":{"code":"String!","description":"String","location":"Location!","phoneRequired":"Boolean!","pickupTime":"String!","presentmentTitle":"String","price":"MoneyV2","title":"String!"}}}, +"SubscriptionPricingPolicy":{"o":{"f":{"basePrice":"MoneyV2!","cycleDiscounts":"[SubscriptionCyclePriceAdjustment!]!"}}}, +"SubscriptionPricingPolicyCycleDiscountsInput":{"i":{"adjustmentType":"SellingPlanPricingPolicyAdjustmentType!","adjustmentValue":"SellingPlanPricingPolicyValueInput!","afterCycle":"Int!","computedPrice":"Decimal!"}}, +"SubscriptionPricingPolicyInput":{"i":{"basePrice":"Decimal!","cycleDiscounts":"[SubscriptionPricingPolicyCycleDiscountsInput!]!"}}, +"SubscriptionShippingOption":{"o":{"f":{"carrierService":"DeliveryCarrierService","code":"String!","description":"String","phoneRequired":"Boolean","presentmentTitle":"String","price":"MoneyV2","title":"String!"},"d":{"carrierService":"This field has never been implemented."}}}, +"SubscriptionShippingOptionResult":{"u":["SubscriptionShippingOptionResultFailure","SubscriptionShippingOptionResultSuccess"]}, +"SubscriptionShippingOptionResultFailure":{"o":{"f":{"message":"String"}}}, +"SubscriptionShippingOptionResultSuccess":{"o":{"f":{"shippingOptions":"[SubscriptionShippingOption!]!"}}}, +"SuggestedOrderTransaction":{"o":{"f":{"accountNumber":"String","amount":"Money!","amountSet":"MoneyBag!","formattedGateway":"String","gateway":"String","kind":"SuggestedOrderTransactionKind!","maximumRefundable":"Money","maximumRefundableSet":"MoneyBag","parentTransaction":"OrderTransaction","paymentDetails":"PaymentDetails"},"d":{"amount":"Use `amountSet` instead.","maximumRefundable":"Use `maximumRefundableSet` instead."}}}, +"SuggestedOrderTransactionKind":{"e":["SUGGESTED_REFUND"]}, +"SuggestedOutcomeExchangeLineItemInput":{"i":{"id":"ID!","quantity":"Int!"}}, +"SuggestedOutcomeReturnLineItemInput":{"i":{"id":"ID!","quantity":"Int!"}}, +"SuggestedRefund":{"o":{"f":{"amount":"Money!","amountSet":"MoneyBag!","discountedSubtotalSet":"MoneyBag!","maximumRefundable":"Money!","maximumRefundableSet":"MoneyBag!","refundDuties":"[RefundDuty!]!","refundLineItems":"[RefundLineItem!]!","shipping":"ShippingRefund!","subtotal":"Money!","subtotalSet":"MoneyBag!","suggestedRefundMethods":"[SuggestedRefundMethod!]!","suggestedTransactions":"[SuggestedOrderTransaction!]!","totalCartDiscountAmountSet":"MoneyBag!","totalDutiesSet":"MoneyBag!","totalTaxSet":"MoneyBag!","totalTaxes":"Money!"},"d":{"amount":"Use `amountSet` instead.","maximumRefundable":"Use `maximumRefundableSet` instead.","subtotal":"Use `subtotalSet` instead.","totalTaxes":"Use `totalTaxSet` instead."}}}, +"SuggestedRefundMethod":{"n":{"f":{"amount":"MoneyBag!","maximumRefundable":"MoneyBag!"},"t":["SuggestedStoreCreditRefund"]}}, +"SuggestedReturnFinancialOutcome":{"o":{"f":{"discountedSubtotal":"MoneyBag!","financialTransfer":"ReturnOutcomeFinancialTransfer","maximumRefundable":"MoneyBag!","refundDuties":"[RefundDuty!]!","shipping":"ShippingRefund!","totalAdditionalFees":"MoneyBag!","totalCartDiscountAmount":"MoneyBag!","totalDuties":"MoneyBag!","totalTax":"MoneyBag!"}}}, +"SuggestedReturnRefund":{"o":{"f":{"amount":"MoneyBag!","discountedSubtotal":"MoneyBag!","maximumRefundable":"MoneyBag!","refundDuties":"[RefundDuty!]!","shipping":"ShippingRefund!","subtotal":"MoneyBag!","suggestedTransactions":"[SuggestedOrderTransaction!]!","totalCartDiscountAmount":"MoneyBag!","totalDuties":"MoneyBag!","totalTax":"MoneyBag!"}}}, +"SuggestedStoreCreditRefund":{"o":{"f":{"amount":"MoneyBag!","expiresAt":"DateTime","maximumRefundable":"MoneyBag!"},"t":["SuggestedRefundMethod"]}}, +"TagsAddPayload":{"o":{"f":{"node":"Node","userErrors":"[UserError!]!"}}}, +"TagsRemovePayload":{"o":{"f":{"node":"Node","userErrors":"[UserError!]!"}}}, +"TaxAppConfiguration":{"o":{"f":{"state":"TaxPartnerState!"}}}, +"TaxAppConfigurePayload":{"o":{"f":{"taxAppConfiguration":"TaxAppConfiguration","userErrors":"[TaxAppConfigureUserError!]!"}}}, +"TaxAppConfigureUserError":{"o":{"f":{"code":"TaxAppConfigureUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"TaxAppConfigureUserErrorCode":{"e":["TAX_PARTNER_NOT_FOUND","TAX_PARTNER_STATE_UPDATE_FAILED","TAX_PARTNER_ALREADY_ACTIVE"]}, +"TaxExemption":{"e":["CA_STATUS_CARD_EXEMPTION","CA_BC_RESELLER_EXEMPTION","CA_MB_RESELLER_EXEMPTION","CA_SK_RESELLER_EXEMPTION","CA_SK_VPT_RESELLER_EXEMPTION","CA_NL_VPT_RESELLER_EXEMPTION","CA_DIPLOMAT_EXEMPTION","CA_BC_COMMERCIAL_FISHERY_EXEMPTION","CA_MB_COMMERCIAL_FISHERY_EXEMPTION","CA_NS_COMMERCIAL_FISHERY_EXEMPTION","CA_PE_COMMERCIAL_FISHERY_EXEMPTION","CA_SK_COMMERCIAL_FISHERY_EXEMPTION","CA_BC_PRODUCTION_AND_MACHINERY_EXEMPTION","CA_SK_PRODUCTION_AND_MACHINERY_EXEMPTION","CA_BC_SUB_CONTRACTOR_EXEMPTION","CA_SK_SUB_CONTRACTOR_EXEMPTION","CA_BC_CONTRACTOR_EXEMPTION","CA_SK_CONTRACTOR_EXEMPTION","CA_ON_PURCHASE_EXEMPTION","CA_MB_FARMER_EXEMPTION","CA_NS_FARMER_EXEMPTION","CA_SK_FARMER_EXEMPTION","EU_REVERSE_CHARGE_EXEMPTION_RULE","US_AL_RESELLER_EXEMPTION","US_AK_RESELLER_EXEMPTION","US_AZ_RESELLER_EXEMPTION","US_AR_RESELLER_EXEMPTION","US_CA_RESELLER_EXEMPTION","US_CO_RESELLER_EXEMPTION","US_CT_RESELLER_EXEMPTION","US_DE_RESELLER_EXEMPTION","US_FL_RESELLER_EXEMPTION","US_GA_RESELLER_EXEMPTION","US_HI_RESELLER_EXEMPTION","US_ID_RESELLER_EXEMPTION","US_IL_RESELLER_EXEMPTION","US_IN_RESELLER_EXEMPTION","US_IA_RESELLER_EXEMPTION","US_KS_RESELLER_EXEMPTION","US_KY_RESELLER_EXEMPTION","US_LA_RESELLER_EXEMPTION","US_ME_RESELLER_EXEMPTION","US_MD_RESELLER_EXEMPTION","US_MA_RESELLER_EXEMPTION","US_MI_RESELLER_EXEMPTION","US_MN_RESELLER_EXEMPTION","US_MS_RESELLER_EXEMPTION","US_MO_RESELLER_EXEMPTION","US_MT_RESELLER_EXEMPTION","US_NE_RESELLER_EXEMPTION","US_NV_RESELLER_EXEMPTION","US_NH_RESELLER_EXEMPTION","US_NJ_RESELLER_EXEMPTION","US_NM_RESELLER_EXEMPTION","US_NY_RESELLER_EXEMPTION","US_NC_RESELLER_EXEMPTION","US_ND_RESELLER_EXEMPTION","US_OH_RESELLER_EXEMPTION","US_OK_RESELLER_EXEMPTION","US_OR_RESELLER_EXEMPTION","US_PA_RESELLER_EXEMPTION","US_RI_RESELLER_EXEMPTION","US_SC_RESELLER_EXEMPTION","US_SD_RESELLER_EXEMPTION","US_TN_RESELLER_EXEMPTION","US_TX_RESELLER_EXEMPTION","US_UT_RESELLER_EXEMPTION","US_VT_RESELLER_EXEMPTION","US_VA_RESELLER_EXEMPTION","US_WA_RESELLER_EXEMPTION","US_WV_RESELLER_EXEMPTION","US_WI_RESELLER_EXEMPTION","US_WY_RESELLER_EXEMPTION","US_DC_RESELLER_EXEMPTION"]}, +"TaxLine":{"o":{"f":{"channelLiable":"Boolean","price":"Money!","priceSet":"MoneyBag!","rate":"Float","ratePercentage":"Float","source":"String","title":"String!"},"d":{"price":"Use `priceSet` instead."}}}, +"TaxPartnerState":{"e":["PENDING","READY","ACTIVE"]}, +"TaxSettings":{"o":{"f":{"taxId":"String"}}}, +"TaxSummaryCreatePayload":{"o":{"f":{"enqueuedOrders":"[Order!]","userErrors":"[TaxSummaryCreateUserError!]!"}}}, +"TaxSummaryCreateUserError":{"o":{"f":{"code":"TaxSummaryCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"TaxSummaryCreateUserErrorCode":{"e":["ORDER_NOT_FOUND","GENERAL_ERROR"]}, +"Taxonomy":{"o":{"f":{"categories":["TaxonomyCategoryConnection!",{"after":"String","before":"String","childrenOf":"ID","descendantsOf":"ID","first":"Int","last":"Int","search":"String","siblingsOf":"ID"}]}}}, +"TaxonomyAttribute":{"o":{"f":{"id":"ID!"},"t":["Node"]}}, +"TaxonomyCategory":{"o":{"f":{"ancestorIds":"[ID!]!","attributes":["TaxonomyCategoryAttributeConnection!",{"after":"String","before":"String","first":"Int","last":"Int"}],"childrenIds":"[ID!]!","fullName":"String!","id":"ID!","isArchived":"Boolean!","isLeaf":"Boolean!","isRoot":"Boolean!","level":"Int!","name":"String!","parentId":"ID"},"t":["Node"]}}, +"TaxonomyCategoryAttribute":{"u":["TaxonomyAttribute","TaxonomyChoiceListAttribute","TaxonomyMeasurementAttribute"]}, +"TaxonomyCategoryAttributeConnection":{"o":{"f":{"edges":"[TaxonomyCategoryAttributeEdge!]!","nodes":"[TaxonomyCategoryAttribute!]!","pageInfo":"PageInfo!"}}}, +"TaxonomyCategoryAttributeEdge":{"o":{"f":{"cursor":"String!","node":"TaxonomyCategoryAttribute!"}}}, +"TaxonomyCategoryConnection":{"o":{"f":{"edges":"[TaxonomyCategoryEdge!]!","nodes":"[TaxonomyCategory!]!","pageInfo":"PageInfo!"}}}, +"TaxonomyCategoryEdge":{"o":{"f":{"cursor":"String!","node":"TaxonomyCategory!"}}}, +"TaxonomyChoiceListAttribute":{"o":{"f":{"id":"ID!","name":"String!","values":["TaxonomyValueConnection!",{"after":"String","before":"String","first":"Int","last":"Int"}]},"t":["Node"]}}, +"TaxonomyMeasurementAttribute":{"o":{"f":{"id":"ID!","name":"String!","options":"[Attribute!]!"},"t":["Node"]}}, +"TaxonomyValue":{"o":{"f":{"id":"ID!","name":"String!"},"t":["Node"]}}, +"TaxonomyValueConnection":{"o":{"f":{"edges":"[TaxonomyValueEdge!]!","nodes":"[TaxonomyValue!]!","pageInfo":"PageInfo!"}}}, +"TaxonomyValueEdge":{"o":{"f":{"cursor":"String!","node":"TaxonomyValue!"}}}, +"TenderTransaction":{"o":{"f":{"amount":"MoneyV2!","id":"ID!","order":"Order","paymentMethod":"String","processedAt":"DateTime","remoteReference":"String","test":"Boolean!","transactionDetails":"TenderTransactionDetails","user":"StaffMember"},"t":["Node"]}}, +"TenderTransactionConnection":{"o":{"f":{"edges":"[TenderTransactionEdge!]!","nodes":"[TenderTransaction!]!","pageInfo":"PageInfo!"}}}, +"TenderTransactionCreditCardDetails":{"o":{"f":{"creditCardCompany":"String","creditCardNumber":"String"}}}, +"TenderTransactionDetails":{"u":["TenderTransactionCreditCardDetails"]}, +"TenderTransactionEdge":{"o":{"f":{"cursor":"String!","node":"TenderTransaction!"}}}, +"ThemeCreatePayload":{"o":{"f":{"theme":"OnlineStoreTheme","userErrors":"[ThemeCreateUserError!]!"}}}, +"ThemeCreateUserError":{"o":{"f":{"code":"ThemeCreateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ThemeCreateUserErrorCode":{"e":["INVALID_ZIP","ZIP_IS_EMPTY","ZIP_TOO_LARGE","THEME_CREATION_NOT_ALLOWED_FOR_THEME_LIMITED_PLAN","INVALID_THEME_ROLE_FOR_THEME_CREATION"]}, +"ThemeDeletePayload":{"o":{"f":{"deletedThemeId":"ID","userErrors":"[ThemeDeleteUserError!]!"}}}, +"ThemeDeleteUserError":{"o":{"f":{"code":"ThemeDeleteUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ThemeDeleteUserErrorCode":{"e":["NOT_FOUND"]}, +"ThemeDuplicatePayload":{"o":{"f":{"newTheme":"OnlineStoreTheme","userErrors":"[ThemeDuplicateUserError!]!"}}}, +"ThemeDuplicateUserError":{"o":{"f":{"code":"ThemeDuplicateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ThemeDuplicateUserErrorCode":{"e":["NOT_FOUND"]}, +"ThemeFilesCopyFileInput":{"i":{"dstFilename":"String!","srcFilename":"String!"}}, +"ThemeFilesCopyPayload":{"o":{"f":{"copiedThemeFiles":"[OnlineStoreThemeFileOperationResult!]","userErrors":"[OnlineStoreThemeFilesUserErrors!]!"}}}, +"ThemeFilesDeletePayload":{"o":{"f":{"deletedThemeFiles":"[OnlineStoreThemeFileOperationResult!]","userErrors":"[OnlineStoreThemeFilesUserErrors!]!"}}}, +"ThemeFilesUpsertPayload":{"o":{"f":{"job":"Job","upsertedThemeFiles":"[OnlineStoreThemeFileOperationResult!]","userErrors":"[OnlineStoreThemeFilesUserErrors!]!"}}}, +"ThemePublishPayload":{"o":{"f":{"theme":"OnlineStoreTheme","userErrors":"[ThemePublishUserError!]!"}}}, +"ThemePublishUserError":{"o":{"f":{"code":"ThemePublishUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ThemePublishUserErrorCode":{"e":["NOT_FOUND","CANNOT_PUBLISH_THEME_DURING_INSTALL","THEME_PUBLISH_NOT_AVAILABLE_FOR_THEME_LIMITED_PLAN"]}, +"ThemeRole":{"e":{"v":["MAIN","UNPUBLISHED","DEMO","DEVELOPMENT","ARCHIVED","LOCKED","MOBILE"],"d":{"MOBILE":"The feature for this role has been deprecated."}}}, +"ThemeUpdatePayload":{"o":{"f":{"theme":"OnlineStoreTheme","userErrors":"[ThemeUpdateUserError!]!"}}}, +"ThemeUpdateUserError":{"o":{"f":{"code":"ThemeUpdateUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ThemeUpdateUserErrorCode":{"e":["NOT_FOUND","TOO_LONG","INVALID"]}, +"TipSale":{"o":{"f":{"actionType":"SaleActionType!","id":"ID!","lineItem":"LineItem!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"TransactionFee":{"o":{"f":{"amount":"MoneyV2!","createdAt":"DateTime!","flatFee":"MoneyV2!","flatFeeName":"String","id":"ID!","rate":"Decimal!","rateName":"String","taxAmount":"MoneyV2!","type":"String!"},"t":["Node"]}}, +"TransactionSortKeys":{"e":["CREATED_AT","EXPIRES_AT"]}, +"TransactionVoidPayload":{"o":{"f":{"transaction":"OrderTransaction","userErrors":"[TransactionVoidUserError!]!"}}}, +"TransactionVoidUserError":{"o":{"f":{"code":"TransactionVoidUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"TransactionVoidUserErrorCode":{"e":["TRANSACTION_NOT_FOUND","AUTH_NOT_SUCCESSFUL","AUTH_NOT_VOIDABLE","GENERIC_ERROR"]}, +"TransferSortKeys":{"e":["CREATED_AT","DESTINATION_NAME","EXPECTED_SHIPMENT_ARRIVAL","ID","NAME","ORIGIN_NAME","SOURCE_NAME","STATUS"]}, +"TranslatableContent":{"o":{"f":{"digest":"String","key":"String!","locale":"String!","type":"LocalizableContentType!","value":"String"}}}, +"TranslatableResource":{"o":{"f":{"nestedTranslatableResources":["TranslatableResourceConnection!",{"after":"String","before":"String","first":"Int","last":"Int","resourceType":"TranslatableResourceType","reverse":"Boolean="}],"resourceId":"ID!","translatableContent":["[TranslatableContent!]!",{"marketId":"ID"}],"translations":["[Translation!]!",{"locale":"String!","marketId":"ID","outdated":"Boolean"}]}}}, +"TranslatableResourceConnection":{"o":{"f":{"edges":"[TranslatableResourceEdge!]!","nodes":"[TranslatableResource!]!","pageInfo":"PageInfo!"}}}, +"TranslatableResourceEdge":{"o":{"f":{"cursor":"String!","node":"TranslatableResource!"}}}, +"TranslatableResourceType":{"e":{"v":["ARTICLE","ARTICLE_IMAGE","BLOG","COLLECTION","COLLECTION_IMAGE","DELIVERY_METHOD_DEFINITION","EMAIL_TEMPLATE","FILTER","LINK","MEDIA_IMAGE","MENU","METAFIELD","METAOBJECT","ONLINE_STORE_THEME","ONLINE_STORE_THEME_APP_EMBED","ONLINE_STORE_THEME_JSON_TEMPLATE","ONLINE_STORE_THEME_LOCALE_CONTENT","ONLINE_STORE_THEME_SECTION_GROUP","ONLINE_STORE_THEME_SETTINGS_CATEGORY","ONLINE_STORE_THEME_SETTINGS_DATA_SECTIONS","PACKING_SLIP_TEMPLATE","PAGE","PAYMENT_GATEWAY","PRODUCT","PRODUCT_OPTION","PRODUCT_OPTION_VALUE","SELLING_PLAN","SELLING_PLAN_GROUP","SHOP","SHOP_POLICY"],"d":{"METAFIELD":"Query metafields via their respective resource owners and use `Metafield.translatable` to determine which is translatable."}}}, +"Translation":{"o":{"f":{"key":"String!","locale":"String!","market":"Market","outdated":"Boolean!","updatedAt":"DateTime","value":"String"}}}, +"TranslationErrorCode":{"e":{"v":["BLANK","INVALID","RESOURCE_NOT_FOUND","RESOURCE_NOT_TRANSLATABLE","TOO_MANY_KEYS_FOR_RESOURCE","INVALID_KEY_FOR_MODEL","FAILS_RESOURCE_VALIDATION","INVALID_TRANSLATABLE_CONTENT","INVALID_MARKET_LOCALIZABLE_CONTENT","INVALID_LOCALE_FOR_SHOP","INVALID_CODE","INVALID_FORMAT","MARKET_CUSTOM_CONTENT_NOT_ALLOWED","MARKET_DOES_NOT_EXIST","MARKET_LOCALE_CREATION_FAILED","RESOURCE_NOT_MARKET_CUSTOMIZABLE","INVALID_LOCALE_FOR_MARKET","INVALID_VALUE_FOR_HANDLE_TRANSLATION"],"d":{"INVALID_LOCALE_FOR_MARKET":"`invalid_locale_for_market` is deprecated because the creation of a locale that's specific to a market no longer needs to be tied to that market's URL."}}}, +"TranslationInput":{"i":{"key":"String!","locale":"String!","marketId":"ID","translatableContentDigest":"String!","value":"String!"}}, +"TranslationUserError":{"o":{"f":{"code":"TranslationErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"TranslationsRegisterPayload":{"o":{"f":{"translations":"[Translation!]","userErrors":"[TranslationUserError!]!"}}}, +"TranslationsRemovePayload":{"o":{"f":{"translations":"[Translation!]","userErrors":"[TranslationUserError!]!"}}}, +"TypedAttribute":{"o":{"f":{"key":"String!","value":"String!"}}}, +"URL":"s", +"UTMInput":{"i":{"campaign":"String!","medium":"String!","source":"String!"}}, +"UTMParameters":{"o":{"f":{"campaign":"String","content":"String","medium":"String","source":"String","term":"String"}}}, +"UniqueMetafieldValueInput":{"i":{"key":"String!","namespace":"String","value":"String!"}}, +"UnitPriceMeasurement":{"o":{"f":{"measuredType":"UnitPriceMeasurementMeasuredType","quantityUnit":"UnitPriceMeasurementMeasuredUnit","quantityValue":"Float!","referenceUnit":"UnitPriceMeasurementMeasuredUnit","referenceValue":"Int!"}}}, +"UnitPriceMeasurementInput":{"i":{"quantityUnit":"UnitPriceMeasurementMeasuredUnit","quantityValue":"Float","referenceUnit":"UnitPriceMeasurementMeasuredUnit","referenceValue":"Int"}}, +"UnitPriceMeasurementMeasuredType":{"e":["VOLUME","WEIGHT","LENGTH","AREA","COUNT","UNKNOWN"]}, +"UnitPriceMeasurementMeasuredUnit":{"e":["ML","CL","L","M3","FLOZ","PT","QT","GAL","MG","G","KG","OZ","LB","MM","CM","M","IN","FT","YD","M2","FT2","ITEM","UNKNOWN"]}, +"UnitSystem":{"e":["IMPERIAL_SYSTEM","METRIC_SYSTEM"]}, +"UnknownSale":{"o":{"f":{"actionType":"SaleActionType!","id":"ID!","lineType":"SaleLineType!","quantity":"Int","taxes":"[SaleTax!]!","totalAmount":"MoneyBag!","totalDiscountAmountAfterTaxes":"MoneyBag!","totalDiscountAmountBeforeTaxes":"MoneyBag!","totalTaxAmount":"MoneyBag!"},"t":["Sale"]}}, +"UnsignedInt64":"s", +"UnverifiedReturnLineItem":{"o":{"f":{"customerNote":"String","id":"ID!","processableQuantity":"Int!","processedQuantity":"Int!","quantity":"Int!","refundableQuantity":"Int!","refundedQuantity":"Int!","returnReason":"ReturnReason!","returnReasonDefinition":"ReturnReasonDefinition","returnReasonNote":"String!","unitPrice":"MoneyV2!","unprocessedQuantity":"Int!"},"t":["Node","ReturnLineItemType"],"d":{"returnReason":"Use `returnReasonDefinition` instead. This field will be removed in the future."}}}, +"UpdateMediaInput":{"i":{"alt":"String","id":"ID!","previewImageSource":"String"}}, +"UrlRedirect":{"o":{"f":{"createdAt":"DateTime!","id":"ID!","path":"String!","target":"String!"},"t":["Node"]}}, +"UrlRedirectBulkDeleteAllPayload":{"o":{"f":{"job":"Job","userErrors":"[UserError!]!"}}}, +"UrlRedirectBulkDeleteByIdsPayload":{"o":{"f":{"job":"Job","userErrors":"[UrlRedirectBulkDeleteByIdsUserError!]!"}}}, +"UrlRedirectBulkDeleteByIdsUserError":{"o":{"f":{"code":"UrlRedirectBulkDeleteByIdsUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"UrlRedirectBulkDeleteByIdsUserErrorCode":{"e":["IDS_EMPTY"]}, +"UrlRedirectBulkDeleteBySavedSearchPayload":{"o":{"f":{"job":"Job","userErrors":"[UrlRedirectBulkDeleteBySavedSearchUserError!]!"}}}, +"UrlRedirectBulkDeleteBySavedSearchUserError":{"o":{"f":{"code":"UrlRedirectBulkDeleteBySavedSearchUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"UrlRedirectBulkDeleteBySavedSearchUserErrorCode":{"e":["SAVED_SEARCH_NOT_FOUND","INVALID_SAVED_SEARCH_QUERY"]}, +"UrlRedirectBulkDeleteBySearchPayload":{"o":{"f":{"job":"Job","userErrors":"[UrlRedirectBulkDeleteBySearchUserError!]!"}}}, +"UrlRedirectBulkDeleteBySearchUserError":{"o":{"f":{"code":"UrlRedirectBulkDeleteBySearchUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"UrlRedirectBulkDeleteBySearchUserErrorCode":{"e":["INVALID_SEARCH_ARGUMENT"]}, +"UrlRedirectConnection":{"o":{"f":{"edges":"[UrlRedirectEdge!]!","nodes":"[UrlRedirect!]!","pageInfo":"PageInfo!"}}}, +"UrlRedirectCreatePayload":{"o":{"f":{"urlRedirect":"UrlRedirect","userErrors":"[UrlRedirectUserError!]!"}}}, +"UrlRedirectDeletePayload":{"o":{"f":{"deletedUrlRedirectId":"ID","userErrors":"[UrlRedirectUserError!]!"}}}, +"UrlRedirectEdge":{"o":{"f":{"cursor":"String!","node":"UrlRedirect!"}}}, +"UrlRedirectErrorCode":{"e":["DOES_NOT_EXIST","CREATE_FAILED","UPDATE_FAILED","DELETE_FAILED"]}, +"UrlRedirectImport":{"o":{"f":{"count":"Int","createdCount":"Int","failedCount":"Int","finished":"Boolean!","finishedAt":"DateTime","id":"ID!","previewRedirects":"[UrlRedirectImportPreview!]!","updatedCount":"Int"},"t":["Node"]}}, +"UrlRedirectImportCreatePayload":{"o":{"f":{"urlRedirectImport":"UrlRedirectImport","userErrors":"[UrlRedirectImportUserError!]!"}}}, +"UrlRedirectImportErrorCode":{"e":{"v":["FILE_DOES_NOT_EXIST","NOT_FOUND","ALREADY_IMPORTED","IN_PROGRESS"],"d":{"FILE_DOES_NOT_EXIST":"This error code is never returned"}}}, +"UrlRedirectImportPreview":{"o":{"f":{"path":"String!","target":"String!"}}}, +"UrlRedirectImportSubmitPayload":{"o":{"f":{"job":"Job","userErrors":"[UrlRedirectImportUserError!]!"}}}, +"UrlRedirectImportUserError":{"o":{"f":{"code":"UrlRedirectImportErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"UrlRedirectInput":{"i":{"path":"String","target":"String"}}, +"UrlRedirectSortKeys":{"e":["ID","PATH","RELEVANCE"]}, +"UrlRedirectUpdatePayload":{"o":{"f":{"urlRedirect":"UrlRedirect","userErrors":"[UrlRedirectUserError!]!"}}}, +"UrlRedirectUserError":{"o":{"f":{"code":"UrlRedirectErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"UserError":{"o":{"f":{"field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"UtcOffset":"s", +"Validation":{"o":{"f":{"blockOnFailure":"Boolean!","enabled":"Boolean!","errorHistory":"FunctionsErrorHistory","id":"ID!","metafield":["Metafield",{"key":"String!","namespace":"String"}],"metafieldDefinitions":["MetafieldDefinitionConnection!",{"after":"String","before":"String","first":"Int","last":"Int","namespace":"String","pinnedStatus":"MetafieldDefinitionPinnedStatus=","query":"String","reverse":"Boolean=","sortKey":"MetafieldDefinitionSortKeys="}],"metafields":["MetafieldConnection!",{"after":"String","before":"String","first":"Int","keys":"[String!]","last":"Int","namespace":"String","reverse":"Boolean="}],"shopifyFunction":"ShopifyFunction!","title":"String!"},"t":["HasMetafieldDefinitions","HasMetafields","Node"],"d":{"metafieldDefinitions":"This field will be removed in a future version. Use `QueryRoot.metafieldDefinitions` instead."}}}, +"ValidationConnection":{"o":{"f":{"edges":"[ValidationEdge!]!","nodes":"[Validation!]!","pageInfo":"PageInfo!"}}}, +"ValidationCreateInput":{"i":{"f":{"blockOnFailure":"Boolean=","enable":"Boolean=","functionHandle":"String","functionId":"String","metafields":"[MetafieldInput!]=","title":"String"},"d":{"functionId":"Use `functionHandle` instead."}}}, +"ValidationCreatePayload":{"o":{"f":{"userErrors":"[ValidationUserError!]!","validation":"Validation"}}}, +"ValidationDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[ValidationUserError!]!"}}}, +"ValidationEdge":{"o":{"f":{"cursor":"String!","node":"Validation!"}}}, +"ValidationSortKeys":{"e":["ID"]}, +"ValidationUpdateInput":{"i":{"blockOnFailure":"Boolean=","enable":"Boolean=","metafields":"[MetafieldInput!]=","title":"String"}}, +"ValidationUpdatePayload":{"o":{"f":{"userErrors":"[ValidationUserError!]!","validation":"Validation"}}}, +"ValidationUserError":{"o":{"f":{"code":"ValidationUserErrorCode","field":"[String!]","message":"String!"},"t":["DisplayableError"]}}, +"ValidationUserErrorCode":{"e":["NOT_FOUND","FUNCTION_NOT_FOUND","CUSTOM_APP_FUNCTION_NOT_ELIGIBLE","FUNCTION_DOES_NOT_IMPLEMENT","PUBLIC_APP_NOT_ALLOWED","FUNCTION_PENDING_DELETION","MAX_VALIDATIONS_ACTIVATED","MISSING_FUNCTION_IDENTIFIER","MULTIPLE_FUNCTION_IDENTIFIERS","INVALID_TYPE","INVALID_VALUE","APP_NOT_AUTHORIZED","UNSTRUCTURED_RESERVED_NAMESPACE","DISALLOWED_OWNER_TYPE","INCLUSION","TAKEN","PRESENT","BLANK","TOO_LONG","TOO_SHORT","INVALID","CAPABILITY_VIOLATION","INTERNAL_ERROR"]}, +"VariantOptionValueInput":{"i":{"id":"ID","linkedMetafieldValue":"String","name":"String","optionId":"ID","optionName":"String"}}, +"VaultCreditCard":{"o":{"f":{"billingAddress":"CustomerCreditCardBillingAddress","brand":"String!","expired":"Boolean!","expiryMonth":"Int!","expiryYear":"Int!","lastDigits":"String!","name":"String!"}}}, +"VaultPaypalBillingAgreement":{"o":{"f":{"inactive":"Boolean!","name":"String!","paypalAccountEmail":"String!"}}}, +"Vector3":{"o":{"f":{"x":"Float!","y":"Float!","z":"Float!"}}}, +"Video":{"o":{"f":{"alt":"String","createdAt":"DateTime!","duration":"Int","fileErrors":"[FileError!]!","fileStatus":"FileStatus!","filename":"String!","id":"ID!","mediaContentType":"MediaContentType!","mediaErrors":"[MediaError!]!","mediaWarnings":"[MediaWarning!]!","originalSource":"VideoSource","preview":"MediaPreviewImage","sources":"[VideoSource!]!","status":"MediaStatus!","updatedAt":"DateTime!"},"t":["File","Media","Node"]}}, +"VideoSource":{"o":{"f":{"fileSize":"Int","format":"String!","height":"Int!","mimeType":"String!","url":"String!","width":"Int!"}}}, +"WebPixel":{"o":{"f":{"id":"ID!","settings":"JSON!"},"t":["Node"]}}, +"WebPixelCreatePayload":{"o":{"f":{"userErrors":"[ErrorsWebPixelUserError!]!","webPixel":"WebPixel"}}}, +"WebPixelDeletePayload":{"o":{"f":{"deletedWebPixelId":"ID","userErrors":"[ErrorsWebPixelUserError!]!"}}}, +"WebPixelInput":{"i":{"settings":"JSON!"}}, +"WebPixelUpdatePayload":{"o":{"f":{"userErrors":"[ErrorsWebPixelUserError!]!","webPixel":"WebPixel"}}}, +"WebPresenceCreateInput":{"i":{"alternateLocales":"[String!]","defaultLocale":"String!","domainId":"ID","subfolderSuffix":"String"}}, +"WebPresenceCreatePayload":{"o":{"f":{"userErrors":"[MarketUserError!]!","webPresence":"MarketWebPresence"}}}, +"WebPresenceDeletePayload":{"o":{"f":{"deletedId":"ID","userErrors":"[MarketUserError!]!"}}}, +"WebPresenceUpdateInput":{"i":{"alternateLocales":"[String!]","defaultLocale":"String","subfolderSuffix":"String"}}, +"WebPresenceUpdatePayload":{"o":{"f":{"userErrors":"[MarketUserError!]!","webPresence":"MarketWebPresence"}}}, +"WebhookEventBridgeEndpoint":{"o":{"f":{"arn":"ARN!"}}}, +"WebhookHttpEndpoint":{"o":{"f":{"callbackUrl":"URL!"}}}, +"WebhookPubSubEndpoint":{"o":{"f":{"pubSubProject":"String!","pubSubTopic":"String!"}}}, +"WebhookSubscription":{"o":{"f":{"apiVersion":"ApiVersion!","callbackUrl":"URL!","createdAt":"DateTime!","endpoint":"WebhookSubscriptionEndpoint!","filter":"String","format":"WebhookSubscriptionFormat!","id":"ID!","includeFields":"[String!]!","legacyResourceId":"UnsignedInt64!","metafieldNamespaces":"[String!]!","metafields":"[WebhookSubscriptionMetafieldIdentifier!]!","name":"String","topic":"WebhookSubscriptionTopic!","updatedAt":"DateTime!","uri":"String!"},"t":["LegacyInteroperability","Node"],"d":{"callbackUrl":"Use `uri` instead.","endpoint":"Use `uri` instead."}}}, +"WebhookSubscriptionConnection":{"o":{"f":{"edges":"[WebhookSubscriptionEdge!]!","nodes":"[WebhookSubscription!]!","pageInfo":"PageInfo!"}}}, +"WebhookSubscriptionCreatePayload":{"o":{"f":{"userErrors":"[UserError!]!","webhookSubscription":"WebhookSubscription"}}}, +"WebhookSubscriptionDeletePayload":{"o":{"f":{"deletedWebhookSubscriptionId":"ID","userErrors":"[UserError!]!"}}}, +"WebhookSubscriptionEdge":{"o":{"f":{"cursor":"String!","node":"WebhookSubscription!"}}}, +"WebhookSubscriptionEndpoint":{"u":["WebhookEventBridgeEndpoint","WebhookHttpEndpoint","WebhookPubSubEndpoint"]}, +"WebhookSubscriptionFormat":{"e":["JSON","XML"]}, +"WebhookSubscriptionInput":{"i":{"f":{"callbackUrl":"URL","filter":"String","format":"WebhookSubscriptionFormat","includeFields":"[String!]","metafieldNamespaces":"[String!]","metafields":"[HasMetafieldsMetafieldIdentifierInput!]","name":"String","uri":"String"},"d":{"callbackUrl":"Use `uri` instead."}}}, +"WebhookSubscriptionMetafieldIdentifier":{"o":{"f":{"key":"String!","namespace":"String!"}}}, +"WebhookSubscriptionSortKeys":{"e":["CREATED_AT","ID"]}, +"WebhookSubscriptionTopic":{"e":["TAX_SUMMARIES_CREATE","APP_UNINSTALLED","APP_SCOPES_UPDATE","CARTS_CREATE","CARTS_UPDATE","CHANNELS_DELETE","CHECKOUTS_CREATE","CHECKOUTS_DELETE","CHECKOUTS_UPDATE","CUSTOMER_PAYMENT_METHODS_CREATE","CUSTOMER_PAYMENT_METHODS_UPDATE","CUSTOMER_PAYMENT_METHODS_REVOKE","COLLECTION_LISTINGS_ADD","COLLECTION_LISTINGS_REMOVE","COLLECTION_LISTINGS_UPDATE","COLLECTION_PUBLICATIONS_CREATE","COLLECTION_PUBLICATIONS_DELETE","COLLECTION_PUBLICATIONS_UPDATE","COLLECTIONS_CREATE","COLLECTIONS_DELETE","COLLECTIONS_UPDATE","CUSTOMER_GROUPS_CREATE","CUSTOMER_GROUPS_DELETE","CUSTOMER_GROUPS_UPDATE","CUSTOMERS_CREATE","CUSTOMERS_DELETE","CUSTOMERS_DISABLE","CUSTOMERS_ENABLE","CUSTOMERS_UPDATE","CUSTOMERS_PURCHASING_SUMMARY","CUSTOMERS_MARKETING_CONSENT_UPDATE","CUSTOMERS_WHATS_APP_MARKETING_CONSENT_UPDATE","CUSTOMER_TAGS_ADDED","CUSTOMER_TAGS_REMOVED","CUSTOMERS_EMAIL_MARKETING_CONSENT_UPDATE","DISPUTES_CREATE","DISPUTES_UPDATE","DRAFT_ORDERS_CREATE","DRAFT_ORDERS_DELETE","DRAFT_ORDERS_UPDATE","FULFILLMENT_EVENTS_CREATE","FULFILLMENT_EVENTS_DELETE","FULFILLMENTS_CREATE","FULFILLMENTS_UPDATE","ATTRIBUTED_SESSIONS_FIRST","ATTRIBUTED_SESSIONS_LAST","ORDER_TRANSACTIONS_CREATE","ORDERS_CANCELLED","ORDERS_CREATE","ORDERS_DELETE","ORDERS_EDITED","ORDERS_FULFILLED","ORDERS_PAID","ORDERS_PARTIALLY_FULFILLED","ORDERS_UPDATED","ORDERS_LINK_REQUESTED","FULFILLMENT_ORDERS_MOVED","FULFILLMENT_ORDERS_HOLD_RELEASED","FULFILLMENT_ORDERS_SCHEDULED_FULFILLMENT_ORDER_READY","FULFILLMENT_HOLDS_RELEASED","FULFILLMENT_ORDERS_ORDER_ROUTING_COMPLETE","FULFILLMENT_ORDERS_CANCELLED","FULFILLMENT_ORDERS_FULFILLMENT_SERVICE_FAILED_TO_COMPLETE","FULFILLMENT_ORDERS_FULFILLMENT_REQUEST_REJECTED","FULFILLMENT_ORDERS_CANCELLATION_REQUEST_SUBMITTED","FULFILLMENT_ORDERS_CANCELLATION_REQUEST_ACCEPTED","FULFILLMENT_ORDERS_CANCELLATION_REQUEST_REJECTED","FULFILLMENT_ORDERS_FULFILLMENT_REQUEST_SUBMITTED","FULFILLMENT_ORDERS_FULFILLMENT_REQUEST_ACCEPTED","FULFILLMENT_HOLDS_ADDED","FULFILLMENT_ORDERS_LINE_ITEMS_PREPARED_FOR_LOCAL_DELIVERY","FULFILLMENT_ORDERS_PLACED_ON_HOLD","FULFILLMENT_ORDERS_MERGED","FULFILLMENT_ORDERS_SPLIT","FULFILLMENT_ORDERS_PROGRESS_REPORTED","FULFILLMENT_ORDERS_MANUALLY_REPORTED_PROGRESS_STOPPED","PRODUCT_LISTINGS_ADD","PRODUCT_LISTINGS_REMOVE","PRODUCT_LISTINGS_UPDATE","SCHEDULED_PRODUCT_LISTINGS_ADD","SCHEDULED_PRODUCT_LISTINGS_UPDATE","SCHEDULED_PRODUCT_LISTINGS_REMOVE","PRODUCT_PUBLICATIONS_CREATE","PRODUCT_PUBLICATIONS_DELETE","PRODUCT_PUBLICATIONS_UPDATE","PRODUCTS_CREATE","PRODUCTS_DELETE","PRODUCTS_UPDATE","REFUNDS_CREATE","SEGMENTS_CREATE","SEGMENTS_DELETE","SEGMENTS_UPDATE","SHIPPING_ADDRESSES_CREATE","SHIPPING_ADDRESSES_UPDATE","SHOP_UPDATE","TAX_PARTNERS_UPDATE","TAX_SERVICES_CREATE","TAX_SERVICES_UPDATE","THEMES_CREATE","THEMES_DELETE","THEMES_PUBLISH","THEMES_UPDATE","VARIANTS_IN_STOCK","VARIANTS_OUT_OF_STOCK","INVENTORY_LEVELS_CONNECT","INVENTORY_LEVELS_UPDATE","INVENTORY_LEVELS_DISCONNECT","INVENTORY_ITEMS_CREATE","INVENTORY_ITEMS_UPDATE","INVENTORY_ITEMS_DELETE","LOCATIONS_ACTIVATE","LOCATIONS_DEACTIVATE","LOCATIONS_CREATE","LOCATIONS_UPDATE","LOCATIONS_DELETE","TENDER_TRANSACTIONS_CREATE","APP_PURCHASES_ONE_TIME_UPDATE","APP_SUBSCRIPTIONS_APPROACHING_CAPPED_AMOUNT","APP_SUBSCRIPTIONS_UPDATE","LOCALES_CREATE","LOCALES_UPDATE","LOCALES_DESTROY","MACHINE_TRANSLATION_BATCH_COMPLETED","DOMAINS_CREATE","DOMAINS_UPDATE","DOMAINS_DESTROY","SUBSCRIPTION_CONTRACTS_CREATE","SUBSCRIPTION_CONTRACTS_UPDATE","SUBSCRIPTION_BILLING_CYCLE_EDITS_CREATE","SUBSCRIPTION_BILLING_CYCLE_EDITS_UPDATE","SUBSCRIPTION_BILLING_CYCLE_EDITS_DELETE","PROFILES_CREATE","PROFILES_UPDATE","PROFILES_DELETE","SUBSCRIPTION_BILLING_ATTEMPTS_SUCCESS","SUBSCRIPTION_BILLING_ATTEMPTS_FAILURE","SUBSCRIPTION_BILLING_ATTEMPTS_CHALLENGED","RETURNS_CANCEL","RETURNS_CLOSE","RETURNS_REOPEN","RETURNS_REQUEST","RETURNS_APPROVE","RETURNS_UPDATE","RETURNS_PROCESS","RETURNS_DECLINE","REVERSE_DELIVERIES_ATTACH_DELIVERABLE","REVERSE_FULFILLMENT_ORDERS_DISPOSE","PAYMENT_TERMS_CREATE","PAYMENT_TERMS_DELETE","PAYMENT_TERMS_UPDATE","PAYMENT_SCHEDULES_DUE","SELLING_PLAN_GROUPS_CREATE","SELLING_PLAN_GROUPS_UPDATE","SELLING_PLAN_GROUPS_DELETE","BULK_OPERATIONS_FINISH","PRODUCT_FEEDS_CREATE","PRODUCT_FEEDS_UPDATE","PRODUCT_FEEDS_INCREMENTAL_SYNC","PRODUCT_FEEDS_FULL_SYNC","PRODUCT_FEEDS_FULL_SYNC_FINISH","MARKETS_CREATE","MARKETS_UPDATE","MARKETS_DELETE","ORDERS_RISK_ASSESSMENT_CHANGED","ORDERS_SHOPIFY_PROTECT_ELIGIBILITY_CHANGED","FINANCE_KYC_INFORMATION_UPDATE","FULFILLMENT_ORDERS_RESCHEDULED","PUBLICATIONS_DELETE","AUDIT_EVENTS_ADMIN_API_ACTIVITY","FULFILLMENT_ORDERS_LINE_ITEMS_PREPARED_FOR_PICKUP","COMPANIES_CREATE","COMPANIES_UPDATE","COMPANIES_DELETE","COMPANY_LOCATIONS_CREATE","COMPANY_LOCATIONS_UPDATE","COMPANY_LOCATIONS_DELETE","COMPANY_CONTACTS_CREATE","COMPANY_CONTACTS_UPDATE","COMPANY_CONTACTS_DELETE","CUSTOMERS_MERGE","INVENTORY_TRANSFERS_ADD_ITEMS","INVENTORY_TRANSFERS_UPDATE_ITEM_QUANTITIES","INVENTORY_TRANSFERS_REMOVE_ITEMS","INVENTORY_TRANSFERS_READY_TO_SHIP","INVENTORY_TRANSFERS_CANCEL","INVENTORY_TRANSFERS_COMPLETE","INVENTORY_TRANSFERS_UPDATED","INVENTORY_SHIPMENTS_DELETE","INVENTORY_SHIPMENTS_CREATE","INVENTORY_SHIPMENTS_MARK_IN_TRANSIT","INVENTORY_SHIPMENTS_UPDATE_TRACKING","INVENTORY_SHIPMENTS_ADD_ITEMS","INVENTORY_SHIPMENTS_UPDATE_ITEM_QUANTITIES","INVENTORY_SHIPMENTS_REMOVE_ITEMS","INVENTORY_SHIPMENTS_RECEIVE_ITEMS","CUSTOMER_ACCOUNT_SETTINGS_UPDATE","CUSTOMER_JOINED_SEGMENT","CUSTOMER_LEFT_SEGMENT","COMPANY_CONTACT_ROLES_ASSIGN","COMPANY_CONTACT_ROLES_REVOKE","SUBSCRIPTION_CONTRACTS_ACTIVATE","SUBSCRIPTION_CONTRACTS_PAUSE","SUBSCRIPTION_CONTRACTS_CANCEL","SUBSCRIPTION_CONTRACTS_FAIL","SUBSCRIPTION_CONTRACTS_EXPIRE","SUBSCRIPTION_CONTRACT_CALCULATIONS_SUCCEED","SUBSCRIPTION_CONTRACT_CALCULATIONS_FAIL","SUBSCRIPTION_BILLING_CYCLES_SKIP","SUBSCRIPTION_BILLING_CYCLES_UNSKIP","METAOBJECTS_CREATE","METAOBJECTS_UPDATE","METAOBJECTS_DELETE","FINANCE_APP_STAFF_MEMBER_GRANT","FINANCE_APP_STAFF_MEMBER_REVOKE","FINANCE_APP_STAFF_MEMBER_DELETE","FINANCE_APP_STAFF_MEMBER_UPDATE","ROLLOUTS_CREATE","ROLLOUTS_DELETE","ROLLOUTS_RESOURCE_CHANGE_ADDED","ROLLOUTS_RESOURCE_CHANGE_REMOVED","ROLLOUTS_RESOURCE_CHANGE_UPDATED","ROLLOUTS_UPDATE","DISCOUNTS_CREATE","DISCOUNTS_UPDATE","DISCOUNTS_DELETE","DISCOUNTS_REDEEMCODE_ADDED","DISCOUNTS_REDEEMCODE_REMOVED","METAFIELD_DEFINITIONS_CREATE","METAFIELD_DEFINITIONS_UPDATE","METAFIELD_DEFINITIONS_DELETE","DELIVERY_PROMISE_SETTINGS_UPDATE","MARKETS_BACKUP_REGION_UPDATE","CHECKOUT_AND_ACCOUNTS_CONFIGURATIONS_UPDATE","REQUESTED_ORDER_EDIT_CREATED","REQUESTED_ORDER_EDIT_RESOLVED","REQUESTED_ORDER_EDIT_DECLINED"]}, +"WebhookSubscriptionUpdatePayload":{"o":{"f":{"userErrors":"[UserError!]!","webhookSubscription":"WebhookSubscription"}}}, +"Weight":{"o":{"f":{"unit":"WeightUnit!","value":"Float!"}}}, +"WeightInput":{"i":{"unit":"WeightUnit!","value":"Float!"}}, +"WeightUnit":{"e":["KILOGRAMS","GRAMS","POUNDS","OUNCES"]} +}} diff --git a/crates/shopify_api/graphql/internal.schema.json b/crates/shopify_api/graphql/internal.schema.json new file mode 100644 index 0000000..468c7b2 --- /dev/null +++ b/crates/shopify_api/graphql/internal.schema.json @@ -0,0 +1,44 @@ +{"format":2,"apiVersion":"2026-10","query":"QueryRoot","mutation":"Mutation", +"directives":{"idempotent":{"l":["FIELD"],"a":{"key":"String!"}},"include":{"l":["FIELD","FRAGMENT_SPREAD","INLINE_FRAGMENT"],"a":{"if":"Boolean!"}},"skip":{"l":["FIELD","FRAGMENT_SPREAD","INLINE_FRAGMENT"],"a":{"if":"Boolean!"}}},"types":{ +"ApiVersion":{"o":{"f":{"handle":"String!"}}}, +"Boolean":"s", +"BulkMutationErrorCode":{"e":["OPERATION_IN_PROGRESS","INVALID_MUTATION","INVALID_STAGED_UPLOAD_FILE","NO_SUCH_FILE","INTERNAL_FILE_SERVER_ERROR","LIMIT_REACHED"]}, +"BulkMutationUserError":{"o":{"f":{"code":"BulkMutationErrorCode","field":"[String!]","message":"String!"}}}, +"BulkOperation":{"o":{"f":{"completedAt":"DateTime","createdAt":"DateTime!","errorCode":"BulkOperationErrorCode","fileSize":"UnsignedInt64","id":"ID!","objectCount":"UnsignedInt64!","partialDataUrl":"URL","query":"String!","rootObjectCount":"UnsignedInt64!","status":"BulkOperationStatus!","type":"BulkOperationType!","url":"URL"}}}, +"BulkOperationCancelPayload":{"o":{"f":{"bulkOperation":"BulkOperation","userErrors":"[UserError!]!"}}}, +"BulkOperationConnection":{"o":{"f":{"nodes":"[BulkOperation!]!","pageInfo":"PageInfo!"}}}, +"BulkOperationErrorCode":{"e":["ACCESS_DENIED","INTERNAL_SERVER_ERROR","TIMEOUT"]}, +"BulkOperationRunMutationPayload":{"o":{"f":{"bulkOperation":"BulkOperation","userErrors":"[BulkMutationUserError!]!"}}}, +"BulkOperationRunQueryPayload":{"o":{"f":{"bulkOperation":"BulkOperation","userErrors":"[BulkOperationUserError!]!"}}}, +"BulkOperationStatus":{"e":["CANCELED","CANCELING","COMPLETED","CREATED","EXPIRED","FAILED","RUNNING"]}, +"BulkOperationType":{"e":["QUERY","MUTATION"]}, +"BulkOperationUserError":{"o":{"f":{"code":"BulkOperationUserErrorCode","field":"[String!]","message":"String!"}}}, +"BulkOperationUserErrorCode":{"e":["OPERATION_IN_PROGRESS","INVALID","LIMIT_REACHED"]}, +"BulkOperationsSortKeys":{"e":["COMPLETED_AT","CREATED_AT"]}, +"DateTime":"s", +"HasMetafieldsMetafieldIdentifierInput":{"i":{"key":"String!","namespace":"String"}}, +"ID":"s", +"Int":"s", +"Mutation":{"o":{"f":{"bulkOperationCancel":["BulkOperationCancelPayload",{"id":"ID!"}],"bulkOperationRunMutation":["BulkOperationRunMutationPayload",{"clientIdentifier":"String","groupObjects":"Boolean=","mutation":"String!","stagedUploadPath":"String!"}],"bulkOperationRunQuery":["BulkOperationRunQueryPayload",{"groupObjects":"Boolean!=","query":"String!"}],"stagedUploadsCreate":["StagedUploadsCreatePayload",{"input":"[StagedUploadInput!]!"}],"webhookSubscriptionCreate":["WebhookSubscriptionCreatePayload",{"topic":"WebhookSubscriptionTopic!","webhookSubscription":"WebhookSubscriptionInput!"}],"webhookSubscriptionDelete":["WebhookSubscriptionDeletePayload",{"id":"ID!"}],"webhookSubscriptionUpdate":["WebhookSubscriptionUpdatePayload",{"id":"ID!","webhookSubscription":"WebhookSubscriptionInput!"}]},"d":{"bulkOperationRunMutation(groupObjects)":"This argument has no effect on output order."}}}, +"PageInfo":{"o":{"f":{"endCursor":"String","hasNextPage":"Boolean!"}}}, +"QueryRoot":{"o":{"f":{"bulkOperation":["BulkOperation",{"id":"ID!"}],"bulkOperations":["BulkOperationConnection!",{"after":"String","before":"String","first":"Int","last":"Int","query":"String","reverse":"Boolean=","sortKey":"BulkOperationsSortKeys="}],"webhookSubscriptions":["WebhookSubscriptionConnection!",{"after":"String","before":"String","callbackUrl":"URL","first":"Int","format":"WebhookSubscriptionFormat","last":"Int","query":"String","reverse":"Boolean=","sortKey":"WebhookSubscriptionSortKeys=","topics":"[WebhookSubscriptionTopic!]","uri":"String"}]},"d":{"webhookSubscriptions(callbackUrl)":"Use `uri` instead."}}}, +"StagedMediaUploadTarget":{"o":{"f":{"parameters":"[StagedUploadParameter!]!","resourceUrl":"URL","url":"URL"}}}, +"StagedUploadHttpMethodType":{"e":["POST","PUT"]}, +"StagedUploadInput":{"i":{"fileSize":"UnsignedInt64","filename":"String!","httpMethod":"StagedUploadHttpMethodType=","mimeType":"String!","resource":"StagedUploadTargetGenerateUploadResource!"}}, +"StagedUploadParameter":{"o":{"f":{"name":"String!","value":"String!"}}}, +"StagedUploadTargetGenerateUploadResource":{"e":{"v":["COLLECTION_IMAGE","FILE","IMAGE","MODEL_3D","PRODUCT_IMAGE","SHOP_IMAGE","VIDEO","BULK_MUTATION_VARIABLES","RETURN_LABEL","URL_REDIRECT_IMPORT","DISPUTE_FILE_UPLOAD"],"d":{"PRODUCT_IMAGE":"Use IMAGE instead. This resource type will be removed in a future version."}}}, +"StagedUploadsCreatePayload":{"o":{"f":{"stagedTargets":"[StagedMediaUploadTarget!]","userErrors":"[UserError!]!"}}}, +"String":"s", +"URL":"s", +"UnsignedInt64":"s", +"UserError":{"o":{"f":{"field":"[String!]","message":"String!"}}}, +"WebhookSubscription":{"o":{"f":{"apiVersion":"ApiVersion!","createdAt":"DateTime!","filter":"String","format":"WebhookSubscriptionFormat!","id":"ID!","includeFields":"[String!]!","metafieldNamespaces":"[String!]!","name":"String","topic":"WebhookSubscriptionTopic!","updatedAt":"DateTime!","uri":"String!"}}}, +"WebhookSubscriptionConnection":{"o":{"f":{"nodes":"[WebhookSubscription!]!","pageInfo":"PageInfo!"}}}, +"WebhookSubscriptionCreatePayload":{"o":{"f":{"userErrors":"[UserError!]!","webhookSubscription":"WebhookSubscription"}}}, +"WebhookSubscriptionDeletePayload":{"o":{"f":{"deletedWebhookSubscriptionId":"ID","userErrors":"[UserError!]!"}}}, +"WebhookSubscriptionFormat":{"e":["JSON","XML"]}, +"WebhookSubscriptionInput":{"i":{"f":{"callbackUrl":"URL","filter":"String","format":"WebhookSubscriptionFormat","includeFields":"[String!]","metafieldNamespaces":"[String!]","metafields":"[HasMetafieldsMetafieldIdentifierInput!]","name":"String","uri":"String"},"d":{"callbackUrl":"Use `uri` instead."}}}, +"WebhookSubscriptionSortKeys":{"e":["CREATED_AT","ID"]}, +"WebhookSubscriptionTopic":{"e":["TAX_SUMMARIES_CREATE","APP_UNINSTALLED","APP_SCOPES_UPDATE","CARTS_CREATE","CARTS_UPDATE","CHANNELS_DELETE","CHECKOUTS_CREATE","CHECKOUTS_DELETE","CHECKOUTS_UPDATE","CUSTOMER_PAYMENT_METHODS_CREATE","CUSTOMER_PAYMENT_METHODS_UPDATE","CUSTOMER_PAYMENT_METHODS_REVOKE","COLLECTION_LISTINGS_ADD","COLLECTION_LISTINGS_REMOVE","COLLECTION_LISTINGS_UPDATE","COLLECTION_PUBLICATIONS_CREATE","COLLECTION_PUBLICATIONS_DELETE","COLLECTION_PUBLICATIONS_UPDATE","COLLECTIONS_CREATE","COLLECTIONS_DELETE","COLLECTIONS_UPDATE","CUSTOMER_GROUPS_CREATE","CUSTOMER_GROUPS_DELETE","CUSTOMER_GROUPS_UPDATE","CUSTOMERS_CREATE","CUSTOMERS_DELETE","CUSTOMERS_DISABLE","CUSTOMERS_ENABLE","CUSTOMERS_UPDATE","CUSTOMERS_PURCHASING_SUMMARY","CUSTOMERS_MARKETING_CONSENT_UPDATE","CUSTOMERS_WHATS_APP_MARKETING_CONSENT_UPDATE","CUSTOMER_TAGS_ADDED","CUSTOMER_TAGS_REMOVED","CUSTOMERS_EMAIL_MARKETING_CONSENT_UPDATE","DISPUTES_CREATE","DISPUTES_UPDATE","DRAFT_ORDERS_CREATE","DRAFT_ORDERS_DELETE","DRAFT_ORDERS_UPDATE","FULFILLMENT_EVENTS_CREATE","FULFILLMENT_EVENTS_DELETE","FULFILLMENTS_CREATE","FULFILLMENTS_UPDATE","ATTRIBUTED_SESSIONS_FIRST","ATTRIBUTED_SESSIONS_LAST","ORDER_TRANSACTIONS_CREATE","ORDERS_CANCELLED","ORDERS_CREATE","ORDERS_DELETE","ORDERS_EDITED","ORDERS_FULFILLED","ORDERS_PAID","ORDERS_PARTIALLY_FULFILLED","ORDERS_UPDATED","ORDERS_LINK_REQUESTED","FULFILLMENT_ORDERS_MOVED","FULFILLMENT_ORDERS_HOLD_RELEASED","FULFILLMENT_ORDERS_SCHEDULED_FULFILLMENT_ORDER_READY","FULFILLMENT_HOLDS_RELEASED","FULFILLMENT_ORDERS_ORDER_ROUTING_COMPLETE","FULFILLMENT_ORDERS_CANCELLED","FULFILLMENT_ORDERS_FULFILLMENT_SERVICE_FAILED_TO_COMPLETE","FULFILLMENT_ORDERS_FULFILLMENT_REQUEST_REJECTED","FULFILLMENT_ORDERS_CANCELLATION_REQUEST_SUBMITTED","FULFILLMENT_ORDERS_CANCELLATION_REQUEST_ACCEPTED","FULFILLMENT_ORDERS_CANCELLATION_REQUEST_REJECTED","FULFILLMENT_ORDERS_FULFILLMENT_REQUEST_SUBMITTED","FULFILLMENT_ORDERS_FULFILLMENT_REQUEST_ACCEPTED","FULFILLMENT_HOLDS_ADDED","FULFILLMENT_ORDERS_LINE_ITEMS_PREPARED_FOR_LOCAL_DELIVERY","FULFILLMENT_ORDERS_PLACED_ON_HOLD","FULFILLMENT_ORDERS_MERGED","FULFILLMENT_ORDERS_SPLIT","FULFILLMENT_ORDERS_PROGRESS_REPORTED","FULFILLMENT_ORDERS_MANUALLY_REPORTED_PROGRESS_STOPPED","PRODUCT_LISTINGS_ADD","PRODUCT_LISTINGS_REMOVE","PRODUCT_LISTINGS_UPDATE","SCHEDULED_PRODUCT_LISTINGS_ADD","SCHEDULED_PRODUCT_LISTINGS_UPDATE","SCHEDULED_PRODUCT_LISTINGS_REMOVE","PRODUCT_PUBLICATIONS_CREATE","PRODUCT_PUBLICATIONS_DELETE","PRODUCT_PUBLICATIONS_UPDATE","PRODUCTS_CREATE","PRODUCTS_DELETE","PRODUCTS_UPDATE","REFUNDS_CREATE","SEGMENTS_CREATE","SEGMENTS_DELETE","SEGMENTS_UPDATE","SHIPPING_ADDRESSES_CREATE","SHIPPING_ADDRESSES_UPDATE","SHOP_UPDATE","TAX_PARTNERS_UPDATE","TAX_SERVICES_CREATE","TAX_SERVICES_UPDATE","THEMES_CREATE","THEMES_DELETE","THEMES_PUBLISH","THEMES_UPDATE","VARIANTS_IN_STOCK","VARIANTS_OUT_OF_STOCK","INVENTORY_LEVELS_CONNECT","INVENTORY_LEVELS_UPDATE","INVENTORY_LEVELS_DISCONNECT","INVENTORY_ITEMS_CREATE","INVENTORY_ITEMS_UPDATE","INVENTORY_ITEMS_DELETE","LOCATIONS_ACTIVATE","LOCATIONS_DEACTIVATE","LOCATIONS_CREATE","LOCATIONS_UPDATE","LOCATIONS_DELETE","TENDER_TRANSACTIONS_CREATE","APP_PURCHASES_ONE_TIME_UPDATE","APP_SUBSCRIPTIONS_APPROACHING_CAPPED_AMOUNT","APP_SUBSCRIPTIONS_UPDATE","LOCALES_CREATE","LOCALES_UPDATE","LOCALES_DESTROY","MACHINE_TRANSLATION_BATCH_COMPLETED","DOMAINS_CREATE","DOMAINS_UPDATE","DOMAINS_DESTROY","SUBSCRIPTION_CONTRACTS_CREATE","SUBSCRIPTION_CONTRACTS_UPDATE","SUBSCRIPTION_BILLING_CYCLE_EDITS_CREATE","SUBSCRIPTION_BILLING_CYCLE_EDITS_UPDATE","SUBSCRIPTION_BILLING_CYCLE_EDITS_DELETE","PROFILES_CREATE","PROFILES_UPDATE","PROFILES_DELETE","SUBSCRIPTION_BILLING_ATTEMPTS_SUCCESS","SUBSCRIPTION_BILLING_ATTEMPTS_FAILURE","SUBSCRIPTION_BILLING_ATTEMPTS_CHALLENGED","RETURNS_CANCEL","RETURNS_CLOSE","RETURNS_REOPEN","RETURNS_REQUEST","RETURNS_APPROVE","RETURNS_UPDATE","RETURNS_PROCESS","RETURNS_DECLINE","REVERSE_DELIVERIES_ATTACH_DELIVERABLE","REVERSE_FULFILLMENT_ORDERS_DISPOSE","PAYMENT_TERMS_CREATE","PAYMENT_TERMS_DELETE","PAYMENT_TERMS_UPDATE","PAYMENT_SCHEDULES_DUE","SELLING_PLAN_GROUPS_CREATE","SELLING_PLAN_GROUPS_UPDATE","SELLING_PLAN_GROUPS_DELETE","BULK_OPERATIONS_FINISH","PRODUCT_FEEDS_CREATE","PRODUCT_FEEDS_UPDATE","PRODUCT_FEEDS_INCREMENTAL_SYNC","PRODUCT_FEEDS_FULL_SYNC","PRODUCT_FEEDS_FULL_SYNC_FINISH","MARKETS_CREATE","MARKETS_UPDATE","MARKETS_DELETE","ORDERS_RISK_ASSESSMENT_CHANGED","ORDERS_SHOPIFY_PROTECT_ELIGIBILITY_CHANGED","FINANCE_KYC_INFORMATION_UPDATE","FULFILLMENT_ORDERS_RESCHEDULED","PUBLICATIONS_DELETE","AUDIT_EVENTS_ADMIN_API_ACTIVITY","FULFILLMENT_ORDERS_LINE_ITEMS_PREPARED_FOR_PICKUP","COMPANIES_CREATE","COMPANIES_UPDATE","COMPANIES_DELETE","COMPANY_LOCATIONS_CREATE","COMPANY_LOCATIONS_UPDATE","COMPANY_LOCATIONS_DELETE","COMPANY_CONTACTS_CREATE","COMPANY_CONTACTS_UPDATE","COMPANY_CONTACTS_DELETE","CUSTOMERS_MERGE","INVENTORY_TRANSFERS_ADD_ITEMS","INVENTORY_TRANSFERS_UPDATE_ITEM_QUANTITIES","INVENTORY_TRANSFERS_REMOVE_ITEMS","INVENTORY_TRANSFERS_READY_TO_SHIP","INVENTORY_TRANSFERS_CANCEL","INVENTORY_TRANSFERS_COMPLETE","INVENTORY_TRANSFERS_UPDATED","INVENTORY_SHIPMENTS_DELETE","INVENTORY_SHIPMENTS_CREATE","INVENTORY_SHIPMENTS_MARK_IN_TRANSIT","INVENTORY_SHIPMENTS_UPDATE_TRACKING","INVENTORY_SHIPMENTS_ADD_ITEMS","INVENTORY_SHIPMENTS_UPDATE_ITEM_QUANTITIES","INVENTORY_SHIPMENTS_REMOVE_ITEMS","INVENTORY_SHIPMENTS_RECEIVE_ITEMS","CUSTOMER_ACCOUNT_SETTINGS_UPDATE","CUSTOMER_JOINED_SEGMENT","CUSTOMER_LEFT_SEGMENT","COMPANY_CONTACT_ROLES_ASSIGN","COMPANY_CONTACT_ROLES_REVOKE","SUBSCRIPTION_CONTRACTS_ACTIVATE","SUBSCRIPTION_CONTRACTS_PAUSE","SUBSCRIPTION_CONTRACTS_CANCEL","SUBSCRIPTION_CONTRACTS_FAIL","SUBSCRIPTION_CONTRACTS_EXPIRE","SUBSCRIPTION_CONTRACT_CALCULATIONS_SUCCEED","SUBSCRIPTION_CONTRACT_CALCULATIONS_FAIL","SUBSCRIPTION_BILLING_CYCLES_SKIP","SUBSCRIPTION_BILLING_CYCLES_UNSKIP","METAOBJECTS_CREATE","METAOBJECTS_UPDATE","METAOBJECTS_DELETE","FINANCE_APP_STAFF_MEMBER_GRANT","FINANCE_APP_STAFF_MEMBER_REVOKE","FINANCE_APP_STAFF_MEMBER_DELETE","FINANCE_APP_STAFF_MEMBER_UPDATE","ROLLOUTS_CREATE","ROLLOUTS_DELETE","ROLLOUTS_RESOURCE_CHANGE_ADDED","ROLLOUTS_RESOURCE_CHANGE_REMOVED","ROLLOUTS_RESOURCE_CHANGE_UPDATED","ROLLOUTS_UPDATE","DISCOUNTS_CREATE","DISCOUNTS_UPDATE","DISCOUNTS_DELETE","DISCOUNTS_REDEEMCODE_ADDED","DISCOUNTS_REDEEMCODE_REMOVED","METAFIELD_DEFINITIONS_CREATE","METAFIELD_DEFINITIONS_UPDATE","METAFIELD_DEFINITIONS_DELETE","DELIVERY_PROMISE_SETTINGS_UPDATE","MARKETS_BACKUP_REGION_UPDATE","CHECKOUT_AND_ACCOUNTS_CONFIGURATIONS_UPDATE","REQUESTED_ORDER_EDIT_CREATED","REQUESTED_ORDER_EDIT_RESOLVED","REQUESTED_ORDER_EDIT_DECLINED"]}, +"WebhookSubscriptionUpdatePayload":{"o":{"f":{"userErrors":"[UserError!]!","webhookSubscription":"WebhookSubscription"}}} +}} diff --git a/crates/shopify_api/graphql/operations/bulk_cancel.graphql b/crates/shopify_api/graphql/operations/bulk_cancel.graphql new file mode 100644 index 0000000..9d55bbe --- /dev/null +++ b/crates/shopify_api/graphql/operations/bulk_cancel.graphql @@ -0,0 +1,9 @@ +mutation BulkOperationCancel($id: ID!) { + bulkOperationCancel(id: $id) { + bulkOperation { ...BulkOperationFields } + userErrors { field message } + } +} +fragment BulkOperationFields on BulkOperation { + id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query +} diff --git a/crates/shopify_api/graphql/operations/bulk_get.graphql b/crates/shopify_api/graphql/operations/bulk_get.graphql new file mode 100644 index 0000000..6df9b6c --- /dev/null +++ b/crates/shopify_api/graphql/operations/bulk_get.graphql @@ -0,0 +1,6 @@ +query BulkOperation($id: ID!) { + bulkOperation(id: $id) { ...BulkOperationFields } +} +fragment BulkOperationFields on BulkOperation { + id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query +} diff --git a/crates/shopify_api/graphql/operations/bulk_list.graphql b/crates/shopify_api/graphql/operations/bulk_list.graphql new file mode 100644 index 0000000..8bf1439 --- /dev/null +++ b/crates/shopify_api/graphql/operations/bulk_list.graphql @@ -0,0 +1,9 @@ +query BulkOperations($first: Int!, $after: String, $query: String, $reverse: Boolean) { + bulkOperations(first: $first, after: $after, query: $query, reverse: $reverse, sortKey: CREATED_AT) { + nodes { ...BulkOperationFields } + pageInfo { hasNextPage endCursor } + } +} +fragment BulkOperationFields on BulkOperation { + id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query +} diff --git a/crates/shopify_api/graphql/operations/bulk_run_mutation.graphql b/crates/shopify_api/graphql/operations/bulk_run_mutation.graphql new file mode 100644 index 0000000..af329d2 --- /dev/null +++ b/crates/shopify_api/graphql/operations/bulk_run_mutation.graphql @@ -0,0 +1,9 @@ +mutation BulkOperationRunMutation($mutation: String!, $stagedUploadPath: String!, $clientIdentifier: String) { + bulkOperationRunMutation(mutation: $mutation, stagedUploadPath: $stagedUploadPath, clientIdentifier: $clientIdentifier) { + bulkOperation { ...BulkOperationFields } + userErrors { field message code } + } +} +fragment BulkOperationFields on BulkOperation { + id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query +} diff --git a/crates/shopify_api/graphql/operations/bulk_run_query.graphql b/crates/shopify_api/graphql/operations/bulk_run_query.graphql new file mode 100644 index 0000000..e613d45 --- /dev/null +++ b/crates/shopify_api/graphql/operations/bulk_run_query.graphql @@ -0,0 +1,9 @@ +mutation BulkOperationRunQuery($query: String!, $groupObjects: Boolean!) { + bulkOperationRunQuery(query: $query, groupObjects: $groupObjects) { + bulkOperation { ...BulkOperationFields } + userErrors { field message code } + } +} +fragment BulkOperationFields on BulkOperation { + id type status errorCode createdAt completedAt objectCount rootObjectCount fileSize url partialDataUrl query +} diff --git a/crates/shopify_api/graphql/operations/bulk_staged_uploads.graphql b/crates/shopify_api/graphql/operations/bulk_staged_uploads.graphql new file mode 100644 index 0000000..ef6394d --- /dev/null +++ b/crates/shopify_api/graphql/operations/bulk_staged_uploads.graphql @@ -0,0 +1,6 @@ +mutation StagedUploadsCreate($input: [StagedUploadInput!]!) { + stagedUploadsCreate(input: $input) { + stagedTargets { url resourceUrl parameters { name value } } + userErrors { field message } + } +} diff --git a/crates/shopify_api/graphql/operations/webhooks_create.graphql b/crates/shopify_api/graphql/operations/webhooks_create.graphql new file mode 100644 index 0000000..bbbbdf2 --- /dev/null +++ b/crates/shopify_api/graphql/operations/webhooks_create.graphql @@ -0,0 +1,10 @@ +mutation WebhookSubscriptionCreate($topic: WebhookSubscriptionTopic!, $webhookSubscription: WebhookSubscriptionInput!) { + webhookSubscriptionCreate(topic: $topic, webhookSubscription: $webhookSubscription) { + webhookSubscription { ...WebhookSubscriptionFields } + userErrors { field message } + } +} +fragment WebhookSubscriptionFields on WebhookSubscription { + id topic uri format filter includeFields metafieldNamespaces name createdAt updatedAt + apiVersion { handle } +} diff --git a/crates/shopify_api/graphql/operations/webhooks_delete.graphql b/crates/shopify_api/graphql/operations/webhooks_delete.graphql new file mode 100644 index 0000000..f7824f7 --- /dev/null +++ b/crates/shopify_api/graphql/operations/webhooks_delete.graphql @@ -0,0 +1,6 @@ +mutation WebhookSubscriptionDelete($id: ID!) { + webhookSubscriptionDelete(id: $id) { + deletedWebhookSubscriptionId + userErrors { field message } + } +} diff --git a/crates/shopify_api/graphql/operations/webhooks_list.graphql b/crates/shopify_api/graphql/operations/webhooks_list.graphql new file mode 100644 index 0000000..ec51e0f --- /dev/null +++ b/crates/shopify_api/graphql/operations/webhooks_list.graphql @@ -0,0 +1,10 @@ +query WebhookSubscriptions($after: String) { + webhookSubscriptions(first: 250, after: $after) { + nodes { ...WebhookSubscriptionFields } + pageInfo { hasNextPage endCursor } + } +} +fragment WebhookSubscriptionFields on WebhookSubscription { + id topic uri format filter includeFields metafieldNamespaces name createdAt updatedAt + apiVersion { handle } +} diff --git a/crates/shopify_api/graphql/operations/webhooks_update.graphql b/crates/shopify_api/graphql/operations/webhooks_update.graphql new file mode 100644 index 0000000..6e9c579 --- /dev/null +++ b/crates/shopify_api/graphql/operations/webhooks_update.graphql @@ -0,0 +1,10 @@ +mutation WebhookSubscriptionUpdate($id: ID!, $webhookSubscription: WebhookSubscriptionInput!) { + webhookSubscriptionUpdate(id: $id, webhookSubscription: $webhookSubscription) { + webhookSubscription { ...WebhookSubscriptionFields } + userErrors { field message } + } +} +fragment WebhookSubscriptionFields on WebhookSubscription { + id topic uri format filter includeFields metafieldNamespaces name createdAt updatedAt + apiVersion { handle } +} diff --git a/crates/shopify_api/src/auth.rs b/crates/shopify_api/src/auth.rs new file mode 100644 index 0000000..e43f0ea --- /dev/null +++ b/crates/shopify_api/src/auth.rs @@ -0,0 +1,738 @@ +//! Access tokens: a static token, the client credentials grant, or an +//! expiring offline token renewed with its refresh token. + +use std::fmt; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use tokio::sync::{Mutex, OwnedMutexGuard}; + +use crate::transport::{BoxFuture, HttpRequest, Method, Transport}; +use crate::{Error, OAuthErrorCode, Result, ShopDomain}; + +/// How a [`Shopify`](crate::Shopify) client gets its access token. +/// +/// ``` +/// use shopify_api::{Auth, TokenData}; +/// +/// // A token of a custom app, or one your app stored at installation. +/// let auth = Auth::access_token("shpat_…"); +/// +/// // A token Shopify gives for 24 hours to an app and a store of the same +/// // organization, asked for again before it expires. +/// let auth = Auth::client_credentials("client-id", "client-secret"); +/// +/// // An expiring offline token, renewed with its refresh token. +/// let mut stored = TokenData::new("shpat_…"); +/// stored.refresh_token = Some("shprt_…".to_string()); +/// let auth = Auth::expiring_token("client-id", "client-secret", stored); +/// ``` +#[derive(Clone)] +pub struct Auth { + kind: Kind, + token: Option, +} + +#[derive(Clone)] +enum Kind { + /// The token is the token: nothing renews it. + Static, + /// The client credentials grant gives a new token. + ClientCredentials { + client_id: String, + client_secret: String, + }, + /// The refresh token of the current token gives a new token. + Refresh { + client_id: String, + client_secret: String, + }, +} + +impl Auth { + /// A token that is used as it is: an Admin API token of a custom app, or + /// a non-expiring offline token. + pub fn access_token(token: impl Into) -> Self { + Self::token(TokenData::new(token)) + } + + /// A token used as it is, with what is known of it (its scopes, when it + /// expires). Nothing renews it. + pub fn token(token: TokenData) -> Self { + Self { + kind: Kind::Static, + token: Some(token), + } + } + + /// The client credentials grant: Shopify gives a token, valid about 24 + /// hours, to an app for a store of the organization that owns the app. + /// The client asks for one at its first request, and again five minutes + /// before it expires or when Shopify refuses it. + pub fn client_credentials( + client_id: impl Into, + client_secret: impl Into, + ) -> Self { + Self { + kind: Kind::ClientCredentials { + client_id: client_id.into(), + client_secret: client_secret.into(), + }, + token: None, + } + } + + /// An expiring offline token and its refresh token: the client renews + /// it five minutes before it expires, or when Shopify refuses it. Shopify + /// gives a new refresh token each time: save it with a + /// [`TokenStore`]. + pub fn expiring_token( + client_id: impl Into, + client_secret: impl Into, + token: TokenData, + ) -> Self { + Self { + kind: Kind::Refresh { + client_id: client_id.into(), + client_secret: client_secret.into(), + }, + token: Some(token), + } + } + + /// Starts from a token you stored, such as the last client credentials + /// token, instead of asking Shopify for one at the first request. + pub fn with_token(mut self, token: TokenData) -> Self { + self.token = Some(token); + self + } +} + +impl fmt::Debug for Auth { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + let kind = match self.kind { + Kind::Static => "Static", + Kind::ClientCredentials { .. } => "ClientCredentials", + Kind::Refresh { .. } => "Refresh", + }; + formatter + .debug_struct("Auth") + .field("kind", &kind) + .field("token", &self.token) + .finish_non_exhaustive() + } +} + +/// An access token and what Shopify said about it. +/// +/// It serializes to JSON, to be stored and given back with +/// [`Auth::with_token`] or [`Auth::expiring_token`]. `Debug` hides the tokens. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct TokenData { + pub access_token: String, + /// The access scopes granted, comma-separated. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scope: Option, + /// When the access token expires; `None` when it does not. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub expires_at: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub refresh_token: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub refresh_token_expires_at: Option>, + /// For an online token: the staff member it acts for. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub associated_user: Option, + /// For an online token: the scopes of that staff member. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub associated_user_scope: Option, +} + +impl TokenData { + /// A token of which nothing else is known. + pub fn new(access_token: impl Into) -> Self { + Self { + access_token: access_token.into(), + scope: None, + expires_at: None, + refresh_token: None, + refresh_token_expires_at: None, + associated_user: None, + associated_user_scope: None, + } + } + + /// The access token expires within `leeway`, or has expired. + pub fn expires_within(&self, leeway: Duration) -> bool { + let limit = chrono::Duration::from_std(leeway) + .ok() + .and_then(|leeway| Utc::now().checked_add_signed(leeway)); + self.expires_at.is_some_and(|expires_at| match limit { + Some(limit) => expires_at <= limit, + // A leeway beyond the calendar: everything expires within it. + None => true, + }) + } + + /// The refresh token is still valid, as far as is known. + pub fn can_refresh(&self) -> bool { + self.refresh_token.is_some() + && self + .refresh_token_expires_at + .is_none_or(|expires_at| Utc::now() < expires_at) + } + + /// The granted scopes. + pub fn scopes(&self) -> Vec<&str> { + self.scope + .as_deref() + .unwrap_or_default() + .split(',') + .map(str::trim) + .filter(|scope| !scope.is_empty()) + .collect() + } +} + +impl fmt::Debug for TokenData { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("TokenData") + .field("access_token", &"[redacted]") + .field("scope", &self.scope) + .field("expires_at", &self.expires_at) + .field( + "refresh_token", + &self.refresh_token.as_ref().map(|_| "[redacted]"), + ) + .field("refresh_token_expires_at", &self.refresh_token_expires_at) + .field("associated_user", &self.associated_user) + .field("associated_user_scope", &self.associated_user_scope) + .finish() + } +} + +/// The staff member an online token acts for. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct AssociatedUser { + pub id: u64, + #[serde(default)] + pub first_name: Option, + #[serde(default)] + pub last_name: Option, + #[serde(default)] + pub email: Option, + #[serde(default)] + pub email_verified: Option, + #[serde(default)] + pub account_owner: Option, + #[serde(default)] + pub locale: Option, + #[serde(default)] + pub collaborator: Option, +} + +/// Where a client saves the tokens it obtains or renews, so that a restart +/// reuses them. An expiring offline token comes with a new refresh token +/// each time: without a store, a restart is left with one that no longer works. +/// +/// Until a renewed token is saved, the client sends nothing with it: the +/// request that renewed it, and every request after, first try the save +/// again, and fail with [`Error::TokenStore`] while it fails. A token +/// Shopify rotated is so never used before it is stored. +/// +/// Saves run one at a time, in the order of the renewals, in a task of their +/// own: a request that is cancelled does not cancel its save. A store must +/// not call the client whose token it saves. +/// +/// ``` +/// use shopify_api::transport::BoxFuture; +/// use shopify_api::{ShopDomain, TokenData, TokenStore}; +/// +/// struct Database; +/// +/// impl TokenStore for Database { +/// fn save<'a>( +/// &'a self, +/// shop: &'a ShopDomain, +/// token: &'a TokenData, +/// ) -> BoxFuture<'a, Result<(), Box>> { +/// Box::pin(async move { +/// let json = serde_json::to_string(token)?; +/// // UPDATE installations SET token = $json WHERE shop = $shop +/// let _ = (shop, json); +/// Ok(()) +/// }) +/// } +/// } +/// ``` +pub trait TokenStore: Send + Sync + 'static { + fn save<'a>( + &'a self, + shop: &'a ShopDomain, + token: &'a TokenData, + ) -> BoxFuture<'a, std::result::Result<(), Box>>; +} + +// ─── Token endpoint ────────────────────────────────────────────────── + +#[derive(Deserialize)] +struct TokenResponse { + access_token: String, + #[serde(default)] + scope: Option, + #[serde(default)] + expires_in: Option, + #[serde(default)] + refresh_token: Option, + #[serde(default)] + refresh_token_expires_in: Option, + #[serde(default)] + associated_user: Option, + #[serde(default)] + associated_user_scope: Option, +} + +impl TokenResponse { + fn into_token(self) -> TokenData { + // Whatever Shopify says, a date that exists: never in the past, at most the last one. + let at = |seconds: i64| { + chrono::Duration::try_seconds(seconds.max(0)) + .and_then(|duration| Utc::now().checked_add_signed(duration)) + .unwrap_or(DateTime::::MAX_UTC) + }; + TokenData { + access_token: self.access_token, + scope: self.scope, + expires_at: self.expires_in.map(at), + refresh_token: self.refresh_token, + refresh_token_expires_at: self.refresh_token_expires_in.map(at), + associated_user: self.associated_user, + associated_user_scope: self.associated_user_scope, + } + } +} + +fn token_url(shop: &ShopDomain) -> String { + format!("https://{shop}/admin/oauth/access_token") +} + +/// How the fields of a token request travel. +#[derive(Clone, Copy)] +pub(crate) enum Encoding { + /// `application/x-www-form-urlencoded`, as Shopify documents the client credentials grant. + Form, + /// `application/json`, as Shopify's libraries send the code and token exchanges. + Json, +} + +/// Asks the token endpoint of `shop` for a token. A refusal says what +/// Shopify answered, never what was sent. +pub(crate) async fn request_token( + transport: &dyn Transport, + shop: &ShopDomain, + user_agent: &str, + encoding: Encoding, + fields: &[(&str, &str)], +) -> Result { + let url = token_url(shop); + let request = HttpRequest::new(Method::Post, &url) + .with_header("Accept", "application/json") + .with_header("User-Agent", user_agent) + .with_timeout(Duration::from_secs(30)); + let request = match encoding { + Encoding::Form => request.with_form(fields), + Encoding::Json => { + let body: serde_json::Map = fields + .iter() + .map(|(name, value)| (name.to_string(), serde_json::Value::from(*value))) + .collect(); + request.with_json(&serde_json::Value::Object(body)) + } + }; + let response = transport + .send(request) + .await + .map_err(|source| Error::transport(&url, source))?; + if !response.is_success() { + // What the endpoint wrote is kept apart: it may echo what it was sent. + let body: serde_json::Value = serde_json::from_slice(&response.body).unwrap_or_default(); + let error = body.get("error").and_then(serde_json::Value::as_str); + let code = error.map(OAuthErrorCode::parse); + let description = body + .get("error_description") + .and_then(serde_json::Value::as_str); + let detail = match (error, description) { + (Some(code), Some(description)) => format!("{code}: {description}"), + (Some(code), None) => code.to_string(), + _ => String::from_utf8_lossy(&response.body).into_owned(), + }; + let message = match code { + Some(code) => format!( + "the token endpoint of {shop} answered {} ({code})", + response.status + ), + None => format!("the token endpoint of {shop} answered {}", response.status), + }; + return Err(Error::auth_refused(message, detail, response.status, code)); + } + let parsed: TokenResponse = crate::decode::from_slice(&response.body).map_err(|failure| { + Error::auth_with_detail( + format!( + "the token endpoint of {shop} answered an invalid token: {} at `{}`", + failure.message, failure.path + ), + failure.detail, + ) + })?; + Ok(parsed.into_token()) +} + +// ─── Token of a client ─────────────────────────────────────────────── + +/// How long a failed renewal ahead of expiry holds back the next one, while +/// the current token still works. +const RENEWAL_BACKOFF: Duration = Duration::from_secs(30); + +/// How long a failed renewal is the answer of the requests that wait for a +/// token, instead of each asking Shopify again. +const FAILURE_HOLD: Duration = Duration::from_secs(5); + +/// What the client needs to ask for a token. +pub(crate) struct Endpoint { + pub transport: Arc, + pub shop: ShopDomain, + pub user_agent: String, +} + +/// The token of a client and of its clones. +/// +/// One renewal runs at a time, in a task of its own: a caller that is +/// cancelled (a request handler dropped, a timeout) does not cancel it, so a +/// refresh token Shopify rotated is never lost halfway. +pub(crate) struct Tokens { + kind: Arc, + /// Held through a renewal and its save: saves run in the order of the + /// renewals, and nothing reads a token that is not saved yet. + state: Arc>, + store: Option>, + leeway: Duration, +} + +struct State { + token: Option, + /// When the last renewal failed, and why. + failure: Option<(Instant, Failure)>, + /// The token was renewed, and the store has not saved it yet. + unsaved: bool, +} + +impl State { + /// The access token, if it has not expired. + fn valid(&self) -> Option { + self.token + .as_ref() + .filter(|token| !token.expires_within(Duration::ZERO)) + .map(|token| token.access_token.clone()) + } + + /// The last failure, if it is recent enough to be the answer. + fn held_failure(&self) -> Option { + let (at, failure) = self.failure.as_ref()?; + (at.elapsed() < FAILURE_HOLD).then(|| Error::Auth { + message: format!("{} (asked again in a few seconds)", failure.message), + detail: None, + status: failure.status, + oauth_code: failure.oauth_code, + held: true, + }) + } +} + +/// What a failed renewal hands to the requests that come while it is held. +struct Failure { + /// The `Display` of the error. + message: String, + status: Option, + oauth_code: Option, +} + +impl Failure { + fn of(error: &Error) -> Self { + Self { + message: error.to_string(), + status: error.token_endpoint_status(), + oauth_code: error.oauth_code(), + } + } +} + +impl Tokens { + pub fn new(auth: Auth, store: Option>, leeway: Duration) -> Self { + Self { + kind: Arc::new(auth.kind), + state: Arc::new(Mutex::new(State { + token: auth.token, + failure: None, + unsaved: false, + })), + store, + leeway, + } + } + + /// The state, once the token it holds is saved: a save that failed is + /// tried again first, in a task of its own. + async fn saved_state(&self, endpoint: &Arc) -> Result> { + let mut state = self.state.clone().lock_owned().await; + if !state.unsaved { + return Ok(state); + } + let store = self.store.clone(); + let endpoint = endpoint.clone(); + tokio::spawn(async move { + save(store.as_deref(), &endpoint.shop, &mut state).await?; + Ok(state) + }) + .await + .map_err(stopped)? + } + + /// The token to send, obtained or renewed first when it is missing or + /// about to expire. + /// + /// When a renewal ahead of expiry fails, the token that has not expired + /// yet is still sent, and the renewal is not tried again for + /// [`RENEWAL_BACKOFF`]. + pub async fn get(&self, endpoint: &Arc) -> Result { + let state = self.saved_state(endpoint).await?; + let still_valid = state.valid(); + if let Some(token) = state.token.as_ref() { + let renewable = !matches!(*self.kind, Kind::Static); + let backing_off = state + .failure + .as_ref() + .is_some_and(|(at, _)| at.elapsed() < RENEWAL_BACKOFF); + if !renewable + || !token.expires_within(self.leeway) + || (backing_off && still_valid.is_some()) + { + return Ok(token.access_token.clone()); + } + } + if still_valid.is_none() + && let Some(error) = state.held_failure() + { + return Err(error); + } + match self.renew_locked(state, endpoint).await { + Err(error) if !matches!(error, Error::TokenStore(_)) => match still_valid { + Some(token) => { + tracing::warn!( + "renewing the token of {} ahead of its expiry failed, the current one is sent: {error}", + endpoint.shop + ); + Ok(token) + } + None => Err(error), + }, + outcome => outcome, + } + } + + /// A token to send again after Shopify refused `rejected`: the one + /// another request already obtained, or a new one. `None` when nothing + /// can renew it. + pub async fn renew(&self, endpoint: &Arc, rejected: &str) -> Result> { + if matches!(*self.kind, Kind::Static) { + return Ok(None); + } + let state = self.saved_state(endpoint).await?; + if let Some(token) = state.token.as_ref() + && token.access_token != rejected + { + return Ok(Some(token.access_token.clone())); + } + if let Some(error) = state.held_failure() { + return Err(error); + } + self.renew_locked(state, endpoint).await.map(Some) + } + + /// The current token, without asking Shopify for one. + pub async fn current(&self) -> Option { + self.state.lock().await.token.clone() + } + + /// Obtains a new token and saves it, in a task of its own that keeps the + /// lock of the state throughout. + async fn renew_locked( + &self, + mut state: OwnedMutexGuard, + endpoint: &Arc, + ) -> Result { + if matches!(*self.kind, Kind::Static) { + // A static client always starts with its token. + return state + .token + .as_ref() + .map(|token| token.access_token.clone()) + .ok_or_else(|| Error::auth("no access token")); + } + let kind = self.kind.clone(); + let endpoint = endpoint.clone(); + let store = self.store.clone(); + let renewal = tokio::spawn(async move { + let token = match obtain(&kind, &state, &endpoint).await { + Ok(token) => token, + Err(error) => { + state.failure = Some((Instant::now(), Failure::of(&error))); + return Err(error); + } + }; + let access_token = token.access_token.clone(); + state.token = Some(token); + state.failure = None; + state.unsaved = true; + save(store.as_deref(), &endpoint.shop, &mut state).await?; + Ok(access_token) + }); + renewal.await.map_err(stopped)? + } +} + +/// Saves the token of `state` when it is not saved yet. +async fn save(store: Option<&dyn TokenStore>, shop: &ShopDomain, state: &mut State) -> Result<()> { + if let (Some(store), Some(token)) = (store, state.token.as_ref()) + && state.unsaved + { + store.save(shop, token).await.map_err(Error::TokenStore)?; + } + state.unsaved = false; + Ok(()) +} + +/// The error of a renewal or a save whose task did not end. +fn stopped(error: tokio::task::JoinError) -> Error { + // A panic's message is not this crate's to show. + Error::auth(if error.is_panic() { + "the renewal of the token panicked" + } else { + "the renewal of the token was cancelled" + }) +} + +/// Asks Shopify for a new token, as `kind` does. +async fn obtain(kind: &Kind, state: &State, endpoint: &Endpoint) -> Result { + let transport = endpoint.transport.as_ref(); + match kind { + Kind::Static => Err(Error::auth("a static token is not renewed")), + Kind::ClientCredentials { + client_id, + client_secret, + } => { + let fields = [ + ("grant_type", "client_credentials"), + ("client_id", client_id.as_str()), + ("client_secret", client_secret.as_str()), + ]; + request_token( + transport, + &endpoint.shop, + &endpoint.user_agent, + Encoding::Form, + &fields, + ) + .await + } + Kind::Refresh { + client_id, + client_secret, + } => { + let current = state.token.as_ref().filter(|token| token.can_refresh()); + let refresh_token = current + .and_then(|token| token.refresh_token.clone()) + .ok_or_else(|| { + Error::auth(format!( + "the token of {} expired and its refresh token is missing or expired: \ + the app must get a new token (token exchange or OAuth)", + endpoint.shop + )) + })?; + let fields = [ + ("grant_type", "refresh_token"), + ("client_id", client_id.as_str()), + ("client_secret", client_secret.as_str()), + ("refresh_token", refresh_token.as_str()), + ]; + let mut token = request_token( + transport, + &endpoint.shop, + &endpoint.user_agent, + Encoding::Json, + &fields, + ) + .await?; + // An answer without a refresh token leaves the current one valid. + if token.refresh_token.is_none() { + token.refresh_token = Some(refresh_token); + token.refresh_token_expires_at = + current.and_then(|token| token.refresh_token_expires_at); + } + Ok(token) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn expiry_uses_the_leeway() { + let mut token = TokenData::new("token"); + assert!(!token.expires_within(Duration::from_secs(365 * 86_400))); + token.expires_at = Some(Utc::now() + chrono::Duration::minutes(1)); + assert!(token.expires_within(Duration::from_secs(5 * 60))); + assert!(!token.expires_within(Duration::from_secs(1))); + assert!(token.expires_within(Duration::MAX)); + } + + #[test] + fn a_refresh_token_works_until_it_expires() { + let mut token = TokenData::new("token"); + assert!(!token.can_refresh()); + token.refresh_token = Some("refresh".to_string()); + assert!(token.can_refresh()); + token.refresh_token_expires_at = Some(Utc::now() - chrono::Duration::seconds(1)); + assert!(!token.can_refresh()); + } + + #[test] + fn debug_hides_tokens_and_secrets() { + let mut token = TokenData::new("shpat_secret"); + token.refresh_token = Some("shprt_secret".to_string()); + let auth = Auth::expiring_token("id", "client-secret", token); + let shown = format!("{auth:?}"); + for secret in ["shpat_secret", "shprt_secret", "client-secret"] { + assert!(!shown.contains(secret), "{shown}"); + } + } + + #[test] + fn tokens_round_trip_through_json() { + let mut token = TokenData::new("shpat"); + token.scope = Some("read_products, write_orders".to_string()); + token.expires_at = Some(Utc::now()); + let json = serde_json::to_string(&token).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), token); + assert_eq!(token.scopes(), ["read_products", "write_orders"]); + // Fields left out of a stored token are read as absent. + let minimal: TokenData = serde_json::from_str(r#"{"access_token":"shpat"}"#).unwrap(); + assert_eq!(minimal, TokenData::new("shpat")); + } +} diff --git a/crates/shopify_api/src/bin/shopify-api.rs b/crates/shopify_api/src/bin/shopify-api.rs new file mode 100644 index 0000000..479bad0 --- /dev/null +++ b/crates/shopify_api/src/bin/shopify-api.rs @@ -0,0 +1,485 @@ +//! `shopify-api`: downloads the Shopify Admin schema of the version a crate's +//! `Cargo.toml` pins, else of the latest version, and checks `.graphql` files +//! against a schema. + +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +use clap::{Args, Parser, Subcommand}; +use shopify_api::{ApiVersion, Auth, Shopify}; +use std::sync::Arc; +use std::time::SystemTime; + +use shopify_api_graphql::project::{ + PORTABLE_PATH, inside_package, package_config, previous_api_version, project_schema, + schema_snippet, write_atomically, +}; +use shopify_api_graphql::{Schema, SchemaSource, analyze, latest_api_version, schema_source}; + +#[derive(Debug, Parser)] +#[command( + name = "shopify-api", + version, + about = "Shopify Admin GraphQL schemas for the graphql! macro of shopify_api" +)] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Debug, Subcommand)] +enum Command { + /// Admin GraphQL schemas. + Schema { + #[command(subcommand)] + command: SchemaCommand, + }, + /// Checks `.graphql` files against the schema `graphql!` would use here. + Check(CheckArgs), +} + +#[derive(Debug, Subcommand)] +enum SchemaCommand { + /// Downloads the Admin schema of the crate's version again, where + /// `graphql!` reads it. + /// + /// The version is `api-version` in `[package.metadata.shopify_api]` of the + /// nearest package, else the latest stable one: this moves a crate that + /// pins none to the latest version. `graphql!` downloads the file by itself + /// only when it is missing, in an older format, or of another version than + /// the pinned one; this command refreshes it, or downloads it through a + /// shop with --shop. + Download(DownloadArgs), +} + +/// `Debug` hides the access token and the client secret. +#[derive(Args)] +struct DownloadArgs { + /// Where to write it. By default, where `graphql!` reads it for the + /// nearest package: `schema` in `[package.metadata.shopify_api]` of its + /// `Cargo.toml`, else `graphql/admin.schema.json` next to it + /// (`graphql/admin.introspection.json` with --introspection). + #[arg(long)] + out: Option, + /// Writes the raw introspection result, for other GraphQL tools, instead + /// of the compact form `graphql!` reads. + #[arg(long)] + introspection: bool, + /// Keeps only what these `.graphql` files use: the types they reach, and + /// the fields they select. For a small schema to commit with a library. + #[arg(long, num_args = 1.., value_name = "FILES", conflicts_with = "introspection")] + only: Vec, + /// Downloads through this shop, with its token: the schema the token sees. + #[arg(long, env = "SHOPIFY_SHOP")] + shop: Option, + #[arg(long, env = "SHOPIFY_ACCESS_TOKEN", hide_env_values = true)] + access_token: Option, + #[arg(long, env = "SHOPIFY_CLIENT_ID")] + client_id: Option, + #[arg(long, env = "SHOPIFY_CLIENT_SECRET", hide_env_values = true)] + client_secret: Option, +} + +impl std::fmt::Debug for DownloadArgs { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let hidden = |secret: &Option| secret.as_ref().map(|_| "[redacted]"); + formatter + .debug_struct("DownloadArgs") + .field("out", &self.out) + .field("introspection", &self.introspection) + .field("only", &self.only) + .field("shop", &self.shop) + .field("access_token", &hidden(&self.access_token)) + .field("client_id", &self.client_id) + .field("client_secret", &hidden(&self.client_secret)) + .finish() + } +} + +#[derive(Debug, Args)] +struct CheckArgs { + /// The `.graphql` files, one operation each. + #[arg(required = true)] + files: Vec, + /// The schema file; else the one `graphql!` would use for the nearest package. + #[arg(long)] + schema: Option, + /// Fails on a deprecated field, argument or value too. + #[arg(long)] + deny_deprecated: bool, +} + +#[tokio::main] +async fn main() -> ExitCode { + let cli = Cli::parse(); + let outcome = match cli.command { + Command::Schema { + command: SchemaCommand::Download(args), + } => download(args).await, + Command::Check(args) => check(args), + }; + match outcome { + Ok(code) => code, + Err(message) => { + eprintln!("error: {message}"); + ExitCode::FAILURE + } + } +} + +async fn download(args: DownloadArgs) -> Result { + let root = package_root().ok_or( + "no Cargo.toml of a package in this directory or above: run it in the crate's directory", + )?; + let config = package_config(&root)?; + let declared = config.api_version.clone(); + let latest = declared.is_none(); + let wanted = declared.unwrap_or_else(|| latest_api_version(SystemTime::now())); + if latest { + eprintln!( + "{} declares no Admin API version: the latest is {wanted}.", + root.join("Cargo.toml").display() + ); + } + let mut version = ApiVersion::new(&wanted).map_err(|error| error.to_string())?; + let introspection = match fetch(&args, version).await { + Ok(introspection) => introspection, + // A new version may not be out on its first day. + Err(error) if latest && args.shop.is_none() => { + let Some(previous) = previous_api_version(&wanted) else { + return Err(error); + }; + eprintln!("{error}\nTrying the version before, {previous}."); + version = ApiVersion::new(&previous).map_err(|error| error.to_string())?; + fetch(&args, version).await? + } + Err(error) => return Err(error), + }; + + let (out, project) = match &args.out { + Some(out) => (out.clone(), false), + None => { + let file = if args.introspection { + root.join("graphql/admin.introspection.json") + } else { + config.schema_path(&root) + }; + (file, !args.introspection) + } + }; + let created = !out.exists(); + let (contents, types) = if args.introspection { + let types = introspection + .pointer("/data/__schema/types") + .and_then(|types| types.as_array()) + .map_or(0, Vec::len); + let pretty = + serde_json::to_string_pretty(&introspection).map_err(|error| error.to_string())?; + (format!("{pretty}\n"), types) + } else { + let mut schema = Schema::from_introspection(&introspection, &version.to_string()) + .map_err(|error| error.to_string())?; + if !args.only.is_empty() { + let texts = args + .only + .iter() + .map(|file| { + std::fs::read_to_string(file) + .map_err(|error| format!("cannot read {}: {error}", file.display())) + }) + .collect::, _>>()?; + let texts: Vec<&str> = texts.iter().map(String::as_str).collect(); + schema = schema + .restricted_to(&texts) + .map_err(|error| error.to_string())?; + } + (schema.to_json(), schema.types.len()) + }; + write_atomically(&out, &contents)?; + eprintln!("Wrote {} ({types} types).", out.display()); + + if project { + if created { + touch_sources(&root); + } + eprintln!( + "`graphql!` checks the operations of this crate against the Admin API {version}, \ + and sends them to that version. Commit the file: offline builds need it." + ); + } else if !args.introspection { + match schema_key(&root, &out) { + Some(named) => eprintln!( + "For `graphql!` to use it, name it in {}:\n\n{}", + root.join("Cargo.toml").display(), + schema_snippet(&version.to_string(), &named) + ), + None => eprintln!( + "`graphql!` cannot use it: `schema` in {} names a file inside the package, \ + as {PORTABLE_PATH}, and `cargo package` ships only the package's files.", + root.join("Cargo.toml").display() + ), + } + } + Ok(ExitCode::SUCCESS) +} + +/// The `schema` value that names `out`, a file just written, for the +/// package in `root`, if any: a path [`inside_package`] accepts, that leads +/// to that same file. `a/../x.json` is normalized to `x.json`, which is +/// another file when `a` links to a directory elsewhere. +fn schema_key(root: &Path, out: &Path) -> Option { + use std::path::Component; + let absolute = std::path::absolute(out).ok()?; + let named = absolute.strip_prefix(root).ok()?; + let value = named + .components() + .map(|component| match component { + Component::Normal(name) => name.to_str(), + Component::CurDir => Some("."), + Component::ParentDir => Some(".."), + Component::Prefix(_) | Component::RootDir => None, + }) + .collect::>>()? + .join("/"); + let normal = inside_package(&value).ok()?; + let written = out.canonicalize().ok()?; + let named = root.join(&normal).canonicalize().ok()?; + (named == written).then_some(normal) +} + +/// The introspection result for `version`, from Shopify's public endpoint or +/// through the shop of `args`. +async fn fetch(args: &DownloadArgs, version: ApiVersion) -> Result { + let Some(shop) = &args.shop else { + eprintln!("Downloading the Admin schema {version} from Shopify's public endpoint…"); + return shopify_api::schema::download_public_admin_schema(version) + .await + .map_err(|error| error.to_string()); + }; + let auth = match (&args.access_token, &args.client_id, &args.client_secret) { + (Some(token), _, _) => Auth::access_token(token), + (None, Some(id), Some(secret)) => Auth::client_credentials(id, secret), + _ => { + return Err( + "--shop needs --access-token, or --client-id and --client-secret".to_string(), + ); + } + }; + let shopify = Shopify::builder(shop) + .auth(auth) + .api_version(version) + .build() + .map_err(|error| error.to_string())?; + eprintln!( + "Downloading the Admin schema {version} through {}…", + shopify.shop() + ); + shopify + .download_admin_schema() + .await + .map_err(|error| error.to_string()) +} + +/// Cargo follows a schema file once `graphql!` read it, not before it +/// exists: touching the sources makes the next build read the new file. +fn touch_sources(package: &Path) { + for source in ["src/main.rs", "src/lib.rs"] { + if let Ok(file) = std::fs::File::options() + .write(true) + .open(package.join(source)) + { + let _ = file.set_modified(std::time::SystemTime::now()); + } + } +} + +/// The directory of the nearest `Cargo.toml` that declares a package, from +/// the current directory up: where `graphql!` resolves its paths. +fn package_root() -> Option { + let mut directory = std::env::current_dir().ok()?; + loop { + let manifest = std::fs::read_to_string(directory.join("Cargo.toml")); + if manifest.is_ok_and(|text| text.lines().any(|line| line.trim() == "[package]")) { + return Some(directory); + } + if !directory.pop() { + return None; + } + } +} + +/// The schema `graphql!` would use for the nearest package, as it looks for it. +fn load_schema(path: Option<&Path>) -> Result<(Schema, String), String> { + let read = |path: &Path| -> Result, String> { + let json = std::fs::read_to_string(path) + .map_err(|error| format!("cannot read {}: {error}", path.display()))?; + Schema::from_json(&json) + .map(Arc::new) + .map_err(|error| format!("{}: {error}", path.display())) + }; + let path = match path { + Some(path) => path.to_path_buf(), + None => match schema_source(package_root().as_deref(), None, None)? { + SchemaSource::File(path) => path, + SchemaSource::Project { dir, path, pinned } => { + let schema = project_schema( + &dir, + &path, + pinned.as_deref(), + true, + SystemTime::now(), + read, + |file, version| { + eprintln!( + "Downloading the Admin schema {version} into {}…", + file.display() + ); + }, + )?; + return Ok((Arc::unwrap_or_clone(schema), path.display().to_string())); + } + }, + }; + let schema = read(&path)?; + Ok((Arc::unwrap_or_clone(schema), path.display().to_string())) +} + +fn check(args: CheckArgs) -> Result { + let (schema, source) = load_schema(args.schema.as_deref())?; + eprintln!( + "Checking against the Admin API {} ({source}).", + schema.api_version + ); + let mut failed = false; + for file in &args.files { + let text = match std::fs::read_to_string(file) { + Ok(text) => text, + Err(error) => { + eprintln!("{}: cannot read: {error}", file.display()); + failed = true; + continue; + } + }; + match analyze(&schema, &text) { + Ok(operation) => { + for deprecation in &operation.deprecations { + let (line, column) = deprecation.position; + let level = if args.deny_deprecated { + "error" + } else { + "warning" + }; + eprintln!( + "{}:{line}:{column}: {level}: `{}` is deprecated: {}", + file.display(), + deprecation.coordinate, + deprecation.reason + ); + } + failed |= args.deny_deprecated && !operation.deprecations.is_empty(); + let name = operation.name.as_deref().unwrap_or("(anonymous)"); + eprintln!("{}: ok, {:?} {name}", file.display(), operation.kind); + } + Err(error) => { + failed = true; + match error.position { + Some((line, column)) => { + eprintln!( + "{}:{line}:{column}: error: {}", + file.display(), + error.message + ) + } + None => eprintln!("{}: error: {}", file.display(), error.message), + } + } + } + } + Ok(if failed { + ExitCode::FAILURE + } else { + ExitCode::SUCCESS + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// An empty directory, canonical, removed when the test ends. + struct Dir(PathBuf); + + impl Dir { + fn new(name: &str) -> Self { + let dir = + std::env::temp_dir().join(format!("shopify-api-cli-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir.canonicalize().unwrap()) + } + + fn write(&self, path: &str) -> PathBuf { + let file = self.0.join(path); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, "{}").unwrap(); + file + } + } + + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn the_key_names_the_file_written() { + let package = Dir::new("key"); + let out = package.write("schemas/admin.json"); + assert_eq!( + schema_key(&package.0, &out), + Some(PathBuf::from("schemas/admin.json")) + ); + package.write("x.json"); + assert_eq!( + schema_key(&package.0, &package.0.join("schemas/../x.json")), + Some(PathBuf::from("x.json")) + ); + let outside = Dir::new("key-outside"); + assert_eq!(schema_key(&package.0, &outside.write("x.json")), None); + } + + #[cfg(unix)] + #[test] + fn a_name_that_is_not_a_portable_key_has_none() { + let package = Dir::new("key-portable"); + for name in ["schemas/a\\b.json", "schemas/D:x.json"] { + let out = package.write(name); + assert_eq!(schema_key(&package.0, &out), None, "{name}"); + } + } + + #[cfg(unix)] + #[test] + fn a_link_followed_by_dot_dot_names_another_file() { + let package = Dir::new("key-link"); + let outside = Dir::new("key-link-outside"); + std::fs::create_dir_all(outside.0.join("dir")).unwrap(); + std::os::unix::fs::symlink(outside.0.join("dir"), package.0.join("a")).unwrap(); + // Written through the link, `a/../x.json` is `outside/x.json`. + let out = package.0.join("a/../x.json"); + std::fs::write(&out, "{}").unwrap(); + assert!(outside.0.join("x.json").is_file()); + assert_eq!(schema_key(&package.0, &out), None); + // Even when the package has an `x.json` of its own. + package.write("x.json"); + assert_eq!(schema_key(&package.0, &out), None); + // A link inside the package to a file elsewhere is followed by both. + std::os::unix::fs::symlink(outside.0.join("x.json"), package.0.join("linked.json")) + .unwrap(); + assert_eq!( + schema_key(&package.0, &package.0.join("linked.json")), + Some(PathBuf::from("linked.json")) + ); + } +} diff --git a/crates/shopify_api/src/bulk.rs b/crates/shopify_api/src/bulk.rs new file mode 100644 index 0000000..312afbf --- /dev/null +++ b/crates/shopify_api/src/bulk.rs @@ -0,0 +1,1277 @@ +//! Bulk operations: a query over a whole catalog, or a mutation over +//! thousands of inputs, run by Shopify in the background, outside the rate limit. +//! +//! Declare one with [`graphql!`](crate::graphql!)`(bulk(…))`: it is checked +//! against the schema and Shopify's bulk rules when the crate compiles, and +//! its results are read as generated types, each nested connection a `Vec` +//! of its nodes (see [the bulk operations of `graphql!`](crate::graphql!#bulk-operations)). +//! +//! ```no_run +//! use shopify_api::bulk::BulkWaitOptions; +//! +//! shopify_api::graphql! { +//! mod all_products = bulk("{ +//! products { edges { node { id title variants { edges { node { sku } } } } } } +//! }"); +//! } +//! +//! # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { +//! // Start, wait for the end, download, and read each product with its variants. +//! let products: Vec = shopify +//! .bulk_query(all_products::operation(), BulkWaitOptions::default()) +//! .await? +//! .collect() +//! .await?; +//! for product in &products { +//! println!("{} has {} variants", product.title, product.variants.len()); +//! } +//! # Ok(()) +//! # } +//! ``` +//! +//! [`Shopify::bulk_query`] reads the file as it downloads, one top-level +//! object at a time ([`BulkItems`]); [`Shopify::bulk_mutation`] runs a +//! mutation over an iterator of its `Variables` and reads the result of each +//! run ([`BulkMutationResult`]). +//! +//! The untyped methods run any text, checked by nothing, and read each line +//! as the type you give, a `serde_json::Value` or a struct of yours: +//! +//! ```no_run +//! use shopify_api::bulk::BulkWaitOptions; +//! +//! # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { +//! let rows: Vec = shopify +//! .bulk_query_rows("{ products { edges { node { id title } } } }", BulkWaitOptions::default()) +//! .await?; +//! # Ok(()) +//! # } +//! ``` +//! +//! [`Shopify::bulk_query_rows`] holds every row in memory. For an export +//! of gigabytes, [`Shopify::bulk_query_stream`] reads the rows as the file +//! downloads ([`BulkRows`]), and [`Shopify::bulk_query_grouped`] each +//! top-level object with its nested objects ([`BulkGroups`]). Neither holds +//! the file: [`BulkRows`] holds the line being read and the rest of the +//! chunk it ends in, in a buffer sized for the longest recent line; [`BulkGroups`] and [`BulkItems`] hold that, and the group being read, +//! its top-level object with every child read so far and their IDs. A +//! product with 2,000 variants is held with its 2,000 variants. + +use std::time::Duration; + +use chrono::{DateTime, Utc}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use tokio::time::Instant; + +use crate::transport::{HttpRequest, Method}; +use crate::{Error, Operation, Page, Result, Shopify, UserError}; +use shopify_api_macros::{__graphql_internal as graphql, __input_internal as input}; + +mod rows; +mod typed; + +pub use rows::{BulkGroups, BulkRows, DEFAULT_MAX_LINE_LENGTH}; +#[doc(hidden)] +pub use typed::TypedQuery; +pub use typed::{BulkItem, BulkItems, BulkMutation, BulkMutationResult, BulkQuery}; + +/// What the code `graphql!(bulk(…))` generates refers to. Not a public API. +#[doc(hidden)] +pub mod __private { + pub use super::typed::{ + BulkArgument, BulkConnection, BulkItem, BulkMutation, BulkPart, BulkQuery, BulkTemplate, + BulkType, BulkValue, BulkVariable, push, unplaced, + }; +} + +/// How long a download waits for the answer, then for each chunk of it; a +/// transport that does not stream gives it the whole download. +const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15 * 60); + +/// What an [`Error::Http`] of a download keeps of the body: its first MiB. +const ERROR_BODY_LIMIT: usize = 1024 * 1024; + +graphql! { + mod run_query = file("graphql/operations/bulk_run_query.graphql"); + mod run_mutation = file("graphql/operations/bulk_run_mutation.graphql"); + mod get = file("graphql/operations/bulk_get.graphql"); + mod list = file("graphql/operations/bulk_list.graphql"); + mod cancel = file("graphql/operations/bulk_cancel.graphql"); + mod staged_uploads = file("graphql/operations/bulk_staged_uploads.graphql"); +} + +/// A bulk operation, as Shopify last reported it. `Debug` leaves out the +/// query string of `url` and `partial_data_url`: their signature. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct BulkOperation { + pub id: String, + pub kind: BulkOperationType, + pub status: BulkOperationStatus, + /// Why it failed: `ACCESS_DENIED`, `INTERNAL_SERVER_ERROR`, `TIMEOUT`. + pub error_code: Option, + pub created_at: DateTime, + /// When it completed, failed or was canceled. + pub completed_at: Option>, + /// The objects written so far, nested ones included. + pub object_count: u64, + /// The top-level objects written so far. + pub root_object_count: u64, + /// The size of the result file, in bytes. + pub file_size: Option, + /// Where to download the results, once completed. It expires a week later. + pub url: Option, + /// Where to download what was written before a failure. + pub partial_data_url: Option, + pub query: String, +} + +impl std::fmt::Debug for BulkOperation { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let unsigned = |url: &Option| url.as_deref().map(crate::error::without_query); + formatter + .debug_struct("BulkOperation") + .field("id", &self.id) + .field("kind", &self.kind) + .field("status", &self.status) + .field("error_code", &self.error_code) + .field("created_at", &self.created_at) + .field("completed_at", &self.completed_at) + .field("object_count", &self.object_count) + .field("root_object_count", &self.root_object_count) + .field("file_size", &self.file_size) + .field("url", &unsigned(&self.url)) + .field("partial_data_url", &unsigned(&self.partial_data_url)) + .field("query", &self.query) + .finish() + } +} + +/// The status of a bulk operation. A status Shopify adds later is `Other`. +/// +/// It serializes as Shopify writes it: `"COMPLETED"`, and `Other` as its text. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum BulkOperationStatus { + Created, + Running, + Completed, + Canceling, + Canceled, + Failed, + Expired, + Other(String), +} + +impl BulkOperationStatus { + /// The status as an error shows it: an unknown one is not quoted. + fn shown(&self) -> &'static str { + match self { + Self::Created => "Created", + Self::Running => "Running", + Self::Completed => "Completed", + Self::Canceling => "Canceling", + Self::Canceled => "Canceled", + Self::Failed => "Failed", + Self::Expired => "Expired", + Self::Other(_) => "with a status this crate does not know", + } + } + + /// As Shopify writes it: `COMPLETED`. + pub fn as_str(&self) -> &str { + match self { + Self::Created => "CREATED", + Self::Running => "RUNNING", + Self::Completed => "COMPLETED", + Self::Canceling => "CANCELING", + Self::Canceled => "CANCELED", + Self::Failed => "FAILED", + Self::Expired => "EXPIRED", + Self::Other(other) => other, + } + } + + fn parse(value: &str) -> Self { + match value { + "CREATED" => Self::Created, + "RUNNING" => Self::Running, + "COMPLETED" => Self::Completed, + "CANCELING" => Self::Canceling, + "CANCELED" => Self::Canceled, + "FAILED" => Self::Failed, + "EXPIRED" => Self::Expired, + other => Self::Other(other.to_string()), + } + } + + /// It will not change anymore. + pub fn is_terminal(&self) -> bool { + matches!( + self, + Self::Completed | Self::Canceled | Self::Failed | Self::Expired + ) + } +} + +/// The type of a bulk operation. A type Shopify adds later is `Other`. +/// +/// It serializes as Shopify writes it: `"QUERY"`, and `Other` as its text. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum BulkOperationType { + Query, + Mutation, + Other(String), +} + +impl BulkOperationType { + /// As Shopify writes it: `QUERY`. + pub fn as_str(&self) -> &str { + match self { + Self::Query => "QUERY", + Self::Mutation => "MUTATION", + Self::Other(other) => other, + } + } + + fn parse(value: &str) -> Self { + match value { + "QUERY" => Self::Query, + "MUTATION" => Self::Mutation, + other => Self::Other(other.to_string()), + } + } +} + +/// Serde as Shopify writes the enum: its text, an unknown one as `Other`. +macro_rules! wire_serde { + ($($type:ty),*) => {$( + impl Serialize for $type { + fn serialize(&self, serializer: S) -> std::result::Result { + serializer.serialize_str(self.as_str()) + } + } + + impl<'de> Deserialize<'de> for $type { + fn deserialize>(deserializer: D) -> std::result::Result { + let text = std::borrow::Cow::::deserialize(deserializer)?; + Ok(Self::parse(&text)) + } + } + )*}; +} + +wire_serde!(BulkOperationStatus, BulkOperationType); + +/// The selection every operation of this module makes on `BulkOperation`, +/// as Shopify sends it. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Wire { + id: String, + #[serde(rename = "type")] + kind: String, + status: String, + error_code: Option, + created_at: DateTime, + completed_at: Option>, + object_count: String, + root_object_count: String, + file_size: Option, + url: Option, + partial_data_url: Option, + query: String, +} + +impl Wire { + fn into_operation(self) -> Result { + let number = |field: &str, value: &str| { + value + .parse::() + // The value is not shown: it is the answer's. + .map_err(|_| bulk_error(format!("`{field}` is not an unsigned integer"))) + }; + Ok(BulkOperation { + object_count: number("objectCount", &self.object_count)?, + root_object_count: number("rootObjectCount", &self.root_object_count)?, + file_size: self + .file_size + .as_deref() + .map(|size| number("fileSize", size)) + .transpose()?, + id: self.id, + kind: BulkOperationType::parse(&self.kind), + status: BulkOperationStatus::parse(&self.status), + error_code: self.error_code, + created_at: self.created_at, + completed_at: self.completed_at, + url: self.url, + partial_data_url: self.partial_data_url, + query: self.query, + }) + } +} + +/// An [`Error::Bulk`] without an operation. +pub(crate) fn bulk_error(message: impl Into) -> Error { + Error::Bulk { + message: message.into(), + operation: None, + } +} + +/// The ID of a bulk operation as an error shows it: a `gid://` of Shopify, +/// else nothing of the text. +pub(crate) fn shown_id(id: &str) -> &str { + let shown = id + .strip_prefix("gid://shopify/BulkOperation/") + .is_some_and(|number| { + !number.is_empty() && number.bytes().all(|byte| byte.is_ascii_digit()) + }); + if shown { id } else { "[id not shown]" } +} + +/// What `Debug` of an [`Error::Bulk`] shows of its operation: what its +/// message shows. +pub(crate) struct ShownOperation<'a>(pub &'a BulkOperation); + +impl std::fmt::Debug for ShownOperation<'_> { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("BulkOperation") + .field("id", &shown_id(&self.0.id)) + .field("status", &self.0.status.shown()) + .field( + "error_code", + &self.0.error_code.as_deref().map(shown_error_code), + ) + .finish_non_exhaustive() + } +} + +/// The error of an operation that ended without completing. +pub(crate) fn not_completed(operation: BulkOperation) -> Error { + Error::Bulk { + message: format!( + "the bulk operation {} ended {}{}", + shown_id(&operation.id), + operation.status.shown(), + operation + .error_code + .as_deref() + .map(|code| format!(" ({})", shown_error_code(code))) + .unwrap_or_default() + ), + operation: Some(Box::new(operation)), + } +} + +/// The error of a wait that ran out. +pub(crate) fn timed_out(id: &str, timeout: Duration) -> Error { + Error::Timeout { + message: format!( + "the bulk operation {} did not end within {timeout:?}", + shown_id(id) + ), + id: Some(id.to_string()), + } +} + +/// A `BulkOperationErrorCode` as an error shows it. +fn shown_error_code(code: &str) -> &'static str { + match code { + "ACCESS_DENIED" => "ACCESS_DENIED", + "INTERNAL_SERVER_ERROR" => "INTERNAL_SERVER_ERROR", + "TIMEOUT" => "TIMEOUT", + _ => "an error code this crate does not know", + } +} + +/// Reads the `BulkOperationFields` of a generated type. +pub(crate) fn operation_of(selection: &impl Serialize) -> Result { + let wire: Wire = crate::decode::reserialize(selection)?; + wire.into_operation() +} + +/// The user errors of a generated payload. +fn user_errors(errors: &impl Serialize) -> Result> { + crate::decode::reserialize(errors) +} + +/// How [`Shopify::wait_for_bulk_operation`] polls. +#[derive(Debug, Clone)] +pub struct BulkWaitOptions { + first_poll: Duration, + poll_interval: Duration, + timeout: Option, +} + +impl BulkWaitOptions { + /// The first poll a second after the start, then twice as late each + /// time, up to every ten seconds; no timeout. + pub const fn new() -> Self { + Self { + first_poll: Duration::from_secs(1), + poll_interval: Duration::from_secs(10), + timeout: None, + } + } + + /// The longest wait between two polls. + pub const fn poll_interval(mut self, interval: Duration) -> Self { + self.poll_interval = interval; + if self.first_poll.as_nanos() > interval.as_nanos() { + self.first_poll = interval; + } + self + } + + /// Gives up after `timeout`, with [`Error::Timeout`]. The operation keeps running. + pub const fn timeout(mut self, timeout: Duration) -> Self { + self.timeout = Some(timeout); + self + } +} + +impl Default for BulkWaitOptions { + fn default() -> Self { + Self::new() + } +} + +/// Which bulk operations [`Shopify::bulk_operations`] lists, newest first. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BulkOperationsFilter { + first: u32, + after: Option, + query: Option, +} + +impl BulkOperationsFilter { + /// The ten newest operations. + pub fn new() -> Self { + Self { + first: 10, + after: None, + query: None, + } + } + + /// How many per page, up to 250. + pub fn first(mut self, first: u32) -> Self { + self.first = first.clamp(1, 250); + self + } + + /// The page after this cursor. + pub fn after(mut self, cursor: impl Into) -> Self { + self.after = Some(cursor.into()); + self + } + + /// A search, such as `status:RUNNING` or `operation_type:QUERY`. + pub fn query(mut self, query: impl Into) -> Self { + self.query = Some(query.into()); + self + } +} + +impl Default for BulkOperationsFilter { + fn default() -> Self { + Self::new() + } +} + +/// What [`Shopify::start_bulk_query`] starts: the text of a bulk query +/// (`&str`, `String`), checked by nothing; the same text in [`GroupObjects`]; +/// or a query declared with `graphql!(bulk(…))`, or the `Variables` of its module. +/// +/// It is sealed: only this crate and `graphql!` implement it. `M` tells +/// the kinds apart and is inferred. +#[diagnostic::on_unimplemented( + message = "`{Self}` is not a bulk query to start", + label = "a `&str`, a `String`, `GroupObjects(…)`, or a `graphql!(bulk(…))` query or its `Variables`" +)] +pub trait StartBulkQuery: sealed::Sealed {} + +pub(crate) mod sealed { + /// The arguments of `bulkOperationRunQuery`. + #[doc(hidden)] + #[derive(Debug)] + pub struct Start { + pub(crate) query: String, + pub(crate) group_objects: bool, + /// `None` for a text checked by nothing, sent as the crate's own + /// operation; else the version a typed query was checked against. + pub(crate) checked_against: Option>, + } + + #[doc(hidden)] + pub trait Sealed { + fn __start(self) -> crate::Result; + } + + /// The kind of a text, checked by nothing. + #[doc(hidden)] + #[derive(Debug)] + pub enum Text {} +} + +/// The text of a bulk query to run with `groupObjects`: each object of a +/// nested connection is written right after its parent, which +/// [`Shopify::download_bulk_results_grouped`] needs. Shopify is slower with +/// it, and more likely to time out. +/// +/// ```no_run +/// use shopify_api::bulk::GroupObjects; +/// +/// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { +/// let operation = shopify +/// .start_bulk_query(GroupObjects( +/// "{ products { edges { node { id variants { edges { node { sku } } } } } } }", +/// )) +/// .await?; +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GroupObjects(pub Q); + +fn start_text(query: String, group_objects: bool) -> sealed::Start { + sealed::Start { + query, + group_objects, + checked_against: None, + } +} + +impl sealed::Sealed for &str { + fn __start(self) -> Result { + Ok(start_text(self.to_string(), false)) + } +} +impl StartBulkQuery for &str {} + +impl sealed::Sealed for String { + fn __start(self) -> Result { + Ok(start_text(self, false)) + } +} +impl StartBulkQuery for String {} + +impl sealed::Sealed for &String { + fn __start(self) -> Result { + Ok(start_text(self.clone(), false)) + } +} +impl StartBulkQuery for &String {} + +impl> sealed::Sealed for GroupObjects { + fn __start(self) -> Result { + Ok(start_text(self.0.into(), true)) + } +} +impl> StartBulkQuery for GroupObjects {} + +impl Shopify { + /// Starts a bulk query, and returns the operation: wait for it with + /// [`Shopify::wait_for_bulk_operation`], then download its results. + /// + /// - A text (`&str`, `String`) is checked by nothing, and runs without + /// `groupObjects`; [`GroupObjects`]`(text)` runs it with. Read its + /// results with [`Shopify::download_bulk_results_stream`], or + /// [`Shopify::download_bulk_results_grouped`] for a grouped one. + /// Shopify refuses a text that is not a bulk query (one connection at + /// the root, no `first`) with user errors, returned as [`Error::UserErrors`]. + /// - A query declared with `graphql!(bulk(…))`, or the `Variables` of its + /// module, sends [`BulkQuery::text`] to the Admin API version it was + /// checked against, as [`Shopify::execute`] would, with `groupObjects` + /// only when it has nested connections. Read its results with + /// [`Shopify::download_bulk_items`]. + /// + /// [`Shopify::bulk_query`], [`Shopify::bulk_query_rows`] and the other + /// `bulk_query*` methods start, wait and read in one call. + /// + /// ```no_run + /// use shopify_api::bulk::BulkWaitOptions; + /// + /// shopify_api::graphql! { + /// mod all_products = bulk("{ products { edges { node { id title } } } }"); + /// } + /// + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let typed = shopify.start_bulk_query(all_products::operation()).await?; + /// let untyped = shopify.start_bulk_query("{ products { edges { node { id } } } }").await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn start_bulk_query( + &self, + query: impl StartBulkQuery, + ) -> Result { + let start = query.__start()?; + let variables = run_query::Variables { + query: start.query, + group_objects: start.group_objects, + }; + let data = match start.checked_against { + None => self.execute_own(variables).await?, + Some(version) => { + self.execute(Operation::from(variables).checked_as(version)) + .await? + } + }; + let payload = data + .bulk_operation_run_query + .ok_or_else(|| bulk_error("bulkOperationRunQuery returned nothing"))?; + started( + "bulkOperationRunQuery", + payload.bulk_operation, + &payload.user_errors, + ) + } + + /// Starts a bulk mutation over `variables`, checked by nothing: one run + /// of `mutation` per item, which holds the variables of that run. The + /// items are uploaded as a JSONL file first, each serialized as it is + /// taken: they need not all be in memory, only the file, which Shopify + /// caps at 100 MB. A slice or a `Vec` is given by reference. + /// + /// The upload target is reserved first: an item that does not + /// serialize fails after it, and the target goes unused. + /// + /// The typed counterpart is [`Shopify::start_bulk_mutation`], whose + /// lines hold their mutation. + /// + /// ```no_run + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let mutation = "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }"; + /// let rows = vec![ + /// serde_json::json!({ "product": { "id": "gid://shopify/Product/1", "title": "New title" } }), + /// serde_json::json!({ "product": { "id": "gid://shopify/Product/2", "title": "Other title" } }), + /// ]; + /// let operation = shopify.start_bulk_mutation_text(mutation, &rows).await?; + /// + /// // Or from an iterator, without the items in memory. + /// let rows = (1..=50_000).map(|id| { + /// serde_json::json!({ "product": { "id": format!("gid://shopify/Product/{id}"), "status": "ARCHIVED" } }) + /// }); + /// let operation = shopify.start_bulk_mutation_text(mutation, rows).await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn start_bulk_mutation_text( + &self, + mutation: &str, + variables: I, + ) -> Result + where + I: IntoIterator, + I::Item: Serialize, + { + let path = self.stage_bulk_variables_iter(variables).await?; + self.start_bulk_mutation_staged(mutation, &path, None).await + } + + /// Starts a bulk mutation, checked by nothing, over a JSONL file already + /// uploaded with [`Shopify::stage_bulk_variables`]. `client_identifier` + /// is yours, kept with the operation. + pub async fn start_bulk_mutation_staged( + &self, + mutation: &str, + staged_upload_path: &str, + client_identifier: Option<&str>, + ) -> Result { + let data = self + .execute_own(run_mutation::Variables { + mutation: mutation.to_string(), + staged_upload_path: staged_upload_path.to_string(), + client_identifier: client_identifier.map(str::to_string), + }) + .await?; + let payload = data + .bulk_operation_run_mutation + .ok_or_else(|| bulk_error("bulkOperationRunMutation returned nothing".to_string()))?; + started( + "bulkOperationRunMutation", + payload.bulk_operation, + &payload.user_errors, + ) + } + + /// Uploads `variables` as the JSONL file of a bulk mutation, one item per + /// line, and returns its staged upload path. + /// + /// The upload target is reserved first: an item that does not + /// serialize fails after it, and the target goes unused. + pub async fn stage_bulk_variables(&self, variables: &[T]) -> Result { + self.stage_bulk_variables_iter(variables).await + } + + /// [`Shopify::stage_bulk_variables`] over the items of an iterator, + /// written straight into the body of the upload as they are taken. + /// + /// The upload target is reserved first: an item that does not + /// serialize fails after it, and the target goes unused. + pub async fn stage_bulk_variables_iter(&self, variables: I) -> Result + where + I: IntoIterator, + I::Item: Serialize, + { + self.stage_jsonl(|body| { + for item in variables { + serde_json::to_writer(&mut *body, &item) + .map_err(|error| Error::variables(None, &error))?; + body.push(b'\n'); + } + Ok(()) + }) + .await + } + + /// Reserves an upload target, then uploads the JSONL file `write_file` + /// writes to it. Returns its staged upload path. + async fn stage_jsonl( + &self, + write_file: impl FnOnce(&mut Vec) -> Result<()>, + ) -> Result { + let data = self + .execute_own(staged_uploads::Variables { + input: vec![input!(StagedUploadInput { + filename: "bulk_op_vars.jsonl", + mimeType: "text/jsonl", + resource: BULK_MUTATION_VARIABLES, + httpMethod: POST, + })], + }) + .await?; + let payload = data + .staged_uploads_create + .ok_or_else(|| bulk_error("stagedUploadsCreate returned nothing".to_string()))?; + let errors = user_errors(&payload.user_errors)?; + if !errors.is_empty() { + return Err(Error::UserErrors { + mutation: "stagedUploadsCreate", + errors, + }); + } + let target = payload + .staged_targets + .into_iter() + .flatten() + .next() + .ok_or_else(|| bulk_error("stagedUploadsCreate returned no target".to_string()))?; + let url = target + .url + .ok_or_else(|| bulk_error("the staged upload target has no address".to_string()))?; + let parameters: Vec<(String, String)> = target + .parameters + .into_iter() + .map(|parameter| (parameter.name, parameter.value)) + .collect(); + let key = parameters + .iter() + .find(|(name, _)| name == "key") + .map(|(_, value)| value.clone()) + .ok_or_else(|| { + bulk_error("the staged upload target has no `key` parameter".to_string()) + })?; + + // The storage server wants the length of the body up front: the + // file is built in memory, once, in the body itself. + let (content_type, body) = + multipart(¶meters, "bulk_op_vars.jsonl", "text/jsonl", write_file)?; + let request = HttpRequest::new(Method::Post, &url) + .with_header("Content-Type", content_type) + .with_body(body) + .with_timeout(DOWNLOAD_TIMEOUT); + let response = self + .shared + .endpoint + .transport + .send(request) + .await + .map_err(|source| Error::transport(&url, source))?; + if !response.is_success() { + return Err(Error::http(&url, &response)); + } + Ok(key) + } + + /// A bulk operation by ID, `None` when the shop has none of that ID. + pub async fn bulk_operation(&self, id: &str) -> Result> { + let data = self + .execute_own(get::Variables { id: id.to_string() }) + .await?; + data.bulk_operation.as_ref().map(operation_of).transpose() + } + + /// One page of the shop's bulk operations, newest first. + pub async fn bulk_operations( + &self, + filter: BulkOperationsFilter, + ) -> Result> { + let data = self + .execute_own(list::Variables { + first: i64::from(filter.first), + after: filter.after, + query: filter.query, + reverse: Some(true), + }) + .await?; + let connection = data.bulk_operations; + let items = connection + .nodes + .iter() + .map(operation_of) + .collect::>()?; + Ok(Page::new( + items, + connection.page_info.has_next_page, + connection.page_info.end_cursor, + )) + } + + /// Asks Shopify to cancel a running bulk operation. + pub async fn cancel_bulk_operation(&self, id: &str) -> Result { + let data = self + .execute_own(cancel::Variables { id: id.to_string() }) + .await?; + let payload = data + .bulk_operation_cancel + .ok_or_else(|| bulk_error("bulkOperationCancel returned nothing".to_string()))?; + started( + "bulkOperationCancel", + payload.bulk_operation, + &payload.user_errors, + ) + } + + /// Polls a bulk operation until it completes, fails, is canceled or expires. + /// + /// It returns the operation as it ended: an operation that failed is + /// `Ok`, with `status` [`BulkOperationStatus::Failed`] and its + /// `error_code`, so check `status`. The calls that start, wait and read, + /// such as [`Shopify::bulk_query_rows`] or [`Shopify::bulk_query`], fail + /// with [`Error::Bulk`] instead. A wait longer than the timeout of + /// `options` is an [`Error::Timeout`]; the operation keeps running. + pub async fn wait_for_bulk_operation( + &self, + id: &str, + options: BulkWaitOptions, + ) -> Result { + let started = Instant::now(); + let mut wait = options.first_poll; + loop { + if let Some(timeout) = options.timeout { + let elapsed = started.elapsed(); + if elapsed >= timeout { + return Err(timed_out(id, timeout)); + } + wait = wait.min(timeout - elapsed); + } + tokio::time::sleep(wait).await; + let operation = self.bulk_operation(id).await?.ok_or_else(|| { + bulk_error(format!( + "the bulk operation {} does not exist", + shown_id(id) + )) + })?; + // A status this version does not know ends the wait too: it is + // the caller's to read, rather than a loop that never ends. + if operation.status.is_terminal() + || matches!(operation.status, BulkOperationStatus::Other(_)) + { + return Ok(operation); + } + wait = wait.saturating_mul(2).min(options.poll_interval); + } + } + + /// Runs a bulk query to its end and reads every line of its results as + /// `T`. Fails when the operation does not complete. + /// + /// The rows are collected in a `Vec`, up to the first error: for an + /// export too large for memory, read them one by one with + /// [`Shopify::bulk_query_stream`]. + /// + /// A nested connection writes its objects on lines of their own, with + /// the `__parentId` of their parent: read the lines as `serde_json::Value`, + /// or as an enum of your types, to put them back together, or use + /// [`Shopify::bulk_query_grouped`]. + pub async fn bulk_query_rows( + &self, + query: &str, + options: BulkWaitOptions, + ) -> Result> { + self.bulk_query_stream(query, options) + .await? + .collect() + .await + } + + /// Runs a bulk query to its end, then reads its results line by line + /// as they download: the memory it takes follows the lines being read, + /// not the file (see [`BulkRows`]). Fails when the operation does not complete. + /// + /// The stream ends after some errors and goes on after others: see + /// [`BulkRows`]. + /// + /// ```no_run + /// use serde::Deserialize; + /// use shopify_api::bulk::BulkWaitOptions; + /// + /// #[derive(Deserialize)] + /// struct Product { + /// id: String, + /// title: String, + /// } + /// + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let mut products = shopify + /// .bulk_query_stream::( + /// "{ products { edges { node { id title } } } }", + /// BulkWaitOptions::default(), + /// ) + /// .await?; + /// while let Some(product) = products.next_row().await { + /// let product = product?; + /// println!("{} {}", product.id, product.title); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn bulk_query_stream( + &self, + query: &str, + options: BulkWaitOptions, + ) -> Result> { + let operation = self.start_bulk_query(query).await?; + match self.completed_url(&operation.id, options).await? { + Some(url) => self.download_bulk_results_stream(&url).await, + None => Ok(BulkRows::new(None, "")), + } + } + + /// Runs a bulk query with `groupObjects` to its end, then reads its + /// results one top-level object at a time, with the objects of its + /// nested connections, as they download. Fails when the operation does + /// not complete. + /// + /// Grouping makes Shopify slower, and more likely to time out: use it + /// when you need the children with their parent. Every object that has + /// a nested connection must select `id`, without an alias: Shopify + /// refuses the query otherwise. See [`BulkGroups`] for the order it + /// relies on and connections two levels deep. + /// + /// ```no_run + /// use serde::Deserialize; + /// use shopify_api::bulk::BulkWaitOptions; + /// + /// #[derive(Deserialize)] + /// struct Product { + /// id: String, + /// title: String, + /// } + /// + /// #[derive(Deserialize)] + /// struct Variant { + /// sku: Option, + /// } + /// + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let mut products = shopify + /// .bulk_query_grouped::( + /// "{ products { edges { node { id title variants { edges { node { sku } } } } } } }", + /// BulkWaitOptions::default(), + /// ) + /// .await?; + /// while let Some(group) = products.next_group().await { + /// let (product, variants) = group?; + /// println!("{} has {} variants", product.title, variants.len()); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn bulk_query_grouped( + &self, + query: &str, + options: BulkWaitOptions, + ) -> Result> { + let operation = self.start_bulk_query(GroupObjects(query)).await?; + match self.completed_url(&operation.id, options).await? { + Some(url) => Ok(self.download_bulk_results_grouped(&url).await?.grouped()), + None => Ok(BulkGroups::new(None, "").grouped()), + } + } + + /// Waits for an operation, and returns the address of its results: + /// `None` when it found nothing. + async fn completed_url(&self, id: &str, options: BulkWaitOptions) -> Result> { + let operation = self.wait_for_bulk_operation(id, options).await?; + if operation.status != BulkOperationStatus::Completed { + return Err(not_completed(operation)); + } + Ok(operation.url) + } + + /// Downloads the results of a bulk operation and reads each line as + /// `T`, up to the first error. + /// + /// The rows are collected in a `Vec`: for an export too large for + /// memory, use [`Shopify::download_bulk_results_stream`]. The address + /// is signed: errors leave its query string out. + pub async fn download_bulk_results(&self, url: &str) -> Result> { + self.download_bulk_results_stream(url) + .await? + .collect() + .await + } + + /// Downloads the results of a bulk operation, its `url` or its + /// `partial_data_url`, and reads each line as `T` as it arrives. See + /// [`BulkRows`]. + /// + /// It returns once the answer's headers arrive. An answer that is not a + /// success is an [`Error::Http`] with the first MiB of its body. The + /// address is signed: errors leave its query string out. + /// + /// The default transport waits 15 minutes at most for the answer, then + /// for each chunk, however long the whole download takes: read the rows + /// as they come, a storage server may close a connection left idle. + pub async fn download_bulk_results_stream( + &self, + url: &str, + ) -> Result> { + let body = self.open_bulk_results(url).await?; + Ok(BulkRows::new(Some(body), url)) + } + + /// [`Shopify::download_bulk_results_stream`], one top-level object and + /// its children at a time. The operation must have run with + /// `groupObjects`, and every object of it that has a nested connection + /// must have an `id`, not aliased: see [`BulkGroups`]. + pub async fn download_bulk_results_grouped( + &self, + url: &str, + ) -> Result> { + let body = self.open_bulk_results(url).await?; + Ok(BulkGroups::new(Some(body), url)) + } + + async fn open_bulk_results(&self, url: &str) -> Result { + let request = HttpRequest::new(Method::Get, url).with_timeout(DOWNLOAD_TIMEOUT); + let response = self + .shared + .endpoint + .transport + .send_streaming(request) + .await + .map_err(|source| Error::transport(url, source))?; + if !response.is_success() { + let response = response.into_response(ERROR_BODY_LIMIT).await; + return Err(Error::http(url, &response)); + } + Ok(response.body) + } +} + +/// The operation a bulk mutation started, or the user errors that refused it. +fn started( + mutation: &'static str, + operation: Option, + errors: &E, +) -> Result { + let errors = user_errors(errors)?; + if !errors.is_empty() { + return Err(Error::UserErrors { mutation, errors }); + } + let operation = + operation.ok_or_else(|| bulk_error(format!("{mutation} returned no operation")))?; + operation_of(&operation) +} + +/// Reads each non-empty line of a JSONL file already in memory as `T`. To +/// read one as it downloads, see [`BulkRows`]. +pub fn parse_jsonl(body: &[u8]) -> Result> { + body.split(|byte| *byte == b'\n') + .enumerate() + .filter(|(_, line)| !line.iter().all(u8::is_ascii_whitespace)) + .map(|(index, line)| crate::decode::from_jsonl_line(line, index + 1)) + .collect() +} + +/// A `multipart/form-data` body: the fields, then the file `write_file` +/// writes. Returns its `Content-Type` and its bytes. +fn multipart( + fields: &[(String, String)], + filename: &str, + mime: &str, + write_file: impl FnOnce(&mut Vec) -> Result<()>, +) -> Result<(String, Vec)> { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_nanos()) + .unwrap_or_default(); + let boundary = format!("shopify-api-{nanos:x}"); + let quoted = |text: &str| text.replace('\\', "\\\\").replace('"', "\\\""); + let mut body = Vec::new(); + for (name, value) in fields { + body.extend_from_slice( + format!( + "--{boundary}\r\nContent-Disposition: form-data; name=\"{}\"\r\n\r\n{value}\r\n", + quoted(name) + ) + .as_bytes(), + ); + } + body.extend_from_slice( + format!( + "--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{}\"\r\nContent-Type: {mime}\r\n\r\n", + quoted(filename) + ) + .as_bytes(), + ); + write_file(&mut body)?; + body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes()); + Ok((format!("multipart/form-data; boundary={boundary}"), body)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn debug_hides_the_signature_of_the_download_addresses() { + let operation = BulkOperation { + id: "gid://shopify/BulkOperation/1".to_string(), + kind: BulkOperationType::Query, + status: BulkOperationStatus::Completed, + error_code: None, + created_at: "2026-10-22T10:00:00Z".parse().unwrap(), + completed_at: None, + object_count: 0, + root_object_count: 0, + file_size: None, + url: Some("https://storage.googleapis.com/a.jsonl?X-Goog-Signature=SECRET".to_string()), + partial_data_url: Some( + "https://storage.googleapis.com/b.jsonl?X-Goog-Signature=SECRET".to_string(), + ), + query: "{ shop { name } }".to_string(), + }; + let shown = format!("{operation:?}"); + assert!(!shown.contains("SECRET"), "{shown}"); + assert!( + shown.contains("https://storage.googleapis.com/a.jsonl"), + "{shown}" + ); + assert!( + shown.contains("https://storage.googleapis.com/b.jsonl"), + "{shown}" + ); + } + + #[test] + fn parses_jsonl_and_names_the_line_at_fault() { + let rows: Vec = parse_jsonl(b"{\"id\":1}\n\n{\"id\":2}\n").unwrap(); + assert_eq!(rows.len(), 2); + assert_eq!(rows[1]["id"], 2); + + #[derive(Debug, Deserialize)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] + struct Row { + id: String, + } + let error = parse_jsonl::(b"{\"id\":\"a\"}\n{\"id\":2}\n").unwrap_err(); + assert_eq!( + error.to_string(), + "Shopify's answer does not match the operation at `id`: invalid type: integer, expected a string at line 2 column 7" + ); + } + + #[test] + fn builds_a_multipart_body() { + let fields = vec![("key".to_string(), "tmp/1/bulk".to_string())]; + let (content_type, body) = multipart(&fields, "vars.jsonl", "text/jsonl", |body| { + body.extend_from_slice(b"{}\n"); + Ok(()) + }) + .unwrap(); + let boundary = content_type + .strip_prefix("multipart/form-data; boundary=") + .unwrap(); + let body = String::from_utf8(body).unwrap(); + assert_eq!( + body, + format!( + "--{boundary}\r\nContent-Disposition: form-data; name=\"key\"\r\n\r\ntmp/1/bulk\r\n\ + --{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"vars.jsonl\"\r\nContent-Type: text/jsonl\r\n\r\n{{}}\n\r\n\ + --{boundary}--\r\n" + ) + ); + } + + #[test] + fn statuses_and_types_serialize_as_shopify_writes_them() { + for (status, text) in [ + (BulkOperationStatus::Completed, "\"COMPLETED\""), + (BulkOperationStatus::Canceling, "\"CANCELING\""), + ( + BulkOperationStatus::Other("PAUSED".to_string()), + "\"PAUSED\"", + ), + ] { + assert_eq!(serde_json::to_string(&status).unwrap(), text); + assert_eq!( + serde_json::from_str::(text).unwrap(), + status + ); + } + for (kind, text) in [ + (BulkOperationType::Mutation, "\"MUTATION\""), + (BulkOperationType::Other("EXPORT".to_string()), "\"EXPORT\""), + ] { + assert_eq!(serde_json::to_string(&kind).unwrap(), text); + assert_eq!( + serde_json::from_str::(text).unwrap(), + kind + ); + } + // A stored operation reads back as it was. + let operation = operation_of(&serde_json::json!({ + "id": "gid://shopify/BulkOperation/1", + "type": "QUERY", + "status": "FAILED", + "errorCode": "TIMEOUT", + "createdAt": "2026-10-22T10:00:00Z", + "completedAt": "2026-10-22T10:05:00Z", + "objectCount": "3", + "rootObjectCount": "1", + "fileSize": null, + "url": null, + "partialDataUrl": null, + "query": "{ shop { id } }", + })) + .unwrap(); + let stored = serde_json::to_value(&operation).unwrap(); + assert_eq!(stored["status"], "FAILED"); + assert_eq!(stored["kind"], "QUERY"); + assert_eq!(stored["created_at"], "2026-10-22T10:00:00Z"); + assert_eq!( + serde_json::from_value::(stored).unwrap(), + operation + ); + } + + #[test] + fn statuses_say_when_they_end() { + assert!(BulkOperationStatus::parse("COMPLETED").is_terminal()); + assert!(!BulkOperationStatus::parse("RUNNING").is_terminal()); + assert_eq!( + BulkOperationStatus::parse("PAUSED"), + BulkOperationStatus::Other("PAUSED".to_string()) + ); + } +} diff --git a/crates/shopify_api/src/bulk/rows.rs b/crates/shopify_api/src/bulk/rows.rs new file mode 100644 index 0000000..641022e --- /dev/null +++ b/crates/shopify_api/src/bulk/rows.rs @@ -0,0 +1,1260 @@ +//! The results of a bulk operation, read line by line as they download. + +use std::collections::{HashMap, HashSet}; +use std::fmt; +use std::marker::PhantomData; +use std::ops::Range; +use std::pin::Pin; +use std::task::{Context, Poll}; + +use futures_core::{FusedStream, Stream}; +use serde::Deserialize; +use serde::de::DeserializeOwned; + +use super::typed::BulkItem; +use crate::transport::BodyStream; +use crate::{Error, Result}; + +/// The longest line [`BulkRows`] and [`BulkGroups`] read by default: 64 MiB. +pub const DEFAULT_MAX_LINE_LENGTH: usize = 64 * 1024 * 1024; + +/// What the buffer may keep, whatever it holds: a buffer more than four +/// times what it held lately, and than this, shrinks after a long line. +const KEPT_CAPACITY: usize = 64 * 1024; + +/// How many lines the buffer remembers what it held: lines of the same +/// size, cut into small chunks, reuse its capacity rather than regrow it. +const KEPT_LINES: usize = 16; + +/// A line: its number, from 1, and where it is in the buffer. +type Line = (usize, Range); + +type Grouped = Result<(P, Vec)>; + +/// The lines of a JSONL body, split as its chunks arrive. It holds the +/// line being read and the rest of the chunk it ends in, never the file. +struct Lines { + body: Option, + /// The address, without its query string, for errors. + url: String, + buffer: Vec, + /// Where the line being read starts in `buffer`. + start: usize, + /// How many bytes of that line were searched for its end already. + scanned: usize, + /// The number of the last line taken, from 1. + line: usize, + max: usize, + done: bool, + /// The most `buffer` held since line `window`, and in the + /// `KEPT_LINES` lines before. + held: usize, + held_before: usize, + window: usize, + #[cfg(test)] + shrinks: usize, +} + +impl Lines { + fn new(body: Option, url: &str) -> Self { + Self { + done: body.is_none(), + body, + url: crate::error::without_query(url), + buffer: Vec::new(), + start: 0, + scanned: 0, + line: 0, + max: DEFAULT_MAX_LINE_LENGTH, + held: 0, + held_before: 0, + window: 0, + #[cfg(test)] + shrinks: 0, + } + } + + fn finish(&mut self) { + self.done = true; + self.body = None; + self.buffer = Vec::new(); + self.start = 0; + self.scanned = 0; + } + + fn too_long(&mut self, line: usize) -> Error { + self.finish(); + super::bulk_error(format!( + "line {line} of the results is longer than {} bytes", + self.max + )) + } + + /// The next line that is not blank: its number and where it is in + /// `buffer`, until the next poll. + fn poll_line(&mut self, context: &mut Context<'_>) -> Poll>> { + while !self.done { + let from = self.start + self.scanned; + if let Some(offset) = self.buffer[from..].iter().position(|byte| *byte == b'\n') { + let range = self.start..from + offset; + self.start = range.end + 1; + self.scanned = 0; + self.line += 1; + if range.len() > self.max { + return Poll::Ready(Some(Err(self.too_long(self.line)))); + } + if !is_blank(&self.buffer[range.clone()]) { + return Poll::Ready(Some(Ok((self.line, range)))); + } + continue; + } + self.scanned = self.buffer.len() - self.start; + if self.scanned > self.max { + return Poll::Ready(Some(Err(self.too_long(self.line + 1)))); + } + let Some(body) = self.body.as_mut() else { + let range = self.start..self.buffer.len(); + self.start = range.end; + self.scanned = 0; + self.done = true; + if range.is_empty() { + break; + } + self.line += 1; + if is_blank(&self.buffer[range.clone()]) { + break; + } + return Poll::Ready(Some(Ok((self.line, range)))); + }; + match body.as_mut().poll_next(context) { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => self.body = None, + Poll::Ready(Some(Err(source))) => { + self.finish(); + return Poll::Ready(Some(Err(Error::transport(&self.url, source)))); + } + Poll::Ready(Some(Ok(chunk))) => { + self.buffer.drain(..self.start); + self.start = 0; + let lines = self.line - self.window; + if lines >= KEPT_LINES { + self.held_before = if lines < 2 * KEPT_LINES { self.held } else { 0 }; + self.held = 0; + self.window = self.line; + } + let kept = (self.buffer.len() + chunk.len()) + .max(self.held) + .max(self.held_before) + .max(KEPT_CAPACITY); + if self.buffer.capacity() > 4 * kept { + self.buffer.shrink_to(kept); + #[cfg(test)] + { + self.shrinks += 1; + } + } + self.buffer.extend_from_slice(&chunk); + self.held = self.held.max(self.buffer.len()); + } + } + } + self.buffer = Vec::new(); + Poll::Ready(None) + } + + #[cfg(test)] + fn capacity(&self) -> usize { + self.buffer.capacity() + } +} + +/// A line of whitespace only, skipped as [`parse_jsonl`](super::parse_jsonl) skips it. +fn is_blank(line: &[u8]) -> bool { + line.iter().all(u8::is_ascii_whitespace) +} + +impl fmt::Debug for Lines { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("Lines") + .field("url", &self.url) + .field("line", &self.line) + .field("max", &self.max) + .field("done", &self.done) + .finish_non_exhaustive() + } +} + +/// The results of a bulk operation, each line read as `T` as the file +/// downloads. [`Shopify::bulk_query_stream`](crate::Shopify::bulk_query_stream) +/// and [`Shopify::download_bulk_results_stream`](crate::Shopify::download_bulk_results_stream) +/// return it. +/// +/// It holds one line at a time, and the rest of the chunk that line ends +/// in: the memory it takes follows the lines being read, not the file. To +/// avoid reallocating for every line, its buffer keeps the room the longest +/// of the last 16 to 32 lines needed, and gives it back once lines stay four +/// times smaller for that long, or when the file ends. Read it with +/// [`BulkRows::next_row`], or as a [`Stream`]. +/// +/// Lines are split on `\n`; a `\r` before it, a last line without one and +/// blank lines are fine, and blank lines are skipped but counted. +/// +/// # Errors +/// +/// - A line that does not read as `T` is an [`Error::Decode`] that gives +/// its line number and nothing of its content (see [`Error`]). The +/// stream **goes on** with the next line: skip the row, or stop. +/// - A line longer than [`BulkRows::max_line_length`] is an [`Error::Bulk`], +/// and a download that fails halfway an [`Error::Transport`]. The stream +/// **ends** after either. +#[must_use = "a stream does nothing until it is read"] +pub struct BulkRows { + lines: Lines, + row: PhantomData T>, +} + +impl fmt::Debug for BulkRows { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("BulkRows") + .field("lines", &self.lines) + .finish() + } +} + +impl BulkRows { + pub(crate) fn new(body: Option, url: &str) -> Self { + Self { + lines: Lines::new(body, url), + row: PhantomData, + } + } + + /// Refuses a line longer than `bytes`, newline left out, instead of + /// [`DEFAULT_MAX_LINE_LENGTH`]: a file without newlines would otherwise + /// be held whole. + pub fn max_line_length(mut self, bytes: usize) -> Self { + self.lines.max = bytes; + self + } + + /// The number of the last line read, from 1, blank lines included. + pub fn line(&self) -> usize { + self.lines.line + } +} + +impl BulkRows { + /// The next row, `None` at the end of the file. + pub async fn next_row(&mut self) -> Option> { + std::future::poll_fn(|context| Pin::new(&mut *self).poll_next(context)).await + } + + /// Every row, in a `Vec`, up to the first error: a line that does not + /// decode ends it here, where [`next_row`](Self::next_row) would go on. + pub async fn collect(mut self) -> Result> { + let mut rows = Vec::new(); + while let Some(row) = self.next_row().await { + rows.push(row?); + } + Ok(rows) + } +} + +impl Stream for BulkRows { + type Item = Result; + + fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll>> { + let lines = &mut self.get_mut().lines; + lines.poll_line(context).map(|line| { + line.map(|line| { + let (number, range) = line?; + crate::decode::from_jsonl_line(&lines.buffer[range], number) + }) + }) + } +} + +impl FusedStream for BulkRows { + fn is_terminated(&self) -> bool { + self.lines.done + } +} + +/// The alias of the `__typename` that [`BulkQuery::text`](crate::bulk::BulkQuery::text) +/// selects where nested lines need it, `shopify_api_graphql::bulk::TYPENAME_KEY`. +pub(crate) const TYPENAME_KEY: &str = "_shopifyApiTypename"; + +/// What places a line. Its `id` is read only when it is a string: an alias +/// `id` of another field is the query's to read, and an object whose lines +/// are placed under it selects `id` itself. +#[derive(Deserialize)] +struct Keys { + #[serde(default, deserialize_with = "string_or_none")] + id: Option, + #[serde(rename = "__parentId")] + parent_id: Option, + #[serde(rename = "_shopifyApiTypename")] + typename: Option, +} + +/// A string, or `None` for any other value. +fn string_or_none<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> std::result::Result, D::Error> { + struct Visitor; + impl<'de> serde::de::Visitor<'de> for Visitor { + type Value = Option; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("any value") + } + + fn visit_str(self, value: &str) -> std::result::Result { + Ok(Some(value.to_string())) + } + + fn visit_string(self, value: String) -> std::result::Result { + Ok(Some(value)) + } + + fn visit_bool(self, _: bool) -> std::result::Result { + Ok(None) + } + + fn visit_i64(self, _: i64) -> std::result::Result { + Ok(None) + } + + fn visit_u64(self, _: u64) -> std::result::Result { + Ok(None) + } + + fn visit_f64(self, _: f64) -> std::result::Result { + Ok(None) + } + + fn visit_unit(self) -> std::result::Result { + Ok(None) + } + + fn visit_none(self) -> std::result::Result { + Ok(None) + } + + fn visit_seq>( + self, + mut seq: A, + ) -> std::result::Result { + while seq.next_element::()?.is_some() {} + Ok(None) + } + + fn visit_map>( + self, + mut map: A, + ) -> std::result::Result { + while map + .next_entry::()? + .is_some() + {} + Ok(None) + } + } + deserializer.deserialize_any(Visitor) +} + +/// The error of a line whose `__parentId` matches no object it may be a child of. +fn misplaced(number: usize, missing_id: bool, grouped: bool) -> Error { + let message = if missing_id { + "has a `__parentId` that no `id` before it matches, and an object before it has no `id`: select `id`, without an alias, on every object that has nested connections" + } else if grouped { + "is a child of neither the top-level object before it nor one of its children, though the query ran with `groupObjects`" + } else { + "is a child of neither the top-level object before it nor one of its children: run the query with `groupObjects`" + }; + super::bulk_error(format!("line {number} of the results {message}")) +} + +struct Group { + parent: P, + children: Vec, + /// The IDs of the objects of the group, the children of the next lines + /// belong to. + ids: HashSet, + /// An object of the group has no `id`: a child of it cannot be placed. + missing_id: bool, +} + +/// The results of a grouped bulk query, each top-level object with the +/// objects of its nested connections, as the file downloads. +/// [`Shopify::bulk_query_grouped`](crate::Shopify::bulk_query_grouped) and +/// [`Shopify::download_bulk_results_grouped`](crate::Shopify::download_bulk_results_grouped) +/// return it. +/// +/// A line without `__parentId` is a top-level object, read as `P`; a line +/// with one is a child, read as `C`. Each item is a top-level object and +/// its children, in the order of the file: the item is complete when the +/// next top-level object, or the end of the file, arrives. One group is +/// held at a time, with every child read so far: its memory follows the +/// largest group, as well as the line being read. +/// +/// # Nested connections two levels deep +/// +/// Shopify allows connections two levels deep: the objects of the second +/// level carry the `__parentId` of an object of the first, not of the +/// top-level one. They are in the same list as the first level, in the +/// order of the file: read `__parentId` in `C` to put them back in place. +/// +/// # The order it needs +/// +/// It needs each child after its parent, before the next top-level object: +/// the order Shopify writes with `groupObjects`, which +/// [`Shopify::bulk_query_grouped`](crate::Shopify::bulk_query_grouped) asks +/// for. Without it, Shopify only promises a child after its parent, +/// anywhere further in the file. A child whose parent is neither the +/// current top-level object nor one of its children is an [`Error::Bulk`] +/// rather than a child put in the wrong group. +/// +/// # The `id` it needs +/// +/// A child is placed by matching its `__parentId` with the `id` of an +/// object before it: every object that has a nested connection must select +/// `id`, without an alias. Shopify refuses a bulk query that does not, so +/// this only matters for a file from elsewhere; a child of an object +/// without `id` is an [`Error::Bulk`] that says so. +/// +/// # Errors +/// +/// Any error ends the stream, a line that does not read as `P` or `C` +/// included: the lines after it could not be placed for sure. The errors +/// are those of [`BulkRows`], and the child out of place or without a +/// matching `id` above. +#[must_use = "a stream does nothing until it is read"] +pub struct BulkGroups { + lines: Lines, + group: Option>, + /// The operation is known to have run with `groupObjects`. + grouped: bool, +} + +// The group is never pinned: it is only reached through `&mut`. +impl Unpin for BulkGroups {} + +impl fmt::Debug for BulkGroups { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("BulkGroups") + .field("lines", &self.lines) + .field( + "children", + &self.group.as_ref().map(|group| group.children.len()), + ) + .finish() + } +} + +impl BulkGroups { + pub(crate) fn new(body: Option, url: &str) -> Self { + Self { + lines: Lines::new(body, url), + group: None, + grouped: false, + } + } + + pub(crate) fn grouped(mut self) -> Self { + self.grouped = true; + self + } + + fn misplaced(&self, number: usize) -> Error { + let missing_id = self.group.as_ref().is_some_and(|group| group.missing_id); + misplaced(number, missing_id, self.grouped) + } + + /// [`BulkRows::max_line_length`]. + pub fn max_line_length(mut self, bytes: usize) -> Self { + self.lines.max = bytes; + self + } + + /// The number of the last line read, from 1, blank lines included. + pub fn line(&self) -> usize { + self.lines.line + } + + fn fail(&mut self, error: Error) -> Poll>> { + self.lines.finish(); + self.group = None; + Poll::Ready(Some(Err(error))) + } +} + +impl BulkGroups { + /// The next top-level object and its children, `None` at the end of the file. + pub async fn next_group(&mut self) -> Option> { + std::future::poll_fn(|context| Pin::new(&mut *self).poll_next(context)).await + } +} + +impl Stream for BulkGroups { + type Item = Grouped; + + fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + loop { + let (number, range) = match this.lines.poll_line(context) { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => { + let group = this.group.take(); + return Poll::Ready(group.map(|group| Ok((group.parent, group.children)))); + } + Poll::Ready(Some(Err(error))) => return this.fail(error), + Poll::Ready(Some(Ok(line))) => line, + }; + let line = &this.lines.buffer[range]; + let keys = match crate::decode::from_jsonl_line::(line, number) { + Ok(keys) => keys, + Err(error) => return this.fail(error), + }; + match keys.parent_id { + None => { + let parent = match crate::decode::from_jsonl_line::

(line, number) { + Ok(parent) => parent, + Err(error) => return this.fail(error), + }; + let next = Group { + parent, + children: Vec::new(), + missing_id: keys.id.is_none(), + ids: keys.id.into_iter().collect(), + }; + if let Some(done) = this.group.replace(next) { + return Poll::Ready(Some(Ok((done.parent, done.children)))); + } + } + Some(parent_id) => { + if !this + .group + .as_ref() + .is_some_and(|group| group.ids.contains(&parent_id)) + { + let error = this.misplaced(number); + return this.fail(error); + } + let child = match crate::decode::from_jsonl_line::(line, number) { + Ok(child) => child, + Err(error) => return this.fail(error), + }; + if let Some(group) = this.group.as_mut() { + group.missing_id |= keys.id.is_none(); + group.ids.extend(keys.id); + group.children.push(child); + } + } + } + } + } +} + +impl FusedStream for BulkGroups { + fn is_terminated(&self) -> bool { + self.lines.done && self.group.is_none() + } +} + +struct ItemGroup { + item: I, + /// The `id` of the item. + id: Option, + /// The children of the item that have connections, by `id`: their + /// connection and their index in it. + children: HashMap, + /// An object of the group that has connections has no `id`. + missing_id: bool, +} + +/// The results of a bulk query declared with `graphql!(bulk(…))`, one +/// top-level object at a time, read as its generated `Item` with the +/// objects of its nested connections in their lists. +/// [`Shopify::bulk_query`](crate::Shopify::bulk_query) and +/// [`Shopify::download_bulk_items`](crate::Shopify::download_bulk_items) +/// return it. +/// +/// It reads the lines as [`BulkGroups`] does, in the order `groupObjects` +/// writes: an item is complete when the next top-level object, or the end +/// of the file, arrives. One item is held at a time, with every nested +/// object read so far: its memory follows the largest item, as well as the +/// line being read. +/// +/// A nested line goes to its parent by its `__parentId`, and, when its +/// parent has several connections, to the connection that returns its +/// `__typename`, which [`BulkQuery::text`](crate::bulk::BulkQuery::text) +/// selects for that under the alias `_shopifyApiTypename`. A `__typename` +/// the query selects itself is not read to place lines. +/// +/// # Errors +/// +/// Any error ends the stream: a line that does not read as its type, a +/// nested line out of place, the errors of [`BulkRows`] and those of +/// [`BulkGroups`]. +#[must_use = "a stream does nothing until it is read"] +pub struct BulkItems { + lines: Lines, + group: Option>, + grouped: bool, +} + +impl Unpin for BulkItems {} + +impl fmt::Debug for BulkItems { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("BulkItems") + .field("lines", &self.lines) + .finish_non_exhaustive() + } +} + +impl BulkItems { + pub(crate) fn new(body: Option, url: &str) -> Self { + Self { + lines: Lines::new(body, url), + group: None, + grouped: false, + } + } + + pub(crate) fn grouped(mut self) -> Self { + self.grouped = true; + self + } + + /// [`BulkRows::max_line_length`]. + pub fn max_line_length(mut self, bytes: usize) -> Self { + self.lines.max = bytes; + self + } + + /// The number of the last line read, from 1, blank lines included. + pub fn line(&self) -> usize { + self.lines.line + } + + fn fail(&mut self, error: Error) -> Poll>> { + self.lines.finish(); + self.group = None; + Poll::Ready(Some(Err(error))) + } +} + +impl BulkItems { + /// The next item, `None` at the end of the file. + pub async fn next_item(&mut self) -> Option> { + std::future::poll_fn(|context| Pin::new(&mut *self).poll_next(context)).await + } + + /// Every item, up to the first error. + pub async fn collect(mut self) -> Result> { + let mut items = Vec::new(); + while let Some(item) = self.next_item().await { + items.push(item?); + } + Ok(items) + } + + /// Places the nested line `number` in the item of `group`. + fn attach( + group: Option<&mut ItemGroup>, + grouped: bool, + keys: Keys, + parent_id: &str, + line: &[u8], + number: usize, + ) -> Result<()> { + let Some(group) = group else { + return Err(misplaced(number, false, grouped)); + }; + let (parent, connections) = if group.id.as_deref() == Some(parent_id) { + (None, I::CONNECTIONS) + } else if let Some(&(slot, index)) = group.children.get(parent_id) { + (Some((slot, index)), I::CONNECTIONS[slot].connections) + } else { + return Err(misplaced(number, group.missing_id, grouped)); + }; + let slot = match connections { + [] => return Err(misplaced(number, group.missing_id, grouped)), + [_] => 0, + _ => { + let typename = keys.typename.as_deref().ok_or_else(|| { + super::bulk_error(format!( + "line {number} of the results has no `{TYPENAME_KEY}`, the `__typename` that tells which connection of its parent it belongs to" + )) + })?; + connections + .iter() + .position(|connection| connection.types.contains(&typename)) + .ok_or_else(|| { + super::bulk_error(format!( + "line {number} of the results has a `{TYPENAME_KEY}`, its `__typename`, that no connection of its parent returns" + )) + })? + } + }; + let index = group.item.__attach(parent, slot, line, number)?; + if parent.is_none() && !I::CONNECTIONS[slot].connections.is_empty() { + match keys.id { + Some(id) => { + group.children.insert(id, (slot, index)); + } + None => group.missing_id = true, + } + } + Ok(()) + } +} + +impl Stream for BulkItems { + type Item = Result; + + fn poll_next(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + loop { + let (number, range) = match this.lines.poll_line(context) { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => { + return Poll::Ready(this.group.take().map(|group| Ok(group.item))); + } + Poll::Ready(Some(Err(error))) => return this.fail(error), + Poll::Ready(Some(Ok(line))) => line, + }; + let line = &this.lines.buffer[range]; + let keys = match crate::decode::from_jsonl_line::(line, number) { + Ok(keys) => keys, + Err(error) => return this.fail(error), + }; + match keys.parent_id.clone() { + None => { + let item = match crate::decode::from_jsonl_line::(line, number) { + Ok(item) => item, + Err(error) => return this.fail(error), + }; + let next = ItemGroup { + item, + missing_id: keys.id.is_none() && !I::CONNECTIONS.is_empty(), + id: keys.id, + children: HashMap::new(), + }; + if let Some(done) = this.group.replace(next) { + return Poll::Ready(Some(Ok(done.item))); + } + } + Some(parent_id) => { + let attached = Self::attach( + this.group.as_mut(), + this.grouped, + keys, + &parent_id, + line, + number, + ); + if let Err(error) = attached { + return this.fail(error); + } + } + } + } + } +} + +impl FusedStream for BulkItems { + fn is_terminated(&self) -> bool { + self.lines.done && self.group.is_none() + } +} + +#[cfg(test)] +mod tests { + #[cfg(feature = "cli")] + #[test] + fn the_typename_key_is_the_one_the_macros_select() { + assert_eq!(super::TYPENAME_KEY, shopify_api_graphql::bulk::TYPENAME_KEY); + } + + use super::*; + use crate::transport::{TransportError, chunks}; + + fn rows_of(parts: Vec>) -> BulkRows { + BulkRows::new( + Some(chunks(parts.into_iter().map(Ok))), + "https://storage.test/r.jsonl", + ) + } + + async fn all(mut rows: BulkRows) -> Vec> { + let mut out = Vec::new(); + while let Some(row) = rows.next_row().await { + out.push(row); + } + out + } + + fn shown(results: &[Result]) -> Vec { + results + .iter() + .map(|result| match result { + Ok(value) => value.to_string(), + Err(error) => format!("error: {error}"), + }) + .collect() + } + + fn buffered(body: &[u8]) -> Vec { + body.split(|byte| *byte == b'\n') + .enumerate() + .filter(|(_, line)| !is_blank(line)) + .map(|(index, line)| { + match crate::decode::from_jsonl_line::(line, index + 1) { + Ok(value) => value.to_string(), + Err(error) => format!("error: {error}"), + } + }) + .collect() + } + + const BODY: &[u8] = "{\"id\":\"gid://shopify/Product/1\",\"title\":\"Café ☕ 𝄞\"}\r\n\ + \r\n\ + {\"id\":\"gid://shopify/ProductVariant/2\",\"__parentId\":\"gid://shopify/Product/1\"}\n\ + \n \n\ + {\"broken\": tru}\n\ + {\"id\":3,\"title\":\"Ünïcødé\"}" + .as_bytes(); + + #[tokio::test] + async fn every_split_in_two_or_three_reads_as_the_whole_file() { + let expected = buffered(BODY); + assert_eq!(expected.len(), 4); + assert!(expected[2].starts_with("error: "), "{expected:?}"); + for first in 0..=BODY.len() { + let parts = vec![BODY[..first].to_vec(), BODY[first..].to_vec()]; + assert_eq!( + shown(&all(rows_of(parts)).await), + expected, + "split at {first}" + ); + for second in first..=BODY.len() { + let parts = vec![ + BODY[..first].to_vec(), + BODY[first..second].to_vec(), + BODY[second..].to_vec(), + ]; + assert_eq!( + shown(&all(rows_of(parts)).await), + expected, + "split at {first} and {second}" + ); + } + } + } + + #[tokio::test] + async fn random_splits_read_as_the_whole_file() { + let mut body = Vec::new(); + for index in 0..300 { + let line = serde_json::json!({ "id": index, "title": "é".repeat(index % 7), "n": [index, index] }); + body.extend_from_slice(line.to_string().as_bytes()); + body.extend_from_slice(if index.is_multiple_of(3) { + b"\r\n" + } else { + b"\n" + }); + if index.is_multiple_of(11) { + body.extend_from_slice(b"\n"); + } + } + let expected = buffered(&body); + assert_eq!(expected.len(), 300); + let whole: Vec = crate::bulk::parse_jsonl(&body).unwrap(); + let whole: Vec = whole.iter().map(ToString::to_string).collect(); + assert_eq!(whole, expected); + // A fixed xorshift: the same splits on every run. + let mut state: u64 = 0x2545_f491_4f6c_dd1d; + for _ in 0..200 { + let mut parts = Vec::new(); + let mut at = 0; + while at < body.len() { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + let size = (state % 97) as usize; + let end = (at + size).min(body.len()); + parts.push(body[at..end].to_vec()); + at = end; + } + assert_eq!(shown(&all(rows_of(parts)).await), expected); + } + let one_byte_each = body.iter().map(|byte| vec![*byte]).collect(); + assert_eq!(shown(&all(rows_of(one_byte_each)).await), expected); + } + + #[tokio::test] + async fn a_last_blank_line_without_a_newline_is_counted() { + for (body, lines) in [ + (&b"{}\n \r"[..], 2), + (b"{}\n\n\t", 3), + (b"{}\n", 1), + (b"{}", 1), + ] { + let mut rows = rows_of::(vec![body.to_vec()]); + assert!(rows.next_row().await.unwrap().is_ok()); + assert!(rows.next_row().await.is_none()); + assert_eq!(rows.line(), lines, "{body:?}"); + } + } + + #[tokio::test] + async fn a_line_longer_than_the_limit_ends_the_stream() { + for parts in [ + vec![b"{\"a\":1}\n{\"b\":\"0123456789\"}\n{\"c\":3}\n".to_vec()], + vec![ + b"{\"a\":1}\n{\"b\":\"01234".to_vec(), + b"56789\"}\n{\"c\":3}\n".to_vec(), + ], + vec![b"{\"a\":1}\n{\"b\":\"0123456789\"}".to_vec()], + ] { + let mut rows = rows_of::(parts).max_line_length(12); + assert_eq!(rows.next_row().await.unwrap().unwrap()["a"], 1); + let error = rows.next_row().await.unwrap().unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: line 2 of the results is longer than 12 bytes" + ); + assert!(rows.next_row().await.is_none()); + assert!(rows.is_terminated()); + } + // A line of exactly the limit is read; `\r` counts, `\n` does not. + let mut rows = rows_of::(vec![b"{\"b\":\"12345\"}\r\n".to_vec()]) + .max_line_length(14); + assert_eq!(rows.next_row().await.unwrap().unwrap()["b"], "12345"); + } + + #[tokio::test] + async fn a_file_without_newlines_is_not_held_whole() { + let chunk = vec![b'x'; 64 * 1024]; + // 1 GiB, never produced: the limit stops it after 1 MiB. + let endless = std::iter::repeat_n(chunk, 16 * 1024).map(Ok); + let mut rows: BulkRows = + BulkRows::new(Some(chunks(endless)), "https://storage.test/r.jsonl") + .max_line_length(1024 * 1024); + let error = rows.next_row().await.unwrap().unwrap_err(); + assert!(matches!(error, Error::Bulk { .. }), "{error:?}"); + assert!(rows.next_row().await.is_none()); + } + + #[tokio::test] + async fn a_body_that_fails_halfway_ends_the_stream() { + let parts = vec![ + Ok(b"{\"a\":1}\n{\"a\":".to_vec()), + Err(TransportError::new("connection reset")), + Ok(b"2}\n".to_vec()), + ]; + let mut rows: BulkRows = BulkRows::new( + Some(chunks(parts)), + "https://storage.test/r.jsonl?sig=SECRET", + ); + assert_eq!(rows.next_row().await.unwrap().unwrap()["a"], 1); + let error = rows.next_row().await.unwrap().unwrap_err(); + assert_eq!( + error.to_string(), + "request to https://storage.test/r.jsonl failed: connection reset" + ); + assert!(rows.next_row().await.is_none()); + } + + #[tokio::test] + async fn a_decode_error_names_its_line_shows_nothing_of_it_and_the_stream_goes_on() { + #[derive(Debug, Deserialize)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] + struct Row { + id: u64, + } + let body = b"{\"id\":1}\n\n{\"id\":\"shpat_SECRET\"}\n{\"id\":3}\n".to_vec(); + let results = all(rows_of::(vec![body])).await; + assert_eq!(results.len(), 3); + assert_eq!(results[0].as_ref().unwrap().id, 1); + let error = results[1].as_ref().unwrap_err(); + let shown = format!("{error}\n{error:?}\n{error:#?}"); + assert!(!shown.contains("SECRET"), "{shown}"); + assert_eq!( + error.to_string(), + "Shopify's answer does not match the operation at `id`: invalid type: string, expected u64 at line 3 column 20" + ); + assert!(error.sensitive_detail().unwrap().contains("shpat_SECRET")); + assert_eq!(results[2].as_ref().unwrap().id, 3); + } + + #[tokio::test] + async fn memory_follows_the_longest_line_not_the_file() { + let line = format!( + "{{\"id\":\"gid://shopify/Product/1\",\"title\":\"{}\"}}\n", + "a".repeat(200) + ); + let chunk = line.repeat(64).into_bytes(); + let chunk_len = chunk.len(); + let count = 20_000_000 / chunk_len; + let body = std::iter::repeat_n(chunk, count).map(Ok); + let mut rows: BulkRows = + BulkRows::new(Some(chunks(body)), "https://storage.test/r.jsonl"); + let mut read = 0; + let mut largest = 0; + while let Some(row) = rows.next_row().await { + row.unwrap(); + read += 1; + largest = largest.max(rows.lines.capacity()); + } + assert_eq!(read, count * 64); + // A chunk and a partial line, with the growth of a `Vec`. + assert!( + largest <= 2 * (chunk_len + line.len()), + "{largest} bytes held" + ); + } + + fn cut(line: &[u8], size: usize) -> impl Iterator> + '_ { + line.chunks(size).map(<[u8]>::to_vec) + } + + fn line_of(bytes: usize) -> Vec { + format!("{{\"a\":\"{}\"}}\n", "x".repeat(bytes)).into_bytes() + } + + #[tokio::test] + async fn the_buffer_is_kept_while_lines_stay_alike() { + let line = line_of(1024 * 1024); + for size in [line.len(), 32 * 1024, 1024] { + let parts = (0..16).flat_map(|_| cut(&line, size)).collect(); + let mut rows = rows_of::(parts); + rows.next_row().await.unwrap().unwrap(); + let capacity = rows.lines.capacity(); + while let Some(row) = rows.next_row().await { + row.unwrap(); + if !rows.lines.done { + assert_eq!(rows.lines.capacity(), capacity, "chunks of {size}"); + } + } + assert_eq!(rows.lines.shrinks, 0, "chunks of {size}"); + } + } + + #[tokio::test] + async fn the_buffer_of_a_huge_line_is_released_a_few_lines_later() { + let mut parts: Vec> = cut(&line_of(16 * 1024 * 1024), 32 * 1024).collect(); + parts.extend(std::iter::repeat_n(b"{\"b\":1}\n".to_vec(), 100)); + let mut rows = rows_of::(parts); + rows.next_row().await.unwrap().unwrap(); + assert!(rows.lines.capacity() > 16 * 1024 * 1024); + for _ in 0..2 * KEPT_LINES { + rows.next_row().await.unwrap().unwrap(); + } + assert!( + rows.lines.capacity() <= 1024 * 1024, + "{} bytes held after {} tiny lines", + rows.lines.capacity(), + 2 * KEPT_LINES + ); + while let Some(row) = rows.next_row().await { + row.unwrap(); + } + assert_eq!(rows.lines.capacity(), 0); + } + + #[tokio::test] + async fn alternating_huge_and_tiny_lines_keep_the_buffer() { + let huge = line_of(1024 * 1024); + for size in [huge.len(), 32 * 1024, 1024] { + let parts = (0..16) + .flat_map(|_| cut(&huge, size).chain([b"{}\n".to_vec()])) + .collect(); + let mut rows = rows_of::(parts); + let mut read = 0; + while let Some(row) = rows.next_row().await { + row.unwrap(); + read += 1; + } + assert_eq!(read, 32); + assert_eq!(rows.lines.shrinks, 0, "chunks of {size}"); + } + } + + fn groups_of(body: &str) -> BulkGroups { + BulkGroups::new( + Some(chunks( + body.as_bytes() + .chunks(5) + .map(|part| Ok(part.to_vec())) + .collect::>(), + )), + "https://storage.test/r.jsonl", + ) + } + + async fn all_groups( + mut groups: BulkGroups, + ) -> Vec)>> { + let mut out = Vec::new(); + while let Some(group) = groups.next_group().await { + out.push(group); + } + out + } + + fn ids(values: &[serde_json::Value]) -> Vec<&str> { + values + .iter() + .map(|value| value["id"].as_str().unwrap()) + .collect() + } + + #[tokio::test] + async fn groups_hold_each_top_level_object_with_its_children() { + let body = r#"{"id":"P1"} +{"id":"V1","__parentId":"P1"} +{"id":"V2","__parentId":"P1"} + +{"id":"P2"} +{"id":"P3"} +{"id":"V3","__parentId":"P3"}"#; + let groups = all_groups(groups_of(body)).await; + let groups: Vec<_> = groups.into_iter().map(Result::unwrap).collect(); + assert_eq!(groups.len(), 3); + assert_eq!(groups[0].0["id"], "P1"); + assert_eq!(ids(&groups[0].1), ["V1", "V2"]); + assert_eq!(groups[1].0["id"], "P2"); + assert!(groups[1].1.is_empty()); + assert_eq!(ids(&groups[2].1), ["V3"]); + } + + #[tokio::test] + async fn the_second_level_joins_the_group_of_its_top_level_object() { + let body = r#"{"id":"P1"} +{"id":"V1","__parentId":"P1"} +{"id":"L1","__parentId":"V1"} +{"id":"L2","__parentId":"V1"} +{"id":"V2","__parentId":"P1"} +{"id":"L3","__parentId":"V2"} +{"id":"M1","__parentId":"P1"} +{"id":"P2"} +{"id":"V3","__parentId":"P2"} +{"id":"L4","__parentId":"V3"} +"#; + let groups: Vec<_> = all_groups(groups_of(body)) + .await + .into_iter() + .map(Result::unwrap) + .collect(); + assert_eq!(groups.len(), 2); + assert_eq!(ids(&groups[0].1), ["V1", "L1", "L2", "V2", "L3", "M1"]); + assert_eq!(groups[0].1[2]["__parentId"], "V1"); + assert_eq!(ids(&groups[1].1), ["V3", "L4"]); + } + + #[tokio::test] + async fn a_child_out_of_its_group_is_an_error_that_ends_the_stream() { + // V3's parent came before P2: the order without `groupObjects`. + let body = r#"{"id":"P1"} +{"id":"V1","__parentId":"P1"} +{"id":"P2"} +{"id":"V3","__parentId":"P1"} +{"id":"P3"} +"#; + let groups = all_groups(groups_of(body)).await; + assert_eq!(groups.len(), 2); + let (parent, children) = groups[0].as_ref().unwrap(); + assert_eq!(parent["id"], "P1"); + assert_eq!(ids(children), ["V1"]); + let error = groups[1].as_ref().unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: line 4 of the results is a child of neither the top-level object before it nor one of its children: run the query with `groupObjects`" + ); + + for body in [ + "{\"id\":\"V1\",\"__parentId\":\"P1\"}\n{\"id\":\"P1\"}\n", + "{\"id\":\"P1\"}\n{\"id\":\"V1\",\"__parentId\":\"P9\"}\n", + ] { + let groups = all_groups(groups_of(body)).await; + assert_eq!(groups.len(), 1, "{body}"); + assert!(matches!(groups[0], Err(Error::Bulk { .. })), "{body}"); + } + } + + #[tokio::test] + async fn a_parent_without_id_is_named_as_the_cause() { + const MISSING: &str = "has a `__parentId` that no `id` before it matches, and an object before it has no `id`: select `id`, without an alias, on every object that has nested connections"; + for (body, line) in [ + ( + "{\"title\":\"P1\"}\n{\"id\":\"V1\",\"__parentId\":\"P1\"}\n", + 2, + ), + ( + "{\"id\":\"P1\"}\n{\"sku\":\"V1\",\"__parentId\":\"P1\"}\n{\"id\":\"L1\",\"__parentId\":\"V1\"}\n", + 3, + ), + ( + "{\"productId\":\"P1\"}\n{\"id\":\"V1\",\"__parentId\":\"P1\"}\n", + 2, + ), + ] { + for groups in [groups_of(body), groups_of(body).grouped()] { + let groups = all_groups(groups).await; + let error = groups.last().unwrap().as_ref().unwrap_err(); + assert_eq!( + error.to_string(), + format!("bulk operation: line {line} of the results {MISSING}"), + "{body}" + ); + } + } + + // A child without `id` has no child of its own to place: fine. + let body = "{\"id\":\"P1\"}\n{\"sku\":\"V1\",\"__parentId\":\"P1\"}\n"; + let groups = all_groups(groups_of(body)).await; + assert_eq!(groups[0].as_ref().unwrap().1.len(), 1); + } + + #[tokio::test] + async fn a_child_out_of_place_does_not_ask_for_group_objects_when_it_is_on() { + let body = "{\"id\":\"P1\"}\n{\"id\":\"P2\"}\n{\"id\":\"V1\",\"__parentId\":\"P1\"}\n"; + let groups = all_groups(groups_of(body).grouped()).await; + let error = groups.last().unwrap().as_ref().unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: line 3 of the results is a child of neither the top-level object before it nor one of its children, though the query ran with `groupObjects`" + ); + } + + #[tokio::test] + async fn groups_read_typed_parents_and_children_and_hide_bad_values() { + #[derive(Debug, Deserialize)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] + struct Product { + id: String, + } + #[derive(Debug, Deserialize)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] + struct Variant { + id: String, + price: u64, + } + let body = "{\"id\":\"P1\"}\n{\"id\":\"V1\",\"__parentId\":\"P1\",\"price\":\"shpat_SECRET\"}\n{\"id\":\"P2\"}\n"; + let mut groups = groups_of::(body); + let error = groups.next_group().await.unwrap().unwrap_err(); + let shown = format!("{error}\n{error:?}"); + assert!(!shown.contains("SECRET"), "{shown}"); + assert!(shown.contains("line 2"), "{shown}"); + assert!(groups.next_group().await.is_none()); + assert!(groups.is_terminated()); + } +} diff --git a/crates/shopify_api/src/bulk/typed.rs b/crates/shopify_api/src/bulk/typed.rs new file mode 100644 index 0000000..482fa6e --- /dev/null +++ b/crates/shopify_api/src/bulk/typed.rs @@ -0,0 +1,936 @@ +//! Bulk operations declared with `graphql!(bulk(…))`: checked when the +//! crate compiles, their results read as the types it generates. + +use std::fmt; + +use serde::Deserialize; +use serde::de::DeserializeOwned; +use serde_json::value::RawValue; + +use super::{ + BulkOperation, BulkRows, BulkWaitOptions, StartBulkQuery, bulk_error, run_mutation, sealed, + started, +}; +use crate::error::is_graphql_name; +use crate::graphql::check::Invalid; +use crate::{ + Error, GraphqlError, IntoVariable, InvalidValueReason, Operation, OperationKind, Result, + Shopify, VariableType, +}; + +pub use super::rows::BulkItems; + +/// The text of a bulk query, with its variables apart. Not a public API. +#[doc(hidden)] +#[derive(Debug)] +pub struct BulkTemplate { + pub parts: &'static [BulkPart], + pub variables: &'static [BulkVariable], +} + +#[doc(hidden)] +#[derive(Debug)] +pub enum BulkPart { + Text(&'static str), + /// `(name: value, …)`, where a value holds a variable. + Arguments(&'static [BulkArgument]), +} + +#[doc(hidden)] +#[derive(Debug)] +pub struct BulkArgument { + pub name: &'static str, + pub value: BulkValue, +} + +#[doc(hidden)] +#[derive(Debug)] +pub enum BulkValue { + /// A constant, as GraphQL text. + Text(&'static str), + /// The variable of this index in [`BulkTemplate::variables`]. + Variable(usize), + List(&'static [BulkValue]), + Object(&'static [BulkArgument]), +} + +#[doc(hidden)] +#[derive(Debug)] +pub struct BulkVariable { + pub name: &'static str, + pub ty: BulkType, + /// Its default value, as GraphQL text. + pub default: Option<&'static str>, +} + +/// Where the enum values of a variable are: they are written bare. +#[doc(hidden)] +#[derive(Debug)] +pub enum BulkType { + /// No enum value. + Plain, + Enum, + List(&'static BulkType), + /// An input object: its fields that hold enum values. + Input(&'static [(&'static str, BulkType)]), +} + +/// A nested connection of a bulk query, and where its lines go. +#[doc(hidden)] +#[derive(Debug)] +pub struct BulkConnection { + pub key: &'static str, + /// The `__typename`s of its nodes. + pub types: &'static [&'static str], + pub connections: &'static [BulkConnection], +} + +/// The type of a top-level object of a bulk query declared with +/// `graphql!(bulk(…))`, which `graphql!` implements: the item of +/// [`BulkItems`]. Its items are not a public API. +pub trait BulkItem: DeserializeOwned { + /// The nested connections of the item, in the order of their slots. + #[doc(hidden)] + const CONNECTIONS: &'static [BulkConnection]; + + /// Reads `line` as an object of the connection `slot` of the item, or, + /// with `parent`, of the child `parent.1` of the connection `parent.0`. + /// Returns its index in its list. + #[doc(hidden)] + fn __attach( + &mut self, + parent: Option<(usize, usize)>, + slot: usize, + line: &[u8], + number: usize, + ) -> Result; +} + +/// What `BulkItem::__attach` pushes with. Not a public API. +#[doc(hidden)] +pub fn push(list: &mut Vec, line: &[u8], number: usize) -> Result { + list.push(crate::decode::from_jsonl_line(line, number)?); + Ok(list.len() - 1) +} + +/// The error of a line `BulkItem::__attach` has no place for. Not a public API. +#[doc(hidden)] +pub fn unplaced() -> Error { + bulk_error("a nested line of the results has no place in the item") +} + +/// The kind of a query declared with `graphql!(bulk(…))`, of item `I`, for +/// [`Shopify::start_bulk_query`]. Not a public API. +#[doc(hidden)] +#[derive(Debug)] +pub struct TypedQuery(std::marker::PhantomData); + +impl>> sealed::Sealed> for Q { + fn __start(self) -> Result { + let query = self.into(); + Ok(sealed::Start { + query: query.text()?, + // Grouping makes Shopify slower and more likely to time out: only + // when there are children to place. + group_objects: !I::CONNECTIONS.is_empty(), + checked_against: Some(query.checked_against()), + }) + } +} + +// Not suggested in errors: `start_bulk_query(42)` gets the message of +// `StartBulkQuery` rather than one about `From`. +#[diagnostic::do_not_recommend] +impl>> StartBulkQuery> for Q {} + +/// A bulk query checked by `graphql!(bulk("…"))`, and its variables. Its +/// results are read as `I`, one top-level object at a time. +/// +/// Shopify takes no variables for a bulk query: [`BulkQuery::text`] writes +/// them into the text. +pub struct BulkQuery { + operation: Operation, + template: &'static BulkTemplate, +} + +impl BulkQuery { + /// What `graphql!` builds. + #[doc(hidden)] + pub fn __checked( + template: &'static BulkTemplate, + query: &'static str, + name: Option<&'static str>, + checked_against: &'static str, + ) -> Self { + Self { + operation: Operation::__checked(query, OperationKind::Query, name, checked_against), + template, + } + } + + /// What the `Variables` of a `graphql!` module set a variable with. + #[doc(hidden)] + pub fn __variable(mut self, name: &str, value: T) -> Self { + self.operation = self.operation.__variable(name, value); + self + } + + /// What `graphql!` sets a variable written as a Rust expression with. + #[doc(hidden)] + pub fn __converted_variable>( + mut self, + name: &str, + value: V, + ) -> Self { + self.operation = self.operation.variable(name, value); + self + } + + /// What `graphql!` sets a variable written as a literal to. + #[doc(hidden)] + pub fn __literal_variable( + mut self, + name: &str, + value: std::result::Result, Invalid>, + ) -> Self { + self.operation = self.operation.__literal_variable(name, value); + self + } + + /// The text of the query as written, with its variables. + pub fn query(&self) -> &str { + self.operation.query() + } + + /// The Admin API version the query was checked against. + pub fn checked_against(&self) -> Option<&'static str> { + self.operation.checked_against() + } + + /// The text Shopify runs: without variable definitions, each variable + /// written in as a GraphQL literal (an enum value bare, an input object + /// as `{field: value}`), and `_shopifyApiTypename: __typename` selected + /// on the nodes of the connections that share a parent, which tells + /// their lines apart. A + /// variable without a value is left out, as GraphQL leaves out an + /// argument whose variable has none, or takes its default value. + /// + /// Fails with [`Error::InvalidValue`] for a value the variables refuse + /// ([`Shopify::execute`] would), for an enum value or a field name + /// that is not a GraphQL name, and for an enum value `true`, `false` or + /// `null`, which would read as another value. + pub fn text(&self) -> Result { + let values = self.operation.variable_values()?; + let writer = Writer { + template: self.template, + values, + }; + let mut text = String::new(); + for part in self.template.parts { + match part { + BulkPart::Text(part) => text.push_str(part), + BulkPart::Arguments(arguments) => { + let written = writer.arguments(arguments)?; + if !written.is_empty() { + text.push('('); + text.push_str(&written.join(", ")); + text.push(')'); + } + } + } + } + Ok(text) + } +} + +impl Clone for BulkQuery { + fn clone(&self) -> Self { + Self { + operation: self.operation.clone(), + template: self.template, + } + } +} + +impl fmt::Debug for BulkQuery { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("BulkQuery") + .field("operation", &self.operation) + .finish_non_exhaustive() + } +} + +/// Writes the variables of a bulk query into its text. +struct Writer<'a> { + template: &'static BulkTemplate, + values: &'a [(String, Box)], +} + +impl Writer<'_> { + /// `name: value` for each argument whose value is not left out. + fn arguments(&self, arguments: &[BulkArgument]) -> Result> { + let mut written = Vec::new(); + for argument in arguments { + if let Some(value) = self.value(&argument.value)? { + written.push(format!("{}: {value}", argument.name)); + } + } + Ok(written) + } + + /// The value as GraphQL text, `None` when its variable has no value. + fn value(&self, value: &BulkValue) -> Result> { + match value { + BulkValue::Text(text) => Ok(Some((*text).to_string())), + BulkValue::Variable(index) => { + let variable = &self.template.variables[*index]; + match self.values.iter().find(|(name, _)| name == variable.name) { + Some((_, json)) => { + let mut text = String::new(); + Json::new(json.get()) + .write(&variable.ty, &mut text) + .map_err(|invalid| invalid.into_error(variable.name))?; + Ok(Some(text)) + } + None => Ok(variable.default.map(str::to_string)), + } + } + BulkValue::List(items) => { + let mut written = Vec::new(); + for item in *items { + // An item whose variable has no value is `null`. + written.push(self.value(item)?.unwrap_or_else(|| "null".to_string())); + } + Ok(Some(format!("[{}]", written.join(", ")))) + } + BulkValue::Object(fields) => { + Ok(Some(format!("{{{}}}", self.arguments(fields)?.join(", ")))) + } + } + } +} + +/// Reads the JSON of a value, which `serde_json` wrote, and writes it as a +/// GraphQL literal: strings and numbers as JSON writes them, which GraphQL +/// reads alike, enum values bare, object keys unquoted. +struct Json<'a> { + text: &'a [u8], + at: usize, +} + +impl<'a> Json<'a> { + fn new(text: &'a str) -> Self { + Self { + text: text.as_bytes(), + at: 0, + } + } + + fn skip_whitespace(&mut self) { + while self + .text + .get(self.at) + .is_some_and(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r')) + { + self.at += 1; + } + } + + /// The JSON text of the string that starts here, quotes included. + fn string(&mut self) -> &'a str { + let start = self.at; + self.at += 1; + while let Some(byte) = self.text.get(self.at) { + match byte { + b'\\' => self.at += 2, + b'"' => { + self.at += 1; + break; + } + _ => self.at += 1, + } + } + let end = self.at.min(self.text.len()); + // Cut at ASCII quotes of UTF-8 text: still UTF-8. + std::str::from_utf8(&self.text[start..end]).unwrap_or("\"\"") + } + + fn name(token: &str) -> std::result::Result { + let name: String = serde_json::from_str(token) + .map_err(|_| Invalid::new(InvalidValueReason::NotAGraphqlName))?; + if is_graphql_name(&name) { + Ok(name) + } else { + Err(Invalid::new(InvalidValueReason::NotAGraphqlName)) + } + } + + /// An enum value: a GraphQL name but `true`, `false` and `null`, which + /// would read as another kind of value. + fn enum_value(token: &str) -> std::result::Result { + let name = Self::name(token)?; + if matches!(name.as_str(), "true" | "false" | "null") { + Err(Invalid::new(InvalidValueReason::ReservedEnumValue)) + } else { + Ok(name) + } + } + + fn write(&mut self, ty: &BulkType, out: &mut String) -> std::result::Result<(), Invalid> { + self.skip_whitespace(); + match self.text.get(self.at) { + Some(b'[') => { + self.at += 1; + let item = match ty { + BulkType::List(item) => item, + other => other, + }; + out.push('['); + let mut index = 0; + loop { + self.skip_whitespace(); + match self.text.get(self.at) { + Some(b']') | None => { + self.at += 1; + break; + } + Some(b',') => { + self.at += 1; + continue; + } + _ => {} + } + if index > 0 { + out.push_str(", "); + } + self.write(item, out) + .map_err(|invalid| invalid.index(index))?; + index += 1; + } + out.push(']'); + } + Some(b'{') => { + self.at += 1; + let fields = match element(ty) { + BulkType::Input(fields) => *fields, + _ => &[], + }; + out.push('{'); + let mut first = true; + loop { + self.skip_whitespace(); + match self.text.get(self.at) { + Some(b'}') | None => { + self.at += 1; + break; + } + Some(b',') => { + self.at += 1; + continue; + } + _ => {} + } + let key = self.string(); + let key = Self::name(key)?; + self.skip_whitespace(); + // The `:` after the key. + self.at += 1; + if !first { + out.push_str(", "); + } + first = false; + out.push_str(&key); + out.push_str(": "); + match fields.iter().find(|(name, _)| *name == key) { + Some((name, field)) => self + .write(field, out) + .map_err(|invalid| invalid.field(name))?, + None => self.write(&BulkType::Plain, out)?, + } + } + out.push('}'); + } + Some(b'"') => { + let token = self.string(); + if matches!(element(ty), BulkType::Enum) { + out.push_str(&Self::enum_value(token)?); + } else { + out.push_str(token); + } + } + _ => { + // `true`, `false`, `null` or a number, which read alike. + let start = self.at; + while self.text.get(self.at).is_some_and(|byte| { + !matches!(byte, b',' | b']' | b'}' | b' ' | b'\t' | b'\n' | b'\r') + }) { + self.at += 1; + } + out.push_str(std::str::from_utf8(&self.text[start..self.at]).unwrap_or("null")); + } + } + Ok(()) + } +} + +/// The type of a value that is not a list where `ty` stands: GraphQL reads +/// a single value where a list is expected as its one item. +fn element(ty: &BulkType) -> &BulkType { + match ty { + BulkType::List(item) => element(item), + other => other, + } +} + +/// One line of a bulk mutation checked by `graphql!(bulk("mutation …"))`: +/// the variables of one run of the mutation. +/// [`Shopify::bulk_mutation`] runs an iterator of them. +pub struct BulkMutation { + operation: Operation, +} + +impl BulkMutation { + /// What `graphql!` builds. + #[doc(hidden)] + pub fn __checked( + query: &'static str, + name: Option<&'static str>, + checked_against: &'static str, + ) -> Self { + Self { + operation: Operation::__checked(query, OperationKind::Mutation, name, checked_against), + } + } + + /// What the `Variables` of a `graphql!` module set a variable with. + #[doc(hidden)] + pub fn __variable(mut self, name: &str, value: T) -> Self { + self.operation = self.operation.__variable(name, value); + self + } + + /// What `graphql!` sets a variable written as a Rust expression with. + #[doc(hidden)] + pub fn __converted_variable>( + mut self, + name: &str, + value: V, + ) -> Self { + self.operation = self.operation.variable(name, value); + self + } + + /// What `graphql!` sets a variable written as a literal to. + #[doc(hidden)] + pub fn __literal_variable( + mut self, + name: &str, + value: std::result::Result, Invalid>, + ) -> Self { + self.operation = self.operation.__literal_variable(name, value); + self + } + + /// The text of the mutation. + pub fn query(&self) -> &str { + self.operation.query() + } + + /// The Admin API version the mutation was checked against. + pub fn checked_against(&self) -> Option<&'static str> { + self.operation.checked_against() + } + + /// The line of the JSONL file of variables: the variables as one JSON + /// object. Fails as [`Shopify::execute`] would for a value refused. + pub fn line(&self) -> Result { + let values = self.operation.variable_values()?; + let mut line = String::from("{"); + for (index, (name, value)) in values.iter().enumerate() { + if index > 0 { + line.push(','); + } + line.push_str( + &serde_json::to_string(name).map_err(|error| Error::variables(None, &error))?, + ); + line.push(':'); + line.push_str(value.get()); + } + line.push('}'); + Ok(line) + } +} + +impl Clone for BulkMutation { + fn clone(&self) -> Self { + Self { + operation: self.operation.clone(), + } + } +} + +impl fmt::Debug for BulkMutation { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("BulkMutation") + .field("operation", &self.operation) + .finish() + } +} + +/// A line of the results of a bulk mutation: what one run of the mutation +/// returned. Shopify runs the lines in no set order: `index` tells which +/// line of variables it ran with. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[non_exhaustive] +pub struct BulkMutationResult { + /// The `data` of the mutation; its `userErrors` are in it. + #[serde(default = "none")] + pub data: Option, + /// The errors of the run: a variable Shopify refused, a missing scope. + #[serde(default)] + pub errors: Vec, + /// The line of variables it ran with, from 0: Shopify's `__lineNumber`. + /// Shopify's documentation does not show it on every line of errors. + #[serde(rename = "__lineNumber", default)] + pub index: Option, +} + +fn none() -> Option { + None +} + +/// The lines of a bulk mutation, checked and written as its JSONL file. +struct Lines { + mutation: String, + checked_against: Option<&'static str>, + jsonl: Vec, +} + +impl Lines { + /// `None` when there is no line. + fn of>>(lines: impl IntoIterator) -> Result> { + let mut lines = lines.into_iter().map(Into::into); + let Some(first) = lines.next() else { + return Ok(None); + }; + let mut jsonl = first.line()?.into_bytes(); + jsonl.push(b'\n'); + for (index, line) in lines.enumerate() { + if line.query() != first.query() { + return Err(bulk_error(format!( + "line {} of the bulk mutation was built from another mutation than line 1: a bulk operation runs one mutation", + index + 2 + ))); + } + jsonl.extend_from_slice(line.line()?.as_bytes()); + jsonl.push(b'\n'); + } + Ok(Some(Self { + mutation: first.query().to_string(), + checked_against: first.checked_against(), + jsonl, + })) + } +} + +impl Shopify { + /// Runs a bulk query declared with `graphql!(bulk(…))` to its end, then + /// reads its results one top-level object at a time, with the objects + /// of its nested connections in their lists, as they download (see + /// [`BulkItems`]). Fails when the operation does not complete. + /// + /// It runs with `groupObjects` when the query has nested connections, + /// which [`BulkItems`] needs to place them: Shopify is slower with it, + /// and more likely to time out, so a flat export runs without. + /// + /// ```no_run + /// use shopify_api::bulk::BulkWaitOptions; + /// + /// shopify_api::graphql! { + /// mod all_products = bulk("query($filter: String) { + /// products(query: $filter) { edges { node { + /// id title + /// variants { edges { node { sku } } } + /// } } } + /// }"); + /// } + /// + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let mut products = shopify + /// .bulk_query( + /// all_products::Variables { filter: Some("status:active".into()) }, + /// BulkWaitOptions::default(), + /// ) + /// .await?; + /// while let Some(product) = products.next_item().await { + /// let product = product?; + /// println!("{} has {} variants", product.title, product.variants.len()); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn bulk_query( + &self, + query: impl Into>, + options: BulkWaitOptions, + ) -> Result> { + let operation = self.start_bulk_query(query).await?; + match self.completed_url(&operation.id, options).await? { + Some(url) => Ok(self.download_bulk_items(&url).await?.grouped()), + None => Ok(BulkItems::new(None, "").grouped()), + } + } + + /// Downloads the results of a bulk query started with + /// [`Shopify::start_bulk_query`], its `url` or its `partial_data_url`, + /// and reads them as [`Shopify::bulk_query`] does. The item type names + /// the query: `all_products::Item`. + /// + /// ```no_run + /// use shopify_api::bulk::{BulkOperationStatus, BulkWaitOptions}; + /// + /// shopify_api::graphql! { + /// mod all_products = bulk("{ products { edges { node { id title } } } }"); + /// } + /// + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let started = shopify.start_bulk_query(all_products::operation()).await?; + /// let operation = shopify + /// .wait_for_bulk_operation(&started.id, BulkWaitOptions::default()) + /// .await?; + /// if let (BulkOperationStatus::Completed, Some(url)) = (&operation.status, &operation.url) { + /// let products: Vec = + /// shopify.download_bulk_items(url).await?.collect().await?; + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn download_bulk_items(&self, url: &str) -> Result> { + let body = self.open_bulk_results(url).await?; + Ok(BulkItems::new(Some(body), url)) + } + + /// Runs a bulk mutation declared with `graphql!(bulk("mutation …"))` + /// over `lines`, the variables of each run, to its end; then reads the + /// result of each run as it downloads. Fails when the operation does + /// not complete. + /// + /// Every line is checked and written before anything is sent: a value + /// refused fails as [`Shopify::execute`] would, and a line of another + /// mutation with [`Error::Bulk`]. Without lines, nothing runs and no + /// result is read. + /// + /// ```no_run + /// use shopify_api::bulk::BulkWaitOptions; + /// + /// shopify_api::graphql! { + /// mod add_tags = bulk("mutation($id: ID!, $tags: [String!]!) { + /// tagsAdd(id: $id, tags: $tags) { userErrors { field message } } + /// }"); + /// } + /// + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let ids = ["gid://shopify/Product/1", "gid://shopify/Product/2"]; + /// let lines = ids.iter().map(|id| add_tags::Variables { + /// id: id.to_string(), + /// tags: vec!["sale".to_string()], + /// }); + /// let mut results = shopify.bulk_mutation(lines, BulkWaitOptions::default()).await?; + /// while let Some(result) = results.next_row().await { + /// let result = result?; + /// let errors = result.data.and_then(|data| data.tags_add).map(|payload| payload.user_errors); + /// println!("line {:?}: {errors:?}", result.index); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn bulk_mutation( + &self, + lines: impl IntoIterator, + options: BulkWaitOptions, + ) -> Result>> + where + D: DeserializeOwned, + L: Into>, + { + let Some(lines) = Lines::of(lines)? else { + return Ok(BulkRows::new(None, "")); + }; + let operation = self.start_lines(lines).await?; + match self.completed_url(&operation.id, options).await? { + Some(url) => self.download_bulk_results_stream(&url).await, + None => Ok(BulkRows::new(None, "")), + } + } + + /// Starts a bulk mutation declared with `graphql!(bulk("mutation …"))` + /// over `lines`, and returns the operation. Its results read as + /// [`BulkMutationResult`]s with [`Shopify::download_bulk_results_stream`]. + /// + /// Every line is checked and written before anything is sent, as + /// [`Shopify::bulk_mutation`] does. Fails with [`Error::Bulk`] without lines. + pub async fn start_bulk_mutation( + &self, + lines: impl IntoIterator, + ) -> Result + where + L: Into>, + { + let lines = Lines::of(lines)? + .ok_or_else(|| bulk_error("a bulk mutation needs one line of variables at least"))?; + self.start_lines(lines).await + } + + async fn start_lines(&self, lines: Lines) -> Result { + let jsonl = lines.jsonl; + let path = self + .stage_jsonl(move |body| { + body.extend_from_slice(&jsonl); + Ok(()) + }) + .await?; + let operation = Operation::from(run_mutation::Variables { + mutation: lines.mutation, + staged_upload_path: path, + client_identifier: None, + }) + .checked_as(lines.checked_against); + let data = self.execute(operation).await?; + let payload = data + .bulk_operation_run_mutation + .ok_or_else(|| bulk_error("bulkOperationRunMutation returned nothing"))?; + started( + "bulkOperationRunMutation", + payload.bulk_operation, + &payload.user_errors, + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn written(json: &str, ty: &BulkType) -> std::result::Result { + let mut out = String::new(); + Json::new(json) + .write(ty, &mut out) + .map(|()| out) + .map_err(|invalid| invalid.into_error("v").to_string()) + } + + static COLORS: BulkType = BulkType::List(&BulkType::Enum); + static INPUT_FIELDS: [(&str, BulkType); 2] = [ + ("status", BulkType::Enum), + ("nested", BulkType::Input(&INPUT_FIELDS)), + ]; + static INPUT: BulkType = BulkType::Input(&INPUT_FIELDS); + + #[test] + fn strings_keep_the_escapes_of_json() { + for (value, expected) in [ + ("plain", r#""plain""#), + ("a \"quoted\" word", r#""a \"quoted\" word""#), + ("back\\slash", r#""back\\slash""#), + ("two\nlines\r\tand a tab", r#""two\nlines\r\tand a tab""#), + ("café ☕ 𝄞", "\"café ☕ 𝄞\""), + ("\u{1}\u{1f}", r#""\u0001\u001f""#), + ("$filter and ${x}", r#""$filter and ${x}""#), + ("\"\"\" block", r#""\"\"\" block""#), + ] { + let json = serde_json::to_string(value).unwrap(); + assert_eq!( + written(&json, &BulkType::Plain).unwrap(), + expected, + "{value:?}" + ); + // GraphQL reads it back as the same string. + let query = format!("{{ f(a: {expected}) }}"); + let document = graphql_parser::parse_query::(&query).unwrap(); + let graphql_parser::query::Definition::Operation( + graphql_parser::query::OperationDefinition::SelectionSet(set), + ) = &document.definitions[0] + else { + panic!("a selection set"); + }; + let graphql_parser::query::Selection::Field(field) = &set.items[0] else { + panic!("a field"); + }; + assert_eq!( + field.arguments[0].1, + graphql_parser::query::Value::String(value.to_string()), + "{value:?}" + ); + } + } + + #[test] + fn scalars_are_written_as_json_writes_them() { + assert_eq!(written("12", &BulkType::Plain).unwrap(), "12"); + assert_eq!(written("-1.5e300", &BulkType::Plain).unwrap(), "-1.5e300"); + assert_eq!(written("true", &BulkType::Plain).unwrap(), "true"); + assert_eq!(written("null", &BulkType::Plain).unwrap(), "null"); + assert_eq!(written("null", &BulkType::Enum).unwrap(), "null"); + assert_eq!( + written("[[1,2],[],[null]]", &BulkType::Plain).unwrap(), + "[[1, 2], [], [null]]" + ); + } + + #[test] + fn enum_values_are_bare_wherever_they_stand() { + assert_eq!(written(r#""ACTIVE""#, &BulkType::Enum).unwrap(), "ACTIVE"); + assert_eq!( + written(r#"["RED","BLUE"]"#, &COLORS).unwrap(), + "[RED, BLUE]" + ); + // One value where a list is expected. + assert_eq!(written(r#""RED""#, &COLORS).unwrap(), "RED"); + assert_eq!( + written( + r#"{"status":"DRAFT","title":"A \"b\"","nested":{"status":"ACTIVE","tags":["X"]}}"#, + &INPUT + ) + .unwrap(), + r#"{status: DRAFT, title: "A \"b\"", nested: {status: ACTIVE, tags: ["X"]}}"# + ); + assert_eq!( + written( + r#"[{"status":"DRAFT"},{"status":null}]"#, + &BulkType::List(&INPUT) + ) + .unwrap(), + "[{status: DRAFT}, {status: null}]" + ); + // A string is not an enum value where none is expected. + assert_eq!( + written(r#""ACTIVE""#, &BulkType::Plain).unwrap(), + r#""ACTIVE""# + ); + } + + #[test] + fn what_is_not_a_graphql_name_is_refused() { + for (json, ty, path) in [ + (r#""ACTIVE) { x }""#, &BulkType::Enum, "$v"), + (r#""""#, &BulkType::Enum, "$v"), + (r#"["RED","1BLUE"]"#, &COLORS, "$v[1]"), + ( + r#"{"nested":{"status":"no way"}}"#, + &INPUT, + "$v.nested.status", + ), + (r#"{"a b":1}"#, &BulkType::Plain, "$v"), + ] { + assert_eq!( + written(json, ty).unwrap_err(), + format!( + "invalid value at `{path}`: not a GraphQL name, as an enum value or a field written into a bulk query must be" + ), + "{json}" + ); + } + } +} diff --git a/crates/shopify_api/src/client.rs b/crates/shopify_api/src/client.rs new file mode 100644 index 0000000..8583a8d --- /dev/null +++ b/crates/shopify_api/src/client.rs @@ -0,0 +1,537 @@ +//! The client of one shop. + +use std::sync::Arc; +use std::time::Duration; + +use crate::auth::{Endpoint, Tokens}; +use crate::transport::{Transport, default_transport}; +use crate::{ApiVersion, Auth, Error, Result, ShopDomain, TokenData, TokenStore}; + +/// The `User-Agent` of every request, unless [`ShopifyBuilder::user_agent`] sets another. +pub const USER_AGENT: &str = concat!("shopify_api/", env!("CARGO_PKG_VERSION"), " (Rust)"); + +/// The Admin API of one shop. +/// +/// A client is cheap to clone: clones share the transport and the token, so +/// that one renewal serves them all. +/// +/// ```no_run +/// use shopify_api::{Shopify, graphql}; +/// +/// # async fn run() -> shopify_api::Result<()> { +/// let shopify = Shopify::new("my-shop", shopify_api::Auth::access_token("shpat_…"))?; +/// +/// let data = shopify +/// .execute(graphql!("query { shop { name currencyCode } }")) +/// .await?; +/// println!("{} sells in {}", data.shop.name, data.shop.currency_code); +/// # Ok(()) +/// # } +/// ``` +#[derive(Clone)] +pub struct Shopify { + pub(crate) shared: Arc, + /// The version every request goes to, when one was chosen. + pinned: Option, + pub(crate) retry: RetryPolicy, +} + +pub(crate) struct Shared { + pub endpoint: Arc, + pub tokens: Tokens, +} + +impl std::fmt::Debug for Shopify { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("Shopify") + .field("shop", &self.shared.endpoint.shop) + .field("api_version", &self.pinned) + .field("retry", &self.retry) + .finish_non_exhaustive() + } +} + +impl Shopify { + /// A client of `shop` (`my-shop` or `my-shop.myshopify.com`) with the + /// default transport, retries and API version. + pub fn new(shop: impl AsRef, auth: Auth) -> Result { + Self::builder(shop).auth(auth).build() + } + + pub fn builder(shop: impl AsRef) -> ShopifyBuilder { + ShopifyBuilder { + shop: shop.as_ref().to_string(), + auth: None, + api_version: None, + transport: None, + retry: RetryPolicy::default(), + token_store: None, + refresh_leeway: Duration::from_secs(5 * 60), + user_agent: USER_AGENT.to_string(), + } + } + + pub fn shop(&self) -> &ShopDomain { + &self.shared.endpoint.shop + } + + /// The version requests go to: the one pinned with + /// [`ShopifyBuilder::api_version`], else [`ApiVersion::DEFAULT`]. + /// + /// Without a pinned version, an operation of [`graphql!`](crate::graphql!) + /// goes to the version of the schema it was checked against. + pub fn api_version(&self) -> ApiVersion { + self.pinned.unwrap_or_default() + } + + /// The version pinned with [`ShopifyBuilder::api_version`], if any. + pub fn pinned_api_version(&self) -> Option { + self.pinned + } + + /// A clone that sends every request to `version`, sharing the token. + pub fn with_api_version(&self, version: ApiVersion) -> Self { + Self { + pinned: Some(version), + ..self.clone() + } + } + + /// A clone with other retries, sharing the token. + pub fn with_retry(&self, retry: RetryPolicy) -> Self { + Self { + retry, + ..self.clone() + } + } + + /// `https://{shop}/admin/api/{version}/graphql.json`. + pub fn graphql_url(&self, version: ApiVersion) -> String { + format!( + "https://{}/admin/api/{version}/graphql.json", + self.shared.endpoint.shop + ) + } + + /// The access token requests send, obtained or renewed first when it is + /// missing or about to expire. + pub async fn access_token(&self) -> Result { + self.shared.tokens.get(&self.shared.endpoint).await + } + + /// The token the client holds, without asking Shopify for one: to store + /// it, or to read its scopes. + pub async fn token(&self) -> Option { + self.shared.tokens.current().await + } + + pub(crate) fn endpoint(&self) -> &Arc { + &self.shared.endpoint + } + + /// The version an operation goes to: the pinned one, else the one its + /// schema was checked against. + pub(crate) fn version_for(&self, checked_against: Option<&'static str>) -> Result { + match (self.pinned, checked_against) { + (Some(pinned), Some(checked)) => { + if pinned.to_string() != checked { + warn_mismatch(pinned, checked); + } + Ok(pinned) + } + (Some(pinned), None) => Ok(pinned), + (None, Some(checked)) => ApiVersion::new(checked), + (None, None) => Ok(ApiVersion::DEFAULT), + } + } +} + +/// Warns once per pair of versions that an operation goes to another +/// version than the one it was checked against. +fn warn_mismatch(pinned: ApiVersion, checked: &'static str) { + static WARNED: std::sync::Mutex> = + std::sync::Mutex::new(Vec::new()); + let mut warned = WARNED + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if !warned.contains(&(pinned, checked)) { + warned.push((pinned, checked)); + tracing::warn!( + "an operation checked against the Admin API {checked} is sent to {pinned}: \ + set `api-version = \"{pinned}\"` in `[package.metadata.shopify_api]` of Cargo.toml, \ + or let the client follow the schema by not pinning a version" + ); + } +} + +/// How a client retries what Shopify did not run. +/// +/// A request Shopify throttled (`THROTTLED`, or a `429`) is sent again after +/// the time its cost says the bucket needs. A query is also sent again after +/// a `5xx` or a network failure, with exponential backoff; a mutation is not, +/// since it may have run. +/// +/// A `429` waits for its `Retry-After`, in seconds or until an HTTP date, +/// however longer than [`max_delay`](Self::max_delay) it is: that cap is for +/// the backoff the client computes. A `Retry-After` longer than +/// [`max_retry_after`](Self::max_retry_after) (five minutes by default) is not +/// waited for: the request ends in [`Error::Throttled`](crate::Error::Throttled), +/// with the wait Shopify asked for in its `retry_after`. +#[derive(Debug, Clone)] +pub struct RetryPolicy { + max_retries: u32, + base_delay: Duration, + max_delay: Duration, + max_retry_after: Duration, + /// `false` only for `testing::client`: a `Retry-After` is not slept through. + wait_for_retry_after: bool, +} + +impl RetryPolicy { + /// At most `max_retries` retries, from one second up to thirty seconds + /// apart, or as long as a `Retry-After` of up to five minutes asks. + pub const fn new(max_retries: u32) -> Self { + Self { + max_retries, + base_delay: Duration::from_secs(1), + max_delay: Duration::from_secs(30), + max_retry_after: Duration::from_secs(300), + wait_for_retry_after: true, + } + } + + /// Never retries. + pub const fn none() -> Self { + Self::new(0) + } + + /// The first backoff, doubled at each retry. + pub const fn with_base_delay(mut self, delay: Duration) -> Self { + self.base_delay = delay; + self + } + + /// The longest backoff between two attempts. A `Retry-After` from + /// Shopify is not capped by it: see [`with_max_retry_after`](Self::with_max_retry_after). + pub const fn with_max_delay(mut self, delay: Duration) -> Self { + self.max_delay = delay; + self + } + + /// The longest `Retry-After` the client waits for before sending a `429` + /// again. A longer one ends the request in + /// [`Error::Throttled`](crate::Error::Throttled) at once. + pub const fn with_max_retry_after(mut self, wait: Duration) -> Self { + self.max_retry_after = wait; + self + } + + /// Retries a `429` at once instead of waiting for its `Retry-After`, for + /// tests with a mocked Shopify. A `Retry-After` beyond `max_retry_after` + /// still ends in [`Error::Throttled`](crate::Error::Throttled). + #[cfg_attr(not(feature = "testing"), allow(dead_code))] + pub(crate) const fn without_retry_after_waits(mut self) -> Self { + self.wait_for_retry_after = false; + self + } + + /// The wait before retrying a `429` whose `Retry-After` asked for `wait`. + pub(crate) const fn retry_after_wait(&self, wait: Duration) -> Duration { + if self.wait_for_retry_after { + wait + } else { + Duration::ZERO + } + } + + pub const fn max_retries(&self) -> u32 { + self.max_retries + } + + /// The longest backoff between two attempts. + pub const fn max_delay(&self) -> Duration { + self.max_delay + } + + /// The longest `Retry-After` the client waits for. + pub const fn max_retry_after(&self) -> Duration { + self.max_retry_after + } + + /// The wait before retry number `retry` (from 0): exponential, with up + /// to a quarter of jitter, capped at the longest wait. + pub(crate) fn backoff(&self, retry: u32) -> Duration { + let exponential = self.base_delay.saturating_mul(1u32 << retry.min(16)); + let jitter = exponential.mul_f64(jitter_fraction() * 0.25); + exponential.saturating_add(jitter).min(self.max_delay) + } + + /// The wait before sending a throttled request again: until the bucket + /// holds its cost, as Shopify reported it, else the backoff. + pub(crate) fn throttled(&self, retry: u32, cost: Option) -> Duration { + match cost.map(|cost| cost.seconds_until_available()) { + Some(seconds) if seconds > 0.0 => { + // A little more than needed: the bucket refills continuously. + // What does not fit in a `Duration` is the longest wait. + Duration::try_from_secs_f64(seconds + 0.1) + .map_or(self.max_delay, |wait| wait.min(self.max_delay)) + } + _ => self.backoff(retry), + } + } +} + +impl Default for RetryPolicy { + /// Four retries. + fn default() -> Self { + Self::new(4) + } +} + +/// A fraction in `[0, 1)`, from the random keys of std's `RandomState`: retries +/// need no better randomness. Not from the clock: macOS gives microseconds, +/// whose nanoseconds are always zero. +fn jitter_fraction() -> f64 { + use std::hash::BuildHasher; + // Each `RandomState` has keys of its own: hashing nothing is random enough. + let bits = std::collections::hash_map::RandomState::new().hash_one(()); + // The top 53 bits, the precision of an `f64`. + (bits >> 11) as f64 / (1u64 << 53) as f64 +} + +/// Builds a [`Shopify`] client. +/// +/// ``` +/// # // Without `rustls` or `native-tls`, `build` needs a `transport(…)`. +/// # #[cfg(any(feature = "rustls", feature = "native-tls"))] +/// # { +/// use std::time::Duration; +/// use shopify_api::{ApiVersion, RetryPolicy, Shopify}; +/// +/// let shopify = Shopify::builder("my-shop") +/// .client_credentials("client-id", "client-secret") +/// .api_version(ApiVersion::V2026_10) +/// .retry(RetryPolicy::new(6).with_max_delay(Duration::from_secs(10))) +/// .build()?; +/// # } +/// # Ok::<(), shopify_api::Error>(()) +/// ``` +#[must_use] +pub struct ShopifyBuilder { + shop: String, + auth: Option, + api_version: Option, + transport: Option>, + retry: RetryPolicy, + token_store: Option>, + refresh_leeway: Duration, + user_agent: String, +} + +impl std::fmt::Debug for ShopifyBuilder { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ShopifyBuilder") + .field("shop", &self.shop) + .field("auth", &self.auth) + .field("api_version", &self.api_version) + .field("retry", &self.retry) + .finish_non_exhaustive() + } +} + +impl ShopifyBuilder { + pub fn auth(mut self, auth: Auth) -> Self { + self.auth = Some(auth); + self + } + + /// [`Auth::access_token`]. + pub fn access_token(self, token: impl Into) -> Self { + self.auth(Auth::access_token(token)) + } + + /// [`Auth::client_credentials`]. + pub fn client_credentials( + self, + client_id: impl Into, + client_secret: impl Into, + ) -> Self { + self.auth(Auth::client_credentials(client_id, client_secret)) + } + + /// Sends every request to `version`, instead of the version each + /// [`graphql!`](crate::graphql!) operation was checked against. + pub fn api_version(mut self, version: ApiVersion) -> Self { + self.api_version = Some(version); + self + } + + /// Sends the requests through `transport`, such as a + /// [`MockTransport`](crate::testing::MockTransport) in tests. + pub fn transport(mut self, transport: impl Transport) -> Self { + self.transport = Some(Arc::new(transport)); + self + } + + /// [`ShopifyBuilder::transport`], for a transport already shared. + pub fn shared_transport(mut self, transport: Arc) -> Self { + self.transport = Some(transport); + self + } + + pub fn retry(mut self, retry: RetryPolicy) -> Self { + self.retry = retry; + self + } + + /// Saves the tokens the client obtains or renews. Until a renewed token + /// is saved, the client sends nothing: see [`TokenStore`]. + pub fn token_store(mut self, store: impl TokenStore) -> Self { + self.token_store = Some(Arc::new(store)); + self + } + + /// [`ShopifyBuilder::token_store`], for a store already shared. + pub fn shared_token_store(mut self, store: Arc) -> Self { + self.token_store = Some(store); + self + } + + /// How long before it expires a token is renewed: five minutes by default. + pub fn refresh_leeway(mut self, leeway: Duration) -> Self { + self.refresh_leeway = leeway; + self + } + + pub fn user_agent(mut self, user_agent: impl Into) -> Self { + self.user_agent = user_agent.into(); + self + } + + pub fn build(self) -> Result { + let shop = ShopDomain::new(&self.shop)?; + let auth = self.auth.ok_or_else(|| { + Error::auth("no credentials: call `access_token`, `client_credentials` or `auth`") + })?; + let transport = match self.transport { + Some(transport) => transport, + None => default_transport()?, + }; + Ok(Shopify { + shared: Arc::new(Shared { + endpoint: Arc::new(Endpoint { + transport, + shop, + user_agent: self.user_agent, + }), + tokens: Tokens::new(auth, self.token_store, self.refresh_leeway), + }), + pinned: self.api_version, + retry: self.retry, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn backoff_doubles_up_to_the_longest_wait() { + let retry = RetryPolicy::new(5) + .with_base_delay(Duration::from_millis(100)) + .with_max_delay(Duration::from_secs(1)); + let within = |retry_number: u32, low: u64, high: u64| { + let wait = retry.backoff(retry_number); + assert!( + wait >= Duration::from_millis(low) && wait <= Duration::from_millis(high), + "retry {retry_number}: {wait:?}" + ); + }; + within(0, 100, 125); + within(1, 200, 250); + within(2, 400, 500); + within(4, 1000, 1000); + within(30, 1000, 1000); + } + + #[test] + fn the_jitter_varies() { + let fractions: Vec = (0..64).map(|_| jitter_fraction()).collect(); + assert!( + fractions + .iter() + .all(|fraction| (0.0..1.0).contains(fraction)) + ); + let mut distinct = fractions.clone(); + distinct.sort_by(f64::total_cmp); + distinct.dedup(); + // 64 draws of 53 bits: a repeat is as likely as a cosmic ray. + assert_eq!(distinct.len(), fractions.len(), "{fractions:?}"); + } + + #[test] + fn a_throttled_request_waits_for_its_cost() { + let retry = RetryPolicy::default(); + let cost = crate::graphql::Cost { + requested_query_cost: 500.0, + actual_query_cost: None, + throttle_status: crate::graphql::ThrottleStatus { + maximum_available: 2000.0, + currently_available: 300.0, + restore_rate: 100.0, + }, + }; + assert_eq!( + retry.throttled(0, Some(cost.clone())), + Duration::from_millis(2100) + ); + let far = crate::graphql::Cost { + requested_query_cost: 20000.0, + ..cost + }; + assert_eq!(retry.throttled(0, Some(far)), Duration::from_secs(30)); + } + + #[cfg(feature = "testing")] + #[test] + fn the_version_follows_the_schema_unless_one_is_pinned() { + let mock = crate::testing::MockTransport::new(); + let shopify = Shopify::builder("shop") + .access_token("t") + .transport(mock) + .build() + .unwrap(); + assert_eq!(shopify.version_for(None).unwrap(), ApiVersion::DEFAULT); + assert_eq!( + shopify.version_for(Some("2026-07")).unwrap(), + ApiVersion::V2026_07 + ); + assert!(shopify.version_for(Some("2025-01")).is_err()); + let pinned = shopify.with_api_version(ApiVersion::UNSTABLE); + assert_eq!( + pinned.version_for(Some("2026-07")).unwrap(), + ApiVersion::UNSTABLE + ); + assert_eq!(pinned.api_version(), ApiVersion::UNSTABLE); + assert_eq!(shopify.api_version(), ApiVersion::DEFAULT); + assert_eq!( + shopify.graphql_url(ApiVersion::V2026_10), + "https://shop.myshopify.com/admin/api/2026-10/graphql.json" + ); + } + + #[test] + fn building_needs_a_shop_and_credentials() { + assert!(matches!( + Shopify::builder("not a shop").access_token("t").build(), + Err(Error::InvalidShop(_)) + )); + assert!(matches!( + Shopify::builder("shop").build(), + Err(Error::Auth { .. }) + )); + } +} diff --git a/crates/shopify_api/src/decode.rs b/crates/shopify_api/src/decode.rs new file mode 100644 index 0000000..78b83b8 --- /dev/null +++ b/crates/shopify_api/src/decode.rs @@ -0,0 +1,1111 @@ +//! Reads JSON as a type, and builds an error that holds nothing of the input. +//! +//! An error of serde or serde_json may quote what it read: a value +//! (`invalid type: string "…"`), a map key in its path, the text a type's own +//! `Deserialize` writes. What [`Failure`] keeps to show is built from this +//! module's own words and from the `&'static str` names a type gives serde +//! (its fields, its variants, its name): a path segment or a quoted name is +//! shown only when it is one of those, never because of what it looks like. +//! serde's whole message is kept apart, in [`Failure::detail`]. + +use std::cell::RefCell; +use std::fmt; + +use serde::de::{ + self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, MapAccess, SeqAccess, + VariantAccess, Visitor, +}; +use serde_json::error::Category; + +/// A value that does not read as its type: what is safe to show, and serde's +/// own message, which is not. +pub(crate) struct Failure { + /// Field names of the type, indexes, and `[key]` for anything else. + pub(crate) path: String, + /// What went wrong, in this module's words. + pub(crate) message: String, + /// serde's message as it was: it may quote the input. + pub(crate) detail: String, +} + +impl Failure { + /// The [`Error::Decode`](crate::Error::Decode) of this failure. + pub(crate) fn into_error(self) -> crate::Error { + crate::Error::decode(self.path, self.message, Some(self.detail)) + } +} + +/// Reads `value` as `T`. +pub(crate) fn from_value(value: serde_json::Value) -> crate::Result { + read(value, None).map_err(Failure::into_error) +} + +/// Reads JSON text as `T`. +pub(crate) fn from_slice(bytes: &[u8]) -> Result { + let mut deserializer = serde_json::Deserializer::from_slice(bytes); + let value = read(&mut deserializer, None)?; + deserializer + .end() + .map_err(|error| failure(&error, &Track::default(), None))?; + Ok(value) +} + +/// Reads line `line` (from 1) of a JSONL file as `T`: the position the +/// error gives is in the file. +pub(crate) fn from_jsonl_line( + bytes: &[u8], + line: usize, +) -> crate::Result { + let mut deserializer = serde_json::Deserializer::from_slice(bytes); + let value = read(&mut deserializer, Some(line)).map_err(Failure::into_error)?; + deserializer + .end() + .map_err(|error| failure(&error, &Track::default(), Some(line)).into_error())?; + Ok(value) +} + +/// Writes `value` as JSON and reads it back as `T`: a generated type read as +/// one of this crate's. +pub(crate) fn reserialize( + value: &impl serde::Serialize, +) -> crate::Result { + let value = serde_json::to_value(value).map_err(|error| { + crate::Error::decode( + ".", + "the answer does not serialize".to_string(), + Some(error.to_string()), + ) + })?; + from_value(value) +} + +fn read<'de, D, T>(deserializer: D, line: Option) -> Result +where + D: Deserializer<'de, Error = serde_json::Error>, + T: Deserialize<'de>, +{ + let track = Track::default(); + T::deserialize(Wrap { + inner: deserializer, + chain: &Chain::Root, + track: &track, + }) + .map_err(|error| failure(&error, &track, line)) +} + +fn failure(error: &serde_json::Error, track: &Track, line: Option) -> Failure { + let path = track.path.borrow().clone().unwrap_or_default(); + let mut message = describe(error, track); + if error.line() > 0 { + let line = line.unwrap_or(error.line()); + message.push_str(&format!(" at line {line} column {}", error.column())); + } else if let Some(line) = line { + message.push_str(&format!(" at line {line}")); + } + Failure { + path: render(&path), + message, + detail: error.to_string(), + } +} + +/// What went wrong, without anything serde quoted from the input. +fn describe(error: &serde_json::Error, track: &Track) -> String { + let full = error.to_string(); + // serde_json adds the position to its message; it is shown on its own. + let position = format!(" at line {} column {}", error.line(), error.column()); + let message = full.strip_suffix(&position).unwrap_or(&full); + if let Some(known) = FIXED.iter().find(|known| **known == message) { + return (*known).to_string(); + } + match error.classify() { + Category::Io => "the input could not be read".to_string(), + Category::Eof => "the input ends too early".to_string(), + Category::Syntax => "invalid JSON".to_string(), + Category::Data => data_message(message, track), + } +} + +/// serde_json's own messages: none of them quotes the input. +const FIXED: &[&str] = &[ + "EOF while parsing a list", + "EOF while parsing an object", + "EOF while parsing a string", + "EOF while parsing a value", + "expected `:`", + "expected `,` or `]`", + "expected `,` or `}`", + "expected ident", + "expected value", + "expected `\"`", + "invalid escape", + "invalid number", + "number out of range", + "invalid unicode code point", + "control character (\\u0000-\\u001F) found while parsing a string", + "key must be a string", + "invalid value: expected key to be a number in quotes", + "float key must be finite (got NaN or +/-inf)", + "lone leading surrogate in hex escape", + "trailing comma", + "trailing characters", + "unexpected end of hex escape", + "recursion limit exceeded", +]; + +/// The kinds serde names an unexpected value by (`Unexpected`'s `Display`). +const KINDS: &[&str] = &[ + "boolean", + "integer", + "floating point", + "character", + "string", + "byte array", + "unit value", + "Option value", + "newtype struct", + "sequence", + "map", + "enum", + "unit variant", + "newtype variant", + "tuple variant", + "struct variant", + "null", +]; + +/// What serde's primitive types and `Value` expect. +const EXPECTED: &[&str] = &[ + "a boolean", + "i8", + "i16", + "i32", + "i64", + "i128", + "u8", + "u16", + "u32", + "u64", + "u128", + "f32", + "f64", + "a character", + "a string", + "a borrowed string", + "a byte array", + "a borrowed byte array", + "option", + "unit", + "a sequence", + "a map", + "any valid JSON value", + "a JSON number", +]; + +fn data_message(message: &str, track: &Track) -> String { + for (prefix, what) in [ + ("invalid type: ", "invalid type"), + ("invalid value: ", "invalid value"), + ] { + if let Some(rest) = message.strip_prefix(prefix) { + let mut shown = what.to_string(); + if let Some(kind) = KINDS.iter().find(|kind| { + rest.strip_prefix(**kind) + .is_some_and(|after| after.is_empty() || after.starts_with([' ', ','])) + }) { + shown.push_str(": "); + shown.push_str(kind); + } + // What the type expects, when it is serde's or the type's name. + if let Some(expected) = rest.rfind(", expected ").map(|at| &rest[at + 11..]) + && let Some(expected) = expected_by_type(expected, track) + { + shown.push_str(", expected "); + shown.push_str(&expected); + } + return shown; + } + } + for (prefix, what) in [ + ("missing field `", "missing field"), + ("duplicate field `", "duplicate field"), + ] { + if let Some(rest) = message.strip_prefix(prefix) { + // The name a derived type gives serde, never one the input wrote. + return match rest + .strip_suffix('`') + .and_then(|name| track.static_name(name)) + { + Some(name) => format!("{what} `{name}`"), + None => what.to_string(), + }; + } + } + for (prefix, what) in [ + ("invalid length ", "invalid length"), + ("unknown variant `", "unknown variant"), + ("unknown field `", "unknown field"), + ( + "data did not match any variant of untagged enum ", + "no variant of an untagged enum matches", + ), + ] { + if message.starts_with(prefix) { + return what.to_string(); + } + } + "the type's `Deserialize` refused the value".to_string() +} + +/// `expected` as this crate writes it, from its tables and the names the +/// type gave serde. +fn expected_by_type(expected: &str, track: &Track) -> Option { + if let Some(known) = EXPECTED.iter().find(|known| **known == expected) { + return Some((*known).to_string()); + } + for kind in ["struct ", "tuple struct ", "unit struct ", "enum "] { + if let Some(name) = expected + .strip_prefix(kind) + .and_then(|name| track.static_name(name)) + { + return Some(format!("{kind}{name}")); + } + } + None +} + +/// One step of the path to a value. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Segment { + /// A field or a variant, by the name its type gives serde. + Name(&'static str), + /// An entry of a sequence. + Index(usize), + /// A map key, or a name the type does not know: never shown. + Key, +} + +fn render(path: &[Segment]) -> String { + if path.is_empty() { + return ".".to_string(); + } + let mut shown = String::new(); + for segment in path { + match segment { + Segment::Name(name) => { + if !shown.is_empty() { + shown.push('.'); + } + shown.push_str(name); + } + Segment::Index(index) => shown.push_str(&format!("[{index}]")), + Segment::Key => shown.push_str("[key]"), + } + } + shown +} + +/// The path to the value being read, on the stack. +enum Chain<'a> { + Root, + Step { + parent: &'a Chain<'a>, + segment: Segment, + }, +} + +impl Chain<'_> { + fn segments(&self) -> Vec { + let mut segments = Vec::new(); + let mut chain = self; + while let Chain::Step { parent, segment } = chain { + segments.push(*segment); + chain = parent; + } + segments.reverse(); + segments + } +} + +/// The path of the first error, and the names the types gave serde. +#[derive(Default)] +struct Track { + path: RefCell>>, + /// The lists of names seen, once each. + lists: RefCell>, + /// The names of the types seen. + types: RefCell>, +} + +impl Track { + /// Keeps the path of the innermost error: the first one to get here. + fn trigger(&self, chain: &Chain<'_>, error: E) -> E { + let mut path = self.path.borrow_mut(); + if path.is_none() { + *path = Some(chain.segments()); + } + error + } + + fn names(&self, names: &'static [&'static str]) { + let mut lists = self.lists.borrow_mut(); + if !lists.iter().any(|seen| std::ptr::eq(*seen, names)) { + lists.push(names); + } + } + + fn type_name(&self, name: &'static str) { + let mut types = self.types.borrow_mut(); + if !types.contains(&name) { + types.push(name); + } + } + + /// `text` as a name a type gave serde, when it is one. + fn static_name(&self, text: &str) -> Option<&'static str> { + let lists = self.lists.borrow(); + let types = self.types.borrow(); + lists + .iter() + .flat_map(|names| names.iter()) + .chain(types.iter()) + .find(|name| **name == text) + .copied() + } +} + +/// The name in `names` that `text` is, else [`Segment::Key`]. +fn segment_of(text: &str, names: Option<&'static [&'static str]>) -> Segment { + names + .and_then(|names| names.iter().find(|name| **name == text)) + .map_or(Segment::Key, |name| Segment::Name(name)) +} + +struct Wrap<'a, 'b, D> { + inner: D, + chain: &'a Chain<'a>, + track: &'b Track, +} + +macro_rules! forward { + ($($method:ident($($arg:ident: $type:ty),*);)*) => {$( + fn $method>(self, $($arg: $type,)* visitor: V) -> Result { + let (chain, track) = (self.chain, self.track); + self.inner + .$method($($arg,)* WrapVisitor { inner: visitor, chain, track, names: None }) + .map_err(|error| track.trigger(chain, error)) + } + )*}; +} + +impl<'de, D: Deserializer<'de>> Deserializer<'de> for Wrap<'_, '_, D> { + type Error = D::Error; + + forward! { + deserialize_any(); + deserialize_bool(); + deserialize_i8(); + deserialize_i16(); + deserialize_i32(); + deserialize_i64(); + deserialize_i128(); + deserialize_u8(); + deserialize_u16(); + deserialize_u32(); + deserialize_u64(); + deserialize_u128(); + deserialize_f32(); + deserialize_f64(); + deserialize_char(); + deserialize_str(); + deserialize_string(); + deserialize_bytes(); + deserialize_byte_buf(); + deserialize_option(); + deserialize_unit(); + deserialize_seq(); + deserialize_tuple(len: usize); + deserialize_map(); + deserialize_identifier(); + deserialize_ignored_any(); + } + + fn deserialize_unit_struct>( + self, + name: &'static str, + visitor: V, + ) -> Result { + self.track.type_name(name); + let (chain, track) = (self.chain, self.track); + self.inner + .deserialize_unit_struct(name, WrapVisitor::new(visitor, chain, track, None)) + .map_err(|error| track.trigger(chain, error)) + } + + fn deserialize_newtype_struct>( + self, + name: &'static str, + visitor: V, + ) -> Result { + self.track.type_name(name); + let (chain, track) = (self.chain, self.track); + self.inner + .deserialize_newtype_struct(name, WrapVisitor::new(visitor, chain, track, None)) + .map_err(|error| track.trigger(chain, error)) + } + + fn deserialize_tuple_struct>( + self, + name: &'static str, + len: usize, + visitor: V, + ) -> Result { + self.track.type_name(name); + let (chain, track) = (self.chain, self.track); + self.inner + .deserialize_tuple_struct(name, len, WrapVisitor::new(visitor, chain, track, None)) + .map_err(|error| track.trigger(chain, error)) + } + + fn deserialize_struct>( + self, + name: &'static str, + fields: &'static [&'static str], + visitor: V, + ) -> Result { + self.track.type_name(name); + self.track.names(fields); + let (chain, track) = (self.chain, self.track); + self.inner + .deserialize_struct( + name, + fields, + WrapVisitor::new(visitor, chain, track, Some(fields)), + ) + .map_err(|error| track.trigger(chain, error)) + } + + fn deserialize_enum>( + self, + name: &'static str, + variants: &'static [&'static str], + visitor: V, + ) -> Result { + self.track.type_name(name); + self.track.names(variants); + let (chain, track) = (self.chain, self.track); + self.inner + .deserialize_enum( + name, + variants, + WrapVisitor::new(visitor, chain, track, Some(variants)), + ) + .map_err(|error| track.trigger(chain, error)) + } + + fn is_human_readable(&self) -> bool { + self.inner.is_human_readable() + } +} + +struct WrapVisitor<'a, 'b, X> { + inner: X, + chain: &'a Chain<'a>, + track: &'b Track, + /// The fields of a struct, the variants of an enum. + names: Option<&'static [&'static str]>, +} + +impl<'a, 'b, X> WrapVisitor<'a, 'b, X> { + fn new( + inner: X, + chain: &'a Chain<'a>, + track: &'b Track, + names: Option<&'static [&'static str]>, + ) -> Self { + Self { + inner, + chain, + track, + names, + } + } +} + +macro_rules! forward_visit { + ($($method:ident($type:ty);)*) => {$( + fn $method(self, value: $type) -> Result { + self.inner.$method(value) + } + )*}; +} + +impl<'de, X: Visitor<'de>> Visitor<'de> for WrapVisitor<'_, '_, X> { + type Value = X::Value; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + self.inner.expecting(formatter) + } + + forward_visit! { + visit_bool(bool); + visit_i8(i8); + visit_i16(i16); + visit_i32(i32); + visit_i64(i64); + visit_i128(i128); + visit_u8(u8); + visit_u16(u16); + visit_u32(u32); + visit_u64(u64); + visit_u128(u128); + visit_f32(f32); + visit_f64(f64); + visit_char(char); + visit_str(&str); + visit_borrowed_str(&'de str); + visit_string(String); + visit_bytes(&[u8]); + visit_borrowed_bytes(&'de [u8]); + visit_byte_buf(Vec); + } + + fn visit_none(self) -> Result { + self.inner.visit_none() + } + + fn visit_unit(self) -> Result { + self.inner.visit_unit() + } + + fn visit_some>(self, deserializer: D) -> Result { + self.inner.visit_some(Wrap { + inner: deserializer, + chain: self.chain, + track: self.track, + }) + } + + fn visit_newtype_struct>( + self, + deserializer: D, + ) -> Result { + self.inner.visit_newtype_struct(Wrap { + inner: deserializer, + chain: self.chain, + track: self.track, + }) + } + + fn visit_seq>(self, seq: A) -> Result { + self.inner.visit_seq(WrapSeq { + inner: seq, + chain: self.chain, + track: self.track, + index: 0, + }) + } + + fn visit_map>(self, map: A) -> Result { + self.inner.visit_map(WrapMap { + inner: map, + chain: self.chain, + track: self.track, + names: self.names, + key: None, + }) + } + + fn visit_enum>(self, data: A) -> Result { + self.inner.visit_enum(WrapEnum { + inner: data, + chain: self.chain, + track: self.track, + names: self.names, + }) + } +} + +struct WrapSeed<'a, 'b, S> { + inner: S, + chain: &'a Chain<'a>, + track: &'b Track, +} + +impl<'de, S: DeserializeSeed<'de>> DeserializeSeed<'de> for WrapSeed<'_, '_, S> { + type Value = S::Value; + + fn deserialize>(self, deserializer: D) -> Result { + self.inner.deserialize(Wrap { + inner: deserializer, + chain: self.chain, + track: self.track, + }) + } +} + +struct WrapSeq<'a, 'b, A> { + inner: A, + chain: &'a Chain<'a>, + track: &'b Track, + index: usize, +} + +impl<'de, A: SeqAccess<'de>> SeqAccess<'de> for WrapSeq<'_, '_, A> { + type Error = A::Error; + + fn next_element_seed>( + &mut self, + seed: T, + ) -> Result, A::Error> { + let chain = Chain::Step { + parent: self.chain, + segment: Segment::Index(self.index), + }; + self.index += 1; + let track = self.track; + self.inner + .next_element_seed(WrapSeed { + inner: seed, + chain: &chain, + track, + }) + .map_err(|error| track.trigger(&chain, error)) + } + + fn size_hint(&self) -> Option { + self.inner.size_hint() + } +} + +struct WrapMap<'a, 'b, A> { + inner: A, + chain: &'a Chain<'a>, + track: &'b Track, + names: Option<&'static [&'static str]>, + /// The segment of the last key read. + key: Option, +} + +impl<'de, A: MapAccess<'de>> MapAccess<'de> for WrapMap<'_, '_, A> { + type Error = A::Error; + + fn next_key_seed>( + &mut self, + seed: K, + ) -> Result, A::Error> { + self.key = None; + let names = self.names; + let result = self.inner.next_key_seed(KeySeed { + inner: seed, + names, + key: &mut self.key, + }); + result.map_err(|error| { + let chain = Chain::Step { + parent: self.chain, + segment: self.key.unwrap_or(Segment::Key), + }; + self.track.trigger(&chain, error) + }) + } + + fn next_value_seed>(&mut self, seed: V) -> Result { + let chain = Chain::Step { + parent: self.chain, + segment: self.key.take().unwrap_or(Segment::Key), + }; + let track = self.track; + self.inner + .next_value_seed(WrapSeed { + inner: seed, + chain: &chain, + track, + }) + .map_err(|error| track.trigger(&chain, error)) + } + + fn size_hint(&self) -> Option { + self.inner.size_hint() + } +} + +struct WrapEnum<'a, 'b, A> { + inner: A, + chain: &'a Chain<'a>, + track: &'b Track, + names: Option<&'static [&'static str]>, +} + +impl<'a, 'b, 'de, A: EnumAccess<'de>> EnumAccess<'de> for WrapEnum<'a, 'b, A> { + type Error = A::Error; + type Variant = WrapVariant<'a, 'b, A::Variant>; + + fn variant_seed>( + self, + seed: V, + ) -> Result<(V::Value, Self::Variant), A::Error> { + let mut key = None; + let (chain, track) = (self.chain, self.track); + let (value, variant) = self + .inner + .variant_seed(KeySeed { + inner: seed, + names: self.names, + key: &mut key, + }) + .map_err(|error| track.trigger(chain, error))?; + Ok(( + value, + WrapVariant { + inner: variant, + parent: chain, + segment: key.unwrap_or(Segment::Key), + track, + }, + )) + } +} + +struct WrapVariant<'a, 'b, A> { + inner: A, + parent: &'a Chain<'a>, + segment: Segment, + track: &'b Track, +} + +impl<'de, A: VariantAccess<'de>> VariantAccess<'de> for WrapVariant<'_, '_, A> { + type Error = A::Error; + + fn unit_variant(self) -> Result<(), A::Error> { + let chain = Chain::Step { + parent: self.parent, + segment: self.segment, + }; + let track = self.track; + self.inner + .unit_variant() + .map_err(|error| track.trigger(&chain, error)) + } + + fn newtype_variant_seed>(self, seed: T) -> Result { + let chain = Chain::Step { + parent: self.parent, + segment: self.segment, + }; + let track = self.track; + self.inner + .newtype_variant_seed(WrapSeed { + inner: seed, + chain: &chain, + track, + }) + .map_err(|error| track.trigger(&chain, error)) + } + + fn tuple_variant>(self, len: usize, visitor: V) -> Result { + let chain = Chain::Step { + parent: self.parent, + segment: self.segment, + }; + let track = self.track; + self.inner + .tuple_variant(len, WrapVisitor::new(visitor, &chain, track, None)) + .map_err(|error| track.trigger(&chain, error)) + } + + fn struct_variant>( + self, + fields: &'static [&'static str], + visitor: V, + ) -> Result { + self.track.names(fields); + let chain = Chain::Step { + parent: self.parent, + segment: self.segment, + }; + let track = self.track; + self.inner + .struct_variant( + fields, + WrapVisitor::new(visitor, &chain, track, Some(fields)), + ) + .map_err(|error| track.trigger(&chain, error)) + } +} + +/// Reads a map key or a variant name, and notes which segment it is. +struct KeySeed<'k, S> { + inner: S, + names: Option<&'static [&'static str]>, + key: &'k mut Option, +} + +impl<'de, S: DeserializeSeed<'de>> DeserializeSeed<'de> for KeySeed<'_, S> { + type Value = S::Value; + + fn deserialize>(self, deserializer: D) -> Result { + self.inner.deserialize(KeyDeserializer { + inner: deserializer, + names: self.names, + key: self.key, + }) + } +} + +struct KeyDeserializer<'k, D> { + inner: D, + names: Option<&'static [&'static str]>, + key: &'k mut Option, +} + +macro_rules! forward_key { + ($($method:ident($($arg:ident: $type:ty),*);)*) => {$( + fn $method>(self, $($arg: $type,)* visitor: V) -> Result { + self.inner.$method($($arg,)* KeyVisitor { inner: visitor, names: self.names, key: self.key }) + } + )*}; +} + +impl<'de, D: Deserializer<'de>> Deserializer<'de> for KeyDeserializer<'_, D> { + type Error = D::Error; + + forward_key! { + deserialize_any(); + deserialize_bool(); + deserialize_i8(); + deserialize_i16(); + deserialize_i32(); + deserialize_i64(); + deserialize_i128(); + deserialize_u8(); + deserialize_u16(); + deserialize_u32(); + deserialize_u64(); + deserialize_u128(); + deserialize_f32(); + deserialize_f64(); + deserialize_char(); + deserialize_str(); + deserialize_string(); + deserialize_bytes(); + deserialize_byte_buf(); + deserialize_option(); + deserialize_unit(); + deserialize_unit_struct(name: &'static str); + deserialize_newtype_struct(name: &'static str); + deserialize_seq(); + deserialize_tuple(len: usize); + deserialize_tuple_struct(name: &'static str, len: usize); + deserialize_map(); + deserialize_struct(name: &'static str, fields: &'static [&'static str]); + deserialize_enum(name: &'static str, variants: &'static [&'static str]); + deserialize_identifier(); + deserialize_ignored_any(); + } + + fn is_human_readable(&self) -> bool { + self.inner.is_human_readable() + } +} + +struct KeyVisitor<'k, X> { + inner: X, + names: Option<&'static [&'static str]>, + key: &'k mut Option, +} + +macro_rules! capture_key { + ($($method:ident($type:ty);)*) => {$( + fn $method(self, value: $type) -> Result { + *self.key = Some(Segment::Key); + self.inner.$method(value) + } + )*}; +} + +impl<'de, X: Visitor<'de>> Visitor<'de> for KeyVisitor<'_, X> { + type Value = X::Value; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + self.inner.expecting(formatter) + } + + capture_key! { + visit_bool(bool); + visit_i8(i8); + visit_i16(i16); + visit_i32(i32); + visit_i64(i64); + visit_i128(i128); + visit_u8(u8); + visit_u16(u16); + visit_u32(u32); + visit_u64(u64); + visit_u128(u128); + visit_f32(f32); + visit_f64(f64); + visit_char(char); + visit_bytes(&[u8]); + visit_borrowed_bytes(&'de [u8]); + visit_byte_buf(Vec); + } + + fn visit_str(self, value: &str) -> Result { + *self.key = Some(segment_of(value, self.names)); + self.inner.visit_str(value) + } + + fn visit_borrowed_str(self, value: &'de str) -> Result { + *self.key = Some(segment_of(value, self.names)); + self.inner.visit_borrowed_str(value) + } + + fn visit_string(self, value: String) -> Result { + *self.key = Some(segment_of(&value, self.names)); + self.inner.visit_string(value) + } + + fn visit_none(self) -> Result { + self.inner.visit_none() + } + + fn visit_unit(self) -> Result { + self.inner.visit_unit() + } + + fn visit_some>(self, deserializer: D) -> Result { + self.inner.visit_some(deserializer) + } + + fn visit_newtype_struct>( + self, + deserializer: D, + ) -> Result { + self.inner.visit_newtype_struct(deserializer) + } + + fn visit_seq>(self, seq: A) -> Result { + self.inner.visit_seq(seq) + } + + fn visit_map>(self, map: A) -> Result { + self.inner.visit_map(map) + } + + fn visit_enum>(self, data: A) -> Result { + self.inner.visit_enum(data) + } +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use serde::Deserialize; + use serde_json::json; + + use super::*; + + fn error(value: serde_json::Value) -> Failure { + match read::<_, T>(value, None) { + Err(failure) => failure, + Ok(value) => panic!("read {value:?}"), + } + } + + #[derive(Debug, Deserialize)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] + struct Order { + name: String, + lines: Vec, + totals: BTreeMap, + } + + #[derive(Debug, Deserialize)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] + struct Line { + quantity: u64, + kind: Kind, + } + + #[derive(Debug, Deserialize)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] + enum Kind { + Physical, + Digital { url: String }, + } + + #[test] + fn paths_name_fields_and_hide_keys() { + let failure = error::(json!({ + "name": "#1", + "lines": [{ "quantity": 1, "kind": "Physical" }, { "quantity": "SECRET", "kind": "Physical" }], + "totals": {}, + })); + assert_eq!(failure.path, "lines[1].quantity"); + assert_eq!(failure.message, "invalid type: string, expected u64"); + assert!(failure.detail.contains("SECRET")); + + let failure = error::(json!({ + "name": "#1", + "lines": [], + "totals": { "https://x.test/k?sig=SECRET": "SECRET" }, + })); + assert_eq!(failure.path, "totals[key]"); + assert_eq!(failure.message, "invalid type: string, expected u64"); + + let failure = error::(json!({ + "name": "#1", + "lines": [{ "quantity": 1, "kind": { "Digital": { "url": 3 } } }], + "totals": {}, + })); + assert_eq!(failure.path, "lines[0].kind.Digital.url"); + assert_eq!(failure.message, "invalid type: integer, expected a string"); + } + + #[test] + fn messages_keep_only_names_the_types_give() { + let failure = error::(json!({ "name": "#1", "lines": [] })); + assert_eq!( + (failure.path.as_str(), failure.message.as_str()), + (".", "missing field `totals`") + ); + let failure = error::(json!("shpat_SECRET")); + assert_eq!(failure.message, "unknown variant"); + assert!(failure.detail.contains("shpat_SECRET")); + + #[derive(Debug)] + struct Custom; + impl<'de> Deserialize<'de> for Custom { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + Err(de::Error::custom(format!( + "missing field `{text}` and invalid type: string {text:?}" + ))) + } + } + // Its message starts like serde's: the name it quotes is not a field's. + let failure = error::(json!("shpat_SECRET")); + assert_eq!(failure.message, "missing field"); + let failure = error::(json!("\"\\\"shpat_SECRET\\\"")); + assert!(!failure.message.contains("SECRET")); + } + + #[test] + fn text_errors_give_a_position_and_no_text() { + let failure = from_slice::(br#"{"name": "shpat_SECRET" "#) + .err() + .unwrap(); + assert_eq!( + failure.message, + "EOF while parsing an object at line 1 column 24" + ); + let failure = from_slice::(br#"{"name": shpat_SECRET}"#) + .err() + .unwrap(); + assert_eq!(failure.message, "expected value at line 1 column 10"); + let failure = from_slice::(b"1 shpat").err().unwrap(); + assert_eq!(failure.message, "trailing characters at line 1 column 3"); + } +} diff --git a/crates/shopify_api/src/error.rs b/crates/shopify_api/src/error.rs new file mode 100644 index 0000000..d9230e8 --- /dev/null +++ b/crates/shopify_api/src/error.rs @@ -0,0 +1,1391 @@ +//! The error of every fallible call of this crate. + +use std::fmt; + +use crate::bulk::BulkOperation; +use crate::graphql::{Cost, GraphqlError, InvalidValueReason, UserError}; +use crate::transport::{HttpResponse, TransportError}; + +/// `Result`. +pub type Result = std::result::Result; + +/// What went wrong, with what Shopify said about it. +/// +/// # What an error shows +/// +/// What an error displays (`Display`, `Debug`, `{:#?}`) and what its +/// [`source`](std::error::Error::source) chain displays is written by this +/// crate. Text the crate does not control is not put in it, whatever it +/// looks like: +/// +/// - no body of an answer: [`Error::Http`] shows the status, the address, +/// the kind of content and the length of the body; +/// - no value of an answer, no map key, no message of serde: +/// [`Error::Decode`] says what kind of mismatch it is (`invalid type: +/// string, expected u64`, ``missing field `id` ``, `unknown variant`, a +/// JSON syntax error), where (the line and column of a text), and the path to +/// it, made of the names of the fields and variants the Rust type declares +/// and of indexes; a map key, or a name the type does not declare, is +/// `[key]`; +/// - nothing of what a `Serialize` implementation wrote: [`Error::Variables`] +/// says which variable does not serialize, and why in this crate's words; +/// - no value of a variable: [`Error::InvalidValue`] says where the value +/// stands and why it is refused; +/// - of an address, the scheme, the host and the path only: no user, no +/// password, no query string (a signature), no fragment; +/// - of the token endpoint's refusal, its status and its standard OAuth error +/// code; +/// - no shop domain or API version that does not validate: a token given in +/// their place is not shown; +/// - of the partial `data` of a GraphQL error, and of its `extensions` but +/// `code`, how many entries there are: no name, no value; +/// - of a bulk operation, its ID when it is a `gid://` of Shopify, a status +/// or error code this crate knows, and which count does not read as a +/// number, not the count; +/// - the name of a variable when it is a GraphQL name, and the names of the +/// fields, variants and types your Rust types declare. +/// +/// What is shown as is, because this crate does not write it: the +/// `message`, `path`, `locations` and `extensions.code` of Shopify's +/// `errors`, and the `field`, `message` and `code` of its `userErrors`, which +/// Shopify writes for people (a message may quote a part of a variable that +/// does not validate); the error of your +/// [`Transport`](crate::transport::Transport) (the default transport's leaves +/// the address out) and of your [`TokenStore`](crate::TokenStore), and the +/// `source` chain of either. +/// +/// # What stays available +/// +/// The text that is not shown stays available to code that asks for it, +/// through accessors that say so: [`Error::raw_http_body`], +/// [`Error::sensitive_detail`] (serde's message, a `Serialize` +/// implementation's, the token endpoint's answer), [`GraphqlErrors::data`], +/// [`GraphqlError::extensions`], and the fields of the variants. +/// They may hold secrets: do not log them. +#[non_exhaustive] +pub enum Error { + /// Not a shop's handle or `myshopify.com` domain. The text is the one + /// given; it is not shown, in case it is a token given in its place. + InvalidShop(String), + + /// Not an API version this crate supports. `version` is shown only when + /// it is written `YYYY-MM`. + #[non_exhaustive] + InvalidApiVersion { version: String, reason: String }, + + /// The request did not reach Shopify, or its answer did not arrive. + #[non_exhaustive] + Transport { + /// The address, without its user, query string and fragment. + url: String, + source: TransportError, + }, + + /// Shopify answered with a status other than 2xx. + #[non_exhaustive] + Http { + status: u16, + /// The address, without its user, query string and fragment. + url: String, + /// The `Content-Type` of the answer, as it was received. `Display` + /// and `Debug` show it only when it is a common type. + content_type: Option, + /// Shopify's `X-Request-Id`, which its support asks for. `Debug` + /// shows it when it is made of hexadecimal digits and dashes. + request_id: Option, + /// The whole body, as it was received; of a bulk download, its first + /// MiB. It may hold secrets: read it with [`Error::raw_http_body`]. + /// Its `Debug` shows its length only. + raw_body: RawBody, + }, + + /// The answer has a non-empty `errors` list. + Graphql(GraphqlErrors), + + /// Shopify still throttled the request after the retries of the client's + /// [`RetryPolicy`](crate::RetryPolicy). + #[non_exhaustive] + Throttled { + retries: u32, + cost: Option, + /// The wait the `Retry-After` of the last `429` asked for, if any. + retry_after: Option, + }, + + /// A JSON text, or the `data` of an answer, that does not fit the type + /// it is read as: the shop runs another API version than the schema the + /// operation was checked against, a test scripts an answer without a + /// non-null field, a body is not JSON. + /// + /// `path` and `message` are written by this crate (see [`Error`]); + /// serde's own message is in `detail`. + #[non_exhaustive] + Decode { + /// The fields and variants the type declares, indexes, and `[key]` + /// for anything else; `.` for the whole value. + path: String, + message: String, + /// serde's message: it may quote the value. See + /// [`Error::sensitive_detail`]. + detail: Option, + }, + + /// Variables that do not serialize, or not to an object. + #[non_exhaustive] + Variables { + message: String, + /// The message of the `Serialize` implementation that failed: it may + /// quote the value. See [`Error::sensitive_detail`]. + detail: Option, + }, + + /// A value of a variable that Shopify would not read as it was + /// written, refused before anything is sent: a `Float` that is NaN or + /// infinite (JSON writes it as `null`), an `Int` outside of 32 bits, a + /// top-level `null` for a non-null `JSON`, or a value that does not + /// serialize. [`input!`](crate::input!), the values of + /// [`graphql!`](crate::graphql!) and [`Operation::variable`](crate::Operation::variable) + /// keep it when the value is built; the operation fails with it when it + /// is sent or its body is read. + #[non_exhaustive] + InvalidValue { + /// Where the value stands: the variable, then the fields and + /// indexes of the schema, `$product.metafields[2].value`. A variable + /// whose name is not a GraphQL name is `$[variable]`. + path: String, + reason: InvalidValueReason, + /// The message of the `Serialize` implementation that failed: it may + /// quote the value. See [`Error::sensitive_detail`]. + detail: Option, + }, + + /// A token could not be obtained or renewed. + /// + /// When the token endpoint refused the request, `status` and + /// `oauth_code` say how, so that a caller can tell a refusal that will + /// last (a `4xx` with an OAuth error code, `invalid_client`, + /// `shop_not_permitted`…) from one that passes (a `5xx`, `408`, `429`, or + /// no code) without reading the message: + /// + /// ``` + /// # use shopify_api::Error; + /// fn lasts(error: &Error) -> bool { + /// matches!( + /// (error.token_endpoint_status(), error.oauth_code()), + /// (Some(status @ 400..=499), Some(_)) if status != 408 && status != 429 + /// ) + /// } + /// ``` + #[non_exhaustive] + Auth { + message: String, + /// What the token endpoint said, or serde's message about its + /// answer. See [`Error::sensitive_detail`]. + detail: Option, + /// The HTTP status of the token endpoint's refusal. `None` when the + /// error is not a refusal: an answer that does not read as a token, + /// a network failure, no refresh token, a renewal that panicked. + status: Option, + /// The OAuth `error` code of the token endpoint's refusal, when its + /// body has one. `None` when the body has none (a `5xx` page, text) + /// or the error is not a refusal. + oauth_code: Option, + /// `true` when the renewal that failed was another request's: this + /// request waited for it, or came within the few seconds a failure + /// is the answer of every request instead of asking Shopify again. + /// `status` and `oauth_code` are those of that renewal; `detail` is + /// `None`. + held: bool, + }, + + /// A mutation that this crate runs for you returned `userErrors`. + #[non_exhaustive] + UserErrors { + mutation: &'static str, + errors: Vec, + }, + + /// A bulk operation failed, or its answer misses what was expected. + #[non_exhaustive] + Bulk { + message: String, + /// The operation as Shopify last reported it, when it ended without + /// completing: its `error_code`, its `partial_data_url`. `Debug` + /// shows its ID, status and error code as `message` does. + operation: Option>, + }, + + /// A wait ran out. + #[non_exhaustive] + Timeout { + message: String, + /// The bulk operation waited for, which keeps running: to cancel it + /// with [`Shopify::cancel_bulk_operation`](crate::Shopify::cancel_bulk_operation). + /// `Debug` shows it when it is a `gid://` of Shopify. + id: Option, + }, + + /// The [`TokenStore`](crate::TokenStore) of the client failed to save a + /// renewed token. The client holds the new token all the same. + TokenStore(Box), + + /// The client has no transport: enable the `rustls` or `native-tls` + /// feature, or give one with [`ShopifyBuilder::transport`](crate::ShopifyBuilder::transport). + NoTransport, + + /// A webhook, an OAuth callback, an app proxy request or a session token + /// that does not verify. + Verification(String), + + /// A client that cannot be set up, such as a transport that does not start. + Config(String), +} + +impl fmt::Display for Error { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidShop(_) => formatter + .write_str("invalid shop: expected `` or `.myshopify.com`"), + Self::InvalidApiVersion { version, reason } => match shown_version(version) { + Some(version) => write!(formatter, "invalid API version `{version}`: {reason}"), + None => write!(formatter, "invalid API version: {reason}"), + }, + Self::Transport { url, source } => write!(formatter, "request to {url} failed: {source}"), + Self::Http { + status, + url, + content_type, + raw_body, + .. + } => write!( + formatter, + "Shopify answered {status} to {url} ({}, {} bytes)", + shown_content_type(content_type.as_deref()), + raw_body.0.len() + ), + Self::Graphql(errors) => write!(formatter, "GraphQL errors: {errors}"), + Self::Throttled { retries, .. } => { + write!(formatter, "throttled by Shopify after {retries} retries") + } + Self::Decode { path, message, .. } => write!( + formatter, + "Shopify's answer does not match the operation at `{path}`: {message}" + ), + Self::Variables { message, .. } => write!(formatter, "invalid variables: {message}"), + Self::InvalidValue { path, reason, .. } => { + write!(formatter, "invalid value at `{path}`: {reason}") + } + Self::Auth { message, .. } => write!(formatter, "authentication failed: {message}"), + Self::UserErrors { mutation, errors } => { + write!(formatter, "{mutation} refused: {}", UserErrors(errors)) + } + Self::Bulk { message, .. } => write!(formatter, "bulk operation: {message}"), + Self::Timeout { message, .. } => write!(formatter, "timed out: {message}"), + Self::TokenStore(error) => write!(formatter, "the token store failed: {error}"), + Self::NoTransport => formatter.write_str( + "no HTTP transport: enable the `rustls` or `native-tls` feature, or set one with `ShopifyBuilder::transport`", + ), + Self::Verification(message) => write!(formatter, "verification failed: {message}"), + Self::Config(message) => write!(formatter, "configuration: {message}"), + } + } +} + +impl fmt::Debug for Error { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidShop(shop) => formatter + .debug_tuple("InvalidShop") + .field(&format_args!("[{} bytes]", shop.len())) + .finish(), + Self::InvalidApiVersion { version, reason } => formatter + .debug_struct("InvalidApiVersion") + .field( + "version", + &shown_version(version).map_or_else( + || format!("[{} bytes]", version.len()), + |version| format!("{version:?}"), + ), + ) + .field("reason", reason) + .finish(), + Self::Transport { url, source } => formatter + .debug_struct("Transport") + .field("url", url) + .field("source", source) + .finish(), + Self::Http { + status, + url, + content_type, + request_id, + raw_body, + } => formatter + .debug_struct("Http") + .field("status", status) + .field("url", url) + .field( + "content_type", + &content_type + .as_deref() + .map(|content_type| shown_content_type(Some(content_type))), + ) + .field( + "request_id", + &request_id + .as_deref() + .map(|id| if is_request_id(id) { id } else { "[not shown]" }), + ) + .field("raw_body", raw_body) + .finish(), + Self::Graphql(errors) => formatter.debug_tuple("Graphql").field(errors).finish(), + Self::Throttled { + retries, + cost, + retry_after, + } => formatter + .debug_struct("Throttled") + .field("retries", retries) + .field("cost", cost) + .field("retry_after", retry_after) + .finish(), + Self::Decode { + path, + message, + detail, + } => formatter + .debug_struct("Decode") + .field("path", path) + .field("message", message) + .field("detail", detail) + .finish(), + Self::Variables { message, detail } => formatter + .debug_struct("Variables") + .field("message", message) + .field("detail", detail) + .finish(), + Self::InvalidValue { + path, + reason, + detail, + } => formatter + .debug_struct("InvalidValue") + .field("path", path) + .field("reason", reason) + .field("detail", detail) + .finish(), + Self::Auth { + message, + detail, + status, + oauth_code, + held, + } => formatter + .debug_struct("Auth") + .field("message", message) + .field("detail", detail) + .field("status", status) + .field("oauth_code", oauth_code) + .field("held", held) + .finish(), + Self::UserErrors { mutation, errors } => formatter + .debug_struct("UserErrors") + .field("mutation", mutation) + .field("errors", errors) + .finish(), + Self::Bulk { message, operation } => formatter + .debug_struct("Bulk") + .field("message", message) + .field( + "operation", + &operation.as_deref().map(crate::bulk::ShownOperation), + ) + .finish(), + Self::Timeout { message, id } => formatter + .debug_struct("Timeout") + .field("message", message) + .field("id", &id.as_deref().map(crate::bulk::shown_id)) + .finish(), + Self::TokenStore(error) => formatter.debug_tuple("TokenStore").field(error).finish(), + Self::NoTransport => formatter.write_str("NoTransport"), + Self::Verification(message) => formatter + .debug_tuple("Verification") + .field(message) + .finish(), + Self::Config(message) => formatter.debug_tuple("Config").field(message).finish(), + } + } +} + +impl std::error::Error for Error { + /// The transport's error, or the token store's: no other error is kept, + /// so that none shows what [`Error`] does not. + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Transport { source, .. } => Some(source), + Self::TokenStore(error) => Some(error.as_ref()), + _ => None, + } + } +} + +/// `version` when it is written `YYYY-MM`: digits cannot be a token. +fn shown_version(version: &str) -> Option<&str> { + crate::version::is_dated(version).then_some(version) +} + +/// The kind of content of an answer, from this crate's list. +fn shown_content_type(content_type: Option<&str>) -> &'static str { + const KNOWN: [&str; 11] = [ + "application/json", + "application/graphql-response+json", + "application/problem+json", + "application/jsonl", + "application/x-ndjson", + "application/xml", + "application/octet-stream", + "text/xml", + "text/html", + "text/plain", + "text/csv", + ]; + let Some(content_type) = content_type else { + return "no content type"; + }; + let essence = content_type.split(';').next().unwrap_or_default().trim(); + KNOWN + .iter() + .find(|known| known.eq_ignore_ascii_case(essence)) + .copied() + .unwrap_or("another content type") +} + +/// An `X-Request-Id` as Shopify writes them: hexadecimal digits and dashes. +fn is_request_id(id: &str) -> bool { + (1..=64).contains(&id.len()) + && id + .bytes() + .all(|byte| byte.is_ascii_hexdigit() || byte == b'-') +} + +impl Error { + /// The HTTP status Shopify answered with, for [`Error::Http`]. + pub fn status(&self) -> Option { + match self { + Self::Http { status, .. } => Some(*status), + _ => None, + } + } + + /// Shopify refused the access token: `401`. + pub fn is_unauthorized(&self) -> bool { + self.status() == Some(401) + } + + /// The request ID Shopify gave, for [`Error::Http`]. + pub fn request_id(&self) -> Option<&str> { + match self { + Self::Http { request_id, .. } => request_id.as_deref(), + _ => None, + } + } + + /// The body of the answer, for [`Error::Http`], exactly as it was + /// received: the whole body, or the first MiB of a bulk download. + /// + /// **It may contain secrets** (a token, a signed address): do not log it + /// or show it to a user. + pub fn raw_http_body(&self) -> Option<&[u8]> { + match self { + Self::Http { raw_body, .. } => Some(raw_body.as_bytes()), + _ => None, + } + } + + /// The text this crate does not show, for [`Error::Decode`] (serde's + /// message), [`Error::Variables`] and [`Error::InvalidValue`] (the + /// message of the `Serialize` implementation that failed) and + /// [`Error::Auth`] (what the token endpoint said). + /// + /// **It may contain secrets**: serde quotes the value that does not fit, + /// a map key, or what a type's own implementation wrote, and a token + /// endpoint may echo what it was sent. Do not log it or show it to a user. + pub fn sensitive_detail(&self) -> Option<&str> { + match self { + Self::Decode { detail, .. } + | Self::Variables { detail, .. } + | Self::InvalidValue { detail, .. } + | Self::Auth { detail, .. } => detail.as_ref().map(SensitiveDetail::as_str), + _ => None, + } + } + + /// The HTTP status of the token endpoint's refusal, for [`Error::Auth`]. + /// `None` for an [`Error::Auth`] that is not a refusal, and for any + /// other variant (the status of [`Error::Http`] is its `status` field). + pub fn token_endpoint_status(&self) -> Option { + match self { + Self::Auth { status, .. } => *status, + _ => None, + } + } + + /// The OAuth `error` code of the token endpoint's refusal, for + /// [`Error::Auth`], when its body has one. + pub fn oauth_code(&self) -> Option { + match self { + Self::Auth { oauth_code, .. } => *oauth_code, + _ => None, + } + } + + /// Whether this [`Error::Auth`] is the failure of a renewal another + /// request ran, handed to this one (see the `held` field). + pub fn is_held_auth_failure(&self) -> bool { + matches!(self, Self::Auth { held: true, .. }) + } + + /// The errors Shopify returned, for [`Error::Graphql`]. + pub fn graphql_errors(&self) -> &[GraphqlError] { + match self { + Self::Graphql(errors) => &errors.errors, + _ => &[], + } + } + + pub(crate) fn transport(url: &str, source: TransportError) -> Self { + Self::Transport { + url: without_query(url), + source, + } + } + + /// The error of an answer that is not a success. + pub(crate) fn http(url: &str, response: &HttpResponse) -> Self { + Self::Http { + status: response.status, + url: without_query(url), + content_type: response.header("Content-Type").map(str::to_string), + request_id: response.header("X-Request-Id").map(str::to_string), + raw_body: RawBody(response.body.clone()), + } + } + + /// An error body that did not come with an [`HttpResponse`]. + pub(crate) fn http_parts(status: u16, url: &str, body: &[u8]) -> Self { + Self::Http { + status, + url: without_query(url), + content_type: None, + request_id: None, + raw_body: RawBody(body.to_vec()), + } + } + + /// An answer that does not fit its type. `message` is this crate's; + /// `detail` is not shown. + pub(crate) fn decode(path: impl Into, message: String, detail: Option) -> Self { + Self::Decode { + path: path.into(), + message, + detail: detail.map(SensitiveDetail), + } + } + + /// Variables that do not serialize: `variable` is the name of the one + /// that failed, when the failure is one variable's. + pub(crate) fn variables(variable: Option<&str>, error: &serde_json::Error) -> Self { + let what = match variable { + Some(name) if is_graphql_name(name) => format!("variable `${name}` does"), + Some(_) => "a variable does".to_string(), + None => "the variables do".to_string(), + }; + // serde_json's own message about a map key does not quote it; any + // other is the `Serialize` implementation's, and may quote the value. + let why = if error.to_string().starts_with("key must be a string") { + "a map key is not a string" + } else { + "a value's `Serialize` implementation failed" + }; + Self::Variables { + message: format!("{what} not serialize: {why}"), + detail: Some(SensitiveDetail(error.to_string())), + } + } + + /// Variables that serialize to something else than an object. + pub(crate) fn variables_not_an_object() -> Self { + Self::Variables { + message: "the variables must serialize to an object".to_string(), + detail: None, + } + } + + pub(crate) fn auth(message: impl Into) -> Self { + Self::Auth { + message: message.into(), + detail: None, + status: None, + oauth_code: None, + held: false, + } + } + + pub(crate) fn auth_with_detail(message: impl Into, detail: String) -> Self { + Self::Auth { + message: message.into(), + detail: Some(SensitiveDetail(detail)), + status: None, + oauth_code: None, + held: false, + } + } + + /// The token endpoint refused the request with `status`. + pub(crate) fn auth_refused( + message: String, + detail: String, + status: u16, + oauth_code: Option, + ) -> Self { + Self::Auth { + message, + detail: Some(SensitiveDetail(detail)), + status: Some(status), + oauth_code, + held: false, + } + } +} + +/// The OAuth `error` code of a token endpoint's refusal: those of RFC 6749 +/// (5.2) and Shopify's, in [`Error::Auth`]. +/// +/// A code this crate does not know is [`Other`](Self::Other), without its +/// text: the endpoint wrote it, and it is in [`Error::sensitive_detail`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum OAuthErrorCode { + /// `shop_not_permitted`: the app may not ask this shop for a token + /// (client credentials on a shop of another organization). + ShopNotPermitted, + /// `invalid_request` + InvalidRequest, + /// `invalid_client`: the client ID or secret is wrong. + InvalidClient, + /// `invalid_grant`: the code, refresh token or credentials do not hold. + InvalidGrant, + /// `unauthorized_client` + UnauthorizedClient, + /// `unsupported_grant_type` + UnsupportedGrantType, + /// `invalid_scope` + InvalidScope, + /// `invalid_subject_token`: the session token of a token exchange. + InvalidSubjectToken, + /// A code this crate does not know. + Other, +} + +impl OAuthErrorCode { + const KNOWN: [(&'static str, Self); 8] = [ + ("shop_not_permitted", Self::ShopNotPermitted), + ("invalid_request", Self::InvalidRequest), + ("invalid_client", Self::InvalidClient), + ("invalid_grant", Self::InvalidGrant), + ("unauthorized_client", Self::UnauthorizedClient), + ("unsupported_grant_type", Self::UnsupportedGrantType), + ("invalid_scope", Self::InvalidScope), + ("invalid_subject_token", Self::InvalidSubjectToken), + ]; + + /// The code as the endpoint writes it; `None` for [`Other`](Self::Other). + pub fn as_str(self) -> Option<&'static str> { + Self::KNOWN + .iter() + .find(|(_, code)| *code == self) + .map(|(text, _)| *text) + } + + pub(crate) fn parse(text: &str) -> Self { + Self::KNOWN + .iter() + .find(|(known, _)| *known == text) + .map_or(Self::Other, |(_, code)| *code) + } +} + +impl fmt::Display for OAuthErrorCode { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str( + self.as_str() + .unwrap_or("an error code this crate does not know"), + ) + } +} + +/// A GraphQL name: what a variable is called in an operation. +pub(crate) fn is_graphql_name(name: &str) -> bool { + let mut bytes = name.bytes(); + bytes + .next() + .is_some_and(|first| first == b'_' || first.is_ascii_alphabetic()) + && bytes.all(|byte| byte == b'_' || byte.is_ascii_alphanumeric()) +} + +/// The body of an answer exactly as it was received, in [`Error::Http`]. +/// +/// **It may contain secrets.** Its `Debug` shows its length, not its content. +#[derive(Clone, PartialEq, Eq, Default)] +pub struct RawBody(Vec); + +impl RawBody { + /// The bytes of the body. They may contain secrets: do not log them. + pub fn as_bytes(&self) -> &[u8] { + &self.0 + } +} + +impl fmt::Debug for RawBody { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "RawBody([{} bytes])", self.0.len()) + } +} + +/// A message this crate does not show: serde's, a `Serialize` +/// implementation's, a token endpoint's. See [`Error::sensitive_detail`]. +/// +/// **It may contain secrets.** Its `Debug` shows its length, not its content, +/// and it has no `Display`. +#[derive(Clone, PartialEq, Eq)] +pub struct SensitiveDetail(String); + +impl SensitiveDetail { + pub(crate) fn new(detail: String) -> Self { + Self(detail) + } + + /// The message. It may contain secrets: do not log it. + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Debug for SensitiveDetail { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "SensitiveDetail([{} bytes])", self.0.len()) + } +} + +/// `url` without its user, password, query string and fragment, which may +/// hold a credential. +pub(crate) fn without_query(url: &str) -> String { + let url = url.split(['?', '#']).next().unwrap_or_default(); + let Some((scheme, rest)) = url.split_once("://") else { + return url.to_string(); + }; + let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len())); + let host = authority + .rsplit_once('@') + .map_or(authority, |(_, host)| host); + format!("{scheme}://{host}{path}") +} + +/// The `errors` of a GraphQL answer, and its `data` when it had some. +/// +/// Its `Debug` shows how many entries `data` has, not their names or values, +/// which may be secret: the signed address of a bulk operation's results. +#[derive(Clone)] +#[non_exhaustive] +pub struct GraphqlErrors { + pub errors: Vec, + /// GraphQL may answer part of a query and fail another part. + pub data: Option, +} + +impl fmt::Debug for GraphqlErrors { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("GraphqlErrors") + .field("errors", &self.errors) + .field("data", &self.data.as_ref().map(DataShape)) + .finish() + } +} + +/// How many entries partial `data` has: its keys are the answer's too. +struct DataShape<'a>(&'a serde_json::Value); + +impl fmt::Debug for DataShape<'_> { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0 { + serde_json::Value::Object(fields) => write!(formatter, "{{{} entries}}", fields.len()), + serde_json::Value::Null => formatter.write_str("null"), + _ => formatter.write_str(".."), + } + } +} + +impl fmt::Display for GraphqlErrors { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + for (index, error) in self.errors.iter().enumerate() { + if index > 0 { + formatter.write_str("; ")?; + } + formatter.write_str(&error.message)?; + if let Some(code) = error.code() { + write!(formatter, " ({code})")?; + } + } + Ok(()) + } +} + +struct UserErrors<'a>(&'a [UserError]); + +impl fmt::Display for UserErrors<'_> { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + for (index, error) in self.0.iter().enumerate() { + if index > 0 { + formatter.write_str("; ")?; + } + if let Some(field) = error.field.as_ref().filter(|field| !field.is_empty()) { + write!(formatter, "{}: ", field.join("."))?; + } + formatter.write_str(&error.message)?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use serde::{Deserialize, Serialize}; + use serde_json::{Value, json}; + + use super::*; + use crate::transport::{BoxFuture, HttpRequest, Transport}; + + /// A token of Shopify's shape, written in two parts so that secret + /// scanners do not take this file for a leak. + const TOKEN: &str = concat!("shpat", "_0123456789abcdef0123456789abcdef"); + /// `TOKEN`, each character a JSON `\u` escape. + fn escaped_token() -> String { + TOKEN + .chars() + .map(|c| format!("\\u{:04x}", c as u32)) + .collect() + } + /// What no error may show: the token, the parts of a signed address, a + /// JSON-escaped token, a token in escaped quotes, a map key. + fn secrets() -> Vec { + vec![ + TOKEN.to_string(), + "SIGNED_SECRET".to_string(), + "USERINFO_SECRET".to_string(), + escaped_token(), + "\\u0073\\u0068".to_string(), + "QUOTED_SECRET".to_string(), + "MAPKEY_SECRET".to_string(), + "storage.test/k?".to_string(), + ] + } + const SIGNED_URL: &str = + "https://me:USERINFO_SECRET@storage.test/k?sig=SIGNED_SECRET#SIGNED_SECRET"; + + /// A body that holds every secret, in every form a body may hold it. + fn secret_body() -> String { + format!( + "{{\"access_token\":\t\"{TOKEN}\",\n\"client_secret\":\n\"QUOTED_SECRET\",\ + \"url\":\"https:\\/\\/storage.test/k?a=1\\u0026sig=SIGNED_SECRET\",\ + \"echo\":\"{}\",\"q\":\"\\\"QUOTED_SECRET\\\"\",\ + \"https://storage.test/k?sig=MAPKEY_SECRET\":1}}\nX-Shopify-Access-Token:\t{TOKEN}", + escaped_token() + ) + } + + /// Every way `error` is shown, its sources' included. + fn shown(error: &Error) -> String { + let mut shown = format!("{error}\n{error:?}\n{error:#?}"); + let mut source = std::error::Error::source(error); + while let Some(cause) = source { + shown.push_str(&format!("\n{cause}\n{cause:?}\n{cause:#?}")); + source = cause.source(); + } + shown + } + + fn assert_hides_secrets(name: &str, error: &Error) { + let shown = shown(error); + for secret in secrets() { + assert!(!shown.contains(&secret), "{name} shows {secret}:\n{shown}"); + } + // Not even decoded from JSON escapes. + assert!(!shown.contains("shpat_"), "{name}:\n{shown}"); + } + + /// A `Serialize` and a `Deserialize` whose own message quotes a token in + /// escaped quotes. + struct Leaky; + + impl Serialize for Leaky { + fn serialize(&self, _: S) -> Result { + Err(serde::ser::Error::custom(format!( + "cannot serialize {:?}", + format!("\"{TOKEN}\" QUOTED_SECRET") + ))) + } + } + + impl<'de> Deserialize<'de> for Leaky { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Err(serde::de::Error::custom(format!( + "cannot parse value {value:?}" + ))) + } + } + + /// A token endpoint that answers `body` with `status`. + struct Answer(u16, String); + + impl Transport for Answer { + fn send(&self, _: HttpRequest) -> BoxFuture<'_, Result> { + let response = HttpResponse::new(self.0, self.1.clone().into_bytes()); + Box::pin(async move { Ok(response) }) + } + } + + fn token_endpoint(status: u16, body: String) -> Error { + let shop = crate::ShopDomain::new("a-shop").unwrap(); + let transport = Answer(status, body); + let future = + crate::auth::request_token(&transport, &shop, "test", crate::auth::Encoding::Form, &[]); + tokio::runtime::Builder::new_current_thread() + .build() + .unwrap() + .block_on(future) + .unwrap_err() + } + + /// Every variant, built the way the crate builds it, from input that + /// holds secrets: none is shown by `Display`, `Debug`, `{:#?}` or the + /// `source` chain. + #[test] + fn no_variant_shows_a_secret() { + let body = secret_body(); + let mut errors: Vec<(&str, Error)> = Vec::new(); + + errors.push(("InvalidShop", crate::ShopDomain::new(TOKEN).unwrap_err())); + errors.push(( + "InvalidApiVersion", + crate::ApiVersion::new(TOKEN).unwrap_err(), + )); + errors.push(( + "Transport", + Error::transport(SIGNED_URL, TransportError::timeout("timed out")), + )); + errors.push(( + "Http", + Error::http( + SIGNED_URL, + &HttpResponse::new(400, body.clone()) + .with_header("Content-Type", format!("text/{TOKEN}")) + .with_header("X-Request-Id", TOKEN), + ), + )); + errors.push(( + "Graphql", + Error::Graphql(GraphqlErrors { + errors: serde_json::from_value(json!([{ + "message": "Variable $url is invalid", + "path": ["bulkOperation"], + "extensions": { + "code": "INVALID_VARIABLE", + "value": format!("https://storage.test/k?sig=SIGNED_SECRET {TOKEN}"), + "https://storage.test/k?sig=MAPKEY_SECRET": 1, + }, + }])) + .unwrap(), + data: Some(json!({ + "https://storage.test/k?sig=MAPKEY_SECRET": TOKEN, + "bulkOperation": { "url": "https://storage.test/k?sig=SIGNED_SECRET" }, + })), + }), + )); + errors.push(( + "Throttled", + Error::Throttled { + retries: 3, + cost: None, + retry_after: None, + }, + )); + // Decode: a map key, a value, a value in escaped quotes, JSON escapes, + // invalid JSON around a token, JSONL. + let raw = crate::RawResponse { + data: Some(json!({ "https://storage.test/k?sig=MAPKEY_SECRET": "SIGNED_SECRET" })), + ..Default::default() + }; + errors.push(( + "Decode map key", + raw.data_as::>().unwrap_err(), + )); + errors.push(( + "Decode escaped quotes", + crate::decode::from_value::(json!(format!("\"{TOKEN}\\\" QUOTED_SECRET"))) + .err() + .unwrap(), + )); + errors.push(( + "Decode JSON escapes", + crate::bulk::parse_jsonl::>( + format!( + "{{\"https://storage.test/k?sig=MAPKEY_SECRET\":\"{}\"}}", + escaped_token() + ) + .as_bytes(), + ) + .unwrap_err(), + )); + errors.push(( + "Decode invalid JSON", + crate::decode::from_slice::(body.as_bytes()) + .err() + .unwrap() + .into_error(), + )); + errors.push(( + "Bulk count", + crate::bulk::operation_of(&json!({ + "id": "gid://shopify/BulkOperation/1", + "type": "QUERY", + "status": "COMPLETED", + "errorCode": null, + "createdAt": "2026-01-01T00:00:00Z", + "completedAt": null, + "objectCount": format!("https://storage.test/k?sig=SIGNED_SECRET {TOKEN}"), + "rootObjectCount": "0", + "fileSize": null, + "url": null, + "partialDataUrl": null, + "query": "{ shop { id } }", + })) + .unwrap_err(), + )); + let mut operation = crate::bulk::operation_of(&json!({ + "id": TOKEN, + "type": "QUERY", + "status": TOKEN, + "errorCode": TOKEN, + "createdAt": "2026-01-01T00:00:00Z", + "completedAt": null, + "objectCount": "1", + "rootObjectCount": "1", + "fileSize": null, + "url": SIGNED_URL, + "partialDataUrl": null, + "query": "{ shop { id } }", + })) + .unwrap(); + errors.push(("Bulk ended", crate::bulk::not_completed(operation.clone()))); + operation.id = format!("gid://shopify/BulkOperation/{TOKEN}"); + errors.push(( + "Bulk ended, odd id", + crate::bulk::not_completed(operation.clone()), + )); + errors.push(( + "Timeout", + crate::bulk::timed_out(TOKEN, std::time::Duration::from_secs(1)), + )); + // Variables: the three ways in, one path. + errors.push(( + "Variables of an operation", + crate::graphql::Operation::::new("query { shop { id } }") + .variables(BTreeMap::from([("x", Leaky)])) + .body() + .unwrap_err(), + )); + errors.push(( + "Variables, one", + crate::graphql::Operation::::new("query { shop { id } }") + .json_variable("x", Leaky) + .body() + .unwrap_err(), + )); + errors.push(( + "Variables, one with an odd name", + crate::graphql::Operation::::new("query { shop { id } }") + .json_variable(&format!("{TOKEN}\""), Leaky) + .body() + .unwrap_err(), + )); + errors.push(( + "InvalidValue", + crate::graphql::Operation::::new("query { shop { id } }") + .variable::(&format!("{TOKEN}\""), f64::NAN) + .body() + .unwrap_err(), + )); + errors.push(( + "InvalidValue, does not serialize", + crate::graphql::Operation::::new("query { shop { id } }") + .__literal_variable( + "x", + Err(crate::graphql::check::Invalid::unserializable( + &serde_json::to_value(Leaky).unwrap_err(), + )), + ) + .body() + .unwrap_err(), + )); + errors.push(( + "Variables of graphql_raw", + crate::graphql::operation::variables_of(BTreeMap::from([("x", Leaky)])).unwrap_err(), + )); + // Auth: a refusal that echoes the request, a token that does not read. + errors.push(( + "Auth refused", + token_endpoint( + 400, + json!({ "error": TOKEN, "error_description": body }).to_string(), + ), + )); + errors.push(("Auth refused, not JSON", token_endpoint(401, body.clone()))); + errors.push(( + "Auth invalid token", + token_endpoint( + 200, + json!({ "access_token": 1, "scope": [TOKEN] }).to_string(), + ), + )); + errors.push(( + "Auth invalid JSON", + token_endpoint(200, format!("{{\"access_token\": \"{TOKEN}\" ")), + )); + errors.push(( + "UserErrors", + Error::UserErrors { + mutation: "bulkOperationRunQuery", + errors: vec![UserError { + field: Some(vec!["query".to_string()]), + message: "Invalid query".to_string(), + code: None, + }], + }, + )); + errors.push(("NoTransport", Error::NoTransport)); + errors.push(("TokenStore", Error::TokenStore("the disk is full".into()))); + errors.push(( + "Config", + Error::Config("the HTTP client does not start".to_string()), + )); + #[cfg(feature = "webhooks")] + { + use base64::Engine; + use hmac::{KeyInit, Mac}; + let body = b"{}"; + let mut mac = hmac::Hmac::::new_from_slice(b"secret").unwrap(); + mac.update(body); + let signature = + base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes()); + let headers = [ + ("X-Shopify-Hmac-Sha256", signature.as_str()), + ("X-Shopify-Shop-Domain", TOKEN), + ("X-Shopify-Topic", "orders/create"), + ]; + errors.push(( + "Verification", + crate::webhooks::Webhook::verify(headers, body.to_vec(), "secret").unwrap_err(), + )); + } + + for (name, error) in &errors { + assert_hides_secrets(name, error); + } + // Each variant is there: a new one needs a case. + let mut variants: Vec<&str> = errors.iter().map(|(_, error)| variant(error)).collect(); + variants.sort_unstable(); + variants.dedup(); + let mut expected = vec![ + "Auth", + "Bulk", + "Config", + "Decode", + "Graphql", + "Http", + "InvalidApiVersion", + "InvalidShop", + "InvalidValue", + "NoTransport", + "Throttled", + "Timeout", + "TokenStore", + "Transport", + "UserErrors", + "Variables", + ]; + if cfg!(feature = "webhooks") { + expected.push("Verification"); + expected.sort_unstable(); + } + assert_eq!(variants, expected); + } + + /// The name of `error`'s variant: a match with no wildcard, so that a new + /// variant does not compile until the test above covers it. + fn variant(error: &Error) -> &'static str { + match error { + Error::InvalidShop(_) => "InvalidShop", + Error::InvalidApiVersion { .. } => "InvalidApiVersion", + Error::Transport { .. } => "Transport", + Error::Http { .. } => "Http", + Error::Graphql(_) => "Graphql", + Error::Throttled { .. } => "Throttled", + Error::Decode { .. } => "Decode", + Error::Variables { .. } => "Variables", + Error::InvalidValue { .. } => "InvalidValue", + Error::Auth { .. } => "Auth", + Error::UserErrors { .. } => "UserErrors", + Error::Bulk { .. } => "Bulk", + Error::Timeout { .. } => "Timeout", + Error::TokenStore(_) => "TokenStore", + Error::NoTransport => "NoTransport", + Error::Verification(_) => "Verification", + Error::Config(_) => "Config", + } + } + + #[test] + fn what_errors_show_instead() { + let error = Error::http( + "https://me:pw@a.myshopify.com/admin/api/2026-10/graphql.json?x=1", + &HttpResponse::new(500, "é".repeat(2000)) + .with_header("Content-Type", "application/json; charset=utf-8") + .with_header("X-Request-Id", "a1b2-c3"), + ); + assert_eq!( + error.to_string(), + "Shopify answered 500 to https://a.myshopify.com/admin/api/2026-10/graphql.json (application/json, 4000 bytes)" + ); + assert!(format!("{error:?}").contains("request_id: Some(\"a1b2-c3\")")); + assert_eq!(error.status(), Some(500)); + assert_eq!(error.request_id(), Some("a1b2-c3")); + assert_eq!(error.raw_http_body().unwrap().len(), 4000); + assert_eq!(error.sensitive_detail(), None); + + let raw = crate::RawResponse { + data: Some(json!({ "orders": [{ "count": "x" }] })), + ..Default::default() + }; + #[derive(Debug, Deserialize)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] + struct Data { + orders: Vec, + } + #[derive(Debug, Deserialize)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] + struct Order { + count: u64, + } + let error = raw.data_as::().unwrap_err(); + assert_eq!( + error.to_string(), + "Shopify's answer does not match the operation at `orders[0].count`: invalid type: string, expected u64" + ); + assert_eq!( + error.sensitive_detail(), + Some("invalid type: string \"x\", expected u64") + ); + let debug = format!("{error:?}"); + assert!(debug.contains("detail: Some(SensitiveDetail(["), "{debug}"); + assert!(!debug.contains("\"x\""), "{debug}"); + + let error = crate::ApiVersion::new("2026-02").unwrap_err(); + assert!( + error + .to_string() + .starts_with("invalid API version `2026-02`: "), + "{error}" + ); + + let error = crate::graphql::Operation::::new("query { shop { id } }") + .json_variable("input", Leaky) + .body() + .unwrap_err(); + assert_eq!( + error.to_string(), + "invalid variables: variable `$input` does not serialize: a value's `Serialize` implementation failed" + ); + assert!(error.sensitive_detail().unwrap().contains(TOKEN)); + + let error = token_endpoint( + 400, + json!({ "error": "invalid_client", "error_description": "Client authentication failed" }) + .to_string(), + ); + assert_eq!( + error.to_string(), + "authentication failed: the token endpoint of a-shop.myshopify.com answered 400 (invalid_client)" + ); + assert_eq!( + error.sensitive_detail(), + Some("invalid_client: Client authentication failed") + ); + } + + #[test] + fn graphql_errors_keep_their_data() { + let errors: Vec = serde_json::from_value(json!([{ + "message": "Access denied for orders field", + "path": ["orders"], + "extensions": { "code": "ACCESS_DENIED", "documentation": "https://x" }, + }])) + .unwrap(); + let error = Error::Graphql(GraphqlErrors { + errors, + data: Some( + json!({ "bulkOperation": { "url": "https://x.test/r?sig=S" }, "orders": null }), + ), + }); + let shown = format!("{error:?}"); + assert!(shown.contains("data: Some({2 entries})"), "{shown}"); + assert!( + shown.contains("code: \"ACCESS_DENIED\", others: 1 entries"), + "{shown}" + ); + assert_eq!( + error.to_string(), + "GraphQL errors: Access denied for orders field (ACCESS_DENIED)" + ); + let Error::Graphql(errors) = &error else { + unreachable!() + }; + assert!(errors.data.as_ref().unwrap()["bulkOperation"]["url"].is_string()); + } + + #[test] + fn user_errors_name_their_field() { + let error = Error::UserErrors { + mutation: "webhookSubscriptionCreate", + errors: vec![ + UserError { + field: Some(vec!["webhookSubscription".to_string(), "uri".to_string()]), + message: "Address is invalid".to_string(), + code: None, + }, + UserError { + field: None, + message: "Too many".to_string(), + code: None, + }, + ], + }; + assert_eq!( + error.to_string(), + "webhookSubscriptionCreate refused: webhookSubscription.uri: Address is invalid; Too many" + ); + } +} diff --git a/crates/shopify_api/src/graphql.rs b/crates/shopify_api/src/graphql.rs new file mode 100644 index 0000000..da7a1a1 --- /dev/null +++ b/crates/shopify_api/src/graphql.rs @@ -0,0 +1,400 @@ +//! Running GraphQL operations: typed ones from [`graphql!`](crate::graphql!), +//! untyped ones from any text. + +pub(crate) mod check; +mod input; +pub mod literal; +pub(crate) mod operation; +mod response; + +use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::{Map, Value}; + +pub use check::{InvalidValueReason, VariableType}; +pub use input::{InputObject, Maybe}; +pub use operation::{IntoVariable, Operation, OperationKind}; +pub use response::{ + Cost, GraphqlError, Location, RawResponse, Response, ThrottleStatus, UserError, +}; + +use crate::error::GraphqlErrors; +use crate::transport::{HttpRequest, Method}; +use crate::{ApiVersion, Error, Result, Shopify}; + +impl Shopify { + /// Runs an operation and returns its typed `data`: an [`Operation`], or + /// the `Variables` of a [`graphql!`](crate::graphql!) module. + /// + /// Fails when Shopify answers with `errors` (after retrying a throttled + /// request), and when `data` does not fit the operation. The `userErrors` + /// of a mutation are part of `data`: read them. + /// + /// ```no_run + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let data = shopify + /// .execute(shopify_api::graphql!( + /// "query($first: Int!) { products(first: $first) { nodes { id title } } }", + /// first = 10, + /// )) + /// .await?; + /// for product in data.products.nodes { + /// println!("{} {}", product.id, product.title); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn execute( + &self, + operation: impl Into>, + ) -> Result { + Ok(self.execute_response(operation).await?.data) + } + + /// [`Shopify::execute`], with the `extensions` of the answer: the cost of + /// the operation and the state of the rate limit. + pub async fn execute_response( + &self, + operation: impl Into>, + ) -> Result> { + let operation = operation.into(); + let version = if operation.is_own() { + // Written for the version of the crate's schema, and kept working + // on the versions it supports: a pinned one is not a mistake. + self.pinned_api_version() + .map_or_else(|| self.version_for(operation.checked_against()), Ok)? + } else { + self.version_for(operation.checked_against())? + }; + let body = operation.body()?.into_bytes(); + let raw = self.send_graphql(version, body, operation.kind()).await?; + let (data, extensions) = into_data(raw)?; + Ok(Response { + data: crate::decode::from_value(data)?, + extensions, + }) + } + + /// [`Shopify::execute`] for one of this crate's operations. + pub(crate) async fn execute_own( + &self, + operation: impl Into>, + ) -> Result { + self.execute(operation.into().own()).await + } + + /// Runs any query or mutation and returns its `data`. Nothing checks the + /// text: prefer [`graphql!`](crate::graphql!) for an operation known + /// when the crate compiles. + /// + /// `variables` is anything that serializes to an object, or `()` for none. + /// + /// ```no_run + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let data = shopify + /// .graphql("query($id: ID!) { product(id: $id) { title } }", serde_json::json!({ "id": "gid://shopify/Product/1" })) + /// .await?; + /// let title = data.pointer("/product/title").and_then(|title| title.as_str()); + /// # Ok(()) + /// # } + /// ``` + pub async fn graphql(&self, query: &str, variables: impl Serialize) -> Result { + let raw = self.graphql_raw(query, variables).await?; + Ok(into_data(raw)?.0) + } + + /// [`Shopify::graphql`], with `data` read as `T`. + pub async fn graphql_as( + &self, + query: &str, + variables: impl Serialize, + ) -> Result { + crate::decode::from_value(self.graphql(query, variables).await?) + } + + /// Runs any query or mutation and returns the answer as Shopify sent + /// it, `errors` included: for an operation whose partial `data` matters. + /// A throttled request is still retried. + pub async fn graphql_raw(&self, query: &str, variables: impl Serialize) -> Result { + let variables = crate::graphql::operation::variables_of(variables)?; + let mut body = Map::new(); + body.insert("query".to_string(), Value::String(query.to_string())); + if !variables.is_empty() { + body.insert("variables".to_string(), Value::Object(variables)); + } + let version = self.version_for(None)?; + let body = serde_json::to_vec(&Value::Object(body)) + .map_err(|error| Error::variables(None, &error))?; + self.send_graphql(version, body, OperationKind::of(query)) + .await + } + + /// Sends a GraphQL body to `version`, retrying what Shopify did not run, + /// and renewing the token once when Shopify refuses it. + pub(crate) async fn send_graphql( + &self, + version: ApiVersion, + body: Vec, + kind: OperationKind, + ) -> Result { + let url = self.graphql_url(version); + let endpoint = self.endpoint(); + let mut token = self.shared.tokens.get(endpoint).await?; + let mut retries = 0; + let mut renewed = false; + loop { + let request = HttpRequest::new(Method::Post, &url) + .with_header("Content-Type", "application/json") + .with_header("Accept", "application/json") + .with_header("User-Agent", &self.shared.endpoint.user_agent) + .with_header("X-Shopify-Access-Token", &token) + .with_body(body.clone()); + let may_retry = retries < self.retry.max_retries(); + let response = match self.shared.endpoint.transport.send(request).await { + Ok(response) => response, + Err(error) if may_retry && !kind.is_mutation() => { + tracing::debug!("retrying a query after a network failure: {error}"); + tokio::time::sleep(self.retry.backoff(retries)).await; + retries += 1; + continue; + } + Err(source) => return Err(Error::transport(&url, source)), + }; + + match response.status { + 200..=299 => {} + 401 if !renewed => { + renewed = true; + match self.shared.tokens.renew(endpoint, &token).await? { + Some(new) => { + token = new; + continue; + } + None => return Err(Error::http(&url, &response)), + } + } + 429 => { + let asked = retry_after(&response); + let throttled = Error::Throttled { + retries, + cost: None, + retry_after: asked, + }; + if !may_retry { + return Err(throttled); + } + // `max_delay` caps the backoff, not the wait Shopify asks for; + // a wait longer than `max_retry_after` goes back to the caller. + let wait = match asked { + Some(wait) if wait > self.retry.max_retry_after() => { + tracing::debug!("Shopify answered 429 with a Retry-After of {wait:?}"); + return Err(throttled); + } + Some(wait) => self.retry.retry_after_wait(wait), + None => self.retry.backoff(retries), + }; + tracing::debug!("Shopify answered 429: retrying in {wait:?}"); + tokio::time::sleep(wait).await; + retries += 1; + continue; + } + 500..=599 if may_retry && !kind.is_mutation() => { + tracing::debug!("Shopify answered {}: retrying the query", response.status); + tokio::time::sleep(self.retry.backoff(retries)).await; + retries += 1; + continue; + } + _ => return Err(Error::http(&url, &response)), + } + + let raw: RawResponse = crate::decode::from_slice(&response.body) + .map_err(|failure| failure.into_error())?; + if raw.is_throttled() { + let cost = raw.cost(); + if !may_retry { + return Err(Error::Throttled { + retries, + cost, + retry_after: None, + }); + } + let wait = self.retry.throttled(retries, cost); + tracing::debug!("throttled by Shopify: retrying in {wait:?}"); + tokio::time::sleep(wait).await; + retries += 1; + continue; + } + return Ok(raw); + } + } +} + +/// The wait a `Retry-After` header asks for: a number of seconds, or an +/// HTTP date (RFC 9110), counted from now. `None` for a value that is +/// neither. A date already past is no wait; a wait too long for a `Duration` +/// is the longest one. +fn retry_after(response: &crate::transport::HttpResponse) -> Option { + retry_after_from(response.header("Retry-After")?, chrono::Utc::now()) +} + +fn retry_after_from( + value: &str, + now: chrono::DateTime, +) -> Option { + let value = value.trim(); + if let Ok(seconds) = value.parse::() { + if seconds.is_nan() || seconds < 0.0 { + return None; + } + return Some( + std::time::Duration::try_from_secs_f64(seconds).unwrap_or(std::time::Duration::MAX), + ); + } + let date = http_date(value, now)?; + Some((date - now).to_std().unwrap_or_default()) +} + +/// An HTTP date in any of its three forms: `Sun, 06 Nov 1994 08:49:37 GMT`, +/// the obsolete `Sunday, 06-Nov-94 08:49:37 GMT` and `Sun Nov 6 08:49:37 1994`. +/// +/// The two-digit year of the second form is read as RFC 9110 (§5.6.7) says: +/// a date more than 50 years after `now` is the most recent past year with +/// the same last two digits. +fn http_date( + value: &str, + now: chrono::DateTime, +) -> Option> { + use chrono::{DateTime, NaiveDateTime, Utc}; + if let Ok(date) = DateTime::parse_from_rfc2822(value) { + return Some(date.with_timezone(&Utc)); + } + if let Some(date) = rfc850_date(value, now) { + return Some(date); + } + NaiveDateTime::parse_from_str(value, "%a %b %e %H:%M:%S %Y") + .ok() + .map(|date| date.and_utc()) +} + +/// `Sunday, 06-Nov-94 08:49:37 GMT`, its century chosen from `now`. +fn rfc850_date( + value: &str, + now: chrono::DateTime, +) -> Option> { + use chrono::{Datelike, Months, NaiveDateTime, Timelike}; + let (weekday, rest) = value.split_once(", ")?; + let (day, rest) = rest.split_once('-')?; + let (month, rest) = rest.split_once('-')?; + let (year, time) = rest.split_once(' ')?; + if year.len() != 2 || !year.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + let two_digits: i32 = year.parse().ok()?; + // The day, month and time, read in a leap year so that 29 February + // reads: the century is chosen before the date is checked. + let parts = NaiveDateTime::parse_from_str( + &format!("{day}-{month}-2000 {time}"), + "%d-%b-%Y %H:%M:%S GMT", + ) + .ok()?; + let latest = now.checked_add_months(Months::new(50 * 12))?; + let at = |date: &NaiveDateTime| (date.month(), date.day(), date.num_seconds_from_midnight()); + // The latest year ending in these digits that is not more than 50 years ahead. + let mut full_year = now.year() - now.year().rem_euclid(100) + 100 + two_digits; + while (full_year, at(&parts)) > (latest.year(), at(&latest.naive_utc())) { + full_year -= 100; + } + let date = parts.with_year(full_year)?.and_utc(); + let named = date.format("%A").to_string(); + (named == weekday).then_some(date) +} +/// The `data` and `extensions` of an answer without errors. +fn into_data(raw: RawResponse) -> Result<(Value, Option)> { + if !raw.errors.is_empty() { + return Err(Error::Graphql(GraphqlErrors { + errors: raw.errors, + data: raw.data, + })); + } + Ok((raw.data.unwrap_or(Value::Null), raw.extensions)) +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::retry_after_from; + + #[test] + fn retry_after_reads_seconds_and_http_dates() { + let now = chrono::DateTime::parse_from_rfc3339("1994-11-06T08:47:37Z") + .unwrap() + .to_utc(); + let read = |value| retry_after_from(value, now); + assert_eq!(read("120"), Some(Duration::from_secs(120))); + assert_eq!(read(" 2.5 "), Some(Duration::from_millis(2500))); + assert_eq!(read("-5"), None); + // The three forms of RFC 9110, two minutes after `now`. + assert_eq!( + read("Sun, 06 Nov 1994 08:49:37 GMT"), + Some(Duration::from_secs(120)) + ); + assert_eq!( + read("Sunday, 06-Nov-94 08:49:37 GMT"), + Some(Duration::from_secs(120)) + ); + assert_eq!( + read("Sun Nov 6 08:49:37 1994"), + Some(Duration::from_secs(120)) + ); + // RFC 850's two-digit years: never more than 50 years ahead (RFC + // 9110 §5.6.7). + let in_2026 = chrono::DateTime::parse_from_rfc3339("2026-10-22T12:00:00Z") + .unwrap() + .to_utc(); + let year = |value| { + use chrono::Datelike; + super::http_date(value, in_2026).map(|date| date.year()) + }; + assert_eq!(year("Friday, 06-Nov-26 08:49:37 GMT"), Some(2026)); + assert_eq!(year("Wednesday, 06-Nov-69 08:49:37 GMT"), Some(2069)); + assert_eq!(year("Wednesday, 21-Oct-76 08:49:37 GMT"), Some(2076)); + // A day after `now` plus 50 years is in the past century. + assert_eq!(year("Saturday, 23-Oct-76 08:49:37 GMT"), Some(1976)); + assert_eq!(year("Saturday, 06-Nov-99 08:49:37 GMT"), Some(1999)); + assert_eq!(year("Thursday, 06-Nov-70 08:49:37 GMT"), Some(2070)); + assert_eq!(year("Monday, 06-Nov-00 08:49:37 GMT"), Some(2000)); + // 29 February: the century first (2100 is no leap year, 2000 is). + assert_eq!(year("Tuesday, 29-Feb-00 08:49:37 GMT"), Some(2000)); + assert_eq!( + retry_after_from("Tuesday, 29-Feb-00 08:49:37 GMT", in_2026), + Some(Duration::ZERO) + ); + assert_eq!(year("Saturday, 29-Feb-76 08:49:37 GMT"), Some(2076)); + // No year ending in `01` has a 29 February. + assert_eq!(year("Thursday, 29-Feb-01 08:49:37 GMT"), None); + // A weekday that does not match its date is no date. + assert_eq!(year("Monday, 06-Nov-69 08:49:37 GMT"), None); + assert_eq!(year("Sunday, 06-Nov-1994 08:49:37 GMT"), None); + // In 2069, `69` is this year, not a century ahead: an hour from now. + let in_2069 = chrono::DateTime::parse_from_rfc3339("2069-11-06T07:49:37Z") + .unwrap() + .to_utc(); + assert_eq!( + retry_after_from("Wednesday, 06-Nov-69 08:49:37 GMT", in_2069), + Some(Duration::from_secs(3600)) + ); + // In 2099, `01` is two years ahead, not 98 years ago. + let in_2099 = chrono::DateTime::parse_from_rfc3339("2099-01-01T00:00:00Z") + .unwrap() + .to_utc(); + assert_eq!( + super::http_date("Saturday, 01-Jan-01 00:00:00 GMT", in_2099) + .map(|date| date.to_rfc3339()), + Some("2101-01-01T00:00:00+00:00".to_string()) + ); + // A date already past is no wait. + assert_eq!(read("Sun, 06 Nov 1994 08:00:00 GMT"), Some(Duration::ZERO)); + assert_eq!(read("soon"), None); + } +} diff --git a/crates/shopify_api/src/graphql/check.rs b/crates/shopify_api/src/graphql/check.rs new file mode 100644 index 0000000..aa2963b --- /dev/null +++ b/crates/shopify_api/src/graphql/check.rs @@ -0,0 +1,412 @@ +//! What a value must be for Shopify to read it as it was written, checked +//! when the value is built: a finite `Float`, an `Int` of 32 bits, no `null` +//! for a non-null `JSON`, a value that serializes. A value that is not is +//! kept as an [`Invalid`], and the operation that holds it fails with +//! [`Error::InvalidValue`] before anything is sent. + +use std::borrow::Cow; +use std::marker::PhantomData; + +use serde::{Serialize, Serializer}; +use serde_json::Value; + +use crate::error::{SensitiveDetail, is_graphql_name}; +use crate::{Error, InputObject}; + +/// Why a value is refused, in [`Error::InvalidValue`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum InvalidValueReason { + /// A `Float` that is NaN or infinite, which JSON writes as `null`. + NotFiniteFloat, + /// An `Int` outside of the 32 bits of GraphQL's `Int`. + IntOutOfRange, + /// A top-level `null` where the type is a non-null `JSON`. + NullJson, + /// A value whose `Serialize` implementation failed. + Unserializable, + /// An enum value or an input field name that is not a GraphQL name: a + /// bulk query writes its variables into its text, where it would not + /// read as written. + NotAGraphqlName, + /// An enum value `true`, `false` or `null`, which GraphQL does not + /// allow: written into a bulk query, it would read as a boolean or as + /// `null`. + ReservedEnumValue, +} + +impl std::fmt::Display for InvalidValueReason { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(match self { + Self::NotFiniteFloat => "not a finite Float", + Self::IntOutOfRange => "Int out of 32-bit range", + Self::NullJson => "null for a non-null JSON field", + Self::Unserializable => "could not serialize", + Self::NotAGraphqlName => { + "not a GraphQL name, as an enum value or a field written into a bulk query must be" + } + Self::ReservedEnumValue => { + "`true`, `false` or `null`, which GraphQL does not allow as an enum value" + } + }) + } +} + +/// A value that is refused, and where it stands. Not a public API. +#[derive(Clone, Debug)] +pub struct Invalid { + /// From the value out: the innermost step first. + path: Vec, + reason: InvalidValueReason, + detail: Option, +} + +#[derive(Clone, Debug)] +enum Step { + Field(&'static str), + Index(usize), +} + +impl Invalid { + pub(crate) fn new(reason: InvalidValueReason) -> Self { + Self { + path: Vec::new(), + reason, + detail: None, + } + } + + pub(crate) fn unserializable(error: &serde_json::Error) -> Self { + Self { + detail: Some(SensitiveDetail::new(error.to_string())), + ..Self::new(InvalidValueReason::Unserializable) + } + } + + pub(crate) fn field(mut self, name: &'static str) -> Self { + self.path.push(Step::Field(name)); + self + } + + pub(crate) fn index(mut self, index: usize) -> Self { + self.path.push(Step::Index(index)); + self + } + + /// `root` and the path from it: `ProductInput.metafields[2].value`. + fn path_from(&self, root: &str) -> String { + let mut path = root.to_string(); + for step in self.path.iter().rev() { + match step { + Step::Field(name) => { + path.push('.'); + path.push_str(name); + } + Step::Index(index) => path.push_str(&format!("[{index}]")), + } + } + path + } + + /// The message of the error of an input object that is serialized on + /// its own: it holds no part of the value. + pub(crate) fn message(&self, input_object: &str) -> String { + format!( + "invalid value at `{}`: {}", + self.path_from(input_object), + self.reason + ) + } + + /// The error of the variable `name`: the name is shown when it is a + /// GraphQL name. + pub(crate) fn into_error(self, name: &str) -> Error { + let root = if is_graphql_name(name) { + format!("${name}") + } else { + "$[variable]".to_string() + }; + Error::InvalidValue { + path: self.path_from(&root), + reason: self.reason, + detail: self.detail, + } + } +} + +fn int(fits: bool) -> Result<(), Invalid> { + if fits { + Ok(()) + } else { + Err(Invalid::new(InvalidValueReason::IntOutOfRange)) + } +} + +fn float(value: f64) -> Result<(), Invalid> { + if value.is_finite() { + Ok(()) + } else { + Err(Invalid::new(InvalidValueReason::NotFiniteFloat)) + } +} + +fn json(value: &Value) -> Result<(), Invalid> { + if value.is_null() { + Err(Invalid::new(InvalidValueReason::NullJson)) + } else { + Ok(()) + } +} + +fn items<'a, T: 'a>( + items: impl IntoIterator, + check: impl Fn(&T) -> Result<(), Invalid>, +) -> Result<(), Invalid> { + for (index, item) in items.into_iter().enumerate() { + check(item).map_err(|invalid| invalid.index(index))?; + } + Ok(()) +} + +/// The Rust type of a GraphQL variable, as [`graphql!`](crate::graphql!) +/// picks it: `String` (strings, IDs, enum values and Shopify's +/// string-encoded scalars), `i64` (`Int`), `f64` (`Float`), `bool`, `Value` +/// (`JSON`), an [`InputObject`], an `Option` of one for a nullable type and +/// a `Vec` for a list. +/// +/// Its value is checked when the variable is set: an `i64` must fit in the +/// 32 bits of a GraphQL `Int`, an `f64` must be finite, a `Value` must not +/// be `null` where its type is non-null. A value that is not makes the +/// operation fail with [`Error::InvalidValue`] before it is sent. This +/// trait is sealed. +pub trait VariableType: Serialize + sealed::Sealed {} + +pub(crate) mod sealed { + use super::Invalid; + + pub trait Sealed { + /// Checks the value; `nullable` when its GraphQL type is. + fn check(&self, nullable: bool) -> Result<(), Invalid>; + } +} + +macro_rules! variable_type { + ($($ty:ty => |$value:ident, $nullable:ident| $check:expr),+ $(,)?) => {$( + impl VariableType for $ty {} + impl sealed::Sealed for $ty { + fn check(&self, $nullable: bool) -> Result<(), Invalid> { + let $value = self; + $check + } + } + )+}; +} + +variable_type!( + String => |_value, _nullable| Ok(()), + bool => |_value, _nullable| Ok(()), + i64 => |value, _nullable| int(i32::try_from(*value).is_ok()), + f64 => |value, _nullable| float(*value), + Value => |value, nullable| if nullable { Ok(()) } else { json(value) }, +); + +impl VariableType for InputObject {} +impl sealed::Sealed for InputObject { + fn check(&self, _: bool) -> Result<(), Invalid> { + self.invalid() + } +} + +impl VariableType for Option {} +impl sealed::Sealed for Option { + fn check(&self, _: bool) -> Result<(), Invalid> { + match self { + Some(value) => value.check(true), + None => Ok(()), + } + } +} + +impl VariableType for Vec {} +impl sealed::Sealed for Vec { + fn check(&self, _: bool) -> Result<(), Invalid> { + items(self, |item| item.check(false)) + } +} + +/// The value of a Rust expression in a literal of `graphql!` or `input!`, +/// checked for the kind `K` of the place it stands in, and written. Not a +/// public API. +pub trait Validate { + fn validate(&self) -> Result<(), Invalid>; + /// Serializes the value: an array of any length as a list, which serde + /// does past 32 items only for slices. + fn write(&self, serializer: S) -> Result; +} + +/// The Rust types of a value of the scalar `K`, lists and `Option` aside: +/// what the check of a place of that scalar accepts. `Site` is a type of +/// the generated code: with it, that no `Option` is accepted is known, and +/// the check may also have an impl for `Option`. Not a public API. +pub trait Accepts: Validate {} + +/// A value written by [`Validate::write`]. +pub struct Written<'a, V, K>(pub &'a V, PhantomData K>); + +impl<'a, V, K> Written<'a, V, K> { + pub fn new(value: &'a V) -> Self { + Self(value, PhantomData) + } +} + +impl, K> Serialize for Written<'_, V, K> { + fn serialize(&self, serializer: S) -> Result { + self.0.write(serializer) + } +} + +/// The kinds of places: the scalars, `JSON` split by whether `null` is +/// refused at its top, and input objects. +#[derive(Debug)] +pub enum Int {} +#[derive(Debug)] +pub enum Float {} +#[derive(Debug)] +pub enum Text {} +#[derive(Debug)] +pub enum Boolean {} +/// A non-null `JSON`. +#[derive(Debug)] +pub enum Json {} +/// A nullable `JSON`. +#[derive(Debug)] +pub enum MaybeJson {} +#[derive(Debug)] +pub enum Input {} + +macro_rules! scalar { + ($kind:ty: $($ty:ty => |$value:ident| $check:expr),+ $(,)?) => {$( + impl Validate<$kind> for $ty { + fn validate(&self) -> Result<(), Invalid> { + let $value = self; + $check + } + + fn write(&self, serializer: S) -> Result { + self.serialize(serializer) + } + } + + impl Accepts<$kind, Site> for $ty {} + )+}; +} + +scalar!(Int: + i8 => |_value| Ok(()), + i16 => |_value| Ok(()), + i32 => |_value| Ok(()), + i64 => |value| int(i32::try_from(*value).is_ok()), + isize => |value| int(i32::try_from(*value).is_ok()), + u8 => |_value| Ok(()), + u16 => |_value| Ok(()), + u32 => |value| int(i32::try_from(*value).is_ok()), + u64 => |value| int(i32::try_from(*value).is_ok()), + usize => |value| int(i32::try_from(*value).is_ok()), +); +scalar!(Float: + f32 => |value| float(f64::from(*value)), + f64 => |value| float(*value), + i32 => |_value| Ok(()), + u32 => |_value| Ok(()), +); +scalar!(Text: + String => |_value| Ok(()), + &str => |_value| Ok(()), + &String => |_value| Ok(()), + Cow<'_, str> => |_value| Ok(()), +); +scalar!(Boolean: bool => |_value| Ok(())); +scalar!(Json: + Value => |value| json(value), + &Value => |value| json(value), +); +scalar!(MaybeJson: + Value => |_value| Ok(()), + &Value => |_value| Ok(()), +); + +impl Validate for InputObject { + fn validate(&self) -> Result<(), Invalid> { + self.invalid() + } + + fn write(&self, serializer: S) -> Result { + self.serialize(serializer) + } +} + +impl Validate for &InputObject { + fn validate(&self) -> Result<(), Invalid> { + self.invalid() + } + + fn write(&self, serializer: S) -> Result { + self.serialize(serializer) + } +} + +impl> Validate for Option { + fn validate(&self) -> Result<(), Invalid> { + match self { + Some(value) => value.validate(), + None => Ok(()), + } + } + + fn write(&self, serializer: S) -> Result { + match self { + Some(value) => value.write(serializer), + None => serializer.serialize_none(), + } + } +} + +impl, const N: usize> Validate for [V; N] { + fn validate(&self) -> Result<(), Invalid> { + self.as_slice().validate() + } + + fn write(&self, serializer: S) -> Result { + self.as_slice().write(serializer) + } +} + +impl> Validate for Vec { + fn validate(&self) -> Result<(), Invalid> { + self.as_slice().validate() + } + + fn write(&self, serializer: S) -> Result { + self.as_slice().write(serializer) + } +} + +impl> Validate for &Vec { + fn validate(&self) -> Result<(), Invalid> { + self.as_slice().validate() + } + + fn write(&self, serializer: S) -> Result { + self.as_slice().write(serializer) + } +} + +impl> Validate for &[V] { + fn validate(&self) -> Result<(), Invalid> { + items(self.iter(), V::validate) + } + + fn write(&self, serializer: S) -> Result { + serializer.collect_seq(self.iter().map(Written::::new)) + } +} diff --git a/crates/shopify_api/src/graphql/input.rs b/crates/shopify_api/src/graphql/input.rs new file mode 100644 index 0000000..c9ef93c --- /dev/null +++ b/crates/shopify_api/src/graphql/input.rs @@ -0,0 +1,95 @@ +//! Input objects built by [`input!`](crate::input!), and the field values +//! that may be left out. + +use serde::{Serialize, Serializer}; +use serde_json::value::RawValue; + +use super::check::Invalid; + +/// An input object of the schema, built and checked by +/// [`input!`](crate::input!): `input!(MetafieldsSetInput { … })`. +/// +/// `TYPE` identifies the GraphQL input type: a hash of its name, so that +/// every `input!` of `MetafieldsSetInput`, in any module or crate, gives the +/// same Rust type, and values of different input types do not mix. A +/// `graphql!` module names it after the GraphQL type +/// (`metafields_set::MetafieldsSetInput`); messages of `graphql!` and +/// `input!` name the GraphQL type too. +/// +/// The value is opaque: it holds the JSON it is sent as, written when it is +/// built. A value Shopify would not read as written (a `Float` that is not +/// finite, an `Int` beyond 32 bits, `null` for a non-null `JSON`) is kept as +/// refused: the operation that holds it fails with +/// [`Error::InvalidValue`](crate::Error::InvalidValue) before it is sent, +/// and serializing it on its own fails. +#[derive(Clone)] +pub struct InputObject { + name: &'static str, + json: Result, Invalid>, +} + +impl InputObject { + /// What `input!` builds. + #[doc(hidden)] + pub fn __new(name: &'static str, json: Result, Invalid>) -> Self { + Self { name, json } + } + + /// Why the value is refused, if it is. + pub(crate) fn invalid(&self) -> Result<(), Invalid> { + match &self.json { + Ok(_) => Ok(()), + Err(invalid) => Err(invalid.clone()), + } + } +} + +impl Serialize for InputObject { + fn serialize(&self, serializer: S) -> Result { + match &self.json { + Ok(json) => json.serialize(serializer), + Err(invalid) => Err(serde::ser::Error::custom(invalid.message(self.name))), + } + } +} + +impl std::fmt::Debug for InputObject { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.json { + Ok(json) => write!(formatter, "{} {}", self.name, json.get()), + Err(invalid) => formatter.write_str(&invalid.message(self.name)), + } + } +} + +/// A field given with `field?: value` in [`graphql!`](crate::graphql!) and +/// [`input!`](crate::input!), when sending `null` is a choice made at run +/// time: an `Option` covers absent or value, `Maybe` adds `null`. +/// +/// ```no_run +/// use shopify_api::{Maybe, input}; +/// +/// # fn vendor(clear: bool, vendor: Option) { +/// let vendor = match (clear, vendor) { +/// (true, _) => Maybe::Null, +/// (false, Some(vendor)) => Maybe::Value(vendor), +/// (false, None) => Maybe::Absent, +/// }; +/// let product = input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor?: vendor }); +/// # } +/// ``` +#[derive(Debug, Clone, PartialEq, Default)] +pub enum Maybe { + /// The field is not sent: Shopify keeps what it has. + #[default] + Absent, + /// The field is sent as `null`: Shopify clears it. + Null, + Value(T), +} + +impl From for Maybe { + fn from(value: T) -> Self { + Self::Value(value) + } +} diff --git a/crates/shopify_api/src/graphql/literal.rs b/crates/shopify_api/src/graphql/literal.rs new file mode 100644 index 0000000..91bb202 --- /dev/null +++ b/crates/shopify_api/src/graphql/literal.rs @@ -0,0 +1,411 @@ +//! What the code `graphql!` and `input!` generate for a literal value +//! (`{ title: "x" }`, `[a, b]`, `raw(…)`) refers to. Not a public API. +//! +//! An object literal is a list of fields nested in tuples, +//! `Object((Field("id", id), (Optional("vendor", vendor), ())))`, written in +//! its order; the macros check its fields and their values first. A Rust +//! expression in it is a [`Leaf`], checked for the scalar it stands for when +//! the value is built. + +use std::marker::PhantomData; + +use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer}; +use serde_json::value::RawValue; + +pub use super::check::{ + Accepts, Boolean, Float, Input, Int, Invalid, Json, MaybeJson, Text, Validate, +}; +use crate::Maybe; + +/// The JSON of a value, or why it is refused. +pub fn to_raw(value: &(impl Check + Serialize)) -> Result, Invalid> { + value.check()?; + serde_json::value::to_raw_value(value).map_err(|error| Invalid::unserializable(&error)) +} + +/// A value of a literal, checked before it is serialized. +pub trait Check { + fn check(&self) -> Result<(), Invalid>; +} + +/// `null`, an enum value, the string of `raw(…)`, a literal Rust value +/// whose type cannot be refused. +macro_rules! unchecked { + ($($ty:ty),+) => {$( + impl Check for $ty { + fn check(&self) -> Result<(), Invalid> { + Ok(()) + } + } + )+}; +} + +unchecked!((), &str, String, bool); + +impl Check for &T { + fn check(&self) -> Result<(), Invalid> { + (**self).check() + } +} + +/// A Rust expression for a value of the scalar `K`. +#[derive(Debug)] +pub struct Leaf(V, PhantomData K>); + +pub fn leaf(value: V) -> Leaf { + Leaf(value, PhantomData) +} + +/// `field?: value`, the value checked as a `K`. +pub fn optional(value: Maybe) -> Maybe> { + match value { + Maybe::Absent => Maybe::Absent, + Maybe::Null => Maybe::Null, + Maybe::Value(value) => Maybe::Value(leaf(value)), + } +} + +impl, K> Check for Leaf { + fn check(&self) -> Result<(), Invalid> { + self.0.validate() + } +} + +impl, K> Serialize for Leaf { + fn serialize(&self, serializer: S) -> Result { + self.0.write(serializer) + } +} + +/// The items of `[for … => …]`, each written in its turn of the loop, and +/// the first that is refused. +#[derive(Debug, Default)] +pub struct Collected { + items: Vec>, + invalid: Option, +} + +impl Collected { + pub fn push(&mut self, value: Result, Invalid>) { + if self.invalid.is_some() { + return; + } + match value { + Ok(item) => self.items.push(item), + Err(invalid) => self.invalid = Some(invalid.index(self.items.len())), + } + } +} + +impl Check for Collected { + fn check(&self) -> Result<(), Invalid> { + match &self.invalid { + Some(invalid) => Err(invalid.clone()), + None => Ok(()), + } + } +} + +impl Serialize for Collected { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_seq(&self.items) + } +} + +#[derive(Debug)] +pub struct Object(pub F); + +#[derive(Debug)] +pub struct Field(pub &'static str, pub V); + +/// `name?: value`: not sent when absent. +#[derive(Debug)] +pub struct Optional(pub &'static str, pub Maybe); + +pub trait Fields { + fn check(&self) -> Result<(), Invalid>; + fn write(&self, map: &mut M) -> Result<(), M::Error>; +} + +impl Fields for () { + fn check(&self) -> Result<(), Invalid> { + Ok(()) + } + + fn write(&self, _: &mut M) -> Result<(), M::Error> { + Ok(()) + } +} + +impl Fields for (Field, R) { + fn check(&self) -> Result<(), Invalid> { + self.0 + .1 + .check() + .map_err(|invalid| invalid.field(self.0.0))?; + self.1.check() + } + + fn write(&self, map: &mut M) -> Result<(), M::Error> { + map.serialize_entry(self.0.0, &self.0.1)?; + self.1.write(map) + } +} + +impl Fields for (Optional, R) { + fn check(&self) -> Result<(), Invalid> { + if let Maybe::Value(value) = &self.0.1 { + value.check().map_err(|invalid| invalid.field(self.0.0))?; + } + self.1.check() + } + + fn write(&self, map: &mut M) -> Result<(), M::Error> { + match &self.0.1 { + Maybe::Absent => {} + Maybe::Null => map.serialize_entry(self.0.0, &())?, + Maybe::Value(value) => map.serialize_entry(self.0.0, value)?, + } + self.1.write(map) + } +} + +impl Check for Object { + fn check(&self) -> Result<(), Invalid> { + self.0.check() + } +} + +impl Serialize for Object { + fn serialize(&self, serializer: S) -> Result { + let mut map = serializer.serialize_map(None)?; + self.0.write(&mut map)?; + map.end() + } +} + +/// `[a, b]`: its items, of types that may differ, nested in tuples. +#[derive(Debug)] +pub struct List(pub I); + +pub trait Items { + /// Checks the items, the first being at `index`. + fn check(&self, index: usize) -> Result<(), Invalid>; + fn write(&self, seq: &mut S) -> Result<(), S::Error>; +} + +impl Items for () { + fn check(&self, _: usize) -> Result<(), Invalid> { + Ok(()) + } + + fn write(&self, _: &mut S) -> Result<(), S::Error> { + Ok(()) + } +} + +impl Items for (V, R) { + fn check(&self, index: usize) -> Result<(), Invalid> { + self.0.check().map_err(|invalid| invalid.index(index))?; + self.1.check(index + 1) + } + + fn write(&self, seq: &mut S) -> Result<(), S::Error> { + seq.serialize_element(&self.0)?; + self.1.write(seq) + } +} + +impl Check for List { + fn check(&self) -> Result<(), Invalid> { + self.0.check(0) + } +} + +impl Serialize for List { + fn serialize(&self, serializer: S) -> Result { + let mut seq = serializer.serialize_seq(None)?; + self.0.write(&mut seq)?; + seq.end() + } +} + +/// The value of `raw(…)`: any string, sent as the enum value. +#[diagnostic::on_unimplemented( + message = "`raw(…)` takes the enum value as a string, not `{Self}`", + label = "a `String`, a `&str` or anything else `Into`" +)] +pub trait RawString { + fn into_string(self) -> String; +} + +impl> RawString for T { + fn into_string(self) -> String { + self.into() + } +} + +pub fn raw(value: impl RawString) -> String { + value.into_string() +} + +/// `field?: raw(…)` on a field that may be `null`. +#[diagnostic::on_unimplemented( + message = "`field?: raw(…)` takes an `Option` or a `shopify_api::Maybe` of a string, not `{Self}`", + label = "`None` and `Maybe::Absent` leave the field out" +)] +pub trait RawOptional { + fn into_maybe(self) -> Maybe; +} + +impl RawOptional for Option { + fn into_maybe(self) -> Maybe { + option(self.map(RawString::into_string)) + } +} + +impl RawOptional for Maybe { + fn into_maybe(self) -> Maybe { + match self { + Maybe::Absent => Maybe::Absent, + Maybe::Null => Maybe::Null, + Maybe::Value(value) => Maybe::Value(value.into_string()), + } + } +} + +pub fn raw_optional(value: impl RawOptional) -> Maybe { + value.into_maybe() +} + +/// `field?: raw(…)` on a non-null field with a default: an `Option` only, +/// since `null` is refused there. +#[diagnostic::on_unimplemented( + message = "`field?: raw(…)` takes an `Option` of a string here, not `{Self}`", + label = "the field is non-null: `None` leaves it out, and `null` is refused" +)] +pub trait RawOption { + fn into_maybe(self) -> Maybe; +} + +impl RawOption for Option { + fn into_maybe(self) -> Maybe { + option(self.map(RawString::into_string)) + } +} + +pub fn raw_option(value: impl RawOption) -> Maybe { + value.into_maybe() +} + +/// The value of `field?: value`, checked as a `K`: `None` leaves the field +/// out. +pub trait OptionalValue { + type Value: Validate; + fn into_maybe(self) -> Maybe; +} + +impl> OptionalValue for Option { + type Value = V; + fn into_maybe(self) -> Maybe { + option(self) + } +} + +impl> OptionalValue for Maybe { + type Value = V; + fn into_maybe(self) -> Maybe { + self + } +} + +fn option(value: Option) -> Maybe { + match value { + Some(value) => Maybe::Value(value), + None => Maybe::Absent, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn objects_and_lists_serialize_in_their_order_and_leave_out_absent_fields() { + let object = Object(( + Field("type", "single_line_text_field"), + ( + Optional("a", Maybe::<&str>::Absent), + ( + Optional("b", Maybe::<&str>::Null), + ( + Optional("c", optional::(option(Some(1)))), + ( + Field("list", List(("x", (leaf::(2), ((), ()))))), + (), + ), + ), + ), + ), + )); + assert_eq!( + to_raw(&object).unwrap().get(), + r#"{"type":"single_line_text_field","b":null,"c":1,"list":["x",2,null]}"# + ); + assert_eq!(to_raw(&Object(())).unwrap().get(), "{}"); + assert_eq!(to_raw(&List(())).unwrap().get(), "[]"); + assert_eq!( + raw_optional(Maybe::Value("A")), + Maybe::Value("A".to_string()) + ); + assert_eq!(raw_option(None::<&str>), Maybe::Absent); + } + + #[test] + fn a_value_is_checked_for_its_scalar_and_refused_with_where_it_stands() { + use serde_json::Value; + + let refused = |value: Result, Invalid>| value.unwrap_err().message("T"); + assert_eq!( + refused(to_raw(&Object(( + Optional("j", optional::(Maybe::Value(Value::Null))), + () + )))), + "invalid value at `T.j`: null for a non-null JSON field" + ); + assert_eq!( + refused(to_raw(&Object(( + Field( + "list", + List(( + leaf::(1.0), + (leaf::(vec![Some(f32::NAN)]), ()) + )) + ), + () + )))), + "invalid value at `T.list[1][0]`: not a finite Float" + ); + let mut collected = Collected::default(); + for quantity in [1_usize, 2, 1 << 40, 3, usize::MAX] { + collected.push(to_raw(&Object(( + Field("quantity", leaf::(quantity)), + (), + )))); + } + assert_eq!( + refused(to_raw(&Object((Field("items", &collected), ())))), + "invalid value at `T.items[2].quantity`: Int out of 32-bit range" + ); + // `null` of a nullable `JSON`, and nulls inside a `JSON`, are sent. + assert_eq!( + to_raw(&List(( + leaf::(Value::Null), + (leaf::(serde_json::json!([null])), ()) + ))) + .unwrap() + .get(), + "[null,[null]]" + ); + } +} diff --git a/crates/shopify_api/src/graphql/operation.rs b/crates/shopify_api/src/graphql/operation.rs new file mode 100644 index 0000000..2597016 --- /dev/null +++ b/crates/shopify_api/src/graphql/operation.rs @@ -0,0 +1,994 @@ +//! Operations, as built by [`graphql!`](crate::graphql!) or by hand. + +use std::borrow::Cow; +use std::marker::PhantomData; + +use serde::ser::{Serialize, SerializeMap, Serializer}; +use serde_json::value::RawValue; +use serde_json::{Map, Value}; + +use super::check::{Invalid, VariableType}; +use crate::{ApiVersion, Error, Result}; + +/// A query or a mutation. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum OperationKind { + Query, + Mutation, +} + +impl OperationKind { + /// Reads the kind of a document: a mutation as soon as one of its + /// operations is one, so that a document that holds a mutation is never + /// sent twice by a retry. + /// + /// It fails safe: a document it can't read to the end (a subscription, a + /// typo, an unclosed string or block…) is a [`Mutation`](Self::Mutation) + /// too, so it is never retried either. Only a document made of queries, + /// fragments and `{ … }` shorthands is a [`Query`](Self::Query). + pub fn of(document: &str) -> Self { + match read_kind(document) { + Some(kind) => kind, + None => Self::Mutation, + } + } + + pub fn is_mutation(&self) -> bool { + matches!(self, Self::Mutation) + } +} + +/// The kind of the document, `None` when it can't be read. +fn read_kind(document: &str) -> Option { + let mut lexer = Lexer { + text: document, + position: 0, + }; + loop { + match lexer.next()? { + None => return Some(OperationKind::Query), + Some(Token::Punctuator(b'{')) => lexer.skip_selection_set()?, + Some(Token::Name("query" | "fragment")) => { + lexer.skip_to_selection_set()?; + lexer.skip_selection_set()?; + } + Some(Token::Name("mutation")) => return Some(OperationKind::Mutation), + Some(_) => return None, + } + } +} + +/// The tokens that tell where a definition starts and ends. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Token<'a> { + Name(&'a str), + /// `{`, `}`, `(`, `)`, `[` or `]`. + Punctuator(u8), + /// Strings, numbers and every other punctuator. + Other, +} + +/// Just enough of a GraphQL lexer to find the definitions of a document. +struct Lexer<'a> { + text: &'a str, + position: usize, +} + +impl<'a> Lexer<'a> { + fn rest(&self) -> &'a [u8] { + &self.text.as_bytes()[self.position..] + } + + /// Skips white space, line terminators, commas, comments and byte order marks. + fn skip_ignored(&mut self) { + loop { + let rest = self.rest(); + match rest.first() { + Some(b' ' | b'\t' | b'\n' | b'\r' | b',') => self.position += 1, + Some(0xEF) if rest.starts_with("\u{feff}".as_bytes()) => self.position += 3, + // A comment runs to the next line terminator: `\n`, `\r` or `\r\n`. + Some(b'#') => { + self.position += rest + .iter() + .position(|byte| matches!(byte, b'\n' | b'\r')) + .unwrap_or(rest.len()); + } + _ => return, + } + } + } + + /// The next token: `None` when the text can't be read, `Some(None)` at its end. + fn next(&mut self) -> Option>> { + self.skip_ignored(); + let rest = self.rest(); + let Some(&first) = rest.first() else { + return Some(None); + }; + let start = self.position; + let token = match first { + b'A'..=b'Z' | b'a'..=b'z' | b'_' => { + let length = rest + .iter() + .position(|byte| !(byte.is_ascii_alphanumeric() || *byte == b'_')) + .unwrap_or(rest.len()); + self.position += length; + Token::Name(&self.text[start..self.position]) + } + b'"' if rest.starts_with(b"\"\"\"") => { + // A block string: its only escape is `\"""`. + let mut index = 3; + loop { + let tail = rest.get(index..)?; + if tail.is_empty() { + return None; + } else if tail.starts_with(b"\\\"\"\"") { + index += 4; + } else if tail.starts_with(b"\"\"\"") { + break; + } else { + index += 1; + } + } + self.position += index + 3; + Token::Other + } + b'"' => { + let mut index = 1; + loop { + match rest.get(index)? { + b'\\' => index += 2, + b'"' => break, + b'\n' | b'\r' => return None, + _ => index += 1, + } + } + self.position += index + 1; + Token::Other + } + b'{' | b'}' | b'(' | b')' | b'[' | b']' => { + self.position += 1; + Token::Punctuator(first) + } + b'0'..=b'9' | b'-' => { + let length = rest + .iter() + .position(|byte| { + !(byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'+' | b'-')) + }) + .unwrap_or(rest.len()); + self.position += length; + Token::Other + } + _ => { + // Any other punctuator, or a character GraphQL doesn't allow here. + let length = self.text[start..].chars().next().map_or(1, char::len_utf8); + self.position += length; + Token::Other + } + }; + Some(Some(token)) + } + + /// Skips the header of a definition (name, variables and their default + /// values, directives), up to and with the `{` of its selection set. + fn skip_to_selection_set(&mut self) -> Option<()> { + let mut depth = 0usize; + loop { + match self.next()?? { + Token::Punctuator(b'{') if depth == 0 => return Some(()), + Token::Punctuator(b'{' | b'(' | b'[') => depth += 1, + Token::Punctuator(_) => depth = depth.checked_sub(1)?, + _ => {} + } + } + } + + /// Skips a selection set, its `{` already read. + fn skip_selection_set(&mut self) -> Option<()> { + let mut depth = 1usize; + loop { + match self.next()?? { + Token::Punctuator(b'{') => depth += 1, + Token::Punctuator(b'}') => { + depth -= 1; + if depth == 0 { + return Some(()); + } + } + _ => {} + } + } + } +} + +/// An operation, its variables, and the type `D` of its `data`. +/// +/// [`graphql!`](crate::graphql!) builds it after checking the operation +/// against Shopify's schema; [`Shopify::execute`](crate::Shopify::execute) +/// runs it. [`Operation::new`] builds one from any text, checked by nothing. +pub struct Operation { + query: Cow<'static, str>, + kind: OperationKind, + name: Option>, + /// The Admin API version of the schema the operation was checked against. + checked_against: Option<&'static str>, + /// One of this crate's operations: it goes to a pinned version unwarned. + own: bool, + /// Each variable as the JSON it is sent as, in the order it was set. + variables: std::result::Result)>, VariablesFailure>, + data: PhantomData D>, +} + +impl Operation { + /// An operation that nothing checked: its result is read as `D` when it runs. + pub fn new(query: impl Into>) -> Self { + let query = query.into(); + Self { + kind: OperationKind::of(&query), + query, + name: None, + checked_against: None, + own: false, + variables: Ok(Vec::new()), + data: PhantomData, + } + } + + /// What `graphql!` builds. + #[doc(hidden)] + pub fn __checked( + query: &'static str, + kind: OperationKind, + name: Option<&'static str>, + checked_against: &'static str, + ) -> Self { + Self { + query: Cow::Borrowed(query), + kind, + name: name.map(Cow::Borrowed), + checked_against: Some(checked_against), + own: false, + variables: Ok(Vec::new()), + data: PhantomData, + } + } + + /// The text of the operation. + pub fn query(&self) -> &str { + &self.query + } + + pub fn kind(&self) -> OperationKind { + self.kind + } + + /// The name of the operation, sent as `operationName`. + pub fn name(&self) -> Option<&str> { + self.name.as_deref() + } + + /// Names the operation: Shopify shows the name in its logs. + pub fn with_name(mut self, name: impl Into>) -> Self { + self.name = Some(name.into()); + self + } + + /// The Admin API version of the schema `graphql!` checked the operation + /// against; `None` for an operation built with [`Operation::new`]. + pub fn checked_against(&self) -> Option<&'static str> { + self.checked_against + } + + /// Marks one of this crate's operations. + pub(crate) fn own(mut self) -> Self { + self.own = true; + self + } + + pub(crate) fn is_own(&self) -> bool { + self.own + } + + /// Sends the operation as one checked against `version`, not as one of + /// this crate's: a bulk operation runs the operation of the caller. + pub(crate) fn checked_as(mut self, version: Option<&'static str>) -> Self { + self.checked_against = version; + self.own = false; + self + } + + /// The variables set, each as the JSON it is sent as; an error when one + /// was refused. + pub(crate) fn variable_values(&self) -> Result<&[(String, Box)]> { + self.variables + .as_deref() + .map_err(|failure| failure.to_error()) + } + + /// The Admin API version the operation is sent to when the client pins + /// none: the one it was checked against, else [`ApiVersion::DEFAULT`]. + pub fn api_version(&self) -> Result { + match self.checked_against { + Some(version) => ApiVersion::new(version), + None => Ok(ApiVersion::DEFAULT), + } + } + + fn set( + mut self, + name: &str, + value: std::result::Result, VariablesFailure>, + ) -> Self { + match (&mut self.variables, value) { + (Ok(variables), Ok(value)) => match variables.iter_mut().find(|(set, _)| set == name) { + Some((_, set)) => *set = value, + None => variables.push((name.to_string(), value)), + }, + (Ok(_), Err(failure)) => self.variables = Err(failure), + (Err(_), _) => {} + } + self + } + + fn set_json(self, name: &str, value: &impl Serialize) -> Self { + let value = serde_json::value::to_raw_value(value) + .map_err(|error| VariablesFailure::of(Error::variables(Some(name), &error))); + self.set(name, value) + } + + fn set_checked(self, name: &str, value: &impl VariableType) -> Self { + match value.check(false) { + Ok(()) => self.set_json(name, value), + Err(invalid) => self.set(name, Err(VariablesFailure::invalid(name, invalid))), + } + } + + /// Sets a variable to a value convertible to `T`, the Rust type of its + /// GraphQL type. + /// + /// The value is checked as [`VariableType`] says: one that Shopify would + /// not read as written makes the operation fail with + /// [`Error::InvalidValue`] before it is sent. + pub fn variable>(self, name: &str, value: V) -> Self { + self.set_checked(name, &value.into_variable()) + } + + /// Sets a variable to any serializable value, checked by nothing. + pub fn json_variable(self, name: &str, value: V) -> Self { + self.set_json(name, &value) + } + + /// What the `Variables` of a `graphql!` module set a variable with. + #[doc(hidden)] + pub fn __variable(self, name: &str, value: T) -> Self { + self.set_checked(name, &value) + } + + /// What `graphql!` sets a variable written as a literal to. + #[doc(hidden)] + pub fn __literal_variable( + self, + name: &str, + value: std::result::Result, Invalid>, + ) -> Self { + let value = value.map_err(|invalid| VariablesFailure::invalid(name, invalid)); + self.set(name, value) + } + + /// Replaces the variables with the fields of a serializable struct or map. + pub fn variables(mut self, variables: V) -> Self { + self.variables = variables_of(variables) + .and_then(|variables| { + variables + .into_iter() + .map( + |(name, value)| match serde_json::value::to_raw_value(&value) { + Ok(value) => Ok((name, value)), + Err(error) => Err(Error::variables(Some(&name), &error)), + }, + ) + .collect() + }) + .map_err(VariablesFailure::of); + self + } + + /// The JSON text the variable `name` is sent as, `None` when it is not + /// set; an error when a variable was refused, as + /// [`Shopify::execute`](crate::Shopify::execute) would fail. + /// + /// Nothing is parsed back: to read it as a [`Value`], parse it with the + /// settings you need, such as `serde_json::from_str::(json)`, + /// which refuses a value nested deeper than 128. + pub fn variable_json(&self, name: &str) -> Result> { + let variables = self + .variables + .as_ref() + .map_err(|failure| failure.to_error())?; + Ok(variables + .iter() + .find(|(set, _)| set == name) + .map(|(_, value)| value.get())) + } + + /// The body as the exact JSON text + /// [`Shopify::execute`](crate::Shopify::execute) sends: `query`, + /// `variables` and `operationName`. + /// + /// Nothing is parsed back: to read it as a [`Value`], parse it with the + /// settings you need, such as `serde_json::from_str::(&body)`, + /// which refuses a value nested deeper than 128. + pub fn body(&self) -> Result { + let variables = self + .variables + .as_ref() + .map_err(|failure| failure.to_error())?; + let body = Body { + query: &self.query, + variables, + name: self.name.as_deref(), + }; + serde_json::to_string(&body).map_err(|error| Error::variables(None, &error)) + } +} + +struct Body<'a> { + query: &'a str, + variables: &'a [(String, Box)], + name: Option<&'a str>, +} + +impl Serialize for Body<'_> { + fn serialize(&self, serializer: S) -> std::result::Result { + struct Variables<'a>(&'a [(String, Box)]); + impl Serialize for Variables<'_> { + fn serialize( + &self, + serializer: S, + ) -> std::result::Result { + serializer.collect_map(self.0.iter().map(|(name, value)| (name, value))) + } + } + + let mut body = serializer.serialize_map(None)?; + body.serialize_entry("query", self.query)?; + if !self.variables.is_empty() { + body.serialize_entry("variables", &Variables(self.variables))?; + } + if let Some(name) = self.name { + body.serialize_entry("operationName", name)?; + } + body.end() + } +} + +/// The variables of a [`Shopify::graphql_raw`](crate::Shopify::graphql_raw) +/// call or an [`Operation`]: one path, so that both fail the same way. +pub(crate) fn variables_of(variables: impl Serialize) -> Result> { + match serde_json::to_value(variables) { + Ok(Value::Object(variables)) => Ok(variables), + Ok(Value::Null) => Ok(Map::new()), + Ok(_) => Err(Error::variables_not_an_object()), + Err(error) => Err(Error::variables(None, &error)), + } +} + +/// An [`Error::Variables`] or an [`Error::InvalidValue`] kept until the +/// operation is sent. Its `Debug` shows no detail. +#[derive(Clone, Debug)] +enum VariablesFailure { + Variables { + message: String, + detail: Option, + }, + Invalid { + variable: String, + invalid: Invalid, + }, +} + +impl VariablesFailure { + fn of(error: Error) -> Self { + match error { + Error::Variables { message, detail } => Self::Variables { message, detail }, + other => Self::Variables { + message: other.to_string(), + detail: None, + }, + } + } + + fn invalid(variable: &str, invalid: Invalid) -> Self { + Self::Invalid { + variable: variable.to_string(), + invalid, + } + } + + fn to_error(&self) -> Error { + match self { + Self::Variables { message, detail } => Error::Variables { + message: message.clone(), + detail: detail.clone(), + }, + Self::Invalid { variable, invalid } => invalid.clone().into_error(variable), + } + } +} + +impl Clone for Operation { + fn clone(&self) -> Self { + Self { + query: self.query.clone(), + kind: self.kind, + name: self.name.clone(), + checked_against: self.checked_against, + own: self.own, + variables: self.variables.clone(), + data: PhantomData, + } + } +} + +impl std::fmt::Debug for Operation { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("Operation") + .field("kind", &self.kind) + .field("name", &self.name) + .field("query", &self.query) + .field("variables", &self.variables) + .field("checked_against", &self.checked_against) + .finish() + } +} + +/// A Rust value accepted for a GraphQL variable whose Rust type is `T`. +/// +/// `graphql!` picks `T` from the type of the variable: `String` for strings, +/// IDs, enum values and Shopify's string-encoded scalars, `i64` for `Int`, +/// `f64` for `Float`, `bool` for `Boolean`, `Value` for `JSON`, wrapped in +/// `Option` when the variable is nullable and in `Vec` for lists. The +/// implementations then accept the usual Rust spellings of those values: +/// `&str` for a string, any integer for an `Int`, a bare value for a nullable +/// variable, a slice for a list. The value converted is then checked, as +/// [`VariableType`] says. +#[diagnostic::on_unimplemented( + message = "`{Self}` is not a value for a GraphQL variable of Rust type `{T}`", + label = "the variable expects a value convertible to `{T}`" +)] +pub trait IntoVariable { + fn into_variable(self) -> T; +} + +macro_rules! into_variable { + ($target:ty: $($source:ty => |$value:ident| $convert:expr),+ $(,)?) => {$( + impl IntoVariable<$target> for $source { + fn into_variable(self) -> $target { + let $value = self; + $convert + } + } + + impl IntoVariable> for $source { + fn into_variable(self) -> Option<$target> { + Some(IntoVariable::<$target>::into_variable(self)) + } + } + )+}; +} + +into_variable!(String: + String => |value| value, + &str => |value| value.to_string(), + &String => |value| value.clone(), + Cow<'_, str> => |value| value.into_owned(), +); +into_variable!(i64: + i8 => |value| value.into(), + i16 => |value| value.into(), + i32 => |value| value.into(), + i64 => |value| value, + u8 => |value| value.into(), + u16 => |value| value.into(), + u32 => |value| value.into(), + // Saturated: out of the range of `Int` all the same, and refused. + u64 => |value| i64::try_from(value).unwrap_or(i64::MAX), + usize => |value| i64::try_from(value).unwrap_or(i64::MAX), + isize => |value| i64::try_from(value).unwrap_or(if value < 0 { i64::MIN } else { i64::MAX }), +); +into_variable!(f64: + f32 => |value| value.into(), + f64 => |value| value, + i32 => |value| value.into(), + u32 => |value| value.into(), +); +into_variable!(bool: bool => |value| value); +into_variable!(Value: + Value => |value| value, + &Value => |value| value.clone(), +); + +impl> IntoVariable> for Option { + fn into_variable(self) -> Option { + self.map(IntoVariable::into_variable) + } +} + +impl> IntoVariable> for Vec { + fn into_variable(self) -> Vec { + self.into_iter().map(IntoVariable::into_variable).collect() + } +} + +impl + Clone> IntoVariable> for &[V] { + fn into_variable(self) -> Vec { + self.iter() + .cloned() + .map(IntoVariable::into_variable) + .collect() + } +} + +impl + Clone> IntoVariable> for &Vec { + fn into_variable(self) -> Vec { + self.as_slice().into_variable() + } +} + +impl, const N: usize> IntoVariable> for [V; N] { + fn into_variable(self) -> Vec { + self.into_iter().map(IntoVariable::into_variable).collect() + } +} + +impl> IntoVariable>> for Vec { + fn into_variable(self) -> Option> { + Some(self.into_variable()) + } +} + +impl + Clone> IntoVariable>> for &[V] { + fn into_variable(self) -> Option> { + Some(self.into_variable()) + } +} + +impl + Clone> IntoVariable>> for &Vec { + fn into_variable(self) -> Option> { + Some(self.into_variable()) + } +} + +impl, const N: usize> IntoVariable>> for [V; N] { + fn into_variable(self) -> Option> { + Some(self.into_variable()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn body(operation: &Operation) -> Value { + serde_json::from_str(&operation.body().unwrap()).unwrap() + } + + fn variables(operation: Operation) -> Value { + body(&operation)["variables"].take() + } + + #[test] + fn reads_the_kind_of_a_document() { + for (document, kind) in [ + ("{ shop { name } }", OperationKind::Query), + ("query Q { shop { name } }", OperationKind::Query), + (" # comment\n mutation { a }", OperationKind::Mutation), + ("\u{feff}mutation M($x: ID!) { a }", OperationKind::Mutation), + ( + "fragment F on Shop { name \"}\" # }\n } , mutation { a { ...F } }", + OperationKind::Mutation, + ), + ( + "fragment F on Shop { name } query { shop { ...F } }", + OperationKind::Query, + ), + ("", OperationKind::Query), + ] { + assert_eq!(OperationKind::of(document), kind, "{document}"); + } + } + + /// A comment ends at `\r`, `\n` or `\r\n` (the spec's LineTerminator). + #[test] + fn a_comment_ends_at_any_line_terminator() { + for document in [ + "# comment\rmutation { tagsAdd(id: \"1\", tags: [\"a\"]) { userErrors { message } } }", + "# comment\r\nmutation { a }", + "# comment\nmutation { a }", + "query { a # }\r } mutation { b }", + "query { a } # x\rmutation { b }", + ] { + assert_eq!( + OperationKind::of(document), + OperationKind::Mutation, + "{document:?}" + ); + } + } + + /// When the document can't be read, it's treated as a mutation: never retried. + #[test] + fn a_document_it_cannot_read_is_a_mutation() { + for document in [ + "mutations", + "subscription { a }", + "query { a", + "query { a(x: \"}) } mutation { b }", + "query { a(x: \"\"\" } \" \"\"\") } mutation { b }", + "query { a } }", + "query @d(x: \"{\") { a } mutation { b }", + "query ($x: In = {a: 1}) { a } mutation { b }", + ] { + assert_eq!( + OperationKind::of(document), + OperationKind::Mutation, + "{document:?}" + ); + } + for document in [ + "query ($x: In = {a: 1}) { a(x: $x) }", + "query { a(x: \"\"\" } \\\"\"\" \"\"\") }", + "query @d(x: \"{\") { a }", + "query { a } # mutation { b }\r\n", + ] { + assert_eq!( + OperationKind::of(document), + OperationKind::Query, + "{document:?}" + ); + } + } + + #[test] + fn converts_the_usual_spellings_of_a_value() { + let operation = Operation::<()>::new("query { shop { id } }") + .variable::("id", "gid://shopify/Order/1") + .variable::, _>("query", "status:open") + .variable::, _>("after", None::) + .variable::("first", 10_u32) + .variable::("count", 3_usize) + .variable::, _>("last", Some(2)) + .variable::("ratio", 1.5_f32) + .variable::("reverse", true) + .variable::, _>("ids", ["a", "b"]) + .variable::, _>("tags", &["x".to_string()][..]) + .variable::>, _>("quantities", vec![1_u8, 2]) + .variable::>, _>("holes", vec![Some("a"), None]) + .variable::("payload", json!({ "a": 1 })) + .json_variable("input", json!({ "title": "Shirt" })); + + assert_eq!(operation.query(), "query { shop { id } }"); + assert_eq!( + variables(operation), + json!({ + "id": "gid://shopify/Order/1", + "query": "status:open", + "after": null, + "first": 10, + "count": 3, + "last": 2, + "ratio": 1.5, + "reverse": true, + "ids": ["a", "b"], + "tags": ["x"], + "quantities": [1, 2], + "holes": ["a", null], + "payload": { "a": 1 }, + "input": { "title": "Shirt" }, + }) + ); + } + + #[test] + fn values_shopify_would_not_read_as_written_are_refused_before_sending() { + let operation = || Operation::<()>::new("query { shop { id } }"); + let fits = operation() + .variable::("min", i32::MIN) + .variable::("max", i64::from(i32::MAX)) + .variable::("unsigned", u64::from(i32::MAX.unsigned_abs())) + .variable::("ratio", f64::MAX) + .variable::, _>("nullable", Value::Null) + .variable::>, _>("items", vec![Value::Null]) + .variable::("nested", json!({ "a": null })); + assert_eq!( + variables(fits), + json!({ + "min": i32::MIN, + "max": i32::MAX, + "unsigned": i32::MAX, + "ratio": f64::MAX, + "nullable": null, + "items": [null], + "nested": { "a": null }, + }) + ); + + for (operation, shown) in [ + ( + operation().variable::("big", u64::MAX), + "invalid value at `$big`: Int out of 32-bit range", + ), + ( + operation().variable::("first", 2_147_483_648_i64), + "invalid value at `$first`: Int out of 32-bit range", + ), + ( + operation().variable::, _>("last", -2_147_483_649_i64), + "invalid value at `$last`: Int out of 32-bit range", + ), + ( + operation().variable::("ratio", f64::NAN), + "invalid value at `$ratio`: not a finite Float", + ), + ( + operation().variable::, _>("ratio", f32::NEG_INFINITY), + "invalid value at `$ratio`: not a finite Float", + ), + ( + operation().variable::, _>("ratios", [1.0, f64::INFINITY]), + "invalid value at `$ratios[1]`: not a finite Float", + ), + ( + operation().variable::>, _>( + "counts", + vec![Some(1), None, Some(1_i64 << 40)], + ), + "invalid value at `$counts[2]`: Int out of 32-bit range", + ), + ( + operation().variable::("settings", Value::Null), + "invalid value at `$settings`: null for a non-null JSON field", + ), + ( + operation().variable::, _>("settings", vec![json!(1), Value::Null]), + "invalid value at `$settings[1]`: null for a non-null JSON field", + ), + ( + operation().variable::("a name", f64::NAN), + "invalid value at `$[variable]`: not a finite Float", + ), + ( + // The first refusal stays. + operation() + .variable::("first", u32::MAX) + .variable::("ratio", f64::NAN) + .variable::("first", 1), + "invalid value at `$first`: Int out of 32-bit range", + ), + ] { + let error = operation.body().unwrap_err(); + assert_eq!(error.to_string(), shown); + assert!(matches!(error, Error::InvalidValue { detail: None, .. })); + assert_eq!( + operation.variable_json("first").unwrap_err().to_string(), + shown + ); + } + } + + /// The text sent, not parsed back: no depth limit, no stack used per + /// level, no float rounded. + #[test] + fn the_body_and_the_variables_are_the_text_sent() { + let mut value = json!(0); + for _ in 0..250 { + value = json!([value]); + } + let deep = format!("{}0{}", "[".repeat(250), "]".repeat(250)); + let float = 2.3318716180463287e-130_f64; + let operation = Operation::<()>::new("query { shop { id } }") + .json_variable("deep", &value) + .variable::("x", float); + let body = std::thread::Builder::new() + .stack_size(256 * 1024) + .spawn(move || operation.body().map(|body| (body, operation))) + .unwrap() + .join() + .unwrap(); + let (body, operation) = body.unwrap(); + assert_eq!( + body, + format!( + r#"{{"query":"query {{ shop {{ id }} }}","variables":{{"deep":{deep},"x":2.3318716180463287e-130}}}}"# + ) + ); + assert_eq!( + operation.variable_json("deep").unwrap(), + Some(deep.as_str()) + ); + assert_eq!( + operation.variable_json("x").unwrap(), + Some("2.3318716180463287e-130") + ); + assert_eq!(operation.variable_json("y").unwrap(), None); + } + + #[test] + fn variables_can_come_from_a_struct() { + #[derive(serde::Serialize)] + struct Variables { + first: i64, + #[serde(skip_serializing_if = "Option::is_none")] + after: Option, + } + let operation = Operation::<()>::new("query { shop { id } }") + .variable::("ignored", 1) + .variables(Variables { + first: 5, + after: None, + }); + assert_eq!(variables(operation), json!({ "first": 5 })); + + let error = Operation::<()>::new("query { shop { id } }") + .variables(vec![1]) + .body() + .unwrap_err(); + assert_eq!( + error.to_string(), + "invalid variables: the variables must serialize to an object" + ); + } + + #[test] + fn a_value_that_does_not_serialize_is_reported_when_the_operation_runs() { + struct Broken; + impl Serialize for Broken { + fn serialize( + &self, + _serializer: S, + ) -> std::result::Result { + Err(serde::ser::Error::custom("no")) + } + } + let error = Operation::<()>::new("query { shop { id } }") + .json_variable("input", Broken) + .variable::("first", 1) + .body() + .unwrap_err(); + assert_eq!( + error.to_string(), + "invalid variables: variable `$input` does not serialize: a value's `Serialize` implementation failed" + ); + assert_eq!(error.sensitive_detail(), Some("no")); + } + + #[test] + fn the_body_holds_the_query_its_variables_and_its_name() { + let operation = Operation::<()>::__checked( + "query Shop { shop { id } }", + OperationKind::Query, + Some("Shop"), + "2026-07", + ); + assert_eq!( + operation.body().unwrap(), + r#"{"query":"query Shop { shop { id } }","operationName":"Shop"}"# + ); + assert_eq!(operation.api_version().unwrap(), ApiVersion::V2026_07); + let operation = operation.variable::("first", 1); + assert_eq!( + operation.body().unwrap(), + r#"{"query":"query Shop { shop { id } }","variables":{"first":1},"operationName":"Shop"}"# + ); + assert_eq!( + Operation::<()>::new("{ shop { id } }") + .api_version() + .unwrap(), + ApiVersion::DEFAULT + ); + } +} diff --git a/crates/shopify_api/src/graphql/response.rs b/crates/shopify_api/src/graphql/response.rs new file mode 100644 index 0000000..80c2bb9 --- /dev/null +++ b/crates/shopify_api/src/graphql/response.rs @@ -0,0 +1,271 @@ +//! What a GraphQL answer holds besides `data`: errors, user errors, cost. + +use std::fmt; + +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// An entry of the `errors` of an answer. +/// +/// Its `Debug` shows `message`, `locations`, `path` and `extensions.code`, +/// and how many other entries `extensions` has, not their names or values: +/// Shopify puts the whole value of a variable that does not validate in +/// `extensions.value`, a signed address included. The fields themselves stay +/// available. +#[derive(Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct GraphqlError { + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub locations: Option>, + /// The path of the field that failed, names and indexes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub path: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub extensions: Option, +} + +impl fmt::Debug for GraphqlError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("GraphqlError") + .field("message", &self.message) + .field("locations", &self.locations) + .field("path", &self.path) + .field("extensions", &self.extensions.as_ref().map(ExtensionsShape)) + .finish() + } +} + +/// `extensions.code`, and how many other entries there are. +struct ExtensionsShape<'a>(&'a Value); + +impl fmt::Debug for ExtensionsShape<'_> { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + let Value::Object(entries) = self.0 else { + return formatter.write_str(".."); + }; + let code = entries.get("code").and_then(Value::as_str); + let others = entries.len() - usize::from(entries.contains_key("code")); + let mut shown = formatter.debug_struct("Extensions"); + if let Some(code) = code { + shown.field("code", &code); + } + shown + .field("others", &format_args!("{others} entries")) + .finish() + } +} + +impl GraphqlError { + /// `extensions.code`, such as `THROTTLED`, `ACCESS_DENIED` or `MAX_COST_EXCEEDED`. + pub fn code(&self) -> Option<&str> { + self.extensions.as_ref()?.get("code")?.as_str() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct Location { + pub line: u32, + pub column: u32, +} + +/// An entry of the `userErrors` of a mutation: what Shopify refused, and why. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct UserError { + /// The path of the input field at fault. + #[serde(default)] + pub field: Option>, + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub code: Option, +} + +/// The cost of a query and the state of the shop's rate limit, from +/// `extensions.cost`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub struct Cost { + pub requested_query_cost: f64, + #[serde(default)] + pub actual_query_cost: Option, + pub throttle_status: ThrottleStatus, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub struct ThrottleStatus { + /// The size of the bucket. + pub maximum_available: f64, + /// What is left in it. + pub currently_available: f64, + /// What comes back each second. + pub restore_rate: f64, +} + +impl Cost { + /// How long until the bucket holds the requested cost again, in seconds. + pub fn seconds_until_available(&self) -> f64 { + let missing = self.requested_query_cost - self.throttle_status.currently_available; + if missing <= 0.0 || self.throttle_status.restore_rate <= 0.0 { + 0.0 + } else { + missing / self.throttle_status.restore_rate + } + } +} + +fn cost_of(extensions: Option<&Value>) -> Option { + serde_json::from_value(extensions?.get("cost")?.clone()).ok() +} + +/// The typed `data` of an operation, with the `extensions` of the answer. +#[derive(Debug, Clone, PartialEq)] +#[non_exhaustive] +pub struct Response { + pub data: D, + pub extensions: Option, +} + +impl Response { + /// What the operation cost, and what is left of the rate limit. + pub fn cost(&self) -> Option { + cost_of(self.extensions.as_ref()) + } +} + +/// A GraphQL answer as Shopify sent it: `data`, `errors` and `extensions`. +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] +#[non_exhaustive] +pub struct RawResponse { + #[serde(default)] + pub data: Option, + #[serde(default, deserialize_with = "errors")] + pub errors: Vec, + #[serde(default)] + pub extensions: Option, +} + +/// `errors` is a list of errors; Shopify answers a few refusals with a +/// string instead (`"errors": "Not Found"`). Anything else is one error whose +/// `extensions.value` holds it. +fn errors<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + #[derive(Deserialize)] + #[serde(untagged)] + enum Errors { + List(Vec), + Message(String), + Other(Value), + } + Ok(match Option::::deserialize(deserializer)? { + None => Vec::new(), + Some(Errors::List(errors)) => errors, + Some(Errors::Message(message)) => vec![GraphqlError { + message, + locations: None, + path: None, + extensions: None, + }], + // Kept in `extensions.value`, out of the message an error displays. + Some(Errors::Other(value)) => vec![GraphqlError { + message: "Shopify answered `errors` that are neither a list nor a string".to_string(), + locations: None, + path: None, + extensions: Some(serde_json::json!({ "value": value })), + }], + }) +} + +impl RawResponse { + pub fn cost(&self) -> Option { + cost_of(self.extensions.as_ref()) + } + + /// Shopify did not run the operation: the rate limit of the shop is reached. + pub fn is_throttled(&self) -> bool { + self.errors + .iter() + .any(|error| error.code() == Some("THROTTLED")) + } + + /// The `data` read as `T`, the path of the first mismatch in the error. + pub fn data_as(&self) -> crate::Result { + crate::decode::from_value(self.data.clone().unwrap_or(Value::Null)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn reads_errors_cost_and_throttling() { + let raw: RawResponse = serde_json::from_value(json!({ + "errors": [{ "message": "Throttled", "extensions": { "code": "THROTTLED" } }], + "extensions": { "cost": { + "requestedQueryCost": 752, + "actualQueryCost": null, + "throttleStatus": { "maximumAvailable": 2000.0, "currentlyAvailable": 252, "restoreRate": 100.0 }, + } }, + })) + .unwrap(); + assert!(raw.is_throttled()); + assert_eq!(raw.errors[0].code(), Some("THROTTLED")); + let cost = raw.cost().unwrap(); + assert_eq!(cost.requested_query_cost, 752.0); + assert_eq!(cost.seconds_until_available(), 5.0); + } + + #[test] + fn a_string_of_errors_is_one_error() { + let raw: RawResponse = serde_json::from_str(r#"{"errors":"Not Found"}"#).unwrap(); + assert_eq!(raw.errors.len(), 1); + assert_eq!(raw.errors[0].message, "Not Found"); + let raw: RawResponse = + serde_json::from_str(r#"{"data":{"shop":{"name":"x"}},"errors":null}"#).unwrap(); + assert!(raw.errors.is_empty()); + } + + #[test] + fn errors_of_another_shape_keep_their_value_out_of_the_message() { + let raw: RawResponse = + serde_json::from_str(r#"{"errors":{"token":"shpat_SECRET"}}"#).unwrap(); + assert_eq!(raw.errors.len(), 1); + let error = &raw.errors[0]; + assert!(!error.message.contains("SECRET"), "{}", error.message); + assert!(!format!("{error:?}").contains("SECRET"), "{error:?}"); + assert_eq!( + error.extensions.as_ref().unwrap()["value"]["token"], + "shpat_SECRET" + ); + } + + #[test] + fn decoding_names_the_path_of_the_mismatch() { + #[derive(Debug, Deserialize)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] + struct Data { + orders: Vec, + } + #[derive(Debug, Deserialize)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] + struct Order { + name: String, + } + let error = + crate::decode::from_value::(json!({ "orders": [{ "name": "#1" }, { "id": 2 }] })) + .unwrap_err(); + assert_eq!( + error.to_string(), + "Shopify's answer does not match the operation at `orders[1]`: missing field `name`" + ); + } +} diff --git a/crates/shopify_api/src/lib.rs b/crates/shopify_api/src/lib.rs new file mode 100644 index 0000000..c45e085 --- /dev/null +++ b/crates/shopify_api/src/lib.rs @@ -0,0 +1,115 @@ +//! A Shopify Admin GraphQL client for Rust. +//! +//! - **Checked operations.** [`graphql!`] checks a query or a mutation +//! against Shopify's Admin schema while your crate compiles, and gives its +//! variables and its result Rust types. A field that does not exist is a +//! compile error; a deprecated one is a compiler warning with Shopify's reason. +//! - **Tokens handled.** A static token, the client credentials grant, or an +//! expiring offline token: the client obtains and renews it, once for all +//! its clones, and saves it where you say ([`TokenStore`]). +//! - **Throttling handled.** A throttled request waits for the time its cost +//! needs, then goes again ([`RetryPolicy`]). +//! - **The rest of the Admin API work:** cursor [pagination](Shopify::paginate), +//! [bulk operations](crate::bulk), [webhooks] and +//! [OAuth](oauth), a [`MockTransport`](testing::MockTransport) +//! for tests, and the `shopify-api` command, which refreshes the schema +//! and checks `.graphql` files. +//! +//! ```no_run +//! use shopify_api::{Auth, Shopify, graphql}; +//! +//! # async fn run() -> shopify_api::Result<()> { +//! let shopify = Shopify::new("my-shop", Auth::access_token("shpat_…"))?; +//! +//! let data = shopify +//! .execute(graphql!( +//! "query Products($first: Int!) { +//! products(first: $first) { nodes { id title totalInventory } } +//! }", +//! first = 10, +//! )) +//! .await?; +//! +//! for product in data.products.nodes { +//! println!("{} has {:?} in stock", product.title, product.total_inventory); +//! } +//! # Ok(()) +//! # } +//! ``` +//! +//! See the [`graphql!`] macro for the mapping of types, named operations, +//! input values and the schema of other API versions, and [`input!`] for an +//! input object built ahead of a call. +//! +//! # Features +//! +//! | Feature | | +//! | --- | --- | +//! | `rustls` (default) | [`ReqwestTransport`](transport::ReqwestTransport) over rustls. | +//! | `native-tls` | The same over the platform's TLS. | +//! | `webhooks` | [`webhooks`]: verification, parsing, subscriptions. | +//! | `oauth` | [`oauth`]: install links, callbacks, token exchange, session tokens, app proxies. | +//! | `testing` | [`testing::MockTransport`], and the signing helpers of tests. | +//! | `cli` | The `shopify-api` command. | +//! | `full` | Every feature but `native-tls`: `webhooks`, `oauth`, `testing`, `cli`, over rustls. | +//! +//! The client runs on Tokio: the default transport, and the token renewals, +//! which run in tasks of their own, need a Tokio runtime. +#![forbid(unsafe_code)] +#![cfg_attr(docsrs, feature(doc_cfg))] + +// The operations of this crate use `graphql!`, whose code refers to `::shopify_api`. +extern crate self as shopify_api; + +mod auth; +pub mod bulk; +mod client; +mod decode; +mod error; +mod graphql; +mod pagination; +pub mod schema; +mod shop; +pub mod transport; +mod version; + +#[cfg(feature = "oauth")] +#[cfg_attr(docsrs, doc(cfg(feature = "oauth")))] +pub mod oauth; +#[cfg(feature = "testing")] +#[cfg_attr(docsrs, doc(cfg(feature = "testing")))] +pub mod testing; +#[cfg(feature = "webhooks")] +#[cfg_attr(docsrs, doc(cfg(feature = "webhooks")))] +pub mod webhooks; + +pub use auth::{AssociatedUser, Auth, TokenData, TokenStore}; +pub use client::{RetryPolicy, Shopify, ShopifyBuilder, USER_AGENT}; +pub use error::{Error, GraphqlErrors, OAuthErrorCode, RawBody, Result, SensitiveDetail}; +pub use graphql::{ + Cost, GraphqlError, InputObject, IntoVariable, InvalidValueReason, Location, Maybe, Operation, + OperationKind, RawResponse, Response, ThrottleStatus, UserError, VariableType, +}; +pub use pagination::Page; +pub use shop::ShopDomain; +pub use version::ApiVersion; + +/// Checks a Shopify Admin GraphQL operation against Shopify's schema while +/// the crate compiles, and gives its variables and its result Rust types. +#[doc = include_str!("../docs/graphql.md")] +pub use shopify_api_macros::graphql; + +/// Builds an input object of the schema, checked like a literal of +/// [`graphql!`]: `input!(MetafieldsSetInput { key: "color", … })`. +#[doc = include_str!("../docs/input.md")] +pub use shopify_api_macros::input; + +/// What the code `graphql!` and `input!` generate refers to. Not a public API. +#[doc(hidden)] +pub mod __private { + pub use crate::bulk::__private as bulk; + pub use crate::graphql::literal; + pub use crate::{InputObject, Maybe, Operation, OperationKind, Result}; + pub use serde; + pub use serde_json; +} diff --git a/crates/shopify_api/src/oauth.rs b/crates/shopify_api/src/oauth.rs new file mode 100644 index 0000000..f90cb50 --- /dev/null +++ b/crates/shopify_api/src/oauth.rs @@ -0,0 +1,1315 @@ +//! OAuth and the requests Shopify signs for an app: install links and their +//! callback, session tokens and the token exchange of embedded apps, app proxies. +//! +//! An embedded app gets its tokens from the session token of each request: +//! +//! ```no_run +//! use shopify_api::oauth::{RequestedToken, ShopifyApp}; +//! +//! # async fn handle(bearer: &str) -> shopify_api::Result<()> { +//! let app = ShopifyApp::new("client-id", "client-secret"); +//! +//! // `Authorization: Bearer …` of a request from the app's frontend. +//! let session = app.verify_session_token(bearer)?; +//! let token = app.exchange_session_token(&session, RequestedToken::ExpiringOffline).await?; +//! // Store `token` (it serializes), then: +//! let shopify = app.client(session.shop(), token)?; +//! # Ok(()) +//! # } +//! ``` +//! +//! [`verify_session_token`](ShopifyApp::verify_session_token) takes only the +//! tokens of Shopify admin, which a staff member's browser sends. The tokens +//! of checkout and customer account UI extensions, which any buyer gets, are +//! verified by [`verify_extension_session_token`](ShopifyApp::verify_extension_session_token), +//! as an [`ExtensionSessionToken`]: a type of its own, so that one never +//! passes for the other. +//! +//! An app outside Shopify admin installs through a link and a callback: +//! +//! ```no_run +//! use shopify_api::ShopDomain; +//! use shopify_api::oauth::{AuthorizationRequest, ShopifyApp}; +//! +//! # async fn run(query_of_the_callback: &str) -> shopify_api::Result<()> { +//! let app = ShopifyApp::new("client-id", "client-secret"); +//! let shop = ShopDomain::new("my-shop")?; +//! let link = app.authorization_url( +//! &shop, +//! &AuthorizationRequest::new("https://example.com/auth/callback", "a-random-state") +//! .scopes(["read_products", "write_orders"]), +//! ); +//! +//! // On the callback: check the signature, then the state you stored. +//! let callback = app.verify_query(query_of_the_callback)?; +//! assert_eq!(callback.get("state"), Some("a-random-state")); +//! let token = app.exchange_code(&callback).await?; +//! # Ok(()) +//! # } +//! ``` + +use std::sync::Arc; + +use base64::Engine; +use base64::alphabet::URL_SAFE; +use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig}; +use chrono::{DateTime, TimeZone, Utc}; +use hmac::{Hmac, KeyInit, Mac}; +use serde_json::Value; +use sha2::Sha256; + +use crate::auth::{Encoding, request_token}; +use crate::transport::{Transport, default_transport}; +use crate::{ + Auth, Error, Result, ShopDomain, Shopify, ShopifyBuilder, TokenData, TokenStore, USER_AGENT, +}; + +/// How far the `timestamp` of a signed query may be from now, as Shopify's libraries allow. +const QUERY_TOLERANCE_SECONDS: i64 = 90; + +/// How far `exp` and `nbf` of a session token may be from now, as Shopify's libraries allow. +const JWT_TOLERANCE_SECONDS: i64 = 10; + +/// The parameters of an app proxy request that Shopify sends once. +const PROXY_SINGLE_VALUES: [&str; 4] = ["hmac", "shop", "signature", "timestamp"]; + +/// base64url, with or without padding. +const BASE64_URL: GeneralPurpose = GeneralPurpose::new( + &URL_SAFE, + GeneralPurposeConfig::new() + .with_encode_padding(false) + .with_decode_padding_mode(DecodePaddingMode::Indifferent), +); + +fn mac(secret: &str) -> Hmac { + Hmac::::new_from_slice(secret.as_bytes()).expect("HMAC takes a key of any length") +} + +fn invalid(message: impl Into) -> Error { + Error::Verification(message.into()) +} + +/// An app: its client ID and secret, what it signs and verifies, and the +/// tokens it obtains for shops. +#[derive(Clone)] +pub struct ShopifyApp { + client_id: String, + client_secret: String, + transport: Option>, + token_store: Option>, + user_agent: String, +} + +impl std::fmt::Debug for ShopifyApp { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ShopifyApp") + .field("client_id", &self.client_id) + .field("token_store", &self.token_store.is_some()) + .finish_non_exhaustive() + } +} + +/// What the install link asks the merchant for. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuthorizationRequest { + redirect_uri: String, + state: String, + scopes: Vec, + online: bool, +} + +impl AuthorizationRequest { + /// `redirect_uri` is one of the app's allowed redirection addresses; + /// `state` a random value you keep for the browser, and compare on the callback. + pub fn new(redirect_uri: impl Into, state: impl Into) -> Self { + Self { + redirect_uri: redirect_uri.into(), + state: state.into(), + scopes: Vec::new(), + online: false, + } + } + + /// The access scopes, such as `read_products`. + pub fn scopes, S: Into>(mut self, scopes: I) -> Self { + self.scopes = scopes.into_iter().map(Into::into).collect(); + self + } + + /// An online token, bound to the staff member who installs, instead of + /// an offline token of the shop. + pub fn online(mut self) -> Self { + self.online = true; + self + } +} + +/// A query string whose signature was verified: an OAuth callback, a launch +/// from Shopify admin, an app proxy request. +/// +/// `Debug` shows the names of the parameters and the shop, not the values, +/// which hold an authorization code or a session token. +#[derive(Clone, PartialEq, Eq)] +pub struct SignedQuery { + params: Vec<(String, String)>, + shop: Option, +} + +impl std::fmt::Debug for SignedQuery { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let names: Vec<&str> = self.params.iter().map(|(name, _)| name.as_str()).collect(); + formatter + .debug_struct("SignedQuery") + .field("params", &names) + .field("shop", &self.shop) + .finish() + } +} + +impl SignedQuery { + /// The first value of a parameter. + pub fn get(&self, name: &str) -> Option<&str> { + self.params + .iter() + .find(|(given, _)| given == name) + .map(|(_, value)| value.as_str()) + } + + /// Every parameter, as received. + pub fn params(&self) -> &[(String, String)] { + &self.params + } + + /// The `shop` parameter, when it is a shop's domain. + pub fn shop(&self) -> Option<&ShopDomain> { + self.shop.as_ref() + } +} + +/// The token an embedded app asks for with a session token. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum RequestedToken { + /// A token of the shop that does not expire. + Offline, + /// A token of the shop that expires after an hour, with a refresh token. + ExpiringOffline, + /// A token bound to the staff member of the session. + Online, +} + +/// A session token of Shopify admin, from [`ShopifyApp::verify_session_token`]: +/// its signature, dates, `dest` and `iss` were verified. +/// +/// Only Shopify admin issues it, to a staff member of the shop: it is what +/// opens the admin side of an app. The tokens of checkout and customer account +/// UI extensions, which any buyer gets, are an [`ExtensionSessionToken`]. +/// +/// `Debug` hides the token itself, which is a bearer. +#[derive(Clone, PartialEq)] +pub struct SessionToken { + shop: ShopDomain, + user_id: Option, + session_id: Option, + expires_at: DateTime, + claims: Value, + token: String, +} + +impl std::fmt::Debug for SessionToken { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("SessionToken") + .field("shop", &self.shop) + .field("user_id", &self.user_id) + .field("session_id", &self.session_id) + .field("expires_at", &self.expires_at) + .finish_non_exhaustive() + } +} + +impl SessionToken { + /// The shop of `dest`. + pub fn shop(&self) -> &ShopDomain { + &self.shop + } + + /// `sub`: the ID of the staff member, such as `42`. + pub fn user_id(&self) -> Option<&str> { + self.user_id.as_deref() + } + + /// The session, `sid`. + pub fn session_id(&self) -> Option<&str> { + self.session_id.as_deref() + } + + pub fn expires_at(&self) -> DateTime { + self.expires_at + } + + /// Every claim of the token. + pub fn claims(&self) -> &Value { + &self.claims + } + + /// The token itself, as the frontend sent it. + pub fn as_str(&self) -> &str { + &self.token + } +} + +/// A session token of a checkout or customer account UI extension, from +/// [`ShopifyApp::verify_extension_session_token`]: its signature, dates and +/// `dest` were verified. +/// +/// Any buyer of the shop gets one, logged in or not: it proves which shop +/// and, through [`customer`](Self::customer), which customer, never a staff +/// member. It is not a [`SessionToken`], and does not exchange for a token. +/// +/// `Debug` hides the token itself, which is a bearer. +#[derive(Clone, PartialEq)] +pub struct ExtensionSessionToken { + shop: ShopDomain, + customer: Option, + expires_at: DateTime, + claims: Value, + token: String, +} + +impl std::fmt::Debug for ExtensionSessionToken { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ExtensionSessionToken") + .field("shop", &self.shop) + .field("customer", &self.customer) + .field("expires_at", &self.expires_at) + .finish_non_exhaustive() + } +} + +impl ExtensionSessionToken { + /// The shop of `dest`. + pub fn shop(&self) -> &ShopDomain { + &self.shop + } + + /// `sub`: the GID of the logged-in customer, such as + /// `gid://shopify/Customer/1`. Shopify only sends it when a customer is + /// logged in and the app may read customers. `None` for an admin token, + /// whose `sub` is a staff member, not a customer: it stays in + /// [`claims`](Self::claims). + pub fn customer(&self) -> Option<&str> { + self.customer.as_deref() + } + + pub fn expires_at(&self) -> DateTime { + self.expires_at + } + + /// Every claim of the token. + pub fn claims(&self) -> &Value { + &self.claims + } + + /// The token itself, as the extension sent it. + pub fn as_str(&self) -> &str { + &self.token + } +} + +/// The claims of a session token whose signature, dates and audience were verified. +struct Verified { + claims: Value, + expires_at: DateTime, + token: String, +} + +impl Verified { + fn text(&self, name: &str) -> Option { + self.claims + .get(name) + .and_then(Value::as_str) + .map(str::to_string) + } + + fn claim(&self, name: &str) -> Option<&str> { + self.claims.get(name).and_then(Value::as_str) + } +} + +/// The shop of a host that is a whole `*.myshopify.com` domain. +fn shop_of_host(host: &str) -> Result { + Some(host) + // A whole domain: a bare handle is not what Shopify writes. + .filter(|host| host.to_ascii_lowercase().ends_with(".myshopify.com")) + .and_then(|host| ShopDomain::new(host).ok()) + .ok_or_else(|| invalid("the `dest` of the session token is not a shop")) +} + +/// Checks that `iss` is exactly the admin of `shop`. +fn check_admin_issuer(issuer: &str, shop: &ShopDomain) -> Result<()> { + if issuer == format!("{}/admin", shop.origin()) { + Ok(()) + } else { + Err(invalid( + "the `iss` of the session token is not the admin of its `dest`", + )) + } +} + +impl ShopifyApp { + pub fn new(client_id: impl Into, client_secret: impl Into) -> Self { + Self { + client_id: client_id.into(), + client_secret: client_secret.into(), + // Without one, the requests that need it fail with `NoTransport`. + transport: default_transport().ok(), + token_store: None, + user_agent: USER_AGENT.to_string(), + } + } + + /// Sends the token requests, and the requests of the clients it builds, + /// through `transport`. + pub fn with_transport(mut self, transport: impl Transport) -> Self { + self.transport = Some(Arc::new(transport)); + self + } + + /// Saves the tokens that the clients it builds obtain or renew: the + /// refresh token of an expiring token changes at each renewal. The store + /// is told the shop of each token. + pub fn with_token_store(mut self, store: impl TokenStore) -> Self { + self.token_store = Some(Arc::new(store)); + self + } + + pub fn with_user_agent(mut self, user_agent: impl Into) -> Self { + self.user_agent = user_agent.into(); + self + } + + pub fn client_id(&self) -> &str { + &self.client_id + } + + fn transport(&self) -> Result<&dyn Transport> { + self.transport.as_deref().ok_or(Error::NoTransport) + } + + /// The secret to verify with. An empty one would verify what anyone signs. + fn secret(&self) -> Result<&str> { + if self.client_secret.is_empty() { + return Err(invalid( + "the client secret of the app is empty: nothing can be verified with it", + )); + } + Ok(&self.client_secret) + } + + // ─── Clients ───────────────────────────────────────────────────── + + /// A builder of a client of `shop` that uses the app's transport and + /// token store. + pub fn builder(&self, shop: &ShopDomain) -> ShopifyBuilder { + let mut builder = Shopify::builder(shop).user_agent(&self.user_agent); + if let Some(transport) = &self.transport { + builder = builder.shared_transport(transport.clone()); + } + if let Some(store) = &self.token_store { + builder = builder.shared_token_store(store.clone()); + } + builder + } + + /// A client of `shop` with a token the app obtained: renewed with its + /// refresh token when it has one, used as it is otherwise. The renewed + /// tokens go to the app's [token store](Self::with_token_store). + pub fn client(&self, shop: &ShopDomain, token: TokenData) -> Result { + let auth = if token.refresh_token.is_some() { + Auth::expiring_token(&self.client_id, &self.client_secret, token) + } else { + Auth::token(token) + }; + self.builder(shop).auth(auth).build() + } + + /// A client of `shop` that gets its tokens with the client credentials + /// grant: for a shop of the organization that owns the app. + pub fn client_credentials_client(&self, shop: &ShopDomain) -> Result { + self.builder(shop) + .client_credentials(&self.client_id, &self.client_secret) + .build() + } + + // ─── Install link and callback ─────────────────────────────────── + + /// The address that asks the merchant to install the app. + pub fn authorization_url(&self, shop: &ShopDomain, request: &AuthorizationRequest) -> String { + let scope = request.scopes.join(","); + let mut params = vec![ + ("client_id", self.client_id.as_str()), + ("scope", scope.as_str()), + ("redirect_uri", request.redirect_uri.as_str()), + ("state", request.state.as_str()), + ]; + if request.online { + params.push(("grant_options[]", "per-user")); + } + let query = serde_urlencoded::to_string(¶ms) + .unwrap_or_default() + .replace('+', "%20"); + format!("https://{shop}/admin/oauth/authorize?{query}") + } + + /// Exchanges the `code` of a verified callback for a token. + pub async fn exchange_code(&self, callback: &SignedQuery) -> Result { + self.exchange_code_with(callback, false).await + } + + /// [`ShopifyApp::exchange_code`], asking for an expiring offline token + /// with a refresh token. + pub async fn exchange_code_expiring(&self, callback: &SignedQuery) -> Result { + self.exchange_code_with(callback, true).await + } + + async fn exchange_code_with( + &self, + callback: &SignedQuery, + expiring: bool, + ) -> Result { + let shop = callback + .shop() + .ok_or_else(|| invalid("the callback has no valid `shop`"))?; + let code = callback + .get("code") + .filter(|code| !code.is_empty()) + .ok_or_else(|| invalid("the callback has no `code`"))?; + let mut fields = vec![ + ("client_id", self.client_id.as_str()), + ("client_secret", self.client_secret.as_str()), + ("code", code), + ]; + if expiring { + fields.push(("expiring", "1")); + } + request_token( + self.transport()?, + shop, + &self.user_agent, + Encoding::Json, + &fields, + ) + .await + } + + // ─── Signed queries ────────────────────────────────────────────── + + /// Verifies the `hmac` of a query string from Shopify admin: the OAuth + /// callback, a launch of the app, an admin link. Its `timestamp` must be + /// within 90 seconds of now. + /// + /// `query` is the raw query string, with or without its `?`. The message + /// signed is the one Shopify's JavaScript library computes: the + /// parameters but `hmac` and `signature`, sorted by name, form-encoded, + /// the values of a repeated one (`ids[]`) joined with commas. + pub fn verify_query(&self, query: &str) -> Result { + self.verify_query_at(query, Utc::now()) + } + + fn verify_query_at(&self, query: &str, now: DateTime) -> Result { + let params = parse_query(query)?; + let signature = + single(¶ms, "hmac")?.ok_or_else(|| invalid("the query has no `hmac`"))?; + let expected = hex::decode(signature) + .map_err(|_| invalid("the `hmac` of the query is not hexadecimal"))?; + let mut mac = mac(self.secret()?); + mac.update(admin_message(¶ms).as_bytes()); + mac.verify_slice(&expected) + .map_err(|_| invalid("the signature of the query does not match"))?; + // Only once the signature holds: nothing unsigned reaches the clock. + check_timestamp(¶ms, now)?; + Ok(signed(params)) + } + + /// The `hmac` Shopify signs a query of Shopify admin with: for tests. + #[cfg(any(test, feature = "testing"))] + #[cfg_attr(docsrs, doc(cfg(feature = "testing")))] + pub fn sign_query(&self, query: &str) -> Result { + let params = parse_query(query)?; + let mut mac = mac(&self.client_secret); + mac.update(admin_message(¶ms).as_bytes()); + Ok(hex::encode(mac.finalize().into_bytes())) + } + + /// Verifies the `signature` of an app proxy request. Its `timestamp` + /// must be within 90 seconds of now. + /// + /// The message signed is the one Shopify computes: for each parameter but + /// `signature`, the string `name=value` (decoded, the values of a repeated + /// one joined with commas), these strings sorted and joined with nothing. + /// The whole strings are sorted, not the names: `page2=x` comes before + /// `page=1`. + pub fn verify_app_proxy(&self, query: &str) -> Result { + self.verify_app_proxy_at(query, Utc::now()) + } + + fn verify_app_proxy_at(&self, query: &str, now: DateTime) -> Result { + let params = parse_query(query)?; + for name in PROXY_SINGLE_VALUES { + single(¶ms, name)?; + } + let signature = + single(¶ms, "signature")?.ok_or_else(|| invalid("the query has no `signature`"))?; + let expected = hex::decode(signature) + .map_err(|_| invalid("the `signature` of the query is not hexadecimal"))?; + let mut mac = mac(self.secret()?); + mac.update(proxy_message(¶ms).as_bytes()); + mac.verify_slice(&expected) + .map_err(|_| invalid("the signature of the app proxy request does not match"))?; + // Only once the signature holds: nothing unsigned reaches the clock. + check_timestamp(¶ms, now)?; + Ok(signed(params)) + } + + /// The `signature` Shopify signs an app proxy request with: for tests. + #[cfg(any(test, feature = "testing"))] + #[cfg_attr(docsrs, doc(cfg(feature = "testing")))] + pub fn sign_app_proxy(&self, query: &str) -> Result { + let params = parse_query(query)?; + let mut mac = mac(&self.client_secret); + mac.update(proxy_message(¶ms).as_bytes()); + Ok(hex::encode(mac.finalize().into_bytes())) + } + + // ─── Session tokens ────────────────────────────────────────────── + + /// Verifies a session token of Shopify admin (the bearer of the requests + /// of the app's embedded frontend): signed by the app's secret with HS256, + /// issued for the app, within its dates, with a `dest` of exactly + /// `https://{shop}.myshopify.com` and an `iss` of exactly + /// `https://{shop}.myshopify.com/admin`. + /// + /// Only Shopify admin issues such a token, to a staff member: trust it to + /// open the admin side of the app, such as loading the shop's stored + /// offline token. The tokens of checkout and customer account UI + /// extensions, which any buyer gets, are refused here: verify them with + /// [`verify_extension_session_token`](Self::verify_extension_session_token). + pub fn verify_session_token(&self, token: &str) -> Result { + self.verify_session_token_at(token, Utc::now()) + } + + fn verify_session_token_at(&self, token: &str, now: DateTime) -> Result { + let verified = self.verify_jwt(token, now)?; + let destination = verified + .claim("dest") + .ok_or_else(|| invalid("the session token has no `dest`"))?; + let shop = destination + .strip_prefix("https://") + .ok_or_else(|| invalid("the `dest` of the session token is not the admin of a shop")) + .and_then(shop_of_host)?; + if destination != shop.origin() { + return Err(invalid("the `dest` of the session token is not a shop")); + } + let issuer = verified.claim("iss").ok_or_else(|| { + invalid("the session token has no `iss`: it is not from Shopify admin") + })?; + check_admin_issuer(issuer, &shop)?; + Ok(SessionToken { + user_id: verified.text("sub"), + session_id: verified.text("sid"), + shop, + expires_at: verified.expires_at, + claims: verified.claims, + token: verified.token, + }) + } + + /// Verifies the session token of a checkout or customer account UI + /// extension (`shopify.sessionToken.get()`): signed by the app's secret with + /// HS256, issued for the app, within its dates, with a `dest` that is a + /// `*.myshopify.com` domain (Shopify writes it without `https://`). An + /// `iss`, when there is one, must be exactly `https://{shop}.myshopify.com/admin`. + /// + /// Any buyer of the shop can get such a token: it proves the shop and, + /// when one is logged in, the customer, never a staff member. It is a type + /// of its own so that it cannot reach what a [`SessionToken`] opens. + pub fn verify_extension_session_token(&self, token: &str) -> Result { + self.verify_extension_session_token_at(token, Utc::now()) + } + + fn verify_extension_session_token_at( + &self, + token: &str, + now: DateTime, + ) -> Result { + let verified = self.verify_jwt(token, now)?; + let destination = verified + .claim("dest") + .ok_or_else(|| invalid("the session token has no `dest`"))?; + let shop = shop_of_host(destination.strip_prefix("https://").unwrap_or(destination))?; + if let Some(issuer) = verified.claim("iss") { + check_admin_issuer(issuer, &shop)?; + } + Ok(ExtensionSessionToken { + // Only a customer's GID: the `sub` of an admin token is a staff member. + customer: verified + .text("sub") + .filter(|sub| sub.starts_with("gid://shopify/Customer/")), + shop, + expires_at: verified.expires_at, + claims: verified.claims, + token: verified.token, + }) + } + + /// The signature, dates and audience of a session token, the same for every kind. + fn verify_jwt(&self, token: &str, now: DateTime) -> Result { + let token = token.trim(); + let token = token.strip_prefix("Bearer ").unwrap_or(token); + let mut parts = token.split('.'); + let (Some(header), Some(payload), Some(signature), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + return Err(invalid("the session token is not a JWT")); + }; + let decode = |part: &str| { + BASE64_URL + .decode(part) + .map_err(|_| invalid("the session token is not base64url")) + }; + let header: Value = serde_json::from_slice(&decode(header)?) + .map_err(|_| invalid("the session token has an invalid header"))?; + if header.get("alg").and_then(Value::as_str) != Some("HS256") { + return Err(invalid("the session token is not signed with HS256")); + } + let mut mac = mac(self.secret()?); + // What is signed: the header and the payload, with the dot between them. + mac.update(&token.as_bytes()[..token.len() - signature.len() - 1]); + mac.verify_slice(&decode(signature)?) + .map_err(|_| invalid("the signature of the session token does not match"))?; + + let claims: Value = serde_json::from_slice(&decode(payload)?) + .map_err(|_| invalid("the session token has invalid claims"))?; + let time = |name: &str| claims.get(name).and_then(Value::as_i64); + let now = now.timestamp(); + let expires = time("exp").ok_or_else(|| invalid("the session token has no `exp`"))?; + if now > expires.saturating_add(JWT_TOLERANCE_SECONDS) { + return Err(invalid("the session token has expired")); + } + if time("nbf") + .is_some_and(|not_before| now < not_before.saturating_sub(JWT_TOLERANCE_SECONDS)) + { + return Err(invalid("the session token is not valid yet")); + } + let audience_matches = match claims.get("aud") { + Some(Value::String(audience)) => audience == &self.client_id, + Some(Value::Array(audiences)) => audiences + .iter() + .any(|audience| audience.as_str() == Some(&self.client_id)), + _ => false, + }; + if !audience_matches { + return Err(invalid("the session token was issued for another app")); + } + Ok(Verified { + expires_at: Utc + .timestamp_opt(expires, 0) + .single() + .ok_or_else(|| invalid("the `exp` of the session token is out of range"))?, + claims, + token: token.to_string(), + }) + } + + /// A session token signed with the app's secret, as Shopify makes them: + /// for tests. `claims` should hold `iss`, `dest`, `aud`, `exp` and `nbf`. + #[cfg(any(test, feature = "testing"))] + #[cfg_attr(docsrs, doc(cfg(feature = "testing")))] + pub fn sign_session_token(&self, claims: &Value) -> String { + let header = BASE64_URL.encode(br#"{"alg":"HS256","typ":"JWT"}"#); + let payload = BASE64_URL.encode(serde_json::to_vec(claims).unwrap_or_default()); + let mut mac = mac(&self.client_secret); + mac.update(format!("{header}.{payload}").as_bytes()); + let signature = BASE64_URL.encode(mac.finalize().into_bytes()); + format!("{header}.{payload}.{signature}") + } + + /// Exchanges a verified session token for an access token of its shop. + pub async fn exchange_session_token( + &self, + session: &SessionToken, + requested: RequestedToken, + ) -> Result { + let (requested_type, expiring) = match requested { + RequestedToken::Offline => ( + "urn:shopify:params:oauth:token-type:offline-access-token", + "0", + ), + RequestedToken::ExpiringOffline => ( + "urn:shopify:params:oauth:token-type:offline-access-token", + "1", + ), + RequestedToken::Online => ( + "urn:shopify:params:oauth:token-type:online-access-token", + "0", + ), + }; + let fields = [ + ("client_id", self.client_id.as_str()), + ("client_secret", self.client_secret.as_str()), + ( + "grant_type", + "urn:ietf:params:oauth:grant-type:token-exchange", + ), + ("subject_token", session.as_str()), + ( + "subject_token_type", + "urn:ietf:params:oauth:token-type:id_token", + ), + ("requested_token_type", requested_type), + ("expiring", expiring), + ]; + request_token( + self.transport()?, + session.shop(), + &self.user_agent, + Encoding::Json, + &fields, + ) + .await + } +} + +fn parse_query(query: &str) -> Result> { + let query = query.trim(); + let query = query.strip_prefix('?').unwrap_or(query); + serde_urlencoded::from_str(query).map_err(|_| invalid("the query string does not parse")) +} + +/// The value of a parameter that must not appear twice. +fn single<'a>(params: &'a [(String, String)], name: &str) -> Result> { + let mut values = params.iter().filter(|(given, _)| given == name); + let first = values.next().map(|(_, value)| value.as_str()); + if values.next().is_some() { + return Err(invalid(format!("the query has `{name}` more than once"))); + } + Ok(first) +} + +fn check_timestamp(params: &[(String, String)], now: DateTime) -> Result<()> { + let timestamp: i64 = single(params, "timestamp")? + .and_then(|timestamp| timestamp.parse().ok()) + .ok_or_else(|| invalid("the query has no valid `timestamp`"))?; + // `abs_diff`: any `i64` timestamp, however far, is a distance, not an overflow. + if now.timestamp().abs_diff(timestamp) > QUERY_TOLERANCE_SECONDS.unsigned_abs() { + return Err(invalid( + "the `timestamp` of the query is more than 90 seconds away", + )); + } + Ok(()) +} + +/// The parameters signed: every one but the signature, the values of a +/// repeated one joined with commas, in the order they first appear. +fn grouped_params(params: &[(String, String)]) -> Vec<(String, String)> { + let mut grouped: Vec<(String, String)> = Vec::new(); + for (name, value) in params { + if name == "hmac" || name == "signature" { + continue; + } + match grouped.iter_mut().find(|(given, _)| given == name) { + Some((_, joined)) => { + joined.push(','); + joined.push_str(value); + } + None => grouped.push((name.clone(), value.clone())), + } + } + grouped +} + +/// What Shopify admin signs: `name=value` pairs sorted by name, +/// form-encoded with `%20` for spaces, joined with `&`. +fn admin_message(params: &[(String, String)]) -> String { + let mut grouped = grouped_params(params); + grouped.sort_by(|left, right| left.0.cmp(&right.0)); + serde_urlencoded::to_string(grouped) + .unwrap_or_default() + .replace('+', "%20") +} + +/// What an app proxy signs: the `name=value` strings, as received, sorted +/// as whole strings and joined with nothing. +/// +/// Not sorted by name: Shopify sorts the strings, so `page2=x` comes before +/// `page=1` (`2` sorts before `=`), where a sort by name puts `page` first. +fn proxy_message(params: &[(String, String)]) -> String { + let mut pairs: Vec = grouped_params(params) + .into_iter() + .map(|(name, value)| format!("{name}={value}")) + .collect(); + pairs.sort_unstable(); + pairs.concat() +} + +fn signed(params: Vec<(String, String)>) -> SignedQuery { + let shop = params + .iter() + .find(|(name, _)| name == "shop") + .and_then(|(_, shop)| ShopDomain::new(shop).ok()); + SignedQuery { params, shop } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn app() -> ShopifyApp { + ShopifyApp::new("client-id", "hush") + } + + fn at(timestamp: i64) -> DateTime { + Utc.timestamp_opt(timestamp, 0).unwrap() + } + + #[test] + fn verifies_the_example_of_shopify_documentation() { + // The OAuth callback of Shopify's documentation, signed with "hush". + let query = "code=0907a61c0c8d55e99db179b68161bc00&hmac=700e2dadb827fcc8609e9d5ce208b2e9cdaab9df07390d2cbca10d7c328fc4bf&shop=some-shop.myshopify.com&state=0.6784241404160823×tamp=1337178173"; + let callback = app().verify_query_at(query, at(1337178173 + 30)).unwrap(); + assert_eq!( + callback.get("code"), + Some("0907a61c0c8d55e99db179b68161bc00") + ); + assert_eq!(callback.shop().unwrap().as_str(), "some-shop.myshopify.com"); + + let error = app() + .verify_query_at(query, at(1337178173 + 91)) + .unwrap_err(); + assert_eq!( + error.to_string(), + "verification failed: the `timestamp` of the query is more than 90 seconds away" + ); + let tampered = query.replace("some-shop", "other-shop"); + assert_eq!( + app() + .verify_query_at(&tampered, at(1337178173)) + .unwrap_err() + .to_string(), + "verification failed: the signature of the query does not match" + ); + } + + #[test] + fn extreme_timestamps_are_rejected_without_panicking() { + for timestamp in [i64::MIN, i64::MAX] { + let query = format!("timestamp={timestamp}&hmac=00&signature=00"); + for result in [ + app().verify_query_at(&query, at(1_700_000_000)), + app().verify_app_proxy_at(&query, at(1_700_000_000)), + ] { + assert!(matches!(result, Err(Error::Verification(_))), "{result:?}"); + } + // Signed, so only the timestamp fails. + let unsigned = format!("shop=a.myshopify.com×tamp={timestamp}"); + let hmac = app().sign_query(&unsigned).unwrap(); + let error = app() + .verify_query_at(&format!("{unsigned}&hmac={hmac}"), at(1_700_000_000)) + .unwrap_err(); + assert!(error.to_string().contains("90 seconds"), "{error}"); + let signature = app().sign_app_proxy(&unsigned).unwrap(); + let error = app() + .verify_app_proxy_at( + &format!("{unsigned}&signature={signature}"), + at(1_700_000_000), + ) + .unwrap_err(); + assert!(error.to_string().contains("90 seconds"), "{error}"); + } + } + + #[test] + fn extreme_session_token_times_do_not_panic() { + let now = 1_700_000_000; + for (exp, nbf) in [(i64::MAX, now), (now + 60, i64::MIN), (i64::MIN, now)] { + let token = app().sign_session_token(&json!({ + "iss": "https://a.myshopify.com/admin", + "dest": "https://a.myshopify.com", + "aud": "client-id", + "exp": exp, + "nbf": nbf, + })); + let _ = app().verify_session_token_at(&token, at(now)); + } + } + + #[test] + fn signs_queries_as_shopify_admin_does() { + // Spaces as %20, repeated values joined, names sorted, the signature left out. + let params = + parse_query("shop=a.myshopify.com&ids[]=2&ids[]=3×tamp=10¬e=a b&hmac=x") + .unwrap(); + assert_eq!( + admin_message(¶ms), + "ids%5B%5D=2%2C3¬e=a%20b&shop=a.myshopify.com×tamp=10" + ); + let query = format!( + "timestamp={}&shop=a.myshopify.com&host=YWRtaW4", + Utc::now().timestamp() + ); + let signature = app().sign_query(&query).unwrap(); + assert!( + app() + .verify_query(&format!("?{query}&hmac={signature}")) + .is_ok() + ); + assert_eq!( + app().verify_query(&query).unwrap_err().to_string(), + "verification failed: the query has no `hmac`" + ); + } + + #[test] + fn verifies_app_proxy_requests() { + let now = Utc::now().timestamp(); + let query = + format!("shop=a.myshopify.com&path_prefix=%2Fapps%2Fx×tamp={now}&extra=1&extra=2"); + assert_eq!( + proxy_message(&parse_query(&query).unwrap()), + format!("extra=1,2path_prefix=/apps/xshop=a.myshopify.comtimestamp={now}") + ); + let signature = app().sign_app_proxy(&query).unwrap(); + let verified = app() + .verify_app_proxy(&format!("{query}&signature={signature}")) + .unwrap(); + assert_eq!(verified.get("path_prefix"), Some("/apps/x")); + assert!( + app() + .verify_app_proxy(&format!( + "{query}&signature={signature}&shop=b.myshopify.com" + )) + .is_err() + ); + } + + #[test] + fn app_proxy_signs_the_sorted_name_value_strings() { + // Shopify sorts `name=value` whole: `page2=x` before `page=1` + // ('2' < '='), `filter.v.price.gte=10` before `filter=red` ('.' < '='). + // The signature below is HMAC-SHA256("hush", message), computed + // outside the crate (`openssl dgst -sha256 -hmac hush`). + let query = "page=1&page2=x&filter=red&filter.v.price.gte=10\ + &shop=a.myshopify.com&path_prefix=%2Fapps%2Fx×tamp=1700000000"; + let message = "filter.v.price.gte=10filter=redpage2=xpage=1\ + path_prefix=/apps/xshop=a.myshopify.comtimestamp=1700000000"; + let signature = "e640778c56c80f8a92904d2b740665f8dd3b3d2d0f30095aa325bf576074f0f9"; + assert_eq!(proxy_message(&parse_query(query).unwrap()), message); + assert_eq!(app().sign_app_proxy(query).unwrap(), signature); + let verified = app() + .verify_app_proxy_at(&format!("{query}&signature={signature}"), at(1_700_000_000)) + .unwrap(); + assert_eq!(verified.get("page2"), Some("x")); + + // `-` sorts before `=` as well. + assert_eq!( + proxy_message(&parse_query("filter=red&filter-x=1").unwrap()), + "filter-x=1filter=red" + ); + assert_eq!( + app().sign_app_proxy("filter=red&filter-x=1").unwrap(), + "31d2d42ad3281aaaf8ca1a9b40f2b21387aee62103e43c3b1564938817b26205" + ); + } + + fn claims(now: i64) -> Value { + json!({ + "iss": "https://my-shop.myshopify.com/admin", + "dest": "https://my-shop.myshopify.com", + "aud": "client-id", + "sub": "42", + "exp": now + 60, + "nbf": now - 1, + "iat": now - 1, + "jti": "f8912129-1af6-4cad-9ca3-76b0f7621087", + "sid": "aaea182f2732d44c23057c0fea584021a4485b2bd25d3eb7fd349313ad24c685", + }) + } + + #[test] + fn verifies_session_tokens() { + let now = 1_800_000_000; + let token = app().sign_session_token(&claims(now)); + let session = app() + .verify_session_token_at(&format!("Bearer {token}"), at(now)) + .unwrap(); + assert_eq!(session.shop().as_str(), "my-shop.myshopify.com"); + assert_eq!(session.user_id(), Some("42")); + assert_eq!(session.session_id(), claims(now)["sid"].as_str()); + assert_eq!(session.expires_at(), at(now + 60)); + assert_eq!(session.as_str(), token); + + let refusal = |token: &str, time: i64| { + app() + .verify_session_token_at(token, at(time)) + .unwrap_err() + .to_string() + }; + assert_eq!( + refusal(&token, now + 71), + "verification failed: the session token has expired" + ); + assert_eq!( + refusal(&token, now - 12), + "verification failed: the session token is not valid yet" + ); + let other_app = ShopifyApp::new("other", "hush").sign_session_token(&claims(now)); + assert_eq!( + ShopifyApp::new("client-id", "other") + .verify_session_token_at(&other_app, at(now)) + .unwrap_err() + .to_string(), + "verification failed: the signature of the session token does not match" + ); + let mut audience = claims(now); + audience["aud"] = json!("other"); + assert_eq!( + refusal(&app().sign_session_token(&audience), now), + "verification failed: the session token was issued for another app" + ); + let mut foreign = claims(now); + foreign["dest"] = json!("https://evil.example.com"); + assert_eq!( + refusal(&app().sign_session_token(&foreign), now), + "verification failed: the `dest` of the session token is not a shop" + ); + let mut mixed = claims(now); + mixed["iss"] = json!("https://other-shop.myshopify.com/admin"); + assert_eq!( + refusal(&app().sign_session_token(&mixed), now), + "verification failed: the `iss` of the session token is not the admin of its `dest`" + ); + // A token whose header claims another algorithm is refused before its signature. + let unsigned = format!( + "{}.{}.", + BASE64_URL.encode(br#"{"alg":"none"}"#), + BASE64_URL.encode(b"{}") + ); + assert_eq!( + refusal(&unsigned, now), + "verification failed: the session token is not signed with HS256" + ); + assert_eq!( + refusal("a.b", now), + "verification failed: the session token is not a JWT" + ); + } + + #[test] + fn an_admin_session_token_has_exactly_the_admin_issuer_and_destination() { + let now = 1_800_000_000; + let refusal = |claims: &Value| { + app() + .verify_session_token_at(&app().sign_session_token(claims), at(now)) + .unwrap_err() + .to_string() + }; + let not_admin = + "verification failed: the `iss` of the session token is not the admin of its `dest`"; + // `iss` is compared whole: a host that only starts with the shop's is another host. + for issuer in [ + "https://my-shop.myshopify.com.evil.example/admin", + "https://my-shop.myshopify.com", + "https://my-shop.myshopify.com/admin/", + "https://my-shop.myshopify.com/adminx", + "http://my-shop.myshopify.com/admin", + ] { + let mut token = claims(now); + token["iss"] = json!(issuer); + assert_eq!(refusal(&token), not_admin, "{issuer}"); + } + let mut no_issuer = claims(now); + no_issuer.as_object_mut().unwrap().remove("iss"); + assert_eq!( + refusal(&no_issuer), + "verification failed: the session token has no `iss`: it is not from Shopify admin" + ); + let mut bare = claims(now); + bare["dest"] = json!("my-shop.myshopify.com"); + assert_eq!( + refusal(&bare), + "verification failed: the `dest` of the session token is not the admin of a shop" + ); + for destination in [ + "https://my-shop.myshopify.com/", + "https://my-shop.myshopify.com/admin", + ] { + let mut token = claims(now); + token["dest"] = json!(destination); + assert!( + app() + .verify_session_token_at(&app().sign_session_token(&token), at(now)) + .is_err(), + "{destination}" + ); + } + } + + /// The payload of Shopify's documentation of the Session Token API of + /// checkout and customer account UI extensions: no `iss`, no `sid`, a + /// `dest` without `https://`, and `sub` only for a logged-in customer. + fn extension_claims(now: i64) -> Value { + json!({ + "dest": "store-name.myshopify.com", + "aud": "client-id", + "exp": now + 300, + "nbf": now, + "iat": now, + "jti": "6c992878-dbaf-48d1-bb9d-6d9b59814fd1", + "sub": "gid://shopify/Customer/1", + }) + } + + #[test] + fn verifies_extension_session_tokens() { + let now = 1_800_000_000; + let verify = |claims: &Value| { + app().verify_extension_session_token_at(&app().sign_session_token(claims), at(now)) + }; + let session = verify(&extension_claims(now)).unwrap(); + assert_eq!(session.shop().as_str(), "store-name.myshopify.com"); + assert_eq!(session.customer(), Some("gid://shopify/Customer/1")); + assert_eq!(session.expires_at(), at(now + 300)); + assert_eq!( + session.claims()["jti"], + "6c992878-dbaf-48d1-bb9d-6d9b59814fd1" + ); + + // An anonymous buyer: no `sub`. + let mut anonymous = extension_claims(now); + anonymous.as_object_mut().unwrap().remove("sub"); + assert_eq!(verify(&anonymous).unwrap().customer(), None); + // `dest` with `https://`, and an `iss` that is the admin of the same shop. + let mut admin_shaped = extension_claims(now); + admin_shaped["dest"] = json!("https://store-name.myshopify.com"); + admin_shaped["iss"] = json!("https://store-name.myshopify.com/admin"); + assert!(verify(&admin_shaped).is_ok()); + // An admin token verifies here too: it proves its shop as well, but + // its staff member is not a customer. + let admin = verify(&claims(now)).unwrap(); + assert_eq!(admin.shop().as_str(), "my-shop.myshopify.com"); + assert_eq!(admin.customer(), None); + assert_eq!(admin.claims()["sub"], claims(now)["sub"]); + + // An `iss` is compared whole here as well. + let mut prefixed = extension_claims(now); + prefixed["iss"] = json!("https://store-name.myshopify.com.evil.example/admin"); + assert_eq!( + verify(&prefixed).unwrap_err().to_string(), + "verification failed: the `iss` of the session token is not the admin of its `dest`" + ); + // A bare handle, or another host, is still not a shop. + for destination in ["store-name", "store-name.example.com", "https://store-name"] { + let mut token = extension_claims(now); + token["dest"] = json!(destination); + assert!(verify(&token).is_err(), "{destination}"); + } + // The checks every session token gets. + let mut other_app = extension_claims(now); + other_app["aud"] = json!("other"); + assert!(verify(&other_app).is_err()); + assert!( + app() + .verify_extension_session_token_at( + &app().sign_session_token(&extension_claims(now)), + at(now + 311) + ) + .is_err() + ); + let foreign = + ShopifyApp::new("client-id", "other").sign_session_token(&extension_claims(now)); + assert!( + app() + .verify_extension_session_token_at(&foreign, at(now)) + .is_err() + ); + } + + #[test] + fn an_extension_session_token_is_not_an_admin_session() { + let now = 1_800_000_000; + let mut anonymous = extension_claims(now); + anonymous.as_object_mut().unwrap().remove("sub"); + for token in [extension_claims(now), anonymous] { + let token = app().sign_session_token(&token); + assert!(app().verify_session_token_at(&token, at(now)).is_err()); + assert!( + app() + .verify_extension_session_token_at(&token, at(now)) + .is_ok() + ); + } + } + + #[test] + fn an_empty_secret_verifies_nothing() { + let unset = ShopifyApp::new("client-id", ""); + let now = Utc::now().timestamp(); + let query = format!("shop=a.myshopify.com×tamp={now}"); + let signature = unset.sign_query(&query).unwrap(); + assert_eq!( + unset + .verify_query(&format!("{query}&hmac={signature}")) + .unwrap_err() + .to_string(), + "verification failed: the client secret of the app is empty: nothing can be verified with it" + ); + let token = unset.sign_session_token(&claims(now)); + assert!(unset.verify_session_token(&token).is_err()); + let signature = unset.sign_app_proxy(&query).unwrap(); + assert!( + unset + .verify_app_proxy(&format!("{query}&signature={signature}")) + .is_err() + ); + } + + #[test] + fn debug_hides_codes_and_tokens() { + let now = Utc::now().timestamp(); + let query = format!("code=secret-code&shop=a.myshopify.com×tamp={now}"); + let signature = app().sign_query(&query).unwrap(); + let callback = app() + .verify_query(&format!("{query}&hmac={signature}")) + .unwrap(); + let shown = format!("{callback:?}"); + assert!(!shown.contains("secret-code"), "{shown}"); + assert!(shown.contains("\"code\""), "{shown}"); + + let token = app().sign_session_token(&claims(now)); + let session = app().verify_session_token(&token).unwrap(); + assert!(!format!("{session:?}").contains(&token)); + let extension = app().sign_session_token(&extension_claims(now)); + let session = app().verify_extension_session_token(&extension).unwrap(); + assert!(!format!("{session:?}").contains(&extension)); + } + + #[test] + fn builds_install_links() { + let shop = ShopDomain::new("my-shop").unwrap(); + let link = app().authorization_url( + &shop, + &AuthorizationRequest::new("https://example.com/auth/callback", "nonce 1") + .scopes(["read_products", "write_orders"]) + .online(), + ); + assert_eq!( + link, + "https://my-shop.myshopify.com/admin/oauth/authorize?client_id=client-id&scope=read_products%2Cwrite_orders\ + &redirect_uri=https%3A%2F%2Fexample.com%2Fauth%2Fcallback&state=nonce%201&grant_options%5B%5D=per-user" + ); + } +} diff --git a/crates/shopify_api/src/pagination.rs b/crates/shopify_api/src/pagination.rs new file mode 100644 index 0000000..814609c --- /dev/null +++ b/crates/shopify_api/src/pagination.rs @@ -0,0 +1,94 @@ +//! Cursor pagination over a connection. + +use serde::de::DeserializeOwned; + +use crate::{Error, Operation, Result, Shopify}; + +/// One page of a connection: its items and its `pageInfo`. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Page { + pub items: Vec, + pub has_next_page: bool, + pub end_cursor: Option, +} + +impl Page { + pub fn new(items: Vec, has_next_page: bool, end_cursor: Option) -> Self { + Self { + items, + has_next_page, + end_cursor, + } + } + + /// The items converted, the page info kept. + pub fn map(self, convert: impl FnMut(T) -> U) -> Page { + Page { + items: self.items.into_iter().map(convert).collect(), + has_next_page: self.has_next_page, + end_cursor: self.end_cursor, + } + } +} + +impl Shopify { + /// Runs `operation` page after page and collects every item. + /// + /// `operation` receives the cursor to start after, `None` for the first + /// page; `page` reads the items and the `pageInfo` out of each answer. + /// + /// ```no_run + /// use shopify_api::{Page, graphql}; + /// + /// # async fn run(shopify: shopify_api::Shopify) -> shopify_api::Result<()> { + /// let products = shopify + /// .paginate( + /// |after| { + /// graphql!( + /// "query($after: String) { + /// products(first: 250, after: $after) { + /// nodes { id title } + /// pageInfo { hasNextPage endCursor } + /// } + /// }", + /// after = after, + /// ) + /// }, + /// |data| { + /// let page_info = data.products.page_info; + /// Page::new(data.products.nodes, page_info.has_next_page, page_info.end_cursor) + /// }, + /// ) + /// .await?; + /// println!("{} products", products.len()); + /// # Ok(()) + /// # } + /// ``` + /// + /// For a large catalog, a [bulk operation](crate::bulk) reads everything + /// at once, without the rate limit. + pub async fn paginate(&self, mut operation: O, mut page: P) -> Result> + where + D: DeserializeOwned, + O: FnMut(Option) -> Operation, + P: FnMut(D) -> Page, + { + let mut items = Vec::new(); + let mut cursor: Option = None; + loop { + let data = self.execute(operation(cursor.clone())).await?; + let current = page(data); + items.extend(current.items); + if !current.has_next_page { + return Ok(items); + } + match current.end_cursor { + Some(next) if cursor.as_ref() != Some(&next) => cursor = Some(next), + _ => { + return Err(Error::decode("pageInfo.endCursor".to_string(), "`hasNextPage` is true but the cursor does not move: select `pageInfo { hasNextPage endCursor }` and pass the cursor as `after`".to_string(), None)); + } + } + } + } +} diff --git a/crates/shopify_api/src/schema.rs b/crates/shopify_api/src/schema.rs new file mode 100644 index 0000000..262b2fd --- /dev/null +++ b/crates/shopify_api/src/schema.rs @@ -0,0 +1,141 @@ +//! Downloading Shopify's Admin GraphQL schema, as an introspection result. +//! +//! [`graphql!`](crate::graphql!) checks operations against a crate's schema +//! file, of the version its `Cargo.toml` pins, else of the version that file +//! holds, else, when there is no file yet, of the latest version. It +//! downloads that file only in some cases, see +//! [the schema rules](crate::graphql!#schema-and-api-version). These +//! functions return the raw introspection result, for other tools. + +use serde_json::{Value, json}; + +use crate::transport::{HttpRequest, Method, Transport}; +use crate::{ApiVersion, Error, Result, Shopify}; + +/// Shopify's public copy of the Admin schema: a GraphQL endpoint per version +/// that answers introspection without a token. +pub const PUBLIC_ADMIN_SCHEMA_ENDPOINT: &str = "https://shopify.dev/admin-graphql-direct-proxy"; + +/// The introspection query: types, fields, arguments, enum values, +/// directives and deprecations, without descriptions. +pub const INTROSPECTION_QUERY: &str = "\ +query IntrospectionQuery { + __schema { + queryType { name } + mutationType { name } + types { + kind + name + fields(includeDeprecated: true) { + name + args(includeDeprecated: true) { ...InputValue } + type { ...TypeRef } + isDeprecated + deprecationReason + } + inputFields(includeDeprecated: true) { ...InputValue } + isOneOf + interfaces { name } + enumValues(includeDeprecated: true) { name isDeprecated deprecationReason } + possibleTypes { name } + } + directives { + name + locations + isRepeatable + args(includeDeprecated: true) { ...InputValue } + } + } +} +fragment InputValue on __InputValue { + name + type { ...TypeRef } + defaultValue + isDeprecated + deprecationReason +} +fragment TypeRef on __Type { + kind name + ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } } +} +"; + +/// Downloads the Admin schema of `version` from Shopify's public endpoint, +/// with the default transport. +#[cfg(any(feature = "rustls", feature = "native-tls"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "rustls", feature = "native-tls"))))] +pub async fn download_public_admin_schema(version: ApiVersion) -> Result { + download_public_admin_schema_with(&crate::transport::ReqwestTransport::new()?, version).await +} + +/// Downloads the Admin schema of `version` from Shopify's public endpoint. +pub async fn download_public_admin_schema_with( + transport: &dyn Transport, + version: ApiVersion, +) -> Result { + let url = format!("{PUBLIC_ADMIN_SCHEMA_ENDPOINT}/{version}"); + let request = HttpRequest::new(Method::Post, &url) + .with_header("Accept", "application/json") + .with_header("User-Agent", crate::USER_AGENT) + .with_json(&json!({ "query": INTROSPECTION_QUERY })) + .with_timeout(std::time::Duration::from_secs(120)); + let response = transport + .send(request) + .await + .map_err(|source| Error::transport(&url, source))?; + if !response.is_success() { + return Err(Error::http(&url, &response)); + } + let value: Value = + crate::decode::from_slice(&response.body).map_err(|failure| failure.into_error())?; + check(value) +} + +impl Shopify { + /// Downloads the Admin schema of the client's version through the shop: + /// the schema the shop's token sees. + pub async fn download_admin_schema(&self) -> Result { + let raw = self.graphql_raw(INTROSPECTION_QUERY, ()).await?; + if !raw.errors.is_empty() { + return Err(Error::Graphql(crate::GraphqlErrors { + errors: raw.errors, + data: None, + })); + } + check(json!({ "data": raw.data })) + } +} + +/// An introspection result, or why it is not one. +fn check(value: Value) -> Result { + if let Some(message) = value.get("error").and_then(Value::as_str) { + return Err(Error::http_parts( + 200, + PUBLIC_ADMIN_SCHEMA_ENDPOINT, + message.as_bytes(), + )); + } + if value.pointer("/data/__schema/types").is_none() { + return Err(Error::decode( + "data.__schema".to_string(), + "the answer is not an introspection result".to_string(), + None, + )); + } + Ok(value) +} + +#[cfg(all(test, feature = "cli"))] +mod tests { + #[test] + fn the_query_and_the_endpoint_are_the_ones_graphql_uses() { + assert_eq!( + super::INTROSPECTION_QUERY, + shopify_api_graphql::INTROSPECTION_QUERY + ); + assert_eq!( + super::PUBLIC_ADMIN_SCHEMA_ENDPOINT, + shopify_api_graphql::project::PUBLIC_ADMIN_SCHEMA_ENDPOINT + ); + } +} diff --git a/crates/shopify_api/src/shop.rs b/crates/shopify_api/src/shop.rs new file mode 100644 index 0000000..f7dd2d0 --- /dev/null +++ b/crates/shopify_api/src/shop.rs @@ -0,0 +1,171 @@ +//! The domain of a shop, which every request and every token is bound to. + +use std::fmt; +use std::str::FromStr; + +use crate::Error; + +const SUFFIX: &str = ".myshopify.com"; + +/// The permanent domain of a shop: `my-shop.myshopify.com`. +/// +/// Requests and tokens go to the address built from it, so it only takes a +/// shop's handle or its `myshopify.com` domain, never another host: +/// +/// ``` +/// use shopify_api::ShopDomain; +/// +/// assert_eq!(ShopDomain::new("my-shop")?.as_str(), "my-shop.myshopify.com"); +/// assert_eq!(ShopDomain::new("https://My-Shop.myshopify.com/")?.handle(), "my-shop"); +/// assert!(ShopDomain::new("my-shop.example.com").is_err()); +/// assert!(ShopDomain::new("evil.com/x?.myshopify.com").is_err()); +/// # Ok::<(), shopify_api::Error>(()) +/// ``` +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ShopDomain(String); + +impl ShopDomain { + /// Accepts `my-shop`, `my-shop.myshopify.com`, with or without `https://` + /// and a trailing `/`, in any case. + pub fn new(shop: &str) -> Result { + let invalid = || Error::InvalidShop(shop.to_string()); + let trimmed = shop.trim(); + let trimmed = trimmed.strip_prefix("https://").unwrap_or(trimmed); + let trimmed = trimmed.strip_suffix('/').unwrap_or(trimmed); + let lowered = trimmed.to_ascii_lowercase(); + let handle = lowered.strip_suffix(SUFFIX).unwrap_or(&lowered); + let valid = !handle.is_empty() + && handle.len() <= 63 + && handle + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') + && !handle.starts_with('-') + && !handle.ends_with('-'); + if !valid { + return Err(invalid()); + } + Ok(Self(format!("{handle}{SUFFIX}"))) + } + + /// `my-shop.myshopify.com`. + pub fn as_str(&self) -> &str { + &self.0 + } + + /// `my-shop`. + pub fn handle(&self) -> &str { + &self.0[..self.0.len() - SUFFIX.len()] + } + + /// `https://my-shop.myshopify.com`. + pub fn origin(&self) -> String { + format!("https://{}", self.0) + } +} + +impl fmt::Display for ShopDomain { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.0) + } +} + +impl AsRef for ShopDomain { + fn as_ref(&self) -> &str { + &self.0 + } +} + +impl FromStr for ShopDomain { + type Err = Error; + + fn from_str(shop: &str) -> Result { + Self::new(shop) + } +} + +impl TryFrom<&str> for ShopDomain { + type Error = Error; + + fn try_from(shop: &str) -> Result { + Self::new(shop) + } +} + +impl TryFrom for ShopDomain { + type Error = Error; + + fn try_from(shop: String) -> Result { + Self::new(&shop) + } +} + +impl TryFrom<&String> for ShopDomain { + type Error = Error; + + fn try_from(shop: &String) -> Result { + Self::new(shop) + } +} + +impl serde::Serialize for ShopDomain { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(&self.0) + } +} + +impl<'de> serde::Deserialize<'de> for ShopDomain { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + Self::new(&text).map_err(serde::de::Error::custom) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn normalizes_handles_and_domains() { + for input in [ + "my-shop", + "my-shop.myshopify.com", + "MY-SHOP.myshopify.com", + " https://my-shop.myshopify.com/ ", + "my-shop.MyShopify.com", + ] { + let shop = ShopDomain::new(input).unwrap(); + assert_eq!(shop.as_str(), "my-shop.myshopify.com", "{input}"); + assert_eq!(shop.handle(), "my-shop"); + assert_eq!(shop.origin(), "https://my-shop.myshopify.com"); + } + assert_eq!( + ShopDomain::new("shop2").unwrap().as_str(), + "shop2.myshopify.com" + ); + } + + #[test] + fn refuses_any_other_host() { + for input in [ + "", + ".myshopify.com", + "my shop", + "my_shop", + "-shop", + "shop-", + "my-shop.example.com", + "http://my-shop.myshopify.com", + "my-shop.myshopify.com.evil.com", + "evil.com/x?.myshopify.com", + "evil.com#.myshopify.com", + "user@my-shop.myshopify.com", + "my-shop.myshopify.com:8443", + "a.b.myshopify.com", + ] { + assert!( + matches!(ShopDomain::new(input), Err(Error::InvalidShop(_))), + "{input}" + ); + } + } +} diff --git a/crates/shopify_api/src/testing.rs b/crates/shopify_api/src/testing.rs new file mode 100644 index 0000000..d699192 --- /dev/null +++ b/crates/shopify_api/src/testing.rs @@ -0,0 +1,337 @@ +//! Testing code that calls Shopify, without the network. +//! +//! A [`MockTransport`] records the requests a client sends and answers them +//! with what the test scripts: queued answers first, in order, then a +//! handler, then `404`. A queued answer may stream its body in chunks you +//! choose ([`MockTransport::push_chunks`]), to test the bulk downloads. +//! +//! ``` +//! use shopify_api::graphql; +//! use shopify_api::testing::{MockTransport, client}; +//! +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() -> shopify_api::Result<()> { +//! let mock = MockTransport::new(); +//! mock.push_data(serde_json::json!({ "shop": { "name": "Test shop" } })); +//! let shopify = client(&mock); +//! +//! let data = shopify.execute(graphql!("query Shop { shop { name } }")).await?; +//! +//! assert_eq!(data.shop.name, "Test shop"); +//! let sent = mock.graphql_requests(); +//! assert_eq!(sent[0].operation_name.as_deref(), Some("Shop")); +//! # Ok(()) +//! # } +//! ``` + +use std::collections::VecDeque; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::transport::{ + BoxFuture, HttpRequest, HttpResponse, StreamingResponse, Transport, TransportError, +}; +use crate::{RetryPolicy, Shopify}; + +type Handler = dyn Fn(&HttpRequest) -> Result + Send + Sync; + +/// A [`Transport`] that answers what the test says. Clones share their state. +#[derive(Clone, Default)] +pub struct MockTransport { + state: Arc>, +} + +enum Answer { + Whole(Result), + Streaming(StreamingResponse), +} + +#[derive(Default)] +struct State { + queue: VecDeque, + handler: Option>, + requests: Vec, +} + +impl std::fmt::Debug for MockTransport { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let state = self.state(); + formatter + .debug_struct("MockTransport") + .field("queued", &state.queue.len()) + .field("handler", &state.handler.is_some()) + .field("requests", &state.requests.len()) + .finish() + } +} + +impl MockTransport { + pub fn new() -> Self { + Self::default() + } + + fn state(&self) -> MutexGuard<'_, State> { + self.state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + /// Answers every request that finds no queued answer. + pub fn respond_with( + &self, + handler: impl Fn(&HttpRequest) -> Result + Send + Sync + 'static, + ) -> &Self { + self.state().handler = Some(Arc::new(handler)); + self + } + + /// Answers the next request that finds no answer queued before this one. + pub fn push(&self, response: HttpResponse) -> &Self { + self.state().queue.push_back(Answer::Whole(Ok(response))); + self + } + + /// Fails the next request, as a network failure. + pub fn push_error(&self, error: TransportError) -> &Self { + self.state().queue.push_back(Answer::Whole(Err(error))); + self + } + + /// Answers the next request with `status` and a body sent in `chunks`, + /// each produced when it is read: split a body at the positions a test + /// needs, or generate a large one lazily. + /// + /// ``` + /// use shopify_api::testing::{MockTransport, client}; + /// + /// # #[tokio::main(flavor = "current_thread")] + /// # async fn main() -> shopify_api::Result<()> { + /// let mock = MockTransport::new(); + /// // A line cut in two, and a two-byte character cut in two. + /// mock.push_chunks(200, [&b"{\"title\":\"Caf"[..], b"\xc3", b"\xa9\"}\n{\"ti", b"tle\":\"Hat\"}"]); + /// let shopify = client(&mock); + /// + /// let mut rows = shopify + /// .download_bulk_results_stream::("https://storage.test/results.jsonl") + /// .await?; + /// assert_eq!(rows.next_row().await.transpose()?.unwrap()["title"], "Café"); + /// assert_eq!(rows.next_row().await.transpose()?.unwrap()["title"], "Hat"); + /// assert!(rows.next_row().await.is_none()); + /// # Ok(()) + /// # } + /// ``` + pub fn push_chunks(&self, status: u16, chunks: I) -> &Self + where + I: IntoIterator, + I::Item: Into>, + I::IntoIter: Send + 'static, + { + let body = crate::transport::chunks(chunks.into_iter().map(|chunk| Ok(chunk.into()))); + self.push_streaming(StreamingResponse { + status, + headers: Vec::new(), + body, + }) + } + + /// Answers the next request with `response`, whose body is read as + /// the client polls it: a body that fails halfway, or one that waits. + pub fn push_streaming(&self, response: StreamingResponse) -> &Self { + self.state().queue.push_back(Answer::Streaming(response)); + self + } + + /// Answers the next request with `200` and `body`. + pub fn push_json(&self, body: Value) -> &Self { + self.push(HttpResponse::json(200, &body)) + } + + /// Answers the next request with `200` and `{ "data": data }`. + pub fn push_data(&self, data: Value) -> &Self { + self.push_json(json!({ "data": data })) + } + + /// Answers the next request with `200` and Shopify's `THROTTLED` error. + pub fn push_throttled(&self) -> &Self { + self.push_json(json!({ + "errors": [{ "message": "Throttled", "extensions": { "code": "THROTTLED" } }], + "extensions": { "cost": { + "requestedQueryCost": 10, + "actualQueryCost": null, + "throttleStatus": { "maximumAvailable": 2000.0, "currentlyAvailable": 0, "restoreRate": 100.0 }, + } }, + })) + } + + /// Every request sent so far, in order. + pub fn requests(&self) -> Vec { + self.state().requests.clone() + } + + pub fn last_request(&self) -> Option { + self.state().requests.last().cloned() + } + + /// The GraphQL requests sent so far, read. + pub fn graphql_requests(&self) -> Vec { + self.state() + .requests + .iter() + .filter_map(GraphqlRequest::read) + .collect() + } + + /// Forgets the requests, the queued answers and the handler. + pub fn clear(&self) { + *self.state() = State::default(); + } +} + +impl MockTransport { + fn answer(&self, request: &HttpRequest) -> Answer { + let mut state = self.state(); + state.requests.push(request.clone()); + if let Some(answer) = state.queue.pop_front() { + return answer; + } + let Some(handler) = state.handler.clone() else { + return Answer::Whole(Ok(HttpResponse::new( + 404, + format!("not mocked: {:?} {}", request.method, request.url), + ))); + }; + drop(state); + Answer::Whole(handler(request)) + } +} + +impl Transport for MockTransport { + fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result> { + let answer = self.answer(&request); + Box::pin(async move { + match answer { + Answer::Whole(answer) => answer, + Answer::Streaming(mut response) => { + let mut body = Vec::new(); + while let Some(chunk) = crate::transport::next_chunk(&mut response.body).await { + body.extend_from_slice(&chunk?); + } + Ok(HttpResponse { + status: response.status, + headers: response.headers, + body, + }) + } + } + }) + } + + fn send_streaming( + &self, + request: HttpRequest, + ) -> BoxFuture<'_, Result> { + let answer = self.answer(&request); + Box::pin(async move { + match answer { + Answer::Whole(answer) => answer.map(StreamingResponse::from), + Answer::Streaming(response) => Ok(response), + } + }) + } +} + +/// A GraphQL request, as a [`MockTransport`] received it. `Debug` hides +/// the access token. +#[derive(Clone, PartialEq)] +#[non_exhaustive] +pub struct GraphqlRequest { + pub url: String, + /// The version of the address: `2026-10`. + pub api_version: String, + pub query: String, + /// The variables, `{}` when there are none. + pub variables: Value, + pub operation_name: Option, + pub access_token: Option, +} + +impl std::fmt::Debug for GraphqlRequest { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("GraphqlRequest") + .field("url", &self.url) + .field("api_version", &self.api_version) + .field("query", &self.query) + .field("variables", &self.variables) + .field("operation_name", &self.operation_name) + .field( + "access_token", + &self.access_token.as_ref().map(|_| "[redacted]"), + ) + .finish() + } +} + +impl GraphqlRequest { + fn read(request: &HttpRequest) -> Option { + let (_, path) = request.url.split_once("/admin/api/")?; + let (api_version, rest) = path.split_once('/')?; + if rest != "graphql.json" { + return None; + } + let body = request.json()?; + Some(Self { + url: request.url.clone(), + api_version: api_version.to_string(), + query: body.get("query")?.as_str()?.to_string(), + variables: body.get("variables").cloned().unwrap_or_else(|| json!({})), + operation_name: body + .get("operationName") + .and_then(Value::as_str) + .map(str::to_string), + access_token: request.header("X-Shopify-Access-Token").map(str::to_string), + }) + } +} + +/// A client of `test-shop.myshopify.com` with the token `test-token`, +/// sending through `mock`, retrying without waiting: neither backoff nor a +/// scripted `Retry-After` is slept through. A `Retry-After` beyond +/// [`RetryPolicy::max_retry_after`] still ends in [`Error::Throttled`](crate::Error::Throttled). +pub fn client(mock: &MockTransport) -> Shopify { + Shopify::builder("test-shop") + .access_token("test-token") + .transport(mock.clone()) + .retry( + RetryPolicy::new(4) + .with_base_delay(Duration::ZERO) + .with_max_delay(Duration::ZERO) + .without_retry_after_waits(), + ) + .build() + .expect("a valid test client") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::transport::Method; + + #[test] + fn a_graphql_request_debug_hides_the_access_token() { + let request = HttpRequest::new( + Method::Post, + "https://shop.myshopify.com/admin/api/2026-10/graphql.json", + ) + .with_header("X-Shopify-Access-Token", "shpat_SECRET") + .with_body(r#"{"query":"{ shop { name } }"}"#); + let request = GraphqlRequest::read(&request).unwrap(); + assert_eq!(request.access_token.as_deref(), Some("shpat_SECRET")); + let shown = format!("{request:?}"); + assert!(!shown.contains("shpat_SECRET"), "{shown}"); + assert!(shown.contains("[redacted]"), "{shown}"); + assert!(shown.contains("{ shop { name } }"), "{shown}"); + } +} diff --git a/crates/shopify_api/src/transport.rs b/crates/shopify_api/src/transport.rs new file mode 100644 index 0000000..4230e32 --- /dev/null +++ b/crates/shopify_api/src/transport.rs @@ -0,0 +1,700 @@ +//! The HTTP layer, behind a trait: [`ReqwestTransport`] by default, a +//! [`MockTransport`](crate::testing::MockTransport) in tests, or your own. +//! +//! # reqwest +//! +//! No item of this crate names a type of `reqwest` but those of +//! [`reqwest_0_13`], the module named after the major version it is built +//! with. A later major version of `reqwest` comes as a module of its own, +//! next to it, in a minor release of this crate: `reqwest_0_13` stays, and +//! code that builds a client with it keeps compiling. [`ReqwestTransport::new`] +//! may move to the newer `reqwest` in a minor release. +//! +//! The default transport, and the token renewals, run on Tokio: call the +//! client from a Tokio runtime. + +use std::fmt; +use std::future::Future; +use std::pin::Pin; +use std::task::{Context, Poll}; +use std::time::Duration; + +use futures_core::Stream; + +/// A boxed, sendable future, as [`Transport::send`] returns. +pub type BoxFuture<'a, T> = Pin + Send + 'a>>; + +/// The body of a [`StreamingResponse`], chunk by chunk. A chunk may be of +/// any size, and may end in the middle of a line or of a UTF-8 character. +pub type BodyStream = Pin, TransportError>> + Send>>; + +/// Header names whose value is a secret, hidden by `Debug`. +const SECRET_HEADERS: [&str; 5] = [ + "x-shopify-access-token", + "authorization", + "proxy-authorization", + "cookie", + "set-cookie", +]; + +/// Headers as `Debug` shows them: secret values hidden, and the query +/// string of a `Location`, which may be a signed address, left out. +fn shown_headers(headers: &[(String, String)]) -> Vec<(&str, String)> { + headers + .iter() + .map(|(name, value)| { + let shown = if SECRET_HEADERS + .iter() + .any(|secret| name.eq_ignore_ascii_case(secret)) + { + "[redacted]".to_string() + } else if name.eq_ignore_ascii_case("location") { + crate::error::without_query(value) + } else { + value.clone() + }; + (name.as_str(), shown) + }) + .collect() +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum Method { + Get, + Post, +} + +/// A request this crate sends. +/// +/// `Debug` hides the value of secret headers, the query string of the +/// address, which may sign it, and the body, which may hold a client secret +/// or a refresh token. +#[derive(Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct HttpRequest { + pub method: Method, + pub url: String, + pub headers: Vec<(String, String)>, + pub body: Vec, + /// How long the whole request may take, when it differs from the transport's default. + pub timeout: Option, +} + +impl HttpRequest { + pub fn new(method: Method, url: impl Into) -> Self { + Self { + method, + url: url.into(), + headers: Vec::new(), + body: Vec::new(), + timeout: None, + } + } + + pub fn with_header(mut self, name: impl Into, value: impl Into) -> Self { + self.headers.push((name.into(), value.into())); + self + } + + pub fn with_body(mut self, body: impl Into>) -> Self { + self.body = body.into(); + self + } + + /// A JSON body, with its `Content-Type`. + pub(crate) fn with_json(self, body: &serde_json::Value) -> Self { + self.with_header("Content-Type", "application/json") + .with_body(serde_json::to_vec(body).unwrap_or_default()) + } + + /// A URL-encoded form body, with its `Content-Type`. + pub(crate) fn with_form(self, fields: &[(&str, &str)]) -> Self { + self.with_header("Content-Type", "application/x-www-form-urlencoded") + .with_body(serde_urlencoded::to_string(fields).unwrap_or_default()) + } + + pub(crate) fn with_timeout(mut self, timeout: Duration) -> Self { + self.timeout = Some(timeout); + self + } + + /// The first value of a header, whatever the case of its name. + pub fn header(&self, name: &str) -> Option<&str> { + header(&self.headers, name) + } + + /// The body read as JSON, `None` when it is not. + pub fn json(&self) -> Option { + serde_json::from_slice(&self.body).ok() + } + + /// The body read as a URL-encoded form. + pub fn form(&self) -> Vec<(String, String)> { + serde_urlencoded::from_bytes(&self.body).unwrap_or_default() + } +} + +impl fmt::Debug for HttpRequest { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("HttpRequest") + .field("method", &self.method) + // A signed address (a bulk download) carries its credential in its query string. + .field("url", &crate::error::without_query(&self.url)) + .field("headers", &shown_headers(&self.headers)) + .field("body", &format_args!("[{} bytes]", self.body.len())) + .field("timeout", &self.timeout) + .finish() + } +} + +/// An answer to an [`HttpRequest`]. +/// +/// `Debug` hides the body, which may hold a token. +#[derive(Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct HttpResponse { + pub status: u16, + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +impl fmt::Debug for HttpResponse { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("HttpResponse") + .field("status", &self.status) + .field("headers", &shown_headers(&self.headers)) + .field("body", &format_args!("[{} bytes]", self.body.len())) + .finish() + } +} + +impl HttpResponse { + pub fn new(status: u16, body: impl Into>) -> Self { + Self { + status, + headers: Vec::new(), + body: body.into(), + } + } + + /// An answer with a JSON body. + pub fn json(status: u16, body: &serde_json::Value) -> Self { + Self::new(status, serde_json::to_vec(body).unwrap_or_default()) + .with_header("Content-Type", "application/json") + } + + pub fn with_header(mut self, name: impl Into, value: impl Into) -> Self { + self.headers.push((name.into(), value.into())); + self + } + + pub fn is_success(&self) -> bool { + (200..300).contains(&self.status) + } + + /// The first value of a header, whatever the case of its name. + pub fn header(&self, name: &str) -> Option<&str> { + header(&self.headers, name) + } + + /// The body as text, what is not UTF-8 replaced. + pub fn text(&self) -> String { + String::from_utf8_lossy(&self.body).into_owned() + } +} + +/// An answer whose body is read as it arrives, as +/// [`Transport::send_streaming`] returns it. +/// +/// `Debug` hides the body, as [`HttpResponse`]'s does. +#[non_exhaustive] +pub struct StreamingResponse { + pub status: u16, + pub headers: Vec<(String, String)>, + pub body: BodyStream, +} + +impl fmt::Debug for StreamingResponse { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("StreamingResponse") + .field("status", &self.status) + .field("headers", &shown_headers(&self.headers)) + .finish_non_exhaustive() + } +} + +impl StreamingResponse { + pub fn new( + status: u16, + body: impl Stream, TransportError>> + Send + 'static, + ) -> Self { + Self { + status, + headers: Vec::new(), + body: Box::pin(body), + } + } + + pub fn with_header(mut self, name: impl Into, value: impl Into) -> Self { + self.headers.push((name.into(), value.into())); + self + } + + pub fn is_success(&self) -> bool { + (200..300).contains(&self.status) + } + + /// The first value of a header, whatever the case of its name. + pub fn header(&self, name: &str) -> Option<&str> { + header(&self.headers, name) + } + + /// The answer with the first `limit` bytes of its body, the rest left + /// unread: what an error keeps of a body that may be of any size. + pub(crate) async fn into_response(mut self, limit: usize) -> HttpResponse { + let mut body = Vec::new(); + while body.len() < limit { + match next_chunk(&mut self.body).await { + Some(Ok(chunk)) => { + let kept = chunk.len().min(limit - body.len()); + body.extend_from_slice(&chunk[..kept]); + } + Some(Err(_)) | None => break, + } + } + HttpResponse { + status: self.status, + headers: self.headers, + body, + } + } +} + +impl From for StreamingResponse { + fn from(response: HttpResponse) -> Self { + let body = (!response.body.is_empty()).then_some(Ok(response.body)); + Self { + status: response.status, + headers: response.headers, + body: chunks(body), + } + } +} + +pub(crate) async fn next_chunk(body: &mut BodyStream) -> Option, TransportError>> { + std::future::poll_fn(|context| body.as_mut().poll_next(context)).await +} + +/// A body made of the chunks `iter` gives, produced as they are polled. +pub(crate) fn chunks(iter: I) -> BodyStream +where + I: IntoIterator, TransportError>>, + I::IntoIter: Send + 'static, +{ + Box::pin(Chunks(iter.into_iter())) +} + +struct Chunks(I); + +// The iterator is never pinned: it is only called through `&mut`. +impl Unpin for Chunks {} + +impl, TransportError>>> Stream for Chunks { + type Item = Result, TransportError>; + + fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(self.0.next()) + } +} + +fn header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> { + headers + .iter() + .find(|(given, _)| given.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.as_str()) +} + +/// A request that did not get an answer: no connection, a timeout, a body +/// that stopped halfway. +#[derive(Debug)] +pub struct TransportError { + message: String, + timeout: bool, + source: Option>, +} + +impl TransportError { + pub fn new(message: impl Into) -> Self { + Self { + message: message.into(), + timeout: false, + source: None, + } + } + + /// The request took longer than it may. + pub fn timeout(message: impl Into) -> Self { + Self { + timeout: true, + ..Self::new(message) + } + } + + pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Self { + self.source = Some(Box::new(source)); + self + } + + pub fn is_timeout(&self) -> bool { + self.timeout + } +} + +impl fmt::Display for TransportError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.message) + } +} + +impl std::error::Error for TransportError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.source.as_deref().map(|source| source as _) + } +} + +/// Sends the requests of a [`Shopify`](crate::Shopify) client. +/// +/// Requests carry secrets in their headers or their body: an implementation +/// must not follow redirections, and returns a `3xx` as the answer, so that a +/// secret is never sent on to another host. +pub trait Transport: Send + Sync + 'static { + fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result>; + + /// Sends `request` and returns the answer as soon as its headers + /// arrive, its body read as the caller polls it. The bulk downloads go + /// through it, so that a file of gigabytes is never held in memory. + /// + /// When it streams, `request.timeout` bounds the wait for the headers + /// and for each chunk, not the whole body, which is read at its + /// consumer's pace. + /// + /// The default sends `request` with [`Transport::send`] and returns the + /// whole body as one chunk: a transport that implements only `send` + /// works, with the body in memory and `request.timeout` for the whole + /// exchange. + fn send_streaming( + &self, + request: HttpRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { self.send(request).await.map(StreamingResponse::from) }) + } +} + +/// A [`ReqwestTransport`] from a client of `reqwest` 0.13 you configure. +/// +/// ``` +/// use shopify_api::transport::reqwest_0_13::{self, reqwest}; +/// +/// let builder = reqwest::Client::builder().connect_timeout(std::time::Duration::from_secs(3)); +/// let transport = reqwest_0_13::from_builder(builder)?; +/// # Ok::<(), shopify_api::Error>(()) +/// ``` +#[cfg(any(feature = "rustls", feature = "native-tls"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "rustls", feature = "native-tls"))))] +pub mod reqwest_0_13 { + use super::ReqwestTransport; + + /// The `reqwest` 0.13 this crate is built with: build the client of + /// [`from_builder`] with it. + pub use reqwest; + + /// A transport from a client you configure: a proxy, other timeouts, + /// other certificates. Redirections are turned off whatever the builder + /// says, as [`Transport`](super::Transport) requires. + pub fn from_builder(builder: reqwest::ClientBuilder) -> Result { + let client = builder + .redirect(reqwest::redirect::Policy::none()) + .build() + .map_err(|error| { + // A proxy's address may hold a password: errors leave it out. + crate::Error::Config(format!( + "the HTTP client does not start: {}", + error.without_url() + )) + })?; + Ok(ReqwestTransport { client }) + } +} + +/// The default [`Transport`], over `reqwest`: no redirections, a 10-second +/// connection timeout and a 60-second request timeout. A streamed answer +/// with a timeout of its own waits that long for its headers and for each +/// chunk instead, however long the whole body takes. +#[cfg(any(feature = "rustls", feature = "native-tls"))] +#[cfg_attr(docsrs, doc(cfg(any(feature = "rustls", feature = "native-tls"))))] +#[derive(Debug, Clone)] +pub struct ReqwestTransport { + client: reqwest::Client, +} + +#[cfg(any(feature = "rustls", feature = "native-tls"))] +impl ReqwestTransport { + /// To configure the client, see [`reqwest_0_13::from_builder`]. + pub fn new() -> Result { + reqwest_0_13::from_builder( + reqwest::Client::builder() + .connect_timeout(Duration::from_secs(10)) + .timeout(Duration::from_secs(60)), + ) + } +} + +#[cfg(any(feature = "rustls", feature = "native-tls"))] +impl ReqwestTransport { + fn builder(&self, request: HttpRequest) -> reqwest::RequestBuilder { + let method = match request.method { + Method::Get => reqwest::Method::GET, + Method::Post => reqwest::Method::POST, + }; + let mut builder = self.client.request(method, &request.url); + for (name, value) in &request.headers { + builder = builder.header(name, value); + } + if let Some(timeout) = request.timeout { + builder = builder.timeout(timeout); + } + if !request.body.is_empty() { + builder = builder.body(request.body); + } + builder + } +} + +#[cfg(any(feature = "rustls", feature = "native-tls"))] +fn reqwest_failed(error: reqwest::Error) -> TransportError { + // Its address may hold a signature: errors leave it out. + let error = error.without_url(); + let message = error.to_string(); + if error.is_timeout() { + TransportError::timeout(message).with_source(error) + } else { + TransportError::new(message).with_source(error) + } +} + +#[cfg(any(feature = "rustls", feature = "native-tls"))] +fn reqwest_headers(response: &reqwest::Response) -> Vec<(String, String)> { + response + .headers() + .iter() + .filter_map(|(name, value)| Some((name.to_string(), value.to_str().ok()?.to_string()))) + .collect() +} + +#[cfg(any(feature = "rustls", feature = "native-tls"))] +impl Transport for ReqwestTransport { + fn send(&self, request: HttpRequest) -> BoxFuture<'_, Result> { + Box::pin(async move { + let response = self.builder(request).send().await.map_err(reqwest_failed)?; + let status = response.status().as_u16(); + let headers = reqwest_headers(&response); + let body = Vec::from(response.bytes().await.map_err(reqwest_failed)?); + Ok(HttpResponse { + status, + headers, + body, + }) + }) + } + + fn send_streaming( + &self, + request: HttpRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + let wait = request.timeout; + let mut builder = self.builder(request); + let response = match wait { + Some(wait) => { + // reqwest's timeout would cover the whole body: it is + // lifted, and `wait` bounds the headers and each chunk. + builder = builder.timeout(Duration::MAX); + tokio::time::timeout(wait, builder.send()) + .await + .map_err(|_| { + TransportError::timeout(format!("no answer within {wait:?}")) + })? + } + None => builder.send().await, + } + .map_err(reqwest_failed)?; + Ok(StreamingResponse { + status: response.status().as_u16(), + headers: reqwest_headers(&response), + body: Box::pin(ReqwestBody { + response: Some(response), + pending: None, + wait, + }), + }) + }) + } +} + +#[cfg(any(feature = "rustls", feature = "native-tls"))] +type PendingChunk = + BoxFuture<'static, (reqwest::Response, Result>, TransportError>)>; + +/// The body of a reqwest answer as a [`Stream`], read with +/// `Response::chunk`, which needs no feature of reqwest. +#[cfg(any(feature = "rustls", feature = "native-tls"))] +struct ReqwestBody { + response: Option, + pending: Option, + wait: Option, +} + +#[cfg(any(feature = "rustls", feature = "native-tls"))] +impl Stream for ReqwestBody { + type Item = Result, TransportError>; + + fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll> { + loop { + if let Some(pending) = self.pending.as_mut() { + let (response, chunk) = match pending.as_mut().poll(context) { + Poll::Ready(done) => done, + Poll::Pending => return Poll::Pending, + }; + self.pending = None; + return Poll::Ready(match chunk { + Ok(Some(chunk)) => { + self.response = Some(response); + Some(Ok(chunk)) + } + Ok(None) => None, + Err(error) => Some(Err(error)), + }); + } + let Some(mut response) = self.response.take() else { + return Poll::Ready(None); + }; + let wait = self.wait; + // The timer starts when the chunk is asked for: a slow consumer + // does not count against it. + self.pending = Some(Box::pin(async move { + let chunk = match wait { + Some(wait) => match tokio::time::timeout(wait, response.chunk()).await { + Ok(chunk) => chunk.map_err(reqwest_failed), + Err(_) => Err(TransportError::timeout(format!( + "the body stalled for {wait:?}" + ))), + }, + None => response.chunk().await.map_err(reqwest_failed), + }; + (response, chunk.map(|chunk| chunk.map(Vec::from))) + })); + } + } +} + +/// The transport a client uses when it is given none. +pub(crate) fn default_transport() -> Result, crate::Error> { + #[cfg(any(feature = "rustls", feature = "native-tls"))] + { + Ok(std::sync::Arc::new(ReqwestTransport::new()?)) + } + #[cfg(not(any(feature = "rustls", feature = "native-tls")))] + { + Err(crate::Error::NoTransport) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn debug_hides_secrets() { + let request = HttpRequest::new( + Method::Post, + "https://shop.myshopify.com/admin/oauth/access_token", + ) + .with_header("X-Shopify-Access-Token", "shpat_secret") + .with_form(&[("client_secret", "very-secret")]); + let shown = format!("{request:?}"); + assert!(!shown.contains("shpat_secret"), "{shown}"); + assert!(!shown.contains("very-secret"), "{shown}"); + assert!(shown.contains("[redacted]"), "{shown}"); + assert_eq!( + request.header("x-shopify-access-token"), + Some("shpat_secret") + ); + assert_eq!( + request.form(), + [("client_secret".to_string(), "very-secret".to_string())] + ); + } + + /// A signed download address carries its credential in its query string. + #[test] + fn debug_hides_the_query_string_of_the_url() { + let request = HttpRequest::new( + Method::Get, + "https://storage.googleapis.com/export.jsonl?X-Goog-Signature=SECRET#frag", + ); + let shown = format!("{request:?}"); + assert!(!shown.contains("SECRET"), "{shown}"); + assert!( + shown.contains("https://storage.googleapis.com/export.jsonl"), + "{shown}" + ); + assert_eq!( + request.url, + "https://storage.googleapis.com/export.jsonl?X-Goog-Signature=SECRET#frag" + ); + + let response = HttpResponse::new(302, "") + .with_header("Set-Cookie", "session=SECRET") + .with_header("Location", "https://storage.googleapis.com/x?sig=SECRET"); + let shown = format!("{response:?}"); + assert!(!shown.contains("SECRET"), "{shown}"); + } + + #[test] + fn responses_read_headers_whatever_their_case() { + let response = HttpResponse::json(429, &serde_json::json!({ "errors": "Throttled" })) + .with_header("Retry-After", "2.0"); + assert_eq!(response.header("retry-after"), Some("2.0")); + assert_eq!(response.header("content-type"), Some("application/json")); + assert!(!response.is_success()); + assert_eq!(response.text(), "{\"errors\":\"Throttled\"}"); + } + + #[tokio::test] + async fn an_error_body_copies_only_what_it_keeps() { + let huge = vec![b'x'; 32 * 1024 * 1024]; + let response = StreamingResponse::new(500, chunks([Ok(huge)])) + .into_response(1024) + .await; + assert_eq!(response.body.len(), 1024); + assert!( + response.body.capacity() <= 1024, + "{} bytes allocated", + response.body.capacity() + ); + + let parts = [ + Ok(b"abc".to_vec()), + Ok(b"defgh".to_vec()), + Ok(b"ij".to_vec()), + ]; + let response = StreamingResponse::new(500, chunks(parts)) + .into_response(6) + .await; + assert_eq!(response.body, b"abcdef"); + } +} diff --git a/crates/shopify_api/src/version.rs b/crates/shopify_api/src/version.rs new file mode 100644 index 0000000..b90a036 --- /dev/null +++ b/crates/shopify_api/src/version.rs @@ -0,0 +1,226 @@ +//! Shopify Admin API versions. + +use std::fmt; +use std::str::FromStr; + +use crate::Error; + +/// A Shopify Admin API version: a quarterly release such as `2026-10`, or `unstable`. +/// +/// ``` +/// use shopify_api::ApiVersion; +/// +/// let version: ApiVersion = "2026-07".parse()?; +/// assert_eq!(version, ApiVersion::V2026_07); +/// assert!(version < ApiVersion::DEFAULT); +/// assert_eq!(ApiVersion::UNSTABLE.to_string(), "unstable"); +/// # Ok::<(), shopify_api::Error>(()) +/// ``` +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ApiVersion(Repr); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +enum Repr { + Dated { year: u16, month: u8 }, + Unstable, +} + +impl ApiVersion { + pub const V2026_04: Self = Self::dated(2026, 4); + pub const V2026_07: Self = Self::dated(2026, 7); + pub const V2026_10: Self = Self::dated(2026, 10); + /// The release candidate of 2027-01. + pub const V2027_01: Self = Self::dated(2027, 1); + pub const UNSTABLE: Self = Self(Repr::Unstable); + + /// The version untyped requests ([`Shopify::graphql`](crate::Shopify::graphql)) + /// go to when none is chosen: the newest stable version this release of + /// the crate knows. A `graphql!` operation goes to the version of the + /// schema it was checked against. + pub const DEFAULT: Self = Self::V2026_10; + + /// The oldest version this crate accepts: the first whose bulk operation + /// API (`bulkOperation(id:)`, `bulkOperations`) it relies on. + pub const MINIMUM: Self = Self::V2026_04; + + const fn dated(year: u16, month: u8) -> Self { + Self(Repr::Dated { year, month }) + } + + /// Parses `2026-10` or `unstable`. Shopify releases a version each + /// quarter, in January, April, July and October. + pub fn new(version: &str) -> Result { + let invalid = |reason: &str| Error::InvalidApiVersion { + version: version.to_string(), + reason: reason.to_string(), + }; + if version == "unstable" { + return Ok(Self::UNSTABLE); + } + if !is_dated(version) { + return Err(invalid( + "expected `YYYY-MM`, such as `2026-10`, or `unstable`", + )); + } + let year: u16 = version[..4].parse().map_err(|_| invalid("invalid year"))?; + let month: u8 = version[5..].parse().map_err(|_| invalid("invalid month"))?; + if !matches!(month, 1 | 4 | 7 | 10) { + return Err(invalid( + "Shopify releases a version in January, April, July and October", + )); + } + let parsed = Self::dated(year, month); + if parsed < Self::MINIMUM { + return Err(invalid("the oldest version this crate supports is 2026-04")); + } + Ok(parsed) + } + + pub fn is_unstable(&self) -> bool { + matches!(self.0, Repr::Unstable) + } +} + +impl Default for ApiVersion { + fn default() -> Self { + Self::DEFAULT + } +} + +/// Written `YYYY-MM`. +pub(crate) fn is_dated(version: &str) -> bool { + let bytes = version.as_bytes(); + bytes.len() == 7 + && bytes[4] == b'-' + && bytes[..4].iter().chain(&bytes[5..]).all(u8::is_ascii_digit) +} + +impl fmt::Display for ApiVersion { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0 { + Repr::Dated { year, month } => write!(formatter, "{year:04}-{month:02}"), + Repr::Unstable => formatter.write_str("unstable"), + } + } +} + +impl FromStr for ApiVersion { + type Err = Error; + + fn from_str(version: &str) -> Result { + Self::new(version) + } +} + +impl TryFrom<&str> for ApiVersion { + type Error = Error; + + fn try_from(version: &str) -> Result { + Self::new(version) + } +} + +impl serde::Serialize for ApiVersion { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_str(self) + } +} + +impl<'de> serde::Deserialize<'de> for ApiVersion { + fn deserialize>(deserializer: D) -> Result { + let text = String::deserialize(deserializer)?; + Self::new(&text).map_err(serde::de::Error::custom) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_and_prints_versions() { + for text in [ + "2026-04", "2026-07", "2026-10", "2027-01", "2030-10", "unstable", + ] { + assert_eq!(ApiVersion::new(text).unwrap().to_string(), text); + } + assert_eq!(ApiVersion::DEFAULT.to_string(), "2026-10"); + assert!(ApiVersion::UNSTABLE.is_unstable()); + assert!(ApiVersion::V2026_04 < ApiVersion::V2026_10); + assert!(ApiVersion::V2027_01 < ApiVersion::UNSTABLE); + } + + #[test] + fn refuses_what_shopify_does_not_release() { + for (text, reason) in [ + ( + "2026-4", + "expected `YYYY-MM`, such as `2026-10`, or `unstable`", + ), + ( + "latest", + "expected `YYYY-MM`, such as `2026-10`, or `unstable`", + ), + ( + "2026-10/../x", + "expected `YYYY-MM`, such as `2026-10`, or `unstable`", + ), + ( + "2026-05", + "Shopify releases a version in January, April, July and October", + ), + ( + "2026-01", + "the oldest version this crate supports is 2026-04", + ), + ( + "2025-10", + "the oldest version this crate supports is 2026-04", + ), + ] { + match ApiVersion::new(text) { + Err(Error::InvalidApiVersion { + version, + reason: given, + }) => { + assert_eq!((version.as_str(), given.as_str()), (text, reason)); + } + other => panic!("{text}: {other:?}"), + } + } + } + + #[cfg(feature = "cli")] + #[test] + fn the_minimum_is_the_one_graphql_checks() { + assert_eq!( + ApiVersion::MINIMUM.to_string(), + shopify_api_graphql::MINIMUM_API_VERSION + ); + for version in ["2026-04", "2026-07", "2027-10", "unstable"] { + assert!( + shopify_api_graphql::is_supported_api_version(version), + "{version}" + ); + assert!(ApiVersion::new(version).is_ok(), "{version}"); + } + for version in ["2026-01", "2025-10", "2026-05", "2026-4", "latest"] { + assert!( + !shopify_api_graphql::is_supported_api_version(version), + "{version}" + ); + assert!(ApiVersion::new(version).is_err(), "{version}"); + } + } + + #[test] + fn travels_as_a_string() { + let json = serde_json::to_string(&ApiVersion::V2026_07).unwrap(); + assert_eq!(json, "\"2026-07\""); + assert_eq!( + serde_json::from_str::(&json).unwrap(), + ApiVersion::V2026_07 + ); + assert!(serde_json::from_str::("\"2026-02\"").is_err()); + } +} diff --git a/crates/shopify_api/src/webhooks.rs b/crates/shopify_api/src/webhooks.rs new file mode 100644 index 0000000..43bd284 --- /dev/null +++ b/crates/shopify_api/src/webhooks.rs @@ -0,0 +1,804 @@ +//! Webhooks: verify and read what Shopify sends, and manage the webhook +//! subscriptions of a shop. +//! +//! ``` +//! use shopify_api::webhooks::Webhook; +//! +//! # fn handle(headers: &[(&str, &str)], body: &[u8]) -> shopify_api::Result<()> { +//! // In your HTTP handler, with the raw body, before parsing it. +//! let webhook = Webhook::verify(headers.iter().copied(), body, "the app's client secret")?; +//! match webhook.topic() { +//! "orders/create" => { +//! let order: serde_json::Value = webhook.payload()?; +//! println!("order {} on {}", order["name"], webhook.shop()); +//! } +//! "app/uninstalled" | "shop/redact" | "customers/redact" => { +//! // Destructive: the shop of the headers is not signed, the payload is. +//! webhook.verify_payload_shop()?; +//! // … delete what the app holds for `webhook.shop()`. +//! } +//! other => println!("{other} ignored"), +//! } +//! # Ok(()) +//! # } +//! ``` +//! +//! With axum, or any framework on the `http` crate, the `HeaderMap` and the +//! raw body go in as they are: +//! +//! ```ignore +//! use axum::body::Bytes; +//! use axum::http::{HeaderMap, StatusCode}; +//! use shopify_api::webhooks::Webhook; +//! +//! async fn webhooks(headers: HeaderMap, body: Bytes) -> StatusCode { +//! let secret = std::env::var("SHOPIFY_API_SECRET").unwrap_or_default(); +//! let Ok(webhook) = Webhook::verify(&headers, body, &secret) else { +//! return StatusCode::UNAUTHORIZED; +//! }; +//! // Answer within 5 seconds: queue the work, then return. +//! tracing::info!("{} from {}", webhook.topic(), webhook.shop()); +//! StatusCode::OK +//! } +//! ``` +//! +//! Shopify may deliver a webhook more than once: [`Webhook::event_id`] +//! identifies the event across deliveries. +//! +//! # What the signature covers +//! +//! The signature covers the body only. The headers (the topic, the shop, the +//! IDs) are what Shopify sent along, unsigned: a captured body could be +//! replayed with other headers. Before deleting anything on `app/uninstalled`, +//! `shop/redact` or `customers/redact`, check that the payload names the shop +//! of the headers, with [`Webhook::verify_payload_shop`]. +//! +//! The client secret also signs the launch queries of Shopify admin, the app +//! proxy requests and the session tokens, which an installer of the app can +//! read. So that none of them passes for a webhook, only JSON webhooks +//! verify, a body whose first byte is `{`, with nothing before it, not even +//! whitespace or a byte order mark. None of the other texts starts so: each +//! starts with a parameter name that sorts before Shopify's own lowercase +//! names, or with `eyJ` for a session token. A signed query can still be made +//! to read as XML, or as JSON after some whitespace, which is why both are +//! refused. The subscriptions this crate creates or syncs are JSON. + +use base64::Engine; +use base64::engine::general_purpose::STANDARD; +use chrono::{DateTime, Utc}; +use hmac::{Hmac, KeyInit, Mac}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use sha2::Sha256; + +use crate::{Error, Result, ShopDomain, Shopify, UserError}; +use shopify_api_macros::{__graphql_internal as graphql, __input_internal as input}; + +/// Whether `hmac_header` (`X-Shopify-Hmac-Sha256`) is the signature of +/// `body` with `secret`, the client secret of the app. Compares in constant time. +/// +/// `false` for a body whose first byte is not `{`, as +/// [`Webhook::verify`] refuses it: see [what the signature covers](self#what-the-signature-covers). +pub fn verify_hmac(secret: &str, body: &[u8], hmac_header: &str) -> bool { + // Anyone can sign with an empty key: it verifies nothing. + if secret.is_empty() || !is_webhook_body(body) { + return false; + } + let Ok(expected) = STANDARD.decode(hmac_header.trim()) else { + return false; + }; + let Ok(mut mac) = Hmac::::new_from_slice(secret.as_bytes()) else { + return false; + }; + mac.update(body); + mac.verify_slice(&expected).is_ok() +} + +/// Whether `body` starts as a JSON webhook does, its first byte `{`. The +/// other texts the client secret signs start otherwise: a query with a +/// parameter name, a session token with `eyJ`, and an app proxy request with +/// a name that sorts before Shopify's lowercase ones, so never `{`, though +/// `[`, `<` (XML) or whitespace may. +fn is_webhook_body(body: &[u8]) -> bool { + // Exactly `{`, nothing skipped: a signed app proxy query can start with + // whitespace then `{`, never with `{`. + body.first() == Some(&b'{') +} + +/// The signature Shopify would send for `body`, base64: for tests. +#[cfg(any(test, feature = "testing"))] +#[cfg_attr(docsrs, doc(cfg(feature = "testing")))] +pub fn sign(secret: &str, body: &[u8]) -> String { + let mut mac = + Hmac::::new_from_slice(secret.as_bytes()).expect("HMAC takes a key of any length"); + mac.update(body); + STANDARD.encode(mac.finalize().into_bytes()) +} + +/// A webhook whose signature was verified. +/// +/// `Debug` shows the length of the body, not the body: it holds the data of +/// customers. +#[derive(Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Webhook { + topic: String, + shop: ShopDomain, + webhook_id: Option, + event_id: Option, + api_version: Option, + triggered_at: Option, + sub_topic: Option, + name: Option, + body: Vec, +} + +impl std::fmt::Debug for Webhook { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("Webhook") + .field("topic", &self.topic) + .field("shop", &self.shop) + .field("webhook_id", &self.webhook_id) + .field("event_id", &self.event_id) + .field("api_version", &self.api_version) + .field("triggered_at", &self.triggered_at) + .field("sub_topic", &self.sub_topic) + .field("name", &self.name) + .field("body", &format_args!("[{} bytes]", self.body.len())) + .finish() + } +} + +impl Webhook { + /// Verifies a webhook from its headers and raw body, and reads its headers. + /// + /// `headers` are name and value pairs: an `http::HeaderMap` by + /// reference, or pairs of strings. Names are read in any case, with or + /// without their `X-` (`X-Shopify-Topic` or `shopify-topic`). Fails when + /// the signature is missing or does not match, when the first byte of the + /// body is not the `{` of a JSON object (XML webhooks are refused), or + /// when a header Shopify always sends is missing. + /// + /// The headers are not signed: see [what the signature covers](self#what-the-signature-covers). + pub fn verify( + headers: impl IntoIterator, + body: impl Into>, + secret: &str, + ) -> Result + where + K: AsRef, + V: AsRef<[u8]>, + { + Self::verify_with_secrets(headers, body, &[secret]) + } + + /// [`Webhook::verify`], accepting the signature of any of `secrets`: + /// while the client secret of the app is being rotated. + pub fn verify_with_secrets( + headers: impl IntoIterator, + body: impl Into>, + secrets: &[&str], + ) -> Result + where + K: AsRef, + V: AsRef<[u8]>, + { + // Lowercase, without `x-`; a value that is not UTF-8 is not Shopify's. + let headers: Vec<(String, String)> = headers + .into_iter() + .filter_map(|(name, value)| { + let name = name.as_ref().to_ascii_lowercase(); + let name = match name.strip_prefix("x-") { + Some(rest) if rest.starts_with("shopify-") => rest.to_string(), + _ => name, + }; + let value = std::str::from_utf8(value.as_ref()).ok()?.trim().to_string(); + Some((name, value)) + }) + .collect(); + let header = |name: &str| { + headers + .iter() + .find(|(given, _)| given == name) + .map(|(_, value)| value.clone()) + }; + let required = |name: &'static str| { + header(name) + .ok_or_else(|| Error::Verification(format!("the webhook has no `x-{name}` header"))) + }; + + let body = body.into(); + let signature = required("shopify-hmac-sha256")?; + if secrets.iter().all(|secret| secret.is_empty()) { + return Err(Error::Verification( + "no secret to verify the webhook with: the client secret of the app is empty" + .to_string(), + )); + } + if !is_webhook_body(&body) { + return Err(Error::Verification( + "the body of the webhook does not start with `{`: only JSON webhooks verify" + .to_string(), + )); + } + if !secrets + .iter() + .any(|secret| verify_hmac(secret, &body, &signature)) + { + return Err(Error::Verification( + "the signature of the webhook does not match".to_string(), + )); + } + let shop = ShopDomain::new(&required("shopify-shop-domain")?).map_err(|error| { + Error::Verification(format!("the webhook names an invalid shop: {error}")) + })?; + Ok(Self { + topic: required("shopify-topic")?, + shop, + webhook_id: header("shopify-webhook-id"), + event_id: header("shopify-event-id"), + api_version: header("shopify-api-version"), + triggered_at: header("shopify-triggered-at"), + sub_topic: header("shopify-sub-topic"), + name: header("shopify-name"), + body, + }) + } + + /// Fails unless the JSON payload names [`Webhook::shop`], the shop of the + /// unsigned `X-Shopify-Shop-Domain`, in its `shop_domain` (the compliance + /// topics) or its `myshopify_domain` (`app/uninstalled`). Call it before + /// acting on a destructive topic: `app/uninstalled`, `shop/redact`, + /// `customers/redact`. + pub fn verify_payload_shop(&self) -> Result<()> { + let payload: serde_json::Value = serde_json::from_slice(&self.body).map_err(|_| { + Error::Verification("the payload of the webhook is not JSON".to_string()) + })?; + let named = ["shop_domain", "myshopify_domain"] + .iter() + .filter_map(|field| payload.get(field)?.as_str()) + .any(|shop| ShopDomain::new(shop).is_ok_and(|shop| shop == self.shop)); + if named { + Ok(()) + } else { + Err(Error::Verification( + "the payload of the webhook does not name the shop of its headers".to_string(), + )) + } + } + + /// `orders/create`. + pub fn topic(&self) -> &str { + &self.topic + } + + /// The topic as the Admin API writes it: `ORDERS_CREATE`. + pub fn topic_enum(&self) -> String { + topic_enum(&self.topic) + } + + pub fn shop(&self) -> &ShopDomain { + &self.shop + } + + /// Identifies this delivery. + pub fn webhook_id(&self) -> Option<&str> { + self.webhook_id.as_deref() + } + + /// Identifies the event, the same across deliveries: to ignore a duplicate. + pub fn event_id(&self) -> Option<&str> { + self.event_id.as_deref() + } + + /// The API version of the payload. + pub fn api_version(&self) -> Option<&str> { + self.api_version.as_deref() + } + + /// When the event happened, as Shopify wrote it. + pub fn triggered_at(&self) -> Option<&str> { + self.triggered_at.as_deref() + } + + pub fn sub_topic(&self) -> Option<&str> { + self.sub_topic.as_deref() + } + + /// The name of the subscription, when it has one. + pub fn name(&self) -> Option<&str> { + self.name.as_deref() + } + + /// The raw body. + pub fn body(&self) -> &[u8] { + &self.body + } + + /// The body read as `T`, the path of the first mismatch in the error. + pub fn payload(&self) -> Result { + crate::decode::from_slice(&self.body).map_err(|failure| failure.into_error()) + } +} + +/// `orders/create` → `ORDERS_CREATE`. A topic already in that form is kept. +pub fn topic_enum(topic: &str) -> String { + topic + .trim() + .replace(['/', '.', '-'], "_") + .to_ascii_uppercase() +} + +// ─── Subscriptions ─────────────────────────────────────────────────── + +graphql! { + mod list = file("graphql/operations/webhooks_list.graphql"); + mod create = file("graphql/operations/webhooks_create.graphql"); + mod update = file("graphql/operations/webhooks_update.graphql"); + mod delete = file("graphql/operations/webhooks_delete.graphql"); +} + +/// The input of `create` or `update` for a spec. An update sends every +/// option, empty when the spec has none, so that it replaces the old ones. +fn subscription_input( + spec: &WebhookSubscriptionSpec, + replace: bool, +) -> create::WebhookSubscriptionInput { + let list = |values: &Vec| (replace || !values.is_empty()).then(|| values.clone()); + input!(WebhookSubscriptionInput { + uri: &spec.uri, + format: raw("JSON"), + filter?: spec.filter.as_deref().or(replace.then_some("")), + includeFields?: list(&spec.include_fields), + metafieldNamespaces?: list(&spec.metafield_namespaces), + name?: spec.name.as_deref(), + }) +} + +/// A webhook subscription of a shop. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct WebhookSubscription { + pub id: String, + /// `ORDERS_CREATE`. + pub topic: String, + /// An HTTPS address, a `pubsub://` or an Amazon EventBridge `arn:`. + pub uri: String, + /// `JSON` or `XML`. Only JSON webhooks verify: [`Shopify::sync_webhook_subscriptions`] + /// updates an XML one of a desired topic and address to JSON. + pub format: String, + pub filter: Option, + pub include_fields: Vec, + pub metafield_namespaces: Vec, + pub name: Option, + /// The API version of the payloads. + pub api_version: String, + pub created_at: DateTime, + pub updated_at: DateTime, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Wire { + id: String, + topic: String, + uri: String, + format: String, + filter: Option, + include_fields: Vec, + metafield_namespaces: Vec, + name: Option, + created_at: DateTime, + updated_at: DateTime, + api_version: WireVersion, +} + +#[derive(Deserialize)] +struct WireVersion { + handle: String, +} + +fn subscription_of(selection: &impl Serialize) -> Result { + let wire: Wire = crate::decode::reserialize(selection)?; + Ok(WebhookSubscription { + id: wire.id, + topic: wire.topic, + uri: wire.uri, + format: wire.format, + filter: wire.filter, + include_fields: wire.include_fields, + metafield_namespaces: wire.metafield_namespaces, + name: wire.name, + api_version: wire.api_version.handle, + created_at: wire.created_at, + updated_at: wire.updated_at, + }) +} + +fn refused(mutation: &'static str, errors: &impl Serialize) -> Result<()> { + let errors: Vec = crate::decode::reserialize(errors)?; + if errors.is_empty() { + Ok(()) + } else { + Err(Error::UserErrors { mutation, errors }) + } +} + +/// A webhook subscription to create, always JSON: only JSON webhooks verify. +/// +/// ``` +/// use shopify_api::webhooks::WebhookSubscriptionSpec; +/// +/// let spec = WebhookSubscriptionSpec::new("orders/create", "https://example.com/webhooks") +/// .include_fields(["id", "name", "total_price"]) +/// .filter("total_price:>100"); +/// assert_eq!(spec.topic(), "ORDERS_CREATE"); +/// ``` +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WebhookSubscriptionSpec { + topic: String, + uri: String, + filter: Option, + include_fields: Vec, + metafield_namespaces: Vec, + name: Option, +} + +impl WebhookSubscriptionSpec { + /// `topic` as `orders/create` or `ORDERS_CREATE`; `uri` an HTTPS address, + /// a `pubsub://project:topic` or an Amazon EventBridge `arn:`. + pub fn new(topic: impl AsRef, uri: impl Into) -> Self { + Self { + topic: topic_enum(topic.as_ref()), + uri: uri.into(), + filter: None, + include_fields: Vec::new(), + metafield_namespaces: Vec::new(), + name: None, + } + } + + /// Only the events that match this search. + pub fn filter(mut self, filter: impl Into) -> Self { + self.filter = Some(filter.into()); + self + } + + /// Only these fields of the payload. + pub fn include_fields, S: Into>(mut self, fields: I) -> Self { + self.include_fields = fields.into_iter().map(Into::into).collect(); + self + } + + /// The metafields of these namespaces in the payload. + pub fn metafield_namespaces, S: Into>( + mut self, + namespaces: I, + ) -> Self { + self.metafield_namespaces = namespaces.into_iter().map(Into::into).collect(); + self + } + + /// A name, sent in the `X-Shopify-Name` header of each delivery. + pub fn name(mut self, name: impl Into) -> Self { + self.name = Some(name.into()); + self + } + + pub fn topic(&self) -> &str { + &self.topic + } + + pub fn uri(&self) -> &str { + &self.uri + } + + /// Whether `subscription` is this one: same topic, address and options, + /// and JSON. + pub fn matches(&self, subscription: &WebhookSubscription) -> bool { + let sorted = |values: &[String]| { + let mut values = values.to_vec(); + values.sort(); + values + }; + subscription.topic == self.topic + && subscription.uri == self.uri + && subscription.format == "JSON" + && subscription + .filter + .as_deref() + .filter(|filter| !filter.is_empty()) + == self.filter.as_deref() + && sorted(&subscription.include_fields) == sorted(&self.include_fields) + && sorted(&subscription.metafield_namespaces) == sorted(&self.metafield_namespaces) + && (self.name.is_none() || subscription.name == self.name) + } +} + +/// What [`Shopify::sync_webhook_subscriptions`] did. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct SyncReport { + pub created: Vec, + /// Subscriptions of a desired topic and address whose options changed. + pub updated: Vec, + /// The IDs of the subscriptions deleted. + pub deleted: Vec, + pub kept: Vec, +} + +impl Shopify { + /// Every webhook subscription the app has on the shop. Those of the + /// app's configuration file (`shopify.app.toml`) are not listed by + /// Shopify. + pub async fn webhook_subscriptions(&self) -> Result> { + let pages = self + .paginate( + |after| list::operation(list::Variables { after }).own(), + |data| { + let connection = data.webhook_subscriptions; + crate::Page::new( + connection.nodes, + connection.page_info.has_next_page, + connection.page_info.end_cursor, + ) + }, + ) + .await?; + pages.iter().map(subscription_of).collect() + } + + pub async fn create_webhook_subscription( + &self, + spec: &WebhookSubscriptionSpec, + ) -> Result { + let data = self + .execute_own(create::Variables { + topic: spec.topic.clone(), + webhook_subscription: subscription_input(spec, false), + }) + .await?; + let payload = data.webhook_subscription_create.ok_or_else(|| { + Error::decode( + "webhookSubscriptionCreate".to_string(), + "Shopify returned nothing".to_string(), + None, + ) + })?; + refused("webhookSubscriptionCreate", &payload.user_errors)?; + let subscription = payload.webhook_subscription.ok_or_else(|| { + Error::decode( + "webhookSubscriptionCreate.webhookSubscription".to_string(), + "Shopify returned no subscription".to_string(), + None, + ) + })?; + subscription_of(&subscription) + } + + pub async fn delete_webhook_subscription(&self, id: &str) -> Result<()> { + let data = self + .execute_own(delete::Variables { id: id.to_string() }) + .await?; + let payload = data.webhook_subscription_delete.ok_or_else(|| { + Error::decode( + "webhookSubscriptionDelete".to_string(), + "Shopify returned nothing".to_string(), + None, + ) + })?; + refused("webhookSubscriptionDelete", &payload.user_errors) + } + + /// Replaces the options of a subscription with those of `spec`; its + /// topic stays. + pub async fn update_webhook_subscription( + &self, + id: &str, + spec: &WebhookSubscriptionSpec, + ) -> Result { + let data = self + .execute_own(update::Variables { + id: id.to_string(), + webhook_subscription: subscription_input(spec, true), + }) + .await?; + let payload = data.webhook_subscription_update.ok_or_else(|| { + Error::decode( + "webhookSubscriptionUpdate".to_string(), + "Shopify returned nothing".to_string(), + None, + ) + })?; + refused("webhookSubscriptionUpdate", &payload.user_errors)?; + let subscription = payload.webhook_subscription.ok_or_else(|| { + Error::decode( + "webhookSubscriptionUpdate.webhookSubscription".to_string(), + "Shopify returned no subscription".to_string(), + None, + ) + })?; + subscription_of(&subscription) + } + + /// Makes the shop's subscriptions exactly `desired`: those that match are + /// kept, those of a desired topic and address are updated, the missing + /// ones created, then the others deleted. Nothing is deleted before what + /// replaces it exists, so no event is missed in between. An XML + /// subscription of a desired topic and address is updated to JSON: only + /// JSON webhooks verify. + /// + /// It deletes every subscription of the app on the shop that `desired` + /// does not list, including those another part of the app created. + pub async fn sync_webhook_subscriptions( + &self, + desired: &[WebhookSubscriptionSpec], + ) -> Result { + let mut report = SyncReport::default(); + let mut missing: Vec<&WebhookSubscriptionSpec> = desired.iter().collect(); + let mut extra = Vec::new(); + for subscription in self.webhook_subscriptions().await? { + match missing.iter().position(|spec| spec.matches(&subscription)) { + Some(index) => { + missing.remove(index); + report.kept.push(subscription); + } + None => extra.push(subscription), + } + } + // A desired topic and address that exists with other options. + let mut leftover = Vec::new(); + for subscription in extra { + let same_place = missing + .iter() + .position(|spec| spec.topic == subscription.topic && spec.uri == subscription.uri); + match same_place { + Some(index) => { + let spec = missing.remove(index); + report.updated.push( + self.update_webhook_subscription(&subscription.id, spec) + .await?, + ); + } + None => leftover.push(subscription), + } + } + for spec in missing { + report + .created + .push(self.create_webhook_subscription(spec).await?); + } + for subscription in leftover { + self.delete_webhook_subscription(&subscription.id).await?; + report.deleted.push(subscription.id); + } + Ok(report) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn verifies_the_signature_of_shopify() { + let body = br#"{"id":1}"#; + let signature = sign("secret", body); + assert!(verify_hmac("secret", body, &signature)); + assert!(!verify_hmac("other", body, &signature)); + assert!(!verify_hmac("secret", b"{\"id\":2}", &signature)); + assert!(!verify_hmac("secret", body, "not base64!")); + assert!(!verify_hmac("secret", body, "")); + } + + fn headers(signature: &str) -> Vec<(&'static str, String)> { + vec![ + ("X-Shopify-Topic", "orders/create".to_string()), + ("X-Shopify-Hmac-SHA256", signature.to_string()), + ("x-shopify-shop-domain", "my-shop.myshopify.com".to_string()), + ("X-Shopify-Webhook-Id", "b54557e4".to_string()), + ("X-Shopify-Event-Id", "98880550".to_string()), + ("X-Shopify-API-Version", "2026-10".to_string()), + ("X-Shopify-Triggered-At", "2026-10-22T10:00:00Z".to_string()), + ] + } + + #[test] + fn reads_a_verified_webhook() { + let body = br##"{"id":1,"name":"#1001"}"##.to_vec(); + let webhook = + Webhook::verify(headers(&sign("secret", &body)), body.clone(), "secret").unwrap(); + assert_eq!(webhook.topic(), "orders/create"); + assert_eq!(webhook.topic_enum(), "ORDERS_CREATE"); + assert_eq!(webhook.shop().as_str(), "my-shop.myshopify.com"); + assert_eq!(webhook.webhook_id(), Some("b54557e4")); + assert_eq!(webhook.event_id(), Some("98880550")); + assert_eq!(webhook.api_version(), Some("2026-10")); + assert_eq!(webhook.triggered_at(), Some("2026-10-22T10:00:00Z")); + assert_eq!(webhook.sub_topic(), None); + assert_eq!(webhook.body(), body); + + #[derive(Deserialize)] + struct Order { + name: String, + } + assert_eq!(webhook.payload::().unwrap().name, "#1001"); + #[derive(Debug, Deserialize)] + #[allow(dead_code, reason = "only decoded: the test checks the decoding")] + struct Wrong { + name: u32, + } + assert_eq!( + webhook.payload::().unwrap_err().to_string(), + "Shopify's answer does not match the operation at `name`: invalid type: string, expected u32 at line 1 column 22" + ); + } + + #[test] + fn refuses_what_does_not_verify() { + let body = b"{}".to_vec(); + let error = + Webhook::verify(headers(&sign("other", &body)), body.clone(), "secret").unwrap_err(); + assert_eq!( + error.to_string(), + "verification failed: the signature of the webhook does not match" + ); + + let unsigned: Vec<_> = headers("") + .into_iter() + .filter(|(name, _)| !name.contains("Hmac")) + .collect(); + let error = Webhook::verify(unsigned, body.clone(), "secret").unwrap_err(); + assert_eq!( + error.to_string(), + "verification failed: the webhook has no `x-shopify-hmac-sha256` header" + ); + + // An empty secret, as from an unset variable, verifies nothing. + let error = Webhook::verify(headers(&sign("", &body)), body.clone(), "").unwrap_err(); + assert!( + error + .to_string() + .contains("the client secret of the app is empty"), + "{error}" + ); + assert!(!verify_hmac("", &body, &sign("", &body))); + + // A rotated secret: either verifies. + let webhook = Webhook::verify_with_secrets( + headers(&sign("old", &body)), + body.clone(), + &["new", "old"], + ); + assert!(webhook.is_ok()); + + let mut wrong_shop = headers(&sign("secret", &body)); + wrong_shop[2].1 = "evil.example.com".to_string(); + assert!(Webhook::verify(wrong_shop, body, "secret").is_err()); + } + + #[test] + fn specs_match_subscriptions_whatever_the_order_of_their_fields() { + let spec = WebhookSubscriptionSpec::new("orders/create", "https://example.com/hooks") + .include_fields(["b", "a"]); + let mut subscription = WebhookSubscription { + id: "gid://shopify/WebhookSubscription/1".to_string(), + topic: "ORDERS_CREATE".to_string(), + uri: "https://example.com/hooks".to_string(), + format: "JSON".to_string(), + filter: Some(String::new()), + include_fields: vec!["a".to_string(), "b".to_string()], + metafield_namespaces: Vec::new(), + name: None, + api_version: "2026-10".to_string(), + created_at: DateTime::default(), + updated_at: DateTime::default(), + }; + assert!(spec.matches(&subscription)); + subscription.uri = "https://example.com/other".to_string(); + assert!(!spec.matches(&subscription)); + assert_eq!(topic_enum("app/uninstalled"), "APP_UNINSTALLED"); + assert_eq!(topic_enum("ORDERS_PAID"), "ORDERS_PAID"); + } +} diff --git a/crates/shopify_api/tests/auth.rs b/crates/shopify_api/tests/auth.rs new file mode 100644 index 0000000..2943089 --- /dev/null +++ b/crates/shopify_api/tests/auth.rs @@ -0,0 +1,744 @@ +//! Tokens: obtained, reused, renewed and saved. +#![cfg(feature = "testing")] + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use serde_json::json; +use shopify_api::testing::MockTransport; +use shopify_api::transport::{BoxFuture, HttpRequest, HttpResponse}; +use shopify_api::{ + Auth, Error, OAuthErrorCode, RetryPolicy, ShopDomain, Shopify, TokenData, TokenStore, +}; + +const TOKEN_URL: &str = "https://test-shop.myshopify.com/admin/oauth/access_token"; + +/// Answers token requests with `shpat_` and GraphQL requests with a shop, +/// refusing the tokens in `refused` with a 401. +fn shopify_like(mock: &MockTransport, expires_in: i64, refused: Vec<&'static str>) { + let issued = Arc::new(Mutex::new(0)); + mock.respond_with(move |request: &HttpRequest| { + if request.url == TOKEN_URL { + let mut issued = issued.lock().unwrap(); + *issued += 1; + return Ok(HttpResponse::json( + 200, + &json!({ + "access_token": format!("shpat_{issued}"), + "scope": "read_products", + "expires_in": expires_in, + "refresh_token": format!("shprt_{issued}"), + "refresh_token_expires_in": 7_776_000, + }), + )); + } + let token = request.header("X-Shopify-Access-Token").unwrap_or_default(); + if refused.contains(&token) { + return Ok(HttpResponse::new( + 401, + "[API] Invalid API key or access token", + )); + } + Ok(HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }); +} + +fn token_requests(mock: &MockTransport) -> Vec { + mock.requests() + .into_iter() + .filter(|request| request.url == TOKEN_URL) + .collect() +} + +fn builder(mock: &MockTransport) -> shopify_api::ShopifyBuilder { + Shopify::builder("test-shop") + .transport(mock.clone()) + .retry(RetryPolicy::none()) +} + +#[tokio::test] +async fn client_credentials_are_asked_once_and_reused() { + let mock = MockTransport::new(); + shopify_like(&mock, 86_399, vec![]); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + shopify + .clone() + .graphql("{ shop { name } }", ()) + .await + .unwrap(); + + let asked = token_requests(&mock); + assert_eq!(asked.len(), 1); + assert_eq!( + asked[0].header("content-type"), + Some("application/x-www-form-urlencoded") + ); + assert_eq!( + asked[0].form(), + [ + ("grant_type".to_string(), "client_credentials".to_string()), + ("client_id".to_string(), "id".to_string()), + ("client_secret".to_string(), "secret".to_string()), + ] + ); + assert_eq!( + mock.graphql_requests()[1].access_token.as_deref(), + Some("shpat_1") + ); + let token = shopify.token().await.unwrap(); + assert_eq!(token.scopes(), ["read_products"]); + assert!(token.expires_at.is_some()); +} + +#[tokio::test] +async fn concurrent_requests_share_one_token_request() { + let mock = MockTransport::new(); + shopify_like(&mock, 86_399, vec![]); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + + let calls = (0..8).map(|_| { + let shopify = shopify.clone(); + tokio::spawn(async move { shopify.graphql("{ shop { name } }", ()).await }) + }); + for call in calls { + call.await.unwrap().unwrap(); + } + assert_eq!(token_requests(&mock).len(), 1); +} + +#[tokio::test] +async fn a_token_about_to_expire_is_renewed_first() { + let mock = MockTransport::new(); + // Each token expires within the five minutes of leeway: each request renews it. + shopify_like(&mock, 60, vec![]); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(token_requests(&mock).len(), 2); + + // With a shorter leeway, the token lasts. + let mock = MockTransport::new(); + shopify_like(&mock, 60, vec![]); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .refresh_leeway(Duration::from_secs(10)) + .build() + .unwrap(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(token_requests(&mock).len(), 1); +} + +#[tokio::test] +async fn a_refused_token_is_renewed_once_and_the_request_sent_again() { + let mock = MockTransport::new(); + shopify_like(&mock, 86_399, vec!["stored"]); + let shopify = builder(&mock) + .auth(Auth::client_credentials("id", "secret").with_token(TokenData::new("stored"))) + .build() + .unwrap(); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + let tokens: Vec> = mock + .graphql_requests() + .into_iter() + .map(|request| request.access_token) + .collect(); + assert_eq!( + tokens, + [Some("stored".to_string()), Some("shpat_1".to_string())] + ); + + // A token refused again is the answer: no loop. + let mock = MockTransport::new(); + shopify_like(&mock, 86_399, vec!["stored", "shpat_1"]); + let shopify = builder(&mock) + .auth(Auth::client_credentials("id", "secret").with_token(TokenData::new("stored"))) + .build() + .unwrap(); + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!(error.is_unauthorized(), "{error:?}"); + assert_eq!(mock.requests().len(), 3); +} + +#[tokio::test] +async fn a_static_token_that_is_refused_is_the_answer() { + let mock = MockTransport::new(); + shopify_like(&mock, 0, vec!["shpat_static"]); + let shopify = builder(&mock).access_token("shpat_static").build().unwrap(); + + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!(error.is_unauthorized()); + assert!(token_requests(&mock).is_empty()); +} + +#[derive(Default, Clone)] +struct Saved(Arc>>); + +impl TokenStore for Saved { + fn save<'a>( + &'a self, + shop: &'a ShopDomain, + token: &'a TokenData, + ) -> BoxFuture<'a, Result<(), Box>> { + Box::pin(async move { + self.0 + .lock() + .unwrap() + .push((shop.to_string(), token.clone())); + Ok(()) + }) + } +} + +#[tokio::test] +async fn an_expiring_token_is_refreshed_and_saved() { + let mock = MockTransport::new(); + shopify_like(&mock, 3600, vec![]); + let saved = Saved::default(); + let mut stored = TokenData::new("shpat_old"); + stored.expires_at = Some(chrono::Utc::now() - chrono::Duration::seconds(1)); + stored.refresh_token = Some("shprt_old".to_string()); + let shopify = builder(&mock) + .auth(Auth::expiring_token("id", "secret", stored)) + .token_store(saved.clone()) + .build() + .unwrap(); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + + let refresh = &token_requests(&mock)[0]; + assert_eq!(refresh.header("content-type"), Some("application/json")); + assert_eq!( + refresh.json().unwrap(), + json!({ "grant_type": "refresh_token", "client_id": "id", "client_secret": "secret", "refresh_token": "shprt_old" }) + ); + let saved = saved.0.lock().unwrap(); + assert_eq!(saved.len(), 1); + assert_eq!(saved[0].0, "test-shop.myshopify.com"); + assert_eq!(saved[0].1.access_token, "shpat_1"); + assert_eq!(saved[0].1.refresh_token.as_deref(), Some("shprt_1")); + assert_eq!( + mock.graphql_requests()[0].access_token.as_deref(), + Some("shpat_1") + ); +} + +#[tokio::test] +async fn an_expired_refresh_token_says_what_to_do() { + let mock = MockTransport::new(); + shopify_like(&mock, 3600, vec![]); + let mut stored = TokenData::new("shpat_old"); + stored.expires_at = Some(chrono::Utc::now() - chrono::Duration::seconds(1)); + stored.refresh_token = Some("shprt_old".to_string()); + stored.refresh_token_expires_at = Some(chrono::Utc::now() - chrono::Duration::seconds(1)); + let shopify = builder(&mock) + .auth(Auth::expiring_token("id", "secret", stored)) + .build() + .unwrap(); + + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!(matches!(error, Error::Auth { .. }), "{error:?}"); + assert!( + error + .to_string() + .contains("refresh token is missing or expired"), + "{error}" + ); + // Not a refusal of the token endpoint: nothing was asked. + assert_eq!(error.token_endpoint_status(), None); + assert_eq!(error.oauth_code(), None); + assert!(mock.requests().is_empty()); +} + +#[tokio::test] +async fn a_refused_grant_says_what_shopify_answered_and_never_the_secret() { + let mock = MockTransport::new(); + mock.push(HttpResponse::json( + 400, + &json!({ "error": "shop_not_permitted", "error_description": "Client credentials cannot be performed on this shop." }), + )); + let shopify = builder(&mock) + .client_credentials("id", "top-secret") + .build() + .unwrap(); + + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + let message = error.to_string(); + assert_eq!( + message, + "authentication failed: the token endpoint of test-shop.myshopify.com answered 400 (shop_not_permitted)" + ); + // What it wrote is there for code that asks. + assert_eq!( + error.sensitive_detail(), + Some("shop_not_permitted: Client credentials cannot be performed on this shop.") + ); + // And how it refused, without reading the message. + assert_eq!(error.token_endpoint_status(), Some(400)); + assert_eq!(error.oauth_code(), Some(OAuthErrorCode::ShopNotPermitted)); + assert!(!error.is_held_auth_failure()); + assert!(matches!( + error, + Error::Auth { + status: Some(400), + oauth_code: Some(OAuthErrorCode::ShopNotPermitted), + held: false, + .. + } + )); + assert!(!format!("{error:?}").contains("top-secret")); +} + +/// The client credentials grant of a client that answers `status` and `body`. +async fn grant_refused_with(status: u16, body: &str) -> Error { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(status, body.to_string())); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + shopify.graphql("{ shop { name } }", ()).await.unwrap_err() +} + +#[tokio::test] +async fn a_refusal_without_an_oauth_code_has_its_status_only() { + for (status, body) in [ + (503, "Service Unavailable"), + (429, "{\"errors\": \"Too many requests\"}"), + (500, ""), + ] { + let error = grant_refused_with(status, body).await; + assert_eq!( + error.to_string(), + format!( + "authentication failed: the token endpoint of test-shop.myshopify.com answered {status}" + ) + ); + assert_eq!(error.token_endpoint_status(), Some(status)); + assert_eq!(error.oauth_code(), None); + assert!(!error.is_held_auth_failure()); + } +} + +#[tokio::test] +async fn an_unknown_oauth_code_is_a_code_without_its_text() { + let error = grant_refused_with(400, r#"{"error": "shpat_LOOKS_LIKE_A_TOKEN"}"#).await; + assert_eq!( + error.to_string(), + "authentication failed: the token endpoint of test-shop.myshopify.com answered 400 \ + (an error code this crate does not know)" + ); + assert_eq!(error.token_endpoint_status(), Some(400)); + assert_eq!(error.oauth_code(), Some(OAuthErrorCode::Other)); + assert_eq!(OAuthErrorCode::Other.as_str(), None); + assert!(!format!("{error:?}").contains("LOOKS_LIKE")); +} + +#[tokio::test] +async fn a_token_answer_that_does_not_read_is_not_a_refusal() { + let mock = MockTransport::new(); + mock.push_json(json!({ "access_token": 1 })); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!(error.to_string().contains("invalid token"), "{error}"); + assert_eq!(error.token_endpoint_status(), None); + assert_eq!(error.oauth_code(), None); +} + +#[tokio::test] +async fn a_refused_refresh_has_its_status_and_code() { + let mock = MockTransport::new(); + mock.push(HttpResponse::json( + 400, + &json!({ "error": "invalid_grant", "error_description": "The refresh token is revoked." }), + )); + let mut stored = TokenData::new("shpat_old"); + stored.expires_at = Some(chrono::Utc::now() - chrono::Duration::seconds(1)); + stored.refresh_token = Some("shprt_old".to_string()); + let shopify = builder(&mock) + .auth(Auth::expiring_token("id", "secret", stored)) + .build() + .unwrap(); + + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert_eq!( + error.to_string(), + "authentication failed: the token endpoint of test-shop.myshopify.com answered 400 (invalid_grant)" + ); + assert_eq!(error.token_endpoint_status(), Some(400)); + assert_eq!(error.oauth_code(), Some(OAuthErrorCode::InvalidGrant)); + assert_eq!(OAuthErrorCode::InvalidGrant.as_str(), Some("invalid_grant")); +} + +#[tokio::test] +async fn a_token_answer_that_does_not_parse_shows_no_token() { + for answer in [ + // A token, with a field of the wrong type next to it. + HttpResponse::json( + 200, + &json!({ "access_token": "shpat_TOKEN_SECRET", "scope": 1, "refresh_token": "shprt_REFRESH_SECRET", "expires_in": "shpat_TOKEN_SECRET" }), + ), + // A refusal that echoes what was sent. + HttpResponse::new( + 400, + "invalid request: client_secret=CLIENT_SECRET&refresh_token=shprt_REFRESH_SECRET", + ), + ] { + let mock = MockTransport::new(); + mock.push(answer); + let shopify = builder(&mock) + .client_credentials("id", "CLIENT_SECRET") + .build() + .unwrap(); + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + for shown in [ + format!("{error}"), + format!("{error:?}"), + format!("{error:#?}"), + ] { + for secret in ["TOKEN_SECRET", "REFRESH_SECRET", "CLIENT_SECRET"] { + assert!(!shown.contains(secret), "{secret} in {shown}"); + } + assert!(shown.contains("token endpoint"), "{shown}"); + } + } +} + +#[tokio::test] +async fn a_failed_renewal_ahead_of_expiry_keeps_the_token_that_still_works() { + let mock = MockTransport::new(); + mock.respond_with(|request: &HttpRequest| { + if request.url == TOKEN_URL { + return Ok(HttpResponse::new(503, "unavailable")); + } + Ok(HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }); + // A token that expires in a minute: within the five minutes of leeway. + let mut stored = TokenData::new("shpat_soon"); + stored.expires_at = Some(chrono::Utc::now() + chrono::Duration::seconds(60)); + let shopify = builder(&mock) + .auth(Auth::client_credentials("id", "secret").with_token(stored)) + .build() + .unwrap(); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + + // One renewal tried, then held back; the current token sent both times. + assert_eq!(token_requests(&mock).len(), 1); + let sent: Vec<_> = mock + .graphql_requests() + .into_iter() + .map(|request| request.access_token) + .collect(); + assert_eq!( + sent, + [ + Some("shpat_soon".to_string()), + Some("shpat_soon".to_string()) + ] + ); +} + +/// Answers token requests after `delay`, and counts them. +struct Slow { + delay: Duration, + asked: Arc>, +} + +impl shopify_api::transport::Transport for Slow { + fn send( + &self, + request: HttpRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + if request.url == TOKEN_URL { + *self.asked.lock().unwrap() += 1; + tokio::time::sleep(self.delay).await; + return Ok(HttpResponse::json( + 200, + &json!({ "access_token": "shpat_new", "expires_in": 3600, "refresh_token": "shprt_new" }), + )); + } + Ok(HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }) + } +} + +#[tokio::test] +async fn a_cancelled_request_does_not_lose_the_rotated_refresh_token() { + let asked = Arc::new(Mutex::new(0)); + let saved = Saved::default(); + let mut stored = TokenData::new("shpat_old"); + stored.expires_at = Some(chrono::Utc::now() - chrono::Duration::seconds(1)); + stored.refresh_token = Some("shprt_old".to_string()); + let shopify = Shopify::builder("test-shop") + .auth(Auth::expiring_token("id", "secret", stored)) + .transport(Slow { + delay: Duration::from_millis(100), + asked: asked.clone(), + }) + .token_store(saved.clone()) + .build() + .unwrap(); + + // The caller gives up while Shopify is answering the refresh. + let gave_up = tokio::time::timeout(Duration::from_millis(10), shopify.access_token()).await; + assert!(gave_up.is_err()); + tokio::time::sleep(Duration::from_millis(200)).await; + + // The renewal finished anyway: the new tokens are held and saved. + let token = shopify.token().await.unwrap(); + assert_eq!(token.refresh_token.as_deref(), Some("shprt_new")); + assert_eq!(saved.0.lock().unwrap().len(), 1); + assert_eq!(shopify.access_token().await.unwrap(), "shpat_new"); + assert_eq!(*asked.lock().unwrap(), 1); +} + +#[tokio::test] +async fn a_failed_grant_answers_the_requests_that_wait_for_it() { + let mock = MockTransport::new(); + mock.respond_with(|request: &HttpRequest| { + if request.url == TOKEN_URL { + return Ok(HttpResponse::new(503, "unavailable")); + } + Ok(HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + + let calls: Vec<_> = (0..5) + .map(|_| { + let shopify = shopify.clone(); + tokio::spawn(async move { shopify.graphql("{ shop { name } }", ()).await }) + }) + .collect(); + for call in calls { + let error = call.await.unwrap().unwrap_err(); + assert!(matches!(error, Error::Auth { .. }), "{error:?}"); + } + // One request to the token endpoint; the others got its failure. + assert_eq!(token_requests(&mock).len(), 1); +} + +#[tokio::test] +async fn the_requests_that_wait_for_a_refused_grant_get_its_status_and_code() { + let mock = MockTransport::new(); + mock.respond_with(|request: &HttpRequest| { + if request.url == TOKEN_URL { + return Ok(HttpResponse::json( + 401, + &json!({ "error": "invalid_client", "error_description": "Client authentication failed" }), + )); + } + Ok(HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + + let calls: Vec<_> = (0..5) + .map(|_| { + let shopify = shopify.clone(); + tokio::spawn(async move { shopify.graphql("{ shop { name } }", ()).await }) + }) + .collect(); + let mut held = 0; + for call in calls { + let error = call.await.unwrap().unwrap_err(); + assert_eq!(error.token_endpoint_status(), Some(401), "{error:?}"); + assert_eq!(error.oauth_code(), Some(OAuthErrorCode::InvalidClient)); + let refusal = "the token endpoint of test-shop.myshopify.com answered 401 (invalid_client)"; + if error.is_held_auth_failure() { + held += 1; + assert_eq!( + error.to_string(), + format!( + "authentication failed: authentication failed: {refusal} (asked again in a few seconds)" + ) + ); + assert_eq!(error.sensitive_detail(), None); + } else { + assert_eq!( + error.to_string(), + format!("authentication failed: {refusal}") + ); + } + } + // One request asked Shopify; the four others were handed its failure. + assert_eq!(token_requests(&mock).len(), 1); + assert_eq!(held, 4); +} + +#[tokio::test] +async fn a_held_failure_that_is_not_a_refusal_has_no_status() { + let mock = MockTransport::new(); + mock.respond_with(|request: &HttpRequest| { + if request.url == TOKEN_URL { + return Ok(HttpResponse::json( + 200, + &json!({ "scope": "read_products" }), + )); + } + Ok(HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + + let first = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + let second = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!(!first.is_held_auth_failure()); + assert!(second.is_held_auth_failure()); + for error in [first, second] { + assert_eq!(error.token_endpoint_status(), None); + assert_eq!(error.oauth_code(), None); + } + assert_eq!(token_requests(&mock).len(), 1); +} + +#[tokio::test] +async fn a_token_that_never_expires_in_practice_is_read() { + let mock = MockTransport::new(); + mock.push_json(json!({ "access_token": "shpat_long", "expires_in": i64::MAX, "refresh_token_expires_in": -1 })); + mock.push_data(json!({ "shop": { "name": "x" } })); + let shopify = builder(&mock) + .client_credentials("id", "secret") + .build() + .unwrap(); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + let token = shopify.token().await.unwrap(); + assert_eq!( + token.expires_at, + Some(chrono::DateTime::::MAX_UTC) + ); + assert!(!token.expires_within(std::time::Duration::from_secs(365 * 86_400))); +} + +/// Fails the first `failures` saves, then saves. +#[derive(Clone)] +struct Flaky { + failures: Arc>, + saved: Saved, +} + +impl TokenStore for Flaky { + fn save<'a>( + &'a self, + shop: &'a ShopDomain, + token: &'a TokenData, + ) -> BoxFuture<'a, Result<(), Box>> { + let mut failures = self.failures.lock().unwrap(); + if *failures > 0 { + *failures -= 1; + return Box::pin(async { Err("the database is down".into()) }); + } + self.saved.save(shop, token) + } +} + +#[tokio::test] +async fn nothing_is_sent_until_a_renewed_token_is_saved() { + let mock = MockTransport::new(); + shopify_like(&mock, 3600, vec![]); + let store = Flaky { + failures: Arc::new(Mutex::new(2)), + saved: Saved::default(), + }; + let mut stored = TokenData::new("shpat_old"); + stored.expires_at = Some(chrono::Utc::now() - chrono::Duration::seconds(1)); + stored.refresh_token = Some("shprt_old".to_string()); + let shopify = builder(&mock) + .auth(Auth::expiring_token("id", "secret", stored)) + .token_store(store.clone()) + .build() + .unwrap(); + + // The renewal works, its save fails: nothing is sent, now or on the next call. + for _ in 0..2 { + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!(matches!(error, Error::TokenStore(_)), "{error:?}"); + assert!(mock.graphql_requests().is_empty()); + } + // The save goes through: the token it saved is the one sent. + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(token_requests(&mock).len(), 1, "renewed once"); + let saved = store.saved.0.lock().unwrap(); + assert_eq!(saved.len(), 1); + assert_eq!(saved[0].1.refresh_token.as_deref(), Some("shprt_1")); + assert_eq!( + mock.graphql_requests()[0].access_token.as_deref(), + Some("shpat_1") + ); +} + +#[tokio::test] +async fn a_refresh_without_a_new_refresh_token_keeps_the_current_one() { + let mock = MockTransport::new(); + mock.respond_with(|request: &HttpRequest| { + if request.url == TOKEN_URL { + return Ok(HttpResponse::json( + 200, + &json!({ "access_token": "shpat_new", "expires_in": 3600 }), + )); + } + Ok(HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }); + let refresh_expires = chrono::Utc::now() + chrono::Duration::days(30); + let mut stored = TokenData::new("shpat_old"); + stored.expires_at = Some(chrono::Utc::now() - chrono::Duration::seconds(1)); + stored.refresh_token = Some("shprt_old".to_string()); + stored.refresh_token_expires_at = Some(refresh_expires); + let shopify = builder(&mock) + .auth(Auth::expiring_token("id", "secret", stored)) + .build() + .unwrap(); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + let token = shopify.token().await.unwrap(); + assert_eq!(token.access_token, "shpat_new"); + assert_eq!(token.refresh_token.as_deref(), Some("shprt_old")); + assert_eq!(token.refresh_token_expires_at, Some(refresh_expires)); +} diff --git a/crates/shopify_api/tests/bulk.rs b/crates/shopify_api/tests/bulk.rs new file mode 100644 index 0000000..906e904 --- /dev/null +++ b/crates/shopify_api/tests/bulk.rs @@ -0,0 +1,370 @@ +//! Bulk operations against a scripted Shopify. +#![cfg(feature = "testing")] + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use serde::Deserialize; +use serde_json::{Value, json}; +use shopify_api::bulk::{BulkOperationStatus, BulkOperationsFilter, BulkWaitOptions}; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::transport::{HttpRequest, HttpResponse, Method}; +use shopify_api::{Error, Shopify}; + +const RESULTS_URL: &str = "https://storage.googleapis.com/shopify-tiers-assets-prod-us-east1/bulk-operation-outputs/1.jsonl"; +const UPLOAD_URL: &str = "https://shopify-staged-uploads.storage.googleapis.com/"; + +fn operation(status: &str, url: Option<&str>) -> Value { + json!({ + "id": "gid://shopify/BulkOperation/1", + "type": "QUERY", + "status": status, + "errorCode": null, + "createdAt": "2026-10-22T10:00:00Z", + "completedAt": if status == "COMPLETED" { json!("2026-10-22T10:01:00Z") } else { Value::Null }, + "objectCount": "2", + "rootObjectCount": "2", + "fileSize": url.map(|_| "120"), + "url": url, + "partialDataUrl": null, + "query": "{ products { edges { node { id title } } } }", + }) +} + +fn operation_name(request: &HttpRequest) -> Option { + request + .json()? + .get("operationName")? + .as_str() + .map(str::to_string) +} + +fn fast() -> BulkWaitOptions { + BulkWaitOptions::new().poll_interval(Duration::from_millis(1)) +} + +#[tokio::test] +async fn a_bulk_query_runs_to_its_end_and_its_rows_are_read() { + let mock = MockTransport::new(); + let polls = Arc::new(Mutex::new(0)); + mock.respond_with(move |request| { + if request.url == RESULTS_URL { + assert_eq!(request.method, Method::Get); + assert_eq!(request.header("X-Shopify-Access-Token"), None, "the token stays with Shopify"); + return Ok(HttpResponse::new( + 200, + "{\"id\":\"gid://shopify/Product/1\",\"title\":\"Shirt\"}\n{\"id\":\"gid://shopify/Product/2\",\"title\":\"Hat\"}\n", + )); + } + let data = match operation_name(request).as_deref() { + Some("BulkOperationRunQuery") => { + json!({ "bulkOperationRunQuery": { "bulkOperation": operation("CREATED", None), "userErrors": [] } }) + } + Some("BulkOperation") => { + let mut polls = polls.lock().unwrap(); + *polls += 1; + let status = if *polls < 3 { "RUNNING" } else { "COMPLETED" }; + let url = (status == "COMPLETED").then_some(RESULTS_URL); + json!({ "bulkOperation": operation(status, url) }) + } + other => panic!("unexpected operation {other:?}"), + }; + Ok(HttpResponse::json(200, &json!({ "data": data }))) + }); + let shopify = client(&mock); + + #[derive(Debug, Deserialize, PartialEq)] + struct Product { + id: String, + title: String, + } + let products: Vec = shopify + .bulk_query_rows("{ products { edges { node { id title } } } }", fast()) + .await + .unwrap(); + assert_eq!( + products + .iter() + .map(|product| product.title.as_str()) + .collect::>(), + ["Shirt", "Hat"] + ); + + let sent = mock.graphql_requests(); + assert_eq!( + sent[0].variables, + json!({ "query": "{ products { edges { node { id title } } } }", "groupObjects": false }) + ); + assert_eq!(sent.len(), 4, "a start and three polls"); +} + +#[tokio::test] +async fn a_text_bulk_query_groups_objects_only_when_asked() { + use shopify_api::bulk::GroupObjects; + + let mock = MockTransport::new(); + for _ in 0..5 { + mock.push_data(json!({ "bulkOperationRunQuery": { + "bulkOperation": operation("CREATED", None), + "userErrors": [], + } })); + } + let shopify = client(&mock); + let query = "{ products { edges { node { id variants { edges { node { sku } } } } } } }"; + + let started = shopify.start_bulk_query(query).await.unwrap(); + assert_eq!(started.status, BulkOperationStatus::Created); + shopify.start_bulk_query(query.to_string()).await.unwrap(); + shopify.start_bulk_query(&query.to_string()).await.unwrap(); + shopify.start_bulk_query(GroupObjects(query)).await.unwrap(); + shopify + .start_bulk_query(GroupObjects(query.to_string())) + .await + .unwrap(); + + let sent: Vec = mock + .graphql_requests() + .iter() + .map(|request| request.variables.clone()) + .collect(); + let expected = |grouped: bool| json!({ "query": query, "groupObjects": grouped }); + assert_eq!( + sent, + [ + expected(false), + expected(false), + expected(false), + expected(true), + expected(true) + ] + ); +} + +#[tokio::test] +async fn a_refused_bulk_query_returns_the_user_errors() { + let mock = MockTransport::new(); + mock.push_data(json!({ "bulkOperationRunQuery": { + "bulkOperation": null, + "userErrors": [{ "field": ["query"], "message": "Bulk queries cannot contain a connection argument named first.", "code": "INVALID" }], + } })); + let shopify = client(&mock); + + let error = shopify + .start_bulk_query("{ products(first: 1) { nodes { id } } }") + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + "bulkOperationRunQuery refused: query: Bulk queries cannot contain a connection argument named first." + ); + let Error::UserErrors { errors, .. } = error else { + panic!("user errors"); + }; + assert_eq!(errors[0].code.as_deref(), Some("INVALID")); +} + +#[tokio::test] +async fn a_failed_operation_is_an_error() { + let mock = MockTransport::new(); + mock.push_data(json!({ "bulkOperationRunQuery": { "bulkOperation": operation("CREATED", None), "userErrors": [] } })); + let mut failed = operation("FAILED", None); + failed["errorCode"] = json!("ACCESS_DENIED"); + failed["partialDataUrl"] = json!(RESULTS_URL); + mock.push_data(json!({ "bulkOperation": failed })); + let shopify = client(&mock); + + let error = shopify + .bulk_query_rows::("{ orders { edges { node { id } } } }", fast()) + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: the bulk operation gid://shopify/BulkOperation/1 ended Failed (ACCESS_DENIED)" + ); + // The operation stays reachable: what failed, and what was written before. + let Error::Bulk { + operation: Some(operation), + .. + } = error + else { + panic!("{error:?}"); + }; + assert_eq!(operation.status, BulkOperationStatus::Failed); + assert_eq!(operation.error_code.as_deref(), Some("ACCESS_DENIED")); + assert_eq!(operation.partial_data_url.as_deref(), Some(RESULTS_URL)); +} + +#[tokio::test] +async fn a_bulk_mutation_uploads_its_variables_then_runs() { + let mock = MockTransport::new(); + let uploaded = Arc::new(Mutex::new(None)); + let seen = uploaded.clone(); + mock.respond_with(move |request| { + if request.url == UPLOAD_URL { + *seen.lock().unwrap() = Some(request.clone()); + return Ok(HttpResponse::new(201, "")); + } + let data = match operation_name(request).as_deref() { + Some("StagedUploadsCreate") => json!({ "stagedUploadsCreate": { + "stagedTargets": [{ + "url": UPLOAD_URL, + "resourceUrl": null, + "parameters": [ + { "name": "key", "value": "tmp/1/bulk/vars.jsonl" }, + { "name": "policy", "value": "abc" }, + ], + }], + "userErrors": [], + } }), + Some("BulkOperationRunMutation") => { + let mut started = operation("CREATED", None); + started["type"] = json!("MUTATION"); + json!({ "bulkOperationRunMutation": { "bulkOperation": started, "userErrors": [] } }) + } + other => panic!("unexpected operation {other:?}"), + }; + Ok(HttpResponse::json(200, &json!({ "data": data }))) + }); + let shopify = client(&mock); + + let rows = [ + json!({ "product": { "id": "gid://shopify/Product/1", "title": "A" } }), + json!({ "product": { "id": "gid://shopify/Product/2", "title": "B" } }), + ]; + let mutation = "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }"; + let started = shopify + .start_bulk_mutation_text(mutation, &rows) + .await + .unwrap(); + assert_eq!(started.kind, shopify_api::bulk::BulkOperationType::Mutation); + assert_eq!(started.status, BulkOperationStatus::Created); + + let sent = mock.graphql_requests(); + assert_eq!( + sent[0].variables, + json!({ "input": [{ "filename": "bulk_op_vars.jsonl", "mimeType": "text/jsonl", "resource": "BULK_MUTATION_VARIABLES", "httpMethod": "POST" }] }) + ); + assert_eq!( + sent[1].variables, + json!({ "mutation": mutation, "stagedUploadPath": "tmp/1/bulk/vars.jsonl" }) + ); + + let upload = uploaded.lock().unwrap().clone().expect("an upload"); + let body = String::from_utf8(upload.body.clone()).unwrap(); + assert!( + upload + .header("content-type") + .unwrap() + .starts_with("multipart/form-data; boundary=") + ); + assert!(body.contains("name=\"policy\"\r\n\r\nabc\r\n"), "{body}"); + assert!( + body.contains( + "{\"product\":{\"id\":\"gid://shopify/Product/1\",\"title\":\"A\"}}\n{\"product\":{\"id\":\"gid://shopify/Product/2\",\"title\":\"B\"}}\n" + ), + "{body}" + ); +} + +#[tokio::test] +async fn bulk_operations_are_listed_and_cancelled() { + let mock = MockTransport::new(); + mock.push_data(json!({ "bulkOperations": { + "nodes": [operation("RUNNING", None)], + "pageInfo": { "hasNextPage": true, "endCursor": "c1" }, + } })); + let mut canceling = operation("CANCELING", None); + canceling["objectCount"] = json!("12"); + mock.push_data( + json!({ "bulkOperationCancel": { "bulkOperation": canceling, "userErrors": [] } }), + ); + let shopify = client(&mock); + + let page = shopify + .bulk_operations(BulkOperationsFilter::new().first(5).query("status:RUNNING")) + .await + .unwrap(); + assert_eq!(page.items[0].status, BulkOperationStatus::Running); + assert_eq!(page.end_cursor.as_deref(), Some("c1")); + assert_eq!( + mock.graphql_requests()[0].variables, + json!({ "first": 5, "query": "status:RUNNING", "reverse": true }) + ); + + let cancelled = shopify + .cancel_bulk_operation("gid://shopify/BulkOperation/1") + .await + .unwrap(); + assert_eq!(cancelled.status, BulkOperationStatus::Canceling); + assert_eq!(cancelled.object_count, 12); +} + +#[tokio::test(start_paused = true)] +async fn waiting_gives_up_after_its_timeout() { + let mock = MockTransport::new(); + mock.respond_with(|_| { + Ok(HttpResponse::json( + 200, + &json!({ "data": { "bulkOperation": operation("RUNNING", None) } }), + )) + }); + let shopify: Shopify = client(&mock); + + let error = shopify + .wait_for_bulk_operation( + "gid://shopify/BulkOperation/1", + BulkWaitOptions::new().timeout(Duration::from_secs(30)), + ) + .await + .unwrap_err(); + // The ID, to cancel the operation that keeps running. + let Error::Timeout { id, .. } = &error else { + panic!("{error:?}"); + }; + assert_eq!(id.as_deref(), Some("gid://shopify/BulkOperation/1")); + // 1 + 2 + 4 + 8 + 10 seconds, then the 5 that are left. + assert_eq!(mock.requests().len(), 6); +} + +/// Counts the warnings of the current thread. +struct Warnings(Arc>>); + +impl tracing::Subscriber for Warnings { + fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool { + *metadata.level() <= tracing::Level::WARN + } + fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id { + tracing::span::Id::from_u64(1) + } + fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {} + fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {} + fn event(&self, event: &tracing::Event<'_>) { + self.0 + .lock() + .unwrap() + .push(event.metadata().name().to_string()); + } + fn enter(&self, _: &tracing::span::Id) {} + fn exit(&self, _: &tracing::span::Id) {} +} + +/// The crate's operations go to a pinned version, without a warning that +/// would tell the app to change its own schema. +#[tokio::test] +async fn the_operations_of_the_crate_follow_a_pinned_version_unwarned() { + let warnings = Arc::new(Mutex::new(Vec::new())); + let _guard = tracing::subscriber::set_default(Warnings(warnings.clone())); + let mock = MockTransport::new(); + mock.push_data(json!({ "bulkOperation": null })); + let shopify = client(&mock).with_api_version(shopify_api::ApiVersion::V2026_07); + + assert!( + shopify + .bulk_operation("gid://shopify/BulkOperation/1") + .await + .unwrap() + .is_none() + ); + assert!(mock.requests()[0].url.contains("/admin/api/2026-07/")); + assert!(warnings.lock().unwrap().is_empty(), "{warnings:?}"); +} diff --git a/crates/shopify_api/tests/bulk_stream.rs b/crates/shopify_api/tests/bulk_stream.rs new file mode 100644 index 0000000..cfd68bf --- /dev/null +++ b/crates/shopify_api/tests/bulk_stream.rs @@ -0,0 +1,595 @@ +//! Bulk results read as they download, and bulk variables uploaded from an iterator. +#![cfg(feature = "testing")] + +use std::pin::Pin; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use shopify_api::bulk::{BulkWaitOptions, parse_jsonl}; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::transport::{ + BoxFuture, HttpRequest, HttpResponse, StreamingResponse, Transport, TransportError, +}; +use shopify_api::{Error, Shopify}; + +const RESULTS_URL: &str = + "https://storage.googleapis.com/bulk-operation-outputs/1.jsonl?X-Goog-Signature=SECRET"; +const UPLOAD_URL: &str = "https://shopify-staged-uploads.storage.googleapis.com/"; + +fn operation(status: &str, url: Option<&str>) -> Value { + json!({ + "id": "gid://shopify/BulkOperation/1", + "type": "QUERY", + "status": status, + "errorCode": null, + "createdAt": "2026-10-22T10:00:00Z", + "completedAt": null, + "objectCount": "3", + "rootObjectCount": "2", + "fileSize": null, + "url": url, + "partialDataUrl": null, + "query": "{ products { edges { node { id title } } } }", + }) +} + +fn fast() -> BulkWaitOptions { + BulkWaitOptions::new().poll_interval(Duration::from_millis(1)) +} + +fn push_run_and_completed(mock: &MockTransport, url: Option<&str>) { + mock.push_data(json!({ "bulkOperationRunQuery": { "bulkOperation": operation("CREATED", None), "userErrors": [] } })); + mock.push_data(json!({ "bulkOperation": operation("COMPLETED", url) })); +} + +#[derive(Debug, Deserialize, PartialEq)] +struct Product { + id: String, + title: String, +} + +#[tokio::test] +async fn a_bulk_query_streams_its_rows_from_chunks_cut_anywhere() { + let mock = MockTransport::new(); + push_run_and_completed(&mock, Some(RESULTS_URL)); + mock.push_chunks( + 200, + [ + &b"{\"id\":\"gid://shopify/Product/1\",\"title\":\"Caf"[..], + b"\xc3", + b"\xa9\"}\r\n\r\n{\"id\":\"gid://shopify/Product/2\",", + b"\"title\":\"Hat\"}\n{\"id\":\"gid://shopify/Product/3\",\"title\":\"Cap\"}", + ], + ); + let shopify = client(&mock); + + let mut rows = shopify + .bulk_query_stream::("{ products { edges { node { id title } } } }", fast()) + .await + .unwrap(); + let mut titles = Vec::new(); + while let Some(row) = rows.next_row().await { + titles.push(row.unwrap().title); + } + assert_eq!(titles, ["Café", "Hat", "Cap"]); + assert_eq!(rows.line(), 4); + + let sent = mock.requests(); + assert_eq!(sent.len(), 3); + assert_eq!(sent[2].url, RESULTS_URL); + assert_eq!(sent[2].header("X-Shopify-Access-Token"), None); + assert_eq!(mock.graphql_requests()[0].variables["groupObjects"], false); +} + +#[tokio::test] +async fn an_operation_without_results_streams_nothing() { + let mock = MockTransport::new(); + push_run_and_completed(&mock, None); + let shopify = client(&mock); + + let mut rows = shopify + .bulk_query_stream::("{ products { edges { node { id title } } } }", fast()) + .await + .unwrap(); + assert!(rows.next_row().await.is_none()); + assert_eq!(mock.requests().len(), 2, "nothing to download"); +} + +#[tokio::test] +async fn a_refused_download_keeps_the_first_mib_of_its_body_and_hides_the_signature() { + let mock = MockTransport::new(); + let chunk = vec![b'x'; 256 * 1024]; + let read = Arc::new(Mutex::new(0)); + let counter = read.clone(); + mock.push_chunks( + 403, + std::iter::repeat_n(chunk, 32).inspect(move |_| *counter.lock().unwrap() += 1), + ); + let shopify = client(&mock); + + let error = shopify + .download_bulk_results_stream::(RESULTS_URL) + .await + .unwrap_err(); + assert_eq!(error.status(), Some(403)); + assert_eq!(error.raw_http_body().unwrap().len(), 1024 * 1024); + assert_eq!(*read.lock().unwrap(), 4); + let shown = format!("{error}\n{error:?}"); + assert!(!shown.contains("SECRET"), "{shown}"); +} + +struct Buffered(Vec); + +impl Transport for Buffered { + fn send(&self, _: HttpRequest) -> BoxFuture<'_, Result> { + let response = HttpResponse::new(200, self.0.clone()); + Box::pin(async move { Ok(response) }) + } +} + +#[tokio::test] +async fn a_transport_that_only_sends_streams_through_the_default() { + let body = b"{\"id\":\"1\",\"title\":\"A\"}\n{\"id\":\"2\",\"title\":\"B\"}\n".to_vec(); + let shopify = Shopify::builder("test-shop") + .access_token("t") + .transport(Buffered(body.clone())) + .build() + .unwrap(); + + let mut rows = shopify + .download_bulk_results_stream::(RESULTS_URL) + .await + .unwrap(); + assert_eq!(rows.next_row().await.unwrap().unwrap().title, "A"); + assert_eq!(rows.next_row().await.unwrap().unwrap().title, "B"); + assert!(rows.next_row().await.is_none()); + + let collected: Vec = shopify.download_bulk_results(RESULTS_URL).await.unwrap(); + assert_eq!(collected, parse_jsonl::(&body).unwrap()); + + // `BulkRows::collect`, as `BulkItems::collect`. + let rows: Vec = shopify + .download_bulk_results_stream(RESULTS_URL) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(rows, collected); +} + +struct FailsAfter(Vec>); + +impl futures_core::Stream for FailsAfter { + type Item = Result, TransportError>; + + fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(Some(if self.0.is_empty() { + Err(TransportError::new("connection reset")) + } else { + Ok(self.0.remove(0)) + })) + } +} + +#[tokio::test] +async fn the_vec_methods_stop_at_the_first_error_as_before() { + let mock = MockTransport::new(); + mock.push_streaming(StreamingResponse::new( + 200, + FailsAfter(vec![b"{\"id\":\"1\",\"title\":\"A\"}\n".to_vec()]), + )); + let shopify = client(&mock); + let error = shopify + .download_bulk_results::(RESULTS_URL) + .await + .unwrap_err(); + assert!(matches!(error, Error::Transport { .. }), "{error:?}"); + assert!(!error.to_string().contains("SECRET")); + + let body = b"{\"id\":\"1\",\"title\":\"A\"}\n{\"id\":2}\n{\"id\":\"3\",\"title\":\"C\"}\n"; + mock.push_chunks(200, [&body[..7], &body[7..]]); + let error = shopify + .download_bulk_results::(RESULTS_URL) + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + parse_jsonl::(body).unwrap_err().to_string() + ); +} + +#[tokio::test] +async fn a_grouped_bulk_query_asks_for_grouping_and_yields_each_parent_with_its_children() { + let mock = MockTransport::new(); + mock.push_data(json!({ "bulkOperationRunQuery": { "bulkOperation": operation("CREATED", None), "userErrors": [] } })); + mock.push_data(json!({ "bulkOperation": operation("COMPLETED", Some(RESULTS_URL)) })); + mock.push_chunks( + 200, + [ + &b"{\"id\":\"P1\",\"title\":\"Shirt\"}\n{\"sku\":\"S\",\"__par"[..], + b"entId\":\"P1\"}\n{\"sku\":\"M\",\"__parentId\":\"P1\"}\n{\"id\":\"P2\",\"title\":\"Hat\"}\n", + ], + ); + let shopify = client(&mock); + + #[derive(Debug, Deserialize)] + struct Variant { + sku: String, + } + let mut groups = shopify + .bulk_query_grouped::( + "{ products { edges { node { id title variants { edges { node { sku } } } } } } }", + fast(), + ) + .await + .unwrap(); + let (shirt, variants) = groups.next_group().await.unwrap().unwrap(); + assert_eq!(shirt.title, "Shirt"); + assert_eq!( + variants.iter().map(|v| v.sku.as_str()).collect::>(), + ["S", "M"] + ); + let (hat, variants) = groups.next_group().await.unwrap().unwrap(); + assert_eq!(hat.title, "Hat"); + assert!(variants.is_empty()); + assert!(groups.next_group().await.is_none()); + + assert_eq!(mock.graphql_requests()[0].variables["groupObjects"], true); +} + +#[tokio::test] +async fn a_child_out_of_place_only_asks_for_grouping_when_it_may_be_off() { + let body = &b"{\"id\":\"P1\",\"title\":\"A\"}\n{\"id\":\"P2\",\"title\":\"B\"}\n{\"__parentId\":\"P1\"}\n"[..]; + let mock = MockTransport::new(); + push_run_and_completed(&mock, Some(RESULTS_URL)); + mock.push_chunks(200, [body]); + mock.push_chunks(200, [body]); + let shopify = client(&mock); + + let mut groups = shopify + .bulk_query_grouped::("{ products { edges { node { id } } } }", fast()) + .await + .unwrap(); + groups.next_group().await.unwrap().unwrap(); + let error = groups.next_group().await.unwrap().unwrap_err().to_string(); + assert!( + error.ends_with("though the query ran with `groupObjects`"), + "{error}" + ); + + let mut groups = shopify + .download_bulk_results_grouped::(RESULTS_URL) + .await + .unwrap(); + groups.next_group().await.unwrap().unwrap(); + let error = groups.next_group().await.unwrap().unwrap_err().to_string(); + assert!( + error.ends_with("run the query with `groupObjects`"), + "{error}" + ); +} + +fn upload_mock() -> (MockTransport, Arc>>) { + let mock = MockTransport::new(); + let uploads = Arc::new(Mutex::new(Vec::new())); + let seen = uploads.clone(); + mock.respond_with(move |request| { + if request.url == UPLOAD_URL { + seen.lock().unwrap().push(request.clone()); + return Ok(HttpResponse::new(201, "")); + } + let name = request.json().unwrap()["operationName"].as_str().unwrap().to_string(); + let data = match name.as_str() { + "StagedUploadsCreate" => json!({ "stagedUploadsCreate": { + "stagedTargets": [{ + "url": UPLOAD_URL, + "resourceUrl": null, + "parameters": [{ "name": "key", "value": "tmp/1/bulk/vars.jsonl" }], + }], + "userErrors": [], + } }), + "BulkOperationRunMutation" => { + let mut started = operation("CREATED", None); + started["type"] = json!("MUTATION"); + json!({ "bulkOperationRunMutation": { "bulkOperation": started, "userErrors": [] } }) + } + other => panic!("unexpected operation {other}"), + }; + Ok(HttpResponse::json(200, &json!({ "data": data }))) + }); + (mock, uploads) +} + +fn uploaded_file(request: &HttpRequest) -> String { + let body = String::from_utf8(request.body.clone()).unwrap(); + let start = body.find("Content-Type: text/jsonl\r\n\r\n").unwrap() + 28; + let end = body.rfind("\r\n--").unwrap(); + body[start..end].to_string() +} + +#[tokio::test] +async fn bulk_variables_upload_from_an_iterator_as_from_a_slice() { + let (mock, uploads) = upload_mock(); + let shopify = client(&mock); + let mutation = "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }"; + + #[derive(Serialize)] + struct Row { + product: Value, + } + let taken = Arc::new(Mutex::new(0)); + let counter = taken.clone(); + let rows = (1..=1000).map(move |id| { + *counter.lock().unwrap() += 1; + Row { + product: json!({ "id": format!("gid://shopify/Product/{id}"), "title": "é\n\"" }), + } + }); + let started = shopify + .start_bulk_mutation_text(mutation, rows) + .await + .unwrap(); + assert_eq!(started.kind, shopify_api::bulk::BulkOperationType::Mutation); + assert_eq!(*taken.lock().unwrap(), 1000); + + let slice: Vec = (1..=1000) + .map(|id| Row { + product: json!({ "id": format!("gid://shopify/Product/{id}"), "title": "é\n\"" }), + }) + .collect(); + shopify + .start_bulk_mutation_text(mutation, &slice) + .await + .unwrap(); + + let uploads = uploads.lock().unwrap(); + assert_eq!(uploads.len(), 2); + let from_iter = uploaded_file(&uploads[0]); + assert_eq!(from_iter, uploaded_file(&uploads[1])); + let lines: Vec = parse_jsonl(from_iter.as_bytes()).unwrap(); + assert_eq!(lines.len(), 1000); + assert_eq!(lines[999]["product"]["id"], "gid://shopify/Product/1000"); + assert_eq!(from_iter.matches('\n').count(), 1000, "one line per item"); + + let graphql = mock.graphql_requests(); + assert_eq!( + graphql[1].variables["stagedUploadPath"], + "tmp/1/bulk/vars.jsonl" + ); +} + +#[tokio::test] +async fn an_item_that_does_not_serialize_stops_the_upload() { + struct Leaky; + impl Serialize for Leaky { + fn serialize(&self, _: S) -> Result { + Err(serde::ser::Error::custom("cannot serialize shpat_SECRET")) + } + } + let (mock, uploads) = upload_mock(); + let shopify = client(&mock); + + let error = shopify + .stage_bulk_variables_iter([Leaky]) + .await + .unwrap_err(); + assert!(matches!(error, Error::Variables { .. }), "{error:?}"); + assert!(!format!("{error}{error:?}").contains("SECRET")); + assert!(uploads.lock().unwrap().is_empty(), "nothing uploaded"); +} + +#[cfg(feature = "rustls")] +mod reqwest_transport { + use super::*; + use shopify_api::transport::{Method, ReqwestTransport}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::{TcpListener, TcpStream}; + + async fn read_request(socket: &mut TcpStream) { + let mut request = Vec::new(); + let mut buffer = [0; 1024]; + while !request.ends_with(b"\r\n\r\n") { + let read = socket.read(&mut buffer).await.unwrap(); + assert!(read > 0); + request.extend_from_slice(&buffer[..read]); + } + } + + async fn write_chunk(socket: &mut TcpStream, data: &[u8]) { + let mut chunk = format!("{:x}\r\n", data.len()).into_bytes(); + chunk.extend_from_slice(data); + chunk.extend_from_slice(b"\r\n"); + socket.write_all(&chunk).await.unwrap(); + socket.flush().await.unwrap(); + } + + async fn next(response: &mut StreamingResponse) -> Option, TransportError>> { + std::future::poll_fn(|context| { + futures_core::Stream::poll_next(response.body.as_mut(), context) + }) + .await + } + + const HEAD: &[u8] = b"HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: application/jsonl\r\nTransfer-Encoding: chunked\r\n\r\n"; + + #[tokio::test] + async fn rows_arrive_before_the_rest_of_the_body_is_sent() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (release, released) = tokio::sync::oneshot::channel::<()>(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + read_request(&mut socket).await; + socket.write_all(HEAD).await.unwrap(); + write_chunk( + &mut socket, + b"{\"id\":\"1\",\"title\":\"A\"}\n{\"id\":\"2\",", + ) + .await; + released.await.unwrap(); + write_chunk(&mut socket, b"\"title\":\"B\"}\n").await; + socket.write_all(b"0\r\n\r\n").await.unwrap(); + }); + let shopify = Shopify::new("test-shop", shopify_api::Auth::access_token("t")).unwrap(); + + let mut rows = shopify + .download_bulk_results_stream::(&format!("http://{address}/r.jsonl?sig=x")) + .await + .unwrap(); + let first = tokio::time::timeout(Duration::from_secs(10), rows.next_row()) + .await + .expect("the first row before the end of the body"); + assert_eq!(first.unwrap().unwrap().title, "A"); + release.send(()).unwrap(); + assert_eq!(rows.next_row().await.unwrap().unwrap().title, "B"); + assert!(rows.next_row().await.is_none()); + server.await.unwrap(); + } + + #[tokio::test] + async fn the_timeout_bounds_each_chunk_not_the_whole_body() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + read_request(&mut socket).await; + socket.write_all(HEAD).await.unwrap(); + for _ in 0..6 { + tokio::time::sleep(Duration::from_millis(100)).await; + write_chunk(&mut socket, b"{}\n").await; + } + socket.write_all(b"0\r\n\r\n").await.unwrap(); + drop(socket); + let (mut socket, _) = listener.accept().await.unwrap(); + read_request(&mut socket).await; + socket.write_all(HEAD).await.unwrap(); + write_chunk(&mut socket, b"{}\n").await; + tokio::time::sleep(Duration::from_secs(30)).await; + }); + let transport = ReqwestTransport::new().unwrap(); + let request = |url: String| { + let mut request = HttpRequest::new(Method::Get, url); + request.timeout = Some(Duration::from_millis(400)); + request + }; + + let started = std::time::Instant::now(); + let mut response = transport + .send_streaming(request(format!("http://{address}/slow"))) + .await + .unwrap(); + let mut body = Vec::new(); + while let Some(chunk) = next(&mut response).await { + body.extend_from_slice(&chunk.unwrap()); + } + assert_eq!(body, b"{}\n".repeat(6)); + assert!( + started.elapsed() > Duration::from_millis(400), + "longer than the timeout in all" + ); + + let mut response = transport + .send_streaming(request(format!("http://{address}/stalled"))) + .await + .unwrap(); + assert_eq!(next(&mut response).await.unwrap().unwrap(), b"{}\n"); + let error = next(&mut response).await.unwrap().unwrap_err(); + assert!(error.is_timeout(), "{error}"); + assert!( + next(&mut response).await.is_none(), + "the stream ends after its error" + ); + server.abort(); + } + + #[tokio::test] + async fn the_timeout_bounds_the_wait_for_the_headers() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (_socket, _) = listener.accept().await.unwrap(); + tokio::time::sleep(Duration::from_secs(30)).await; + }); + let mut request = HttpRequest::new(Method::Get, format!("http://{address}/silent")); + request.timeout = Some(Duration::from_millis(200)); + let error = ReqwestTransport::new() + .unwrap() + .send_streaming(request) + .await + .unwrap_err(); + assert!(error.is_timeout(), "{error}"); + server.abort(); + } +} + +/// Streams 200 MB generated as it is read, and prints the peak resident +/// memory of the process, then reads the same file whole for comparison. +/// `cargo test --release -p shopify_api --all-features --test bulk_stream -- --ignored --nocapture` +#[tokio::test] +#[ignore = "a measure, not a check: slow, and the numbers depend on the machine"] +async fn measure_the_memory_of_a_200_mb_export() { + fn resident_kib() -> u64 { + let output = std::process::Command::new("ps") + .args(["-o", "rss=", "-p", &std::process::id().to_string()]) + .output() + .unwrap(); + String::from_utf8(output.stdout) + .unwrap() + .trim() + .parse() + .unwrap() + } + let line = format!( + "{{\"id\":\"gid://shopify/Product/1234567890\",\"title\":\"{}\",\"price\":\"19.99\"}}\n", + "x".repeat(150) + ); + let chunk = line.repeat(256).into_bytes(); + let chunks = 200_000_000 / chunk.len(); + let total = chunk.len() * chunks; + + #[derive(Deserialize)] + #[allow(dead_code, reason = "decoded for the memory it takes, never read")] + struct Row { + id: String, + title: String, + price: String, + } + let mock = MockTransport::new(); + mock.push_chunks(200, std::iter::repeat_n(chunk.clone(), chunks)); + let shopify = client(&mock); + + let before = resident_kib(); + let mut rows = shopify + .download_bulk_results_stream::(RESULTS_URL) + .await + .unwrap(); + let mut count = 0usize; + let mut peak = before; + while let Some(row) = rows.next_row().await { + row.unwrap(); + count += 1; + if count.is_multiple_of(20_000) { + peak = peak.max(resident_kib()); + } + } + assert_eq!(count, 256 * chunks); + println!( + "streamed {} MB, {count} rows: resident {} KiB before, {} KiB at the peak (+{} KiB)", + total / 1_000_000, + before, + peak, + peak - before + ); + + let body = chunk.repeat(chunks); + let rows: Vec = parse_jsonl(&body).unwrap(); + println!( + "read whole: resident {} KiB with the file and its {} rows in memory", + resident_kib(), + rows.len() + ); +} diff --git a/crates/shopify_api/tests/bulk_text.rs b/crates/shopify_api/tests/bulk_text.rs new file mode 100644 index 0000000..b7c4e69 --- /dev/null +++ b/crates/shopify_api/tests/bulk_text.rs @@ -0,0 +1,476 @@ +//! What the text of a bulk query holds, and how its lines are placed: the +//! values written into it, its strings, and the keys that route its lines. +#![cfg(feature = "testing")] + +use shopify_api::testing::{MockTransport, client}; +use shopify_api::{Error, InvalidValueReason, graphql, input}; + +const URL: &str = "https://storage.googleapis.com/shopify-tiers-assets-prod-us-east1/bulk-operation-outputs/text.jsonl"; + +graphql! { + mod sorted = bulk("query($sort: ProductSortKeys) { products(sortKey: $sort) { edges { node { title } } } }"); + mod sorted_by_title = bulk("query($sort: ProductSortKeys = TITLE) { products(sortKey: $sort) { edges { node { title } } } }"); + mod topics = bulk("query($topics: [WebhookSubscriptionTopic!]) { webhookSubscriptions(topics: $topics) { edges { node { id } } } }"); + mod priced = bulk("query($context: ContextualPricingContext!) { products { edges { node { contextualPricing(context: $context) { priceRange { minVariantPrice { amount } } } } } } }"); + mod aliased_id = bulk("{ products { edges { node { id: totalInventory title } } } }"); + mod aliased_child_id = bulk("{ products { edges { node { id variants { edges { node { id: inventoryQuantity sku } } } } } } }"); + mod typenames = bulk("{ products { edges { node { id variants { edges { node { __typename kind: __typename sku } } } media { edges { node { __typename @include(if: false) alt } } } } } } }"); +} + +// ─── Enum values `true`, `false` and `null` ────────────────────────────── + +fn refused_as_reserved(result: shopify_api::Result, path: &str) { + let error = result.unwrap_err(); + let Error::InvalidValue { + path: at, reason, .. + } = &error + else { + panic!("{error:?}"); + }; + assert_eq!(at, path); + assert_eq!(*reason, InvalidValueReason::ReservedEnumValue); +} + +#[test] +fn an_enum_variable_true_false_or_null_is_refused() { + for word in ["null", "true", "false"] { + let text = sorted::operation(sorted::Variables { + sort: Some(word.into()), + }) + .text(); + refused_as_reserved(text, "$sort"); + } + // A real `null` is still `null`, and a name that only starts like one is a name. + let text = graphql!( + bulk("query($sort: ProductSortKeys) { products(sortKey: $sort) { edges { node { title } } } }"), + sort = null, + ) + .text() + .unwrap(); + assert!(text.contains("products(sortKey: null)"), "{text}"); + let text = sorted::operation(sorted::Variables { + sort: Some("nullable".into()), + }) + .text() + .unwrap(); + assert!(text.contains("products(sortKey: nullable)"), "{text}"); +} + +#[test] +fn a_none_in_variables_is_absence_and_null_is_null() { + // `None` in `Variables` leaves the variable out: its argument goes, or + // takes the variable's default. + let text = sorted::operation(sorted::Variables { sort: None }) + .text() + .unwrap(); + assert_eq!(text, "{ products { edges { node { title } } } }"); + let text = sorted_by_title::operation(sorted_by_title::Variables { sort: None }) + .text() + .unwrap(); + assert!(text.contains("products(sortKey: TITLE)"), "{text}"); + // An explicit `null` is written, and replaces the default. + let text = graphql!( + bulk("query($sort: ProductSortKeys = TITLE) { products(sortKey: $sort) { edges { node { title } } } }"), + sort = null, + ) + .text() + .unwrap(); + assert!(text.contains("products(sortKey: null)"), "{text}"); +} + +#[test] +fn an_enum_true_false_or_null_in_a_list_is_refused() { + for word in ["null", "true", "false"] { + let text = topics::operation(topics::Variables { + topics: Some(vec!["ORDERS_CREATE".into(), word.into()]), + }) + .text(); + refused_as_reserved(text, "$topics[1]"); + } +} + +#[test] +fn an_enum_true_false_or_null_in_an_input_field_is_refused() { + for text in [ + priced::operation(priced::Variables { + context: input!(ContextualPricingContext { + country: raw("null") + }), + }) + .text(), + priced::operation(priced::Variables { + context: input!(ContextualPricingContext { + country: raw("true") + }), + }) + .text(), + priced::operation(priced::Variables { + context: input!(ContextualPricingContext { + country: raw("false") + }), + }) + .text(), + ] { + refused_as_reserved(text, "$context.country"); + } + let text = priced::operation(priced::Variables { + context: input!(ContextualPricingContext { country: null }), + }) + .text() + .unwrap(); + assert!( + text.contains("contextualPricing(context: {country: null})"), + "{text}" + ); +} + +// ─── Strings ───────────────────────────────────────────────────────────── + +/// A GraphQL string token, quoted or block, read as the specification +/// reads it: a decoder of the test's own, not the crate's. +fn decode(token: &str) -> String { + if let Some(body) = token.strip_prefix("\"\"\"") { + let body = body.strip_suffix("\"\"\"").unwrap(); + let raw = body.replace("\\\"\"\"", "\"\"\""); + let lines: Vec = raw + .replace("\r\n", "\n") + .replace('\r', "\n") + .split('\n') + .map(str::to_string) + .collect(); + let white = |line: &str| line.chars().take_while(|c| *c == ' ' || *c == '\t').count(); + let common = lines[1..] + .iter() + .filter(|line| white(line) < line.chars().count()) + .map(|line| white(line)) + .min(); + let mut lines: Vec = lines + .iter() + .enumerate() + .map(|(index, line)| match common { + Some(common) if index > 0 => line.chars().skip(common).collect(), + _ => line.clone(), + }) + .collect(); + while lines + .first() + .is_some_and(|line| white(line) == line.chars().count()) + { + lines.remove(0); + } + while lines + .last() + .is_some_and(|line| white(line) == line.chars().count()) + { + lines.pop(); + } + return lines.join("\n"); + } + let body = token.strip_prefix('"').unwrap().strip_suffix('"').unwrap(); + let mut out = String::new(); + let mut chars = body.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + assert!(c != '\n' && c != '\r', "a line break in {token:?}"); + out.push(c); + continue; + } + match chars.next().unwrap() { + '"' => out.push('"'), + '\\' => out.push('\\'), + '/' => out.push('/'), + 'b' => out.push('\u{8}'), + 'f' => out.push('\u{c}'), + 'n' => out.push('\n'), + 'r' => out.push('\r'), + 't' => out.push('\t'), + 'u' => { + let hex: String = chars.by_ref().take(4).collect(); + let code = u32::from_str_radix(&hex, 16).unwrap(); + if (0xD800..0xDC00).contains(&code) { + // A surrogate pair. + assert_eq!(chars.next(), Some('\\')); + assert_eq!(chars.next(), Some('u')); + let low: String = chars.by_ref().take(4).collect(); + let low = u32::from_str_radix(&low, 16).unwrap(); + out.push( + char::from_u32(0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00)).unwrap(), + ); + } else { + out.push(char::from_u32(code).unwrap()); + } + } + other => panic!("unknown escape \\{other} in {token:?}"), + } + } + out +} + +/// The string token that follows `after` in `text`. +fn token_after<'t>(text: &'t str, after: &str) -> &'t str { + let start = text + .find(after) + .unwrap_or_else(|| panic!("{after} in {text}")) + + after.len(); + let rest = &text[start..]; + let mut escaped = false; + for (index, c) in rest.char_indices().skip(1) { + match c { + '"' if !escaped => return &rest[..=index], + _ => escaped = !escaped && c == '\\', + } + } + panic!("an unterminated string in {text}"); +} + +/// The value Shopify reads for the string of `products(query: …)`. +fn sent(query: shopify_api::bulk::BulkQuery) -> String { + decode(token_after(&query.text().unwrap(), "products(query: ")) +} + +#[test] +fn every_escape_reaches_shopify_as_written() { + // Each escape GraphQL defines, but `\b`, which `graphql!` refuses + // (`tests/ui/bulk_string_escape.rs`): the value written, and the one + // Shopify reads in the text sent, decoded by the test. + let cases = [ + ( + sent(graphql!(bulk( + r#"{ products(query: "a\"b") { edges { node { id } } } }"# + ))), + "a\"b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\\b") { edges { node { id } } } }"# + ))), + "a\\b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\/b") { edges { node { id } } } }"# + ))), + "a/b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\u0008b") { edges { node { id } } } }"# + ))), + "a\u{8}b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\fb") { edges { node { id } } } }"# + ))), + "a\u{c}b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\nb") { edges { node { id } } } }"# + ))), + "a\nb", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\rb") { edges { node { id } } } }"# + ))), + "a\rb", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\tb") { edges { node { id } } } }"# + ))), + "a\tb", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\u00e9\u20AC\uFFFFb") { edges { node { id } } } }"# + ))), + "aé€\u{FFFF}b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "a\u0000\u001f\u007fb") { edges { node { id } } } }"# + ))), + "a\u{0}\u{1f}\u{7f}b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: "é😀 \u2028 $x #y") { edges { node { id } } } }"# + ))), + "é😀 \u{2028} $x #y", + ), + ( + sent(graphql!(bulk( + r#"query($filter: String = "a\"\\\/\u0008\f\n\r\t\u00e9b") { products(query: $filter) { edges { node { id } } } }"# + ))), + "a\"\\/\u{8}\u{c}\n\r\téb", + ), + ]; + for (index, (sent, written)) in cases.iter().enumerate() { + assert_eq!(sent, written, "case {index}"); + } +} + +#[test] +fn block_strings_reach_shopify_as_written() { + let cases = [ + ( + sent(graphql!(bulk( + r#"{ products(query: """plain""") { edges { node { id } } } }"# + ))), + "plain", + ), + ( + sent(graphql!(bulk( + "{ products(query: \"\"\"\n first\n indented\n last\n \"\"\") { edges { node { id } } } }" + ))), + "first\n indented\nlast", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: """a \""" b""") { edges { node { id } } } }"# + ))), + "a \"\"\" b", + ), + ( + sent(graphql!(bulk( + r#"{ products(query: """no \n escape \u0041""") { edges { node { id } } } }"# + ))), + "no \\n escape \\u0041", + ), + ( + sent(graphql!(bulk( + "{ products(query: \"\"\"\r\n\ta\r\n\t\tb\r\n\"\"\") { edges { node { id } } } }" + ))), + "a\n\tb", + ), + ( + sent(graphql!(bulk( + "query($filter: String = \"\"\"\n x\n \"y\"\n\"\"\") { products(query: $filter) { edges { node { id } } } }" + ))), + "x\n\"y\"", + ), + ]; + for (index, (sent, written)) in cases.iter().enumerate() { + assert_eq!(sent, written, "case {index}"); + } +} + +#[test] +fn a_string_variable_reaches_shopify_as_given() { + let value: String = (0..=0x10ffff).filter_map(char::from_u32).collect(); + let query = graphql!( + bulk("query($filter: String) { products(query: $filter) { edges { node { title } } } }"), + filter = value.clone(), + ); + assert_eq!(sent(query), value); +} + +// ─── The keys that place lines ─────────────────────────────────────────── + +#[tokio::test] +async fn an_item_with_an_alias_id_of_another_type_reads() { + let mock = MockTransport::new(); + mock.push_chunks( + 200, + [b"{\"id\":12,\"title\":\"Shirt\"}\n{\"id\":7,\"title\":\"Hat\"}\n".as_slice()], + ); + let items = client(&mock) + .download_bulk_items::(URL) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(items.len(), 2); + assert_eq!(items[0].id, 12); + assert_eq!(items[0].title, "Shirt"); + assert_eq!(items[1].id, 7); +} + +#[tokio::test] +async fn a_child_with_an_alias_id_of_another_type_reads() { + let mock = MockTransport::new(); + mock.push_chunks( + 200, + [b"{\"id\":\"P1\"}\n{\"id\":12,\"sku\":\"S-1\",\"__parentId\":\"P1\"}\n{\"id\":[1],\"sku\":\"S-2\",\"__parentId\":\"P1\"}\n{\"id\":\"P2\"}\n".as_slice()], + ); + let items = client(&mock) + .download_bulk_items::(URL) + .await + .unwrap() + .collect() + .await; + // `[1]` is not an `Int`: that line alone fails, as its type says. + let error = items.unwrap_err(); + assert!(matches!(error, Error::Decode { .. }), "{error:?}"); + + let mock = MockTransport::new(); + mock.push_chunks( + 200, + [b"{\"id\":\"P1\"}\n{\"id\":12,\"sku\":\"S-1\",\"__parentId\":\"P1\"}\n{\"id\":\"P2\"}\n".as_slice()], + ); + let items = client(&mock) + .download_bulk_items::(URL) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(items.len(), 2); + assert_eq!(items[0].variants[0].id, Some(12)); + assert_eq!(items[0].variants[0].sku.as_deref(), Some("S-1")); + assert!(items[1].variants.is_empty()); +} + +#[tokio::test] +async fn lines_are_placed_by_the_reserved_key_not_by_the_query_s_typename() { + let text = typenames::operation().text().unwrap(); + assert_eq!( + text, + "{ products { edges { node { id \ + variants { edges { node { _shopifyApiTypename: __typename __typename kind: __typename sku } } } \ + media { edges { node { _shopifyApiTypename: __typename __typename @include(if: false) alt } } } } } } }" + ); + // The query's own `__typename` is absent where its `@include` left it + // out, and says nothing of where a line goes. + let mock = MockTransport::new(); + mock.push_chunks(200, [br#"{"id":"P1"} +{"_shopifyApiTypename":"ProductVariant","__typename":"ProductVariant","kind":"ProductVariant","sku":"S-1","__parentId":"P1"} +{"_shopifyApiTypename":"MediaImage","alt":"Front","__parentId":"P1"} +"# + .as_slice()]); + let items = client(&mock) + .download_bulk_items::(URL) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(items[0].variants[0].typename, "ProductVariant"); + assert_eq!(items[0].variants[0].kind, "ProductVariant"); + assert_eq!(items[0].media[0].typename, None); + assert_eq!(items[0].media[0].alt.as_deref(), Some("Front")); + + // A `__typename` alone does not place a line. + let mock = MockTransport::new(); + mock.push_chunks( + 200, + [br#"{"id":"P1"} +{"__typename":"ProductVariant","kind":"ProductVariant","sku":"S-1","__parentId":"P1"} +"# + .as_slice()], + ); + let error = client(&mock) + .download_bulk_items::(URL) + .await + .unwrap() + .collect() + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: line 2 of the results has no `_shopifyApiTypename`, the `__typename` that tells which connection of its parent it belongs to" + ); +} diff --git a/crates/shopify_api/tests/bulk_typed.rs b/crates/shopify_api/tests/bulk_typed.rs new file mode 100644 index 0000000..3c84286 --- /dev/null +++ b/crates/shopify_api/tests/bulk_typed.rs @@ -0,0 +1,512 @@ +//! Bulk operations declared with `graphql!(bulk(…))`, against a scripted Shopify. +#![cfg(feature = "testing")] + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use serde_json::{Value, json}; +use shopify_api::bulk::{BulkMutation, BulkMutationResult, BulkWaitOptions}; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::transport::{HttpRequest, HttpResponse}; +use shopify_api::{Error, InvalidValueReason, graphql}; + +const RESULTS_URL: &str = "https://storage.googleapis.com/shopify-tiers-assets-prod-us-east1/bulk-operation-outputs/1.jsonl"; +const UPLOAD_URL: &str = "https://shopify-staged-uploads.storage.googleapis.com/"; + +graphql! { + /// Products, their variants with their metafields, and their images. + pub mod catalog = bulk("{ + products(query: \"status:active\") { edges { node { + id title + variants { edges { node { id sku metafields { edges { node { key value } } } } } } + media { edges { node { ... on MediaImage { id alt } } } } + } } } + }"); + + mod by_title = bulk("query($filter: String, $sort: ProductSortKeys = TITLE) { + products(query: $filter, sortKey: $sort, reverse: true) { edges { node { id } } } + }"); + + mod add_tags = bulk("mutation($id: ID!, $tags: [String!]!) { + tagsAdd(id: $id, tags: $tags) { userErrors { field message } } + }"); +} + +fn operation(kind: &str, status: &str, url: Option<&str>) -> Value { + json!({ + "id": "gid://shopify/BulkOperation/1", + "type": kind, + "status": status, + "errorCode": null, + "createdAt": "2026-10-22T10:00:00Z", + "completedAt": if status == "COMPLETED" { json!("2026-10-22T10:01:00Z") } else { Value::Null }, + "objectCount": "2", + "rootObjectCount": "2", + "fileSize": url.map(|_| "120"), + "url": url, + "partialDataUrl": null, + "query": "{ products { edges { node { id } } } }", + }) +} + +fn operation_name(request: &HttpRequest) -> Option { + request + .json()? + .get("operationName")? + .as_str() + .map(str::to_string) +} + +fn fast() -> BulkWaitOptions { + BulkWaitOptions::new().poll_interval(Duration::from_millis(1)) +} + +/// A Shopify that runs any bulk operation at once, its results `jsonl`; +/// the uploads it receives go to `uploads`. +fn shopify_with(jsonl: &'static str) -> (MockTransport, Arc>>) { + let mock = MockTransport::new(); + let uploads = Arc::new(Mutex::new(Vec::new())); + let seen = uploads.clone(); + mock.respond_with(move |request| { + if request.url == RESULTS_URL { + return Ok(HttpResponse::new(200, jsonl)); + } + if request.url == UPLOAD_URL { + seen.lock().unwrap().push(request.clone()); + return Ok(HttpResponse::new(201, "")); + } + let data = match operation_name(request).as_deref() { + Some("BulkOperationRunQuery") => json!({ "bulkOperationRunQuery": { + "bulkOperation": operation("QUERY", "CREATED", None), "userErrors": [], + } }), + Some("BulkOperationRunMutation") => json!({ "bulkOperationRunMutation": { + "bulkOperation": operation("MUTATION", "CREATED", None), "userErrors": [], + } }), + Some("StagedUploadsCreate") => json!({ "stagedUploadsCreate": { + "stagedTargets": [{ + "url": UPLOAD_URL, + "resourceUrl": null, + "parameters": [{ "name": "key", "value": "tmp/1/bulk/vars.jsonl" }], + }], + "userErrors": [], + } }), + Some("BulkOperation") => { + json!({ "bulkOperation": operation("QUERY", "COMPLETED", Some(RESULTS_URL)) }) + } + other => panic!("unexpected operation {other:?}"), + }; + Ok(HttpResponse::json(200, &json!({ "data": data }))) + }); + (mock, uploads) +} + +const CATALOG: &str = r#"{"id":"gid://shopify/Product/1","title":"Shirt"} +{"_shopifyApiTypename":"ProductVariant","id":"gid://shopify/ProductVariant/1","sku":"S-1","__parentId":"gid://shopify/Product/1"} +{"key":"color","value":"red","__parentId":"gid://shopify/ProductVariant/1"} +{"_shopifyApiTypename":"MediaImage","id":"gid://shopify/MediaImage/1","alt":"Front","__parentId":"gid://shopify/Product/1"} +{"key":"size","value":"M","__parentId":"gid://shopify/ProductVariant/1"} +{"_shopifyApiTypename":"ProductVariant","id":"gid://shopify/ProductVariant/2","sku":null,"__parentId":"gid://shopify/Product/1"} +{"_shopifyApiTypename":"Video","__parentId":"gid://shopify/Product/1"} +{"id":"gid://shopify/Product/2","title":"Hat"} +"#; + +#[tokio::test] +async fn a_bulk_query_sends_its_text_with_group_objects_and_reads_its_items() { + let (mock, _) = shopify_with(CATALOG); + let shopify = client(&mock); + + let products: Vec = shopify + .bulk_query(catalog::operation(), fast()) + .await + .unwrap() + .collect() + .await + .unwrap(); + + let start = &mock.graphql_requests()[0]; + // `__typename`, aliased, on the nodes of the two connections of a product, which + // tells their lines apart; not on those of `metafields`, alone under + // its variant. + assert_eq!( + start.variables, + json!({ + "query": "{ products(query: \"status:active\") { edges { node { id title \ + variants { edges { node { _shopifyApiTypename: __typename id sku metafields { edges { node { key value } } } } } } \ + media { edges { node { _shopifyApiTypename: __typename ... on MediaImage { id alt } } } } } } } }", + "groupObjects": true, + }) + ); + // The version the query was checked against. + assert!(mock.requests()[0].url.contains("/admin/api/2026-10/")); + + assert_eq!(products.len(), 2); + let shirt = &products[0]; + assert_eq!(shirt.title, "Shirt"); + let skus: Vec> = shirt + .variants + .iter() + .map(|variant| variant.sku.as_deref()) + .collect(); + assert_eq!(skus, [Some("S-1"), None]); + // Two levels deep: under the variant they belong to. + let keys: Vec<&str> = shirt.variants[0] + .metafields + .iter() + .map(|field| field.key.as_str()) + .collect(); + assert_eq!(keys, ["color", "size"]); + assert!(shirt.variants[1].metafields.is_empty()); + // An interface: the fields of a fragment are there when it applies. + assert_eq!(shirt.media.len(), 2); + assert_eq!(shirt.media[0].alt.as_deref(), Some("Front")); + assert_eq!(shirt.media[1].id, None); + let hat = &products[1]; + assert_eq!(hat.title, "Hat"); + assert!(hat.variants.is_empty() && hat.media.is_empty()); +} + +#[tokio::test] +async fn the_variables_of_a_bulk_query_are_written_into_its_text() { + let (mock, _) = shopify_with(""); + let shopify = client(&mock); + + // A string with quotes, a backslash, a newline and a `$`; the default + // of `$sort`. + let filter = "title:\"Café \\ $filter\"\nvendor:x"; + let items = shopify + .bulk_query( + by_title::Variables { + filter: Some(filter.to_string()), + sort: None, + }, + fast(), + ) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert!(items.is_empty()); + let text = mock.graphql_requests()[0].variables["query"] + .as_str() + .unwrap() + .to_string(); + assert_eq!( + text, + r#"{ products(query: "title:\"Café \\ $filter\"\nvendor:x", sortKey: TITLE, reverse: true) { edges { node { id } } } }"# + ); + // No nested connection: no `groupObjects`, which slows Shopify down. + assert_eq!(mock.graphql_requests()[0].variables["groupObjects"], false); + + // An enum value bare; a variable without a value or a default left out. + let query = by_title::operation(by_title::Variables { + filter: None, + sort: Some("CREATED_AT".into()), + }); + assert_eq!( + query.text().unwrap(), + "{ products(sortKey: CREATED_AT, reverse: true) { edges { node { id } } } }" + ); + assert_eq!(query.query(), by_title::QUERY); +} + +#[tokio::test] +async fn an_inline_bulk_query_writes_lists_of_enum_values_bare() { + let (mock, _) = shopify_with( + "{\"id\":\"gid://shopify/WebhookSubscription/1\",\"topic\":\"ORDERS_CREATE\"}\n", + ); + let shopify = client(&mock); + + let hooks = shopify + .bulk_query( + graphql!( + bulk("query Hooks($topics: [WebhookSubscriptionTopic!], $format: WebhookSubscriptionFormat, $uri: String) { + webhookSubscriptions(topics: $topics, format: $format, uri: $uri, query: \"a $b\") { edges { node { id topic } } } + }"), + topics = [ORDERS_CREATE, raw("PRODUCTS_UPDATE")], + format = JSON, + ), + fast(), + ) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(hooks[0].topic, "ORDERS_CREATE"); + assert_eq!( + mock.graphql_requests()[0].variables["query"], + "query Hooks { webhookSubscriptions(topics: [ORDERS_CREATE, PRODUCTS_UPDATE], format: JSON, query: \"a $b\") { edges { node { id topic } } } }" + ); +} + +#[tokio::test] +async fn an_enum_value_that_is_not_a_name_fails_before_anything_is_sent() { + let (mock, _) = shopify_with(""); + let shopify = client(&mock); + + let error = shopify + .bulk_query( + graphql!( + bulk( + "query($topics: [WebhookSubscriptionTopic!]) { + webhookSubscriptions(topics: $topics) { edges { node { id } } } + }" + ), + topics = [ORDERS_CREATE, raw("X) { shop { name } } #")], + ), + fast(), + ) + .await + .unwrap_err(); + let Error::InvalidValue { path, reason, .. } = &error else { + panic!("{error:?}"); + }; + assert_eq!(path, "$topics[1]"); + assert_eq!(*reason, InvalidValueReason::NotAGraphqlName); + assert!(mock.requests().is_empty()); +} + +#[tokio::test] +async fn a_child_out_of_place_ends_the_stream() { + let (mock, _) = shopify_with( + r#"{"id":"gid://shopify/Product/1","title":"Shirt"} +{"_shopifyApiTypename":"ProductVariant","id":"gid://shopify/ProductVariant/1","sku":"S-1","__parentId":"gid://shopify/Product/9"} +{"id":"gid://shopify/Product/2","title":"Hat"} +"#, + ); + let shopify = client(&mock); + let mut items = shopify + .bulk_query(catalog::operation(), fast()) + .await + .unwrap(); + let error = items.next_item().await.unwrap().unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: line 2 of the results is a child of neither the top-level object before it nor one of its children, though the query ran with `groupObjects`" + ); + assert!(items.next_item().await.is_none()); +} + +#[tokio::test] +async fn a_child_no_connection_returns_ends_the_stream() { + for (line, message) in [ + ( + r#"{"_shopifyApiTypename":"Collection","id":"gid://shopify/Collection/1","__parentId":"gid://shopify/Product/1"}"#, + "line 2 of the results has a `_shopifyApiTypename`, its `__typename`, that no connection of its parent returns", + ), + ( + r#"{"id":"gid://shopify/ProductVariant/1","__parentId":"gid://shopify/Product/1"}"#, + "line 2 of the results has no `_shopifyApiTypename`, the `__typename` that tells which connection of its parent it belongs to", + ), + ] { + let jsonl: &'static str = Box::leak( + format!("{{\"id\":\"gid://shopify/Product/1\",\"title\":\"Shirt\"}}\n{line}\n") + .into_boxed_str(), + ); + let (mock, _) = shopify_with(jsonl); + let shopify = client(&mock); + let mut items = shopify + .bulk_query(catalog::operation(), fast()) + .await + .unwrap(); + let error = items.next_item().await.unwrap().unwrap_err(); + assert_eq!(error.to_string(), format!("bulk operation: {message}")); + assert!(items.next_item().await.is_none()); + } +} + +#[tokio::test] +async fn a_line_that_does_not_read_as_its_type_ends_the_stream() { + let (mock, _) = shopify_with( + r#"{"id":"gid://shopify/Product/1","title":"Shirt"} +{"_shopifyApiTypename":"ProductVariant","id":"gid://shopify/ProductVariant/1","sku":12,"__parentId":"gid://shopify/Product/1"} +{"id":"gid://shopify/Product/2","title":"Hat"} +"#, + ); + let shopify = client(&mock); + let mut items = shopify + .bulk_query(catalog::operation(), fast()) + .await + .unwrap(); + let error = items.next_item().await.unwrap().unwrap_err(); + assert!(matches!(error, Error::Decode { .. }), "{error:?}"); + assert!(error.to_string().contains("at line 2"), "{error}"); + assert!(items.next_item().await.is_none()); +} + +#[tokio::test] +async fn the_items_of_an_operation_started_by_hand_are_read_from_its_url() { + let (mock, _) = shopify_with(CATALOG); + let shopify = client(&mock); + + let started = shopify + .start_bulk_query(catalog::operation()) + .await + .unwrap(); + let operation = shopify + .wait_for_bulk_operation(&started.id, fast()) + .await + .unwrap(); + let products: Vec = shopify + .download_bulk_items(operation.url.as_deref().unwrap()) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(products[0].variants[0].metafields.len(), 2); + assert_eq!(mock.graphql_requests()[0].variables["groupObjects"], true); +} + +#[tokio::test] +async fn a_typed_bulk_query_groups_objects_only_with_nested_connections() { + let mock = MockTransport::new(); + for _ in 0..3 { + mock.push_data(json!({ "bulkOperationRunQuery": { + "bulkOperation": operation("QUERY", "CREATED", None), + "userErrors": [], + } })); + } + let shopify = client(&mock); + + // Flat, given as the `Variables` of its module, or as its operation. + shopify + .start_bulk_query(by_title::Variables { + filter: None, + sort: None, + }) + .await + .unwrap(); + shopify + .start_bulk_query(by_title::operation(by_title::Variables { + filter: None, + sort: None, + })) + .await + .unwrap(); + // Nested connections, two levels deep. + shopify + .start_bulk_query(catalog::operation()) + .await + .unwrap(); + + let grouped: Vec = mock + .graphql_requests() + .iter() + .map(|request| request.variables["groupObjects"].clone()) + .collect(); + assert_eq!(grouped, [json!(false), json!(false), json!(true)]); +} + +#[tokio::test] +async fn a_bulk_mutation_stages_its_lines_and_reads_typed_results() { + let (mock, uploads) = shopify_with( + r#"{"data":{"tagsAdd":{"userErrors":[]}},"__lineNumber":1} +{"data":{"tagsAdd":{"userErrors":[{"field":["id"],"message":"Product does not exist"}]}},"__lineNumber":0} +{"errors":[{"message":"Variable $id of type ID! was provided invalid value","locations":[{"line":1,"column":10}]}]} +"#, + ); + let shopify = client(&mock); + + let lines = + ["gid://shopify/Product/1", "gid://shopify/Product/2"].map(|id| add_tags::Variables { + id: id.to_string(), + tags: vec!["sale".to_string(), "a \"b\"".to_string()], + }); + let mut rows = shopify.bulk_mutation(lines, fast()).await.unwrap(); + let mut results: Vec> = Vec::new(); + while let Some(row) = rows.next_row().await { + results.push(row.unwrap()); + } + + let sent = mock.graphql_requests(); + assert_eq!(sent[1].variables["mutation"], add_tags::QUERY); + assert_eq!( + sent[1].variables["stagedUploadPath"], + "tmp/1/bulk/vars.jsonl" + ); + let body = String::from_utf8(uploads.lock().unwrap()[0].body.clone()).unwrap(); + assert!( + body.contains( + "{\"id\":\"gid://shopify/Product/1\",\"tags\":[\"sale\",\"a \\\"b\\\"\"]}\n\ + {\"id\":\"gid://shopify/Product/2\",\"tags\":[\"sale\",\"a \\\"b\\\"\"]}\n" + ), + "{body}" + ); + + assert_eq!(results.len(), 3); + assert_eq!(results[0].index, Some(1)); + assert!(results[0].errors.is_empty()); + let refused = results[1].data.as_ref().unwrap().tags_add.as_ref().unwrap(); + assert_eq!(refused.user_errors[0].message, "Product does not exist"); + assert_eq!(results[1].index, Some(0)); + assert!(results[2].data.is_none()); + assert_eq!(results[2].index, None); + assert_eq!( + results[2].errors[0].message, + "Variable $id of type ID! was provided invalid value" + ); +} + +#[tokio::test] +async fn the_lines_of_an_inline_bulk_mutation_are_checked_before_anything_is_sent() { + let (mock, _) = shopify_with(""); + let shopify = client(&mock); + let deltas: [i64; 2] = [1, 1 << 40]; + let lines = deltas.map(|delta| { + graphql!( + bulk("mutation($input: InventoryAdjustQuantitiesInput!) { + inventoryAdjustQuantities(input: $input) { userErrors { message } } + }"), + input = { + name: "available", + reason: "correction", + changes: [{ delta: delta, inventoryItemId: "gid://shopify/InventoryItem/1", locationId: "gid://shopify/Location/1" }], + }, + ) + }); + let error = shopify.bulk_mutation(lines, fast()).await.unwrap_err(); + let Error::InvalidValue { path, reason, .. } = &error else { + panic!("{error:?}"); + }; + assert_eq!(path, "$input.changes[0].delta"); + assert_eq!(*reason, InvalidValueReason::IntOutOfRange); + assert!(mock.requests().is_empty()); + + // No line: nothing runs. + let none: Vec = Vec::new(); + let mut results = shopify.bulk_mutation(none, fast()).await.unwrap(); + assert!(results.next_row().await.is_none()); + assert!(mock.requests().is_empty()); + let none: Vec = Vec::new(); + let error = shopify.start_bulk_mutation(none).await.unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: a bulk mutation needs one line of variables at least" + ); +} + +#[tokio::test] +async fn the_lines_of_a_bulk_mutation_run_one_mutation() { + let (mock, _) = shopify_with(""); + let shopify = client(&mock); + let line = graphql!( + bulk("mutation($id: ID!) { tagsAdd(id: $id, tags: [\"a\"]) { userErrors { message } } }"), + id = "gid://shopify/Product/1", + ); + assert_eq!(line.line().unwrap(), r#"{"id":"gid://shopify/Product/1"}"#); + + // Each `graphql!` has its own types: only lines built by hand can mix + // mutations. + let lines = [ + BulkMutation::::__checked("mutation { a }", None, "2026-10"), + BulkMutation::::__checked("mutation { b }", None, "2026-10"), + ]; + let error = shopify.start_bulk_mutation(lines).await.unwrap_err(); + assert_eq!( + error.to_string(), + "bulk operation: line 2 of the bulk mutation was built from another mutation than line 1: a bulk operation runs one mutation" + ); + assert!(mock.requests().is_empty()); +} diff --git a/crates/shopify_api/tests/compile_fail.rs b/crates/shopify_api/tests/compile_fail.rs new file mode 100644 index 0000000..d3e8ea8 --- /dev/null +++ b/crates/shopify_api/tests/compile_fail.rs @@ -0,0 +1,8 @@ +//! What `graphql!` refuses at compile time, and how it says so. The expected +//! errors are in `tests/ui/*.stderr`; `mise run ui:bless` rewrites them. + +#[test] +fn graphql_refusals() { + let cases = trybuild::TestCases::new(); + cases.compile_fail("tests/ui/*.rs"); +} diff --git a/crates/shopify_api/tests/facade.rs b/crates/shopify_api/tests/facade.rs new file mode 100644 index 0000000..7ca165c --- /dev/null +++ b/crates/shopify_api/tests/facade.rs @@ -0,0 +1,184 @@ +//! The code `graphql!` and `input!` generate reaches `shopify_api` through +//! `::shopify_api::__private` only, or `crate = path`: an app that depends +//! on a crate re-exporting it, and not on `shopify_api`, compiles, even when +//! that crate has a `Result`, an `Operation` or a `bulk` of its own. +//! +//! Builds a small workspace with cargo, offline, in `CARGO_TARGET_TMPDIR`. + +use std::path::Path; +use std::process::Command; + +/// Builds and runs `app`, which depends on `probe_facade` only, whose +/// `lib.rs` is `facade`: what the app printed. +fn run_app(name: &str, facade: &str, app: &str) -> String { + let tmp = Path::new(env!("CARGO_TARGET_TMPDIR")); + let root = tmp.join(name); + let _ = std::fs::remove_dir_all(&root); + let shopify_api = Path::new(env!("CARGO_MANIFEST_DIR")); + let write = |path: &str, contents: &str| { + let path = root.join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, contents).unwrap(); + }; + write( + "Cargo.toml", + "[workspace]\nresolver = \"3\"\nmembers = [\"facade\", \"app\"]\n", + ); + let lock = shopify_api.join("../../Cargo.lock"); + write("Cargo.lock", &std::fs::read_to_string(lock).unwrap()); + write( + "facade/Cargo.toml", + &format!( + "[package]\nname = \"probe_facade\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\ + [dependencies]\nshopify_api = {{ path = '{}', default-features = false }}\n", + shopify_api.display() + ), + ); + write("facade/src/lib.rs", facade); + // No `shopify_api` here: the app reaches it through the facade only. + write( + "app/Cargo.toml", + "[package]\nname = \"probe_facade_app\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\ + [dependencies]\nprobe_facade = { path = \"../facade\" }\n\ + [package.metadata.shopify_api]\napi-version = \"2026-10\"\n", + ); + write( + "app/graphql/admin.schema.json", + &std::fs::read_to_string(shopify_api.join("graphql/admin.schema.json")).unwrap(), + ); + write("app/src/main.rs", app); + + let output = Command::new(std::env::var_os("CARGO").unwrap_or("cargo".into())) + .args(["run", "--offline", "--quiet", "-p", "probe_facade_app"]) + .arg("--manifest-path") + .arg(root.join("Cargo.toml")) + .env("CARGO_TARGET_DIR", tmp.join(format!("{name}_target"))) + .env_remove("CARGO_PRIMARY_PACKAGE") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8_lossy(&output.stdout).into_owned() +} + +#[test] +fn the_generated_code_compiles_through_a_facade_with_names_of_its_own() { + let printed = run_app( + "facade", + "pub use shopify_api::*;\n\ + // Names of its own, which shadow those of the glob.\n\ + pub type Result = std::result::Result;\n\ + pub struct Operation;\n\ + pub struct OperationKind;\n\ + pub struct InputObject;\n\ + pub struct Maybe;\n\ + pub mod bulk {}\n", + r#"extern crate probe_facade as shopify_api; + +shopify_api::graphql! { + mod products = "query($first: Int!) { products(first: $first) { nodes { id title } } }"; + mod set = "mutation($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { userErrors { message } } + }"; + mod catalog = bulk("{ products { edges { node { + id + variants { edges { node { id } } } + media { edges { node { id } } } + } } } }"); + mod tags = bulk("mutation($id: ID!, $tags: [String!]!) { + tagsAdd(id: $id, tags: $tags) { userErrors { message } } + }"); +} + +fn main() { + let note: Option = None; + let metafield = shopify_api::input!(MetafieldsSetInput { + ownerId: "gid://shopify/Product/1", + namespace: "a", + key: "b", + type: "single_line_text_field", + value: "c", + }); + let _ = set::Variables { metafields: vec![metafield] }; + let _ = shopify_api::graphql!( + "mutation($p: ProductUpdateInput!) { productUpdate(product: $p) { userErrors { message } } }", + p = { id: "gid://shopify/Product/1", descriptionHtml?: note, status: ACTIVE }, + ); + let _ = products::operation(products::Variables { first: 1 }); + let _ = catalog::operation(); + let _ = shopify_api::graphql!(bulk("{ orders { edges { node { id } } } }")); + let _ = tags::Variables { id: String::new(), tags: Vec::new() }; + print!("ok"); +} +"#, + ); + assert_eq!(printed, "ok"); +} + +#[test] +fn crate_names_the_path_of_shopify_api_in_a_crate_that_does_not_depend_on_it() { + // A framework that re-exports the crate and its macros, with names of + // its own at its root that the generated code must not take. + let printed = run_app( + "facade_crate_path", + "pub use shopify_api;\n\ + pub use shopify_api::{graphql, input};\n\ + pub type Result = std::result::Result;\n\ + pub struct Operation;\n\ + pub mod __private {}\n", + r#"use probe_facade::{graphql, input}; + +graphql! { + crate = ::probe_facade::shopify_api; + mod products = "query($first: Int!) { products(first: $first) { nodes { id title } } }"; + pub(crate) mod set = "mutation($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { userErrors { message } } + }"; + mod catalog = bulk("{ products { edges { node { + id + variants { edges { node { id } } } + } } } }"); + mod tags = bulk("mutation($id: ID!, $tags: [String!]!) { + tagsAdd(id: $id, tags: $tags) { userErrors { message } } + }"); +} + +mod nested { + // A path from the root of the crate works too, from any module. + pub use probe_facade::shopify_api as sa; + probe_facade::graphql! { crate = crate::nested::sa; pub mod shop = "{ shop { name } }"; } +} + +fn main() { + let note: Option = None; + let metafield = input!(crate = ::probe_facade::shopify_api, MetafieldsSetInput { + ownerId: "gid://shopify/Product/1", + namespace: "a", + key: "b", + type: "single_line_text_field", + value: "c", + }); + let set = probe_facade::shopify_api::Operation::from(set::Variables { metafields: vec![metafield] }); + let update = graphql!( + crate = ::probe_facade::shopify_api, + "mutation($p: ProductUpdateInput!) { productUpdate(product: $p) { userErrors { message } } }", + p = { id: "gid://shopify/Product/1", descriptionHtml?: note, status: ACTIVE }, + ); + let _ = products::operation(products::Variables { first: 1 }); + let _ = catalog::operation(); + let _ = graphql!(crate = ::probe_facade::shopify_api, bulk("{ orders { edges { node { id } } } }")); + let _ = tags::Variables { id: String::new(), tags: Vec::new() }; + let _ = nested::shop::operation(); + print!("{}\n{}", set.variable_json("metafields").unwrap().unwrap(), update.variable_json("p").unwrap().unwrap()); +} +"#, + ); + assert_eq!( + printed, + "[{\"ownerId\":\"gid://shopify/Product/1\",\"namespace\":\"a\",\"key\":\"b\",\"type\":\"single_line_text_field\",\"value\":\"c\"}]\n\ + {\"id\":\"gid://shopify/Product/1\",\"status\":\"ACTIVE\"}" + ); +} diff --git a/crates/shopify_api/tests/graphql.rs b/crates/shopify_api/tests/graphql.rs new file mode 100644 index 0000000..6b5552d --- /dev/null +++ b/crates/shopify_api/tests/graphql.rs @@ -0,0 +1,471 @@ +//! `graphql!` operations end to end: what is sent, and how the answer is typed. +#![cfg(feature = "testing")] + +use serde_json::{Value, json}; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::{ApiVersion, Error, OperationKind, graphql, input}; + +graphql! { + /// Writes metafields and reports what Shopify refused. + pub mod metafields_set = "#graphql + mutation MetafieldsSet($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { + metafields { id key namespace } + userErrors { field message code } + } + }"; +} + +graphql! { + mod shop_name = "query ShopName { shop { name } }"; +} + +graphql! { + mod from_file = file("tests/graphql/order.graphql"); +} + +#[tokio::test] +async fn an_inline_query_sends_its_variables_and_returns_typed_data() { + let mock = MockTransport::new(); + mock.push_data(json!({ "orders": { "nodes": [ + { "id": "gid://shopify/Order/1", "name": "#1001" }, + { "id": "gid://shopify/Order/2", "name": "#1002" }, + ] } })); + let shopify = client(&mock); + let limit: u32 = 2; + + let data = shopify + .execute(graphql!( + "query Recent($first: Int!, $query: String) { orders(first: $first, query: $query) { nodes { id name } } }", + first = limit, + query = "status:open", + )) + .await + .unwrap(); + + let names: Vec<&str> = data + .orders + .nodes + .iter() + .map(|order| order.name.as_str()) + .collect(); + assert_eq!(names, ["#1001", "#1002"]); + + let sent = &mock.graphql_requests()[0]; + assert_eq!( + sent.url, + "https://test-shop.myshopify.com/admin/api/2026-10/graphql.json" + ); + assert_eq!(sent.api_version, "2026-10"); + assert_eq!( + sent.variables, + json!({ "first": 2, "query": "status:open" }) + ); + assert_eq!(sent.operation_name.as_deref(), Some("Recent")); + assert_eq!(sent.access_token.as_deref(), Some("test-token")); + let request = mock.last_request().unwrap(); + assert_eq!(request.header("content-type"), Some("application/json")); + assert!( + request + .header("user-agent") + .unwrap() + .starts_with("shopify_api/") + ); +} + +#[tokio::test] +async fn nullability_lists_aliases_fragments_and_scalars_follow_the_schema() { + let mock = MockTransport::new(); + mock.push_data(json!({ + "order": { + "id": "gid://shopify/Order/1", + "note": null, + "createdAt": "2026-10-01T00:00:00Z", + "tags": ["vip", "b2b"], + "displayFinancialStatus": "PAID", + "total": { "shopMoney": { "amount": "42.50", "currencyCode": "EUR" } }, + "customer": null, + "metafield": { "jsonValue": { "gift": true }, "type": "json" }, + "lineItems": { "nodes": [{ "title": "Shirt", "quantity": 2 }] }, + }, + "nodes": [ + { "__typename": "Product", "id": "gid://shopify/Product/1", "title": "Shirt" }, + null, + { "__typename": "Collection", "id": "gid://shopify/Collection/1" }, + ], + })); + let shopify = client(&mock); + + let data = shopify + .execute(graphql!( + r#"#graphql + query Order($id: ID!, $ids: [ID!]!, $namespace: String) { + order(id: $id) { + id + note + createdAt + tags + displayFinancialStatus + total: totalPriceSet { shopMoney { amount currencyCode } } + customer { displayName } + metafield(namespace: $namespace, key: "settings") { jsonValue type } + lineItems(first: 5) { nodes { title quantity } } + } + nodes(ids: $ids) { + __typename + id + ... on Product { title } + } + }"#, + id = "gid://shopify/Order/1", + ids = ["gid://shopify/Product/1", "gid://shopify/Collection/1"], + namespace = "custom", + )) + .await + .unwrap(); + + // `order` is nullable in the schema. + let order = data.order.expect("an order"); + let note: Option = order.note; + assert_eq!(note, None); + let created_at: String = order.created_at; + assert_eq!(created_at, "2026-10-01T00:00:00Z"); + assert_eq!(order.tags, ["vip", "b2b"]); + // Enum values are strings. + assert_eq!(order.display_financial_status.as_deref(), Some("PAID")); + // An alias names its field. + assert_eq!(order.total.shop_money.amount, "42.50"); + assert_eq!(order.customer, None); + // `JSON` is any value. + let metafield = order.metafield.unwrap(); + assert_eq!(metafield.json_value, json!({ "gift": true })); + // `Int` is `i64`. + let quantity: i64 = order.line_items.nodes[0].quantity; + assert_eq!(quantity, 2); + + // A field under a fragment on another type is an `Option`. + let nodes = data.nodes; + assert_eq!(nodes.len(), 3); + let product = nodes[0].as_ref().unwrap(); + assert_eq!( + (product.typename.as_str(), product.title.as_deref()), + ("Product", Some("Shirt")) + ); + assert!(nodes[1].is_none()); + assert_eq!(nodes[2].as_ref().unwrap().title, None); +} + +#[tokio::test] +async fn a_module_names_its_types_and_builds_input_objects() { + let mock = MockTransport::new(); + mock.push_data(json!({ "metafieldsSet": { + "metafields": [{ "id": "gid://shopify/Metafield/1", "key": "color", "namespace": "custom" }], + "userErrors": [], + } })); + let shopify = client(&mock); + + let variables = metafields_set::Variables { + metafields: vec![input!(MetafieldsSetInput { + ownerId: "gid://shopify/Product/1", + namespace: "custom", + key: "color", + value: "blue", + })], + }; + let data: metafields_set::Data = shopify + .execute(metafields_set::operation(variables)) + .await + .unwrap(); + let payload: metafields_set::DataMetafieldsSet = data.metafields_set.unwrap(); + assert!(payload.user_errors.is_empty()); + assert_eq!(payload.metafields.unwrap()[0].key, "color"); + + assert_eq!(metafields_set::NAME, Some("MetafieldsSet")); + assert_eq!(metafields_set::KIND, OperationKind::Mutation); + assert_eq!(metafields_set::API_VERSION, ApiVersion::DEFAULT.to_string()); + assert_eq!( + mock.graphql_requests()[0].variables, + json!({ "metafields": [{ "ownerId": "gid://shopify/Product/1", "namespace": "custom", "key": "color", "value": "blue" }] }) + ); +} + +#[tokio::test] +async fn an_operation_can_come_from_a_file() { + let mock = MockTransport::new(); + mock.push_data(json!({ "order": { "name": "#1001", "email": null } })); + let shopify = client(&mock); + + let data = shopify + .execute(from_file::operation(from_file::Variables { + id: "gid://shopify/Order/1".to_string(), + })) + .await + .unwrap(); + assert_eq!(data.order.unwrap().name, "#1001"); + assert_eq!(from_file::QUERY, include_str!("graphql/order.graphql")); + assert_eq!( + mock.graphql_requests()[0].operation_name.as_deref(), + Some("OrderFromFile") + ); +} + +#[tokio::test] +async fn graphql_errors_fail_the_operation_and_keep_partial_data() { + let mock = MockTransport::new(); + mock.push_json(json!({ + "data": { "shop": null }, + "errors": [{ "message": "Access denied for shop field.", "extensions": { "code": "ACCESS_DENIED" }, "path": ["shop"] }], + })); + let shopify = client(&mock); + + let error = shopify.execute(shop_name::operation()).await.unwrap_err(); + assert_eq!( + error.to_string(), + "GraphQL errors: Access denied for shop field. (ACCESS_DENIED)" + ); + let Error::Graphql(errors) = &error else { + panic!("GraphQL errors: {error:?}"); + }; + assert_eq!(errors.data, Some(json!({ "shop": null }))); + assert_eq!(error.graphql_errors()[0].code(), Some("ACCESS_DENIED")); + + // The raw answer holds both. + mock.push_json(json!({ "data": { "shop": null }, "errors": [{ "message": "Denied" }] })); + let raw = shopify.graphql_raw("{ shop { name } }", ()).await.unwrap(); + assert_eq!(raw.errors[0].message, "Denied"); + assert_eq!(raw.data, Some(json!({ "shop": null }))); +} + +graphql! { + /// One key, `price`, on fields of two types below exclusive object types. + mod prices = "query Prices($ids: [ID!]!) { + nodes(ids: $ids) { + ... on Product { price: priceRangeV2 { value: minVariantPrice { amount currencyCode } } } + ... on Order { price: totalPriceSet { value: shopMoney { amount currencyCode } } } + } + }"; +} + +#[tokio::test] +async fn one_key_on_fields_of_different_types_reads_both() { + let mock = MockTransport::new(); + let money = json!({ "value": { "amount": "10.0", "currencyCode": "EUR" } }); + mock.push_data(json!({ "nodes": [ + { "price": money }, + { "price": { "value": { "amount": "25.5", "currencyCode": "USD" } } }, + {}, + null, + ] })); + let shopify = client(&mock); + + let data = shopify + .execute(prices::operation(prices::Variables { + ids: vec![ + "gid://shopify/Product/1".into(), + "gid://shopify/Order/2".into(), + ], + })) + .await + .unwrap(); + let price = |index: usize| { + let node: &Option = &data.nodes[index]; + node.as_ref() + .and_then(|node| node.price.as_ref()) + .map(|price| { + let prices::DataNodesPrice { + value: + prices::DataNodesPriceValue { + amount, + currency_code, + }, + } = price; + (amount.as_str(), currency_code.as_str()) + }) + }; + assert_eq!(price(0), Some(("10.0", "EUR"))); + assert_eq!(price(1), Some(("25.5", "USD"))); + assert_eq!(price(2), None); + assert!(data.nodes[3].is_none()); +} + +#[tokio::test] +async fn an_error_shows_no_value_shopify_echoes_in_its_extensions() { + // What GraphQL Ruby answers to a variable that does not validate: the + // whole value, a signed address included, under `extensions.value`. + let mock = MockTransport::new(); + mock.push_json(json!({ "errors": [{ + "message": "Variable $media of type [CreateMediaInput!] was provided invalid value for 0.mediaContentType (Expected \"INVALID\" to be one of: IMAGE, VIDEO)", + "locations": [{ "line": 1, "column": 10 }], + "extensions": { + "value": [{ + "originalSource": "https://storage.test/image.jpg?X-Goog-Signature=SIGNED_SECRET", + "mediaContentType": "INVALID", + }], + "problems": [{ "path": [0, "mediaContentType"], "explanation": "Expected \"INVALID\" to be one of: IMAGE, VIDEO" }], + "code": "INVALID_VARIABLE", + }, + }] })); + let shopify = client(&mock); + + let error = shopify + .graphql( + "mutation($media: [CreateMediaInput!]) { productCreate(media: $media) { product { id } } }", + json!({ "media": [{ + "originalSource": "https://storage.test/image.jpg?X-Goog-Signature=SIGNED_SECRET", + "mediaContentType": "INVALID", + }] }), + ) + .await + .unwrap_err(); + for shown in [ + format!("{error}"), + format!("{error:?}"), + format!("{error:#?}"), + format!("{:?}", error.graphql_errors()), + ] { + assert!(!shown.contains("SIGNED_SECRET"), "{shown}"); + assert!(!shown.contains("storage.test"), "{shown}"); + } + let debug = format!("{error:?}"); + assert!( + debug.contains(r#"Extensions { code: "INVALID_VARIABLE", others: 2 entries }"#), + "{debug}" + ); + assert!(debug.contains("Variable $media"), "{debug}"); + // The values stay available to the caller. + let extensions = error.graphql_errors()[0].extensions.as_ref().unwrap(); + assert!(extensions["value"][0]["originalSource"].is_string()); +} + +#[tokio::test] +async fn an_answer_that_does_not_fit_names_the_path() { + let mock = MockTransport::new(); + mock.push_data(json!({ "shop": {} })); + let shopify = client(&mock); + + let error = shopify.execute(shop_name::operation()).await.unwrap_err(); + assert_eq!( + error.to_string(), + "Shopify's answer does not match the operation at `shop`: missing field `name`" + ); +} + +#[tokio::test] +async fn http_errors_say_how_shopify_answered_and_keep_the_body_apart() { + let mock = MockTransport::new(); + mock.push(shopify_api::transport::HttpResponse::new( + 403, + "[API] This action requires merchant approval for write_orders scope.", + )); + let shopify = client(&mock); + + let error = shopify.execute(shop_name::operation()).await.unwrap_err(); + assert_eq!(error.status(), Some(403)); + assert_eq!( + error.to_string(), + "Shopify answered 403 to https://test-shop.myshopify.com/admin/api/2026-10/graphql.json (no content type, 68 bytes)" + ); + assert_eq!( + error.raw_http_body(), + Some(&b"[API] This action requires merchant approval for write_orders scope."[..]) + ); +} + +#[tokio::test] +async fn untyped_calls_take_any_serializable_variables() { + let mock = MockTransport::new(); + mock.push_data(json!({ "product": { "title": "Shirt" } })); + mock.push_data(json!({ "product": { "title": "Shirt" } })); + let shopify = client(&mock); + + let data: Value = shopify + .graphql( + "query($id: ID!) { product(id: $id) { title } }", + json!({ "id": "gid://shopify/Product/1" }), + ) + .await + .unwrap(); + assert_eq!(data.pointer("/product/title"), Some(&json!("Shirt"))); + + #[derive(serde::Deserialize)] + struct Data { + product: Option, + } + #[derive(serde::Deserialize)] + struct Product { + title: String, + } + #[derive(serde::Serialize)] + struct Variables<'a> { + id: &'a str, + } + let data: Data = shopify + .graphql_as( + "query($id: ID!) { product(id: $id) { title } }", + Variables { + id: "gid://shopify/Product/1", + }, + ) + .await + .unwrap(); + assert_eq!(data.product.unwrap().title, "Shirt"); + + let error = shopify + .graphql("{ shop { name } }", [1, 2]) + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + "invalid variables: the variables must serialize to an object" + ); + // Nothing was sent for it. + assert_eq!(mock.requests().len(), 2); +} + +#[tokio::test] +async fn operations_go_to_the_version_of_their_schema_unless_one_is_pinned() { + let mock = MockTransport::new(); + mock.respond_with(|_| { + Ok(shopify_api::transport::HttpResponse::json( + 200, + &json!({ "data": { "shop": { "name": "x" } } }), + )) + }); + let shopify = client(&mock); + + shopify.execute(shop_name::operation()).await.unwrap(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + let pinned = shopify.with_api_version(ApiVersion::V2026_07); + pinned.execute(shop_name::operation()).await.unwrap(); + pinned.graphql("{ shop { name } }", ()).await.unwrap(); + + let versions: Vec = mock + .graphql_requests() + .into_iter() + .map(|request| request.api_version) + .collect(); + assert_eq!(versions, ["2026-10", "2026-10", "2026-07", "2026-07"]); +} + +#[tokio::test] +async fn the_response_carries_the_cost() { + let mock = MockTransport::new(); + mock.push_json(json!({ + "data": { "shop": { "name": "x" } }, + "extensions": { "cost": { + "requestedQueryCost": 1, + "actualQueryCost": 1, + "throttleStatus": { "maximumAvailable": 2000.0, "currentlyAvailable": 1999, "restoreRate": 100.0 }, + } }, + })); + let shopify = client(&mock); + + let response = shopify + .execute_response(shop_name::operation()) + .await + .unwrap(); + assert_eq!(response.data.shop.name, "x"); + let cost = response.cost().unwrap(); + assert_eq!(cost.actual_query_cost, Some(1.0)); + assert_eq!(cost.throttle_status.currently_available, 1999.0); +} diff --git a/crates/shopify_api/tests/graphql/order.graphql b/crates/shopify_api/tests/graphql/order.graphql new file mode 100644 index 0000000..e26fb29 --- /dev/null +++ b/crates/shopify_api/tests/graphql/order.graphql @@ -0,0 +1,7 @@ +# An operation kept in a file: `graphql! { mod from_file = file("tests/graphql/order.graphql"); }`. +query OrderFromFile($id: ID!) { + order(id: $id) { + name + email + } +} diff --git a/crates/shopify_api/tests/literals.rs b/crates/shopify_api/tests/literals.rs new file mode 100644 index 0000000..6f2058b --- /dev/null +++ b/crates/shopify_api/tests/literals.rs @@ -0,0 +1,1104 @@ +//! Values written in Rust for input types: object literals in inline +//! operations, `input!`, and the `Variables` of modules. Each test reads the +//! exact body sent. +#![cfg(feature = "testing")] + +use serde_json::json; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::{Maybe, graphql, input}; + +const PRODUCT_UPDATE: &str = "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { field message } } }"; + +graphql! { + /// Writes metafields. + pub mod metafields_set = "mutation MetafieldsSet($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { metafields { id key } userErrors { field message } } + }"; + mod shop_name = "query ShopName { shop { name } }"; + pub(crate) mod recent_products = "query RecentProducts($first: Int!, $sortKey: ProductSortKeys) { + products(first: $first, sortKey: $sortKey) { nodes { id } } + }"; + mod product_count = "query ProductCount($query: String) { productsCount(query: $query) { count } }" +} + +/// The body of the last request, as sent. +fn sent(mock: &MockTransport) -> String { + String::from_utf8(mock.last_request().unwrap().body).unwrap() +} + +/// The variables of `operation`, parsed from the body it sends. +fn variables(operation: &shopify_api::Operation) -> serde_json::Value { + serde_json::from_str::(&operation.body().unwrap()).unwrap()["variables"] + .take() +} + +/// A body of `query` with `variables`, written as `shopify_api` writes it. +fn body(query: &str, variables: &str) -> String { + format!( + r#"{{"query":{},"variables":{variables}}}"#, + serde_json::to_string(query).unwrap() + ) +} + +struct Row { + product_id: String, + key: &'static str, + value: &'static str, + digest: Option, +} + +fn rows() -> Vec { + let row = |id: u32, key, value, digest: Option<&str>| Row { + product_id: format!("gid://shopify/Product/{id}"), + key, + value, + digest: digest.map(str::to_string), + }; + vec![ + row(1, "color", "blue", None), + row(2, "color", "", None), + row(3, "color", "red", Some("d3")), + ] +} + +fn color_metafields(rows: &[Row]) -> Vec { + let mut metafields = Vec::new(); + for row in rows { + if row.value.is_empty() { + continue; + } + metafields.push(input!(MetafieldsSetInput { + ownerId: &row.product_id, + namespace: "custom", + key: row.key, + value: row.value, + type: "single_line_text_field", + compareDigest?: row.digest.as_deref(), + })); + } + metafields +} + +const COLOR_METAFIELDS: &str = r#"[{"ownerId":"gid://shopify/Product/1","namespace":"custom","key":"color","value":"blue","type":"single_line_text_field"},{"ownerId":"gid://shopify/Product/3","namespace":"custom","key":"color","value":"red","type":"single_line_text_field","compareDigest":"d3"}]"#; + +#[tokio::test] +async fn an_object_literal_sends_values_nulls_enums_nested_objects_and_built_lists() { + let mock = MockTransport::new(); + mock.push_data(json!({ "productUpdate": { "userErrors": [] } })); + let shopify = client(&mock); + let product_id = "gid://shopify/Product/1"; + let name = "Shirt"; + let new_vendor: Option = None; + let seo_title = "Shirt, on sale".to_string(); + let rows = rows(); + + let data = shopify + .execute(graphql!( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { field message } } }", + product = { + id: product_id, + title: format!("{name} (promo)"), + status: ACTIVE, + descriptionHtml: null, + vendor?: new_vendor, + seo: { title: &seo_title }, + metafields: [for m in &rows if !m.value.is_empty() => { + namespace: "custom", key: m.key, value: m.value, type: "single_line_text_field", + }], + }, + )) + .await + .unwrap(); + + assert!(data.product_update.unwrap().user_errors.is_empty()); + assert_eq!( + sent(&mock), + body( + PRODUCT_UPDATE, + r#"{"product":{"id":"gid://shopify/Product/1","title":"Shirt (promo)","status":"ACTIVE","descriptionHtml":null,"seo":{"title":"Shirt, on sale"},"metafields":[{"namespace":"custom","key":"color","value":"blue","type":"single_line_text_field"},{"namespace":"custom","key":"color","value":"red","type":"single_line_text_field"}]}}"# + ) + ); +} + +#[tokio::test] +async fn a_field_with_a_question_mark_is_left_out_sent_null_or_sent() { + let mock = MockTransport::new(); + mock.push_data(json!({ "productUpdate": { "userErrors": [] } })); + let shopify = client(&mock); + let clear_description = true; + let status: Option = Some("DRAFT".to_string()); + + shopify + .execute(graphql!( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { field message } } }", + product = { + id: "gid://shopify/Product/1", + vendor?: Some("Acme"), + handle?: None::, + descriptionHtml?: if clear_description { Maybe::Null } else { Maybe::Value("

x

") }, + productType?: Maybe::Value("Shirts".to_string()), + templateSuffix?: Maybe::<&str>::Absent, + giftCardTemplateSuffix?: Maybe::::default(), + status?: raw(status.as_deref()), + tags: ["a", "b"], + collectionsToJoin: [], + }, + )) + .await + .unwrap(); + + assert_eq!( + sent(&mock), + body( + PRODUCT_UPDATE, + r#"{"product":{"id":"gid://shopify/Product/1","vendor":"Acme","descriptionHtml":null,"productType":"Shirts","status":"DRAFT","tags":["a","b"],"collectionsToJoin":[]}}"# + ) + ); +} + +#[tokio::test] +async fn enum_variables_take_a_bare_value_or_raw_and_scalars_take_rust_as_before() { + let mock = MockTransport::new(); + mock.respond_with(|_| { + Ok(shopify_api::transport::HttpResponse::json( + 200, + &json!({ "data": { "products": { "nodes": [] }, "nodes": [] } }), + )) + }); + let shopify = client(&mock); + let query = "query($first: Int!, $sortKey: ProductSortKeys, $ids: [ID!]!) { products(first: $first, sortKey: $sortKey) { nodes { id } } nodes(ids: $ids) { id } }"; + let (a, b) = ( + "gid://shopify/Product/1", + "gid://shopify/Product/2".to_string(), + ); + + shopify + .execute(graphql!( + "query($first: Int!, $sortKey: ProductSortKeys, $ids: [ID!]!) { products(first: $first, sortKey: $sortKey) { nodes { id } } nodes(ids: $ids) { id } }", + first = { 1 + 1 }, + sortKey = TITLE, + ids = [a, &b], + )) + .await + .unwrap(); + assert_eq!( + sent(&mock), + body( + query, + r#"{"first":2,"sortKey":"TITLE","ids":["gid://shopify/Product/1","gid://shopify/Product/2"]}"# + ) + ); + + let sort_key: Option<&str> = None; + shopify + .execute(graphql!( + "query($first: Int!, $sortKey: ProductSortKeys, $ids: [ID!]!) { products(first: $first, sortKey: $sortKey) { nodes { id } } nodes(ids: $ids) { id } }", + first = 1_u8, + sortKey = raw(sort_key), + ids = [for id in [a, b.as_str()] => id], + )) + .await + .unwrap(); + assert_eq!( + sent(&mock), + body( + query, + r#"{"first":1,"sortKey":null,"ids":["gid://shopify/Product/1","gid://shopify/Product/2"]}"# + ) + ); + + shopify + .execute(recent_products::Variables { + first: 5, + sort_key: Some("CREATED_AT".to_string()), + }) + .await + .unwrap(); + assert_eq!( + mock.graphql_requests().last().unwrap().variables, + json!({ "first": 5, "sortKey": "CREATED_AT" }) + ); +} + +#[tokio::test] +async fn one_vec_of_input_objects_goes_to_an_inline_operation_and_to_a_module() { + let mock = MockTransport::new(); + mock.respond_with(|_| { + Ok(shopify_api::transport::HttpResponse::json( + 200, + &json!({ "data": { "metafieldsSet": { "metafields": [], "userErrors": [] } } }), + )) + }); + let shopify = client(&mock); + let metafields = color_metafields(&rows()); + + let inline = "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }"; + shopify + .execute(graphql!( + "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", + metafields = &metafields, + )) + .await + .unwrap(); + assert_eq!( + sent(&mock), + body(inline, &format!(r#"{{"metafields":{COLOR_METAFIELDS}}}"#)) + ); + + let data = shopify + .execute(metafields_set::Variables { metafields }) + .await + .unwrap(); + assert!(data.metafields_set.unwrap().user_errors.is_empty()); + assert_eq!( + sent(&mock), + format!( + r#"{{"query":{},"variables":{{"metafields":{COLOR_METAFIELDS}}},"operationName":"MetafieldsSet"}}"#, + serde_json::to_string(metafields_set::QUERY).unwrap() + ) + ); + + // `operation(variables)` still builds the operation. + let operation = metafields_set::operation(metafields_set::Variables { + metafields: color_metafields(&rows()), + }); + assert_eq!( + variables(&operation)["metafields"][1]["compareDigest"], + "d3" + ); +} + +#[tokio::test] +async fn input_objects_of_two_call_sites_share_one_vec_and_a_module_type() { + let mock = MockTransport::new(); + mock.push_data(json!({ "metafieldsSet": { "metafields": [], "userErrors": [] } })); + let shopify = client(&mock); + + let metafields: Vec = rows() + .iter() + .map(|row| match &row.digest { + Some(digest) => input!(MetafieldsSetInput { + ownerId: &row.product_id, + key: "color", + value: row.value, + compareDigest: digest, + }), + None => input!(MetafieldsSetInput { + ownerId: &row.product_id, + key: "color", + value: row.value, + type: "single_line_text_field", + }), + }) + .collect(); + let first = metafields[0].clone(); + assert_eq!( + format!("{first:?}"), + r#"MetafieldsSetInput {"ownerId":"gid://shopify/Product/1","key":"color","value":"blue","type":"single_line_text_field"}"# + ); + assert_eq!( + serde_json::to_string(&first).unwrap(), + r#"{"ownerId":"gid://shopify/Product/1","key":"color","value":"blue","type":"single_line_text_field"}"# + ); + + shopify + .execute(metafields_set::Variables { metafields }) + .await + .unwrap(); + assert_eq!( + mock.graphql_requests()[0].variables, + json!({ "metafields": [ + { "ownerId": "gid://shopify/Product/1", "key": "color", "value": "blue", "type": "single_line_text_field" }, + { "ownerId": "gid://shopify/Product/2", "key": "color", "value": "", "type": "single_line_text_field" }, + { "ownerId": "gid://shopify/Product/3", "key": "color", "value": "red", "compareDigest": "d3" }, + ] }) + ); +} + +#[tokio::test] +async fn the_modules_of_one_block_each_run() { + let mock = MockTransport::new(); + mock.push_data(json!({ "shop": { "name": "Test shop" } })); + mock.push_data(json!({ "products": { "nodes": [{ "id": "gid://shopify/Product/1" }] } })); + mock.push_data(json!({ "productsCount": { "count": 3 } })); + let shopify = client(&mock); + + let data: shop_name::Data = shopify.execute(shop_name::operation()).await.unwrap(); + assert_eq!(data.shop.name, "Test shop"); + let data = shopify + .execute(recent_products::Variables { + first: 1, + sort_key: None, + }) + .await + .unwrap(); + assert_eq!(data.products.nodes[0].id, "gid://shopify/Product/1"); + // No variable is required: `Default` cannot leave one out. + let data = shopify + .execute(product_count::Variables::default()) + .await + .unwrap(); + assert_eq!(data.products_count.unwrap().count, 3); + + let names: Vec> = mock + .graphql_requests() + .into_iter() + .map(|request| request.operation_name) + .collect(); + assert_eq!( + names, + [ + Some("ShopName".to_string()), + Some("RecentProducts".to_string()), + Some("ProductCount".to_string()) + ] + ); + assert_eq!(mock.graphql_requests()[1].variables, json!({ "first": 1 })); +} + +#[tokio::test] +async fn a_nullable_input_variable_takes_null_an_option_or_a_literal() { + let mock = MockTransport::new(); + mock.respond_with(|_| { + Ok(shopify_api::transport::HttpResponse::json( + 200, + &json!({ "data": { "productCreate": { "product": null } } }), + )) + }); + let shopify = client(&mock); + let query = "mutation($product: ProductCreateInput, $media: [CreateMediaInput!]) { productCreate(product: $product, media: $media) { product { id } } }"; + + shopify + .execute(graphql!( + "mutation($product: ProductCreateInput, $media: [CreateMediaInput!]) { productCreate(product: $product, media: $media) { product { id } } }", + product = { title: "Shirt", status: DRAFT }, + media = null, + )) + .await + .unwrap(); + assert_eq!( + sent(&mock), + body( + query, + r#"{"product":{"title":"Shirt","status":"DRAFT"},"media":null}"# + ) + ); + + let image = input!(CreateMediaInput { + originalSource: "https://example.com/shirt.jpg", + mediaContentType: IMAGE, + }); + let product = Some(input!(ProductCreateInput { title: "Shirt" })); + shopify + .execute(graphql!( + "mutation($product: ProductCreateInput, $media: [CreateMediaInput!]) { productCreate(product: $product, media: $media) { product { id } } }", + product = product, + media = [image], + )) + .await + .unwrap(); + assert_eq!( + sent(&mock), + body( + query, + r#"{"product":{"title":"Shirt"},"media":[{"originalSource":"https://example.com/shirt.jpg","mediaContentType":"IMAGE"}]}"# + ) + ); +} + +graphql! { + mod defaults = "query Defaults($first: Int! = 10, $query: String! = \"a\", $sortKey: ProductSortKeys! = TITLE) { + products(first: $first, query: $query, sortKey: $sortKey) { nodes { id } } + }"; + mod pixel = "mutation Pixel($settings: JSON! = {}) { webPixelCreate(webPixel: {settings: $settings}) { userErrors { message } } }"; + mod weight = "mutation Weight($id: ID!, $value: Float! = 1.0) { + inventoryItemUpdate(id: $id, input: {measurement: {weight: {value: $value, unit: KILOGRAMS}}}) { userErrors { message } } + }"; + mod draft = "mutation Draft($input: DraftOrderInput! = {}, $items: [DraftOrderLineItemInput!]! = [], $tags: [String!]! = []) { + a: draftOrderCreate(input: $input) { userErrors { message } } + b: draftOrderCreate(input: {lineItems: $items, tags: $tags}) { userErrors { message } } + }"; +} + +/// A non-null variable with a default, given `None`, is left out, for +/// Shopify to use the default. +#[test] +fn a_defaulted_non_null_variable_given_none_is_left_out() { + use serde_json::Value; + + let operation = defaults::operation(defaults::Variables::default()); + assert_eq!(operation.variable_json("first").unwrap(), None); + assert_eq!(operation.variable_json("query").unwrap(), None); + assert_eq!(operation.variable_json("sortKey").unwrap(), None); + assert_eq!( + pixel::operation(pixel::Variables::default()) + .variable_json("settings") + .unwrap(), + None + ); + let operation = weight::operation(weight::Variables { + id: "gid://shopify/InventoryItem/1".into(), + value: None, + }); + assert_eq!(operation.variable_json("value").unwrap(), None); + let operation = draft::operation(draft::Variables { + input: None, + items: None, + tags: None, + }); + assert_eq!(variables(&operation), Value::Null); +} + +/// A non-null variable with a default, given a value, sends it. +#[test] +fn a_defaulted_non_null_variable_given_a_value_sends_it() { + let operation = defaults::operation(defaults::Variables { + first: Some(i64::from(i32::MAX)), + query: Some("b".into()), + sort_key: Some("ID".into()), + }); + assert_eq!( + variables(&operation), + json!({ "first": i32::MAX, "query": "b", "sortKey": "ID" }) + ); + let operation = pixel::operation(pixel::Variables { + settings: Some(json!({ "a": null })), + }); + assert_eq!( + operation.variable_json("settings").unwrap(), + Some(r#"{"a":null}"#) + ); + let operation = weight::operation(weight::Variables { + id: "gid://shopify/InventoryItem/1".into(), + value: Some(2.5), + }); + assert_eq!(operation.variable_json("value").unwrap(), Some("2.5")); + let operation = draft::operation(draft::Variables { + input: Some(input!(DraftOrderInput { note: "n" })), + items: Some(vec![input!(DraftOrderLineItemInput { quantity: 1 })]), + tags: Some(vec!["t".into()]), + }); + assert_eq!( + variables(&operation), + json!({ "input": { "note": "n" }, "items": [{ "quantity": 1 }], "tags": ["t"] }) + ); +} + +/// A value given to a non-null variable with a default is checked as +/// non-null, never sent as `null`, by a module and an inline operation +/// alike. +#[test] +fn a_defaulted_non_null_variable_checks_its_value() { + use serde_json::Value; + use shopify_api::{Error, InvalidValueReason}; + + let reason = |body: shopify_api::Result| match body { + Err(Error::InvalidValue { reason, .. }) => reason, + other => panic!("not refused: {other:?}"), + }; + let big: i64 = 1 << 31; + let line_item = input!(DraftOrderLineItemInput { quantity: big }); + for (body, expected) in [ + ( + defaults::operation(defaults::Variables { + first: Some(big), + ..Default::default() + }) + .body(), + InvalidValueReason::IntOutOfRange, + ), + ( + graphql!( + "query Defaults($first: Int! = 10, $query: String! = \"a\", $sortKey: ProductSortKeys! = TITLE) { products(first: $first, query: $query, sortKey: $sortKey) { nodes { id } } }", + first = big, + ) + .body(), + InvalidValueReason::IntOutOfRange, + ), + ( + pixel::operation(pixel::Variables { + settings: Some(Value::Null), + }) + .body(), + InvalidValueReason::NullJson, + ), + ( + graphql!( + "mutation Pixel($settings: JSON! = {}) { webPixelCreate(webPixel: {settings: $settings}) { userErrors { message } } }", + settings = Value::Null, + ) + .body(), + InvalidValueReason::NullJson, + ), + ( + weight::operation(weight::Variables { + id: "gid://shopify/InventoryItem/1".into(), + value: Some(f64::NAN), + }) + .body(), + InvalidValueReason::NotFiniteFloat, + ), + ( + graphql!( + "mutation Weight($id: ID!, $value: Float! = 1.0) { inventoryItemUpdate(id: $id, input: {measurement: {weight: {value: $value, unit: KILOGRAMS}}}) { userErrors { message } } }", + id = "gid://shopify/InventoryItem/1", + value = f64::INFINITY, + ) + .body(), + InvalidValueReason::NotFiniteFloat, + ), + ( + draft::operation(draft::Variables { + input: Some(input!(DraftOrderInput { lineItems: [line_item.clone()] })), + items: None, + tags: None, + }) + .body(), + InvalidValueReason::IntOutOfRange, + ), + ( + draft::operation(draft::Variables { + input: None, + items: Some(vec![line_item.clone()]), + tags: None, + }) + .body(), + InvalidValueReason::IntOutOfRange, + ), + ( + graphql!( + "mutation Draft($input: DraftOrderInput! = {}, $items: [DraftOrderLineItemInput!]! = [], $tags: [String!]! = []) { a: draftOrderCreate(input: $input) { userErrors { message } } b: draftOrderCreate(input: {lineItems: $items, tags: $tags}) { userErrors { message } } }", + input = { lineItems: [{ quantity: big }] }, + ) + .body(), + InvalidValueReason::IntOutOfRange, + ), + ( + graphql!( + "mutation Draft($input: DraftOrderInput! = {}, $items: [DraftOrderLineItemInput!]! = [], $tags: [String!]! = []) { a: draftOrderCreate(input: $input) { userErrors { message } } b: draftOrderCreate(input: {lineItems: $items, tags: $tags}) { userErrors { message } } }", + items = [line_item.clone()], + ) + .body(), + InvalidValueReason::IntOutOfRange, + ), + ] { + assert_eq!(reason(body), expected); + } +} + +/// What Shopify would not read as written: an `Int` beyond 32 bits, a +/// `Float` that is not finite, `null` for a non-null `JSON`. The operation +/// fails before anything is sent, saying where and why, never the value. +#[tokio::test] +async fn values_shopify_would_not_read_as_written_fail_before_anything_is_sent() { + let mock = MockTransport::new(); + let shopify = client(&mock); + let big: i64 = 1 << 40; + let quantities = [1_u64, 2, u64::MAX]; + let nan = f64::NAN; + let weights = [Some(1.5), None, Some(f64::INFINITY)]; + let line_item = input!(DraftOrderLineItemInput { quantity: big }); + let pixel = input!(WebPixelInput { + settings: serde_json::Value::Null + }); + + let errors = [ + shopify + .execute(graphql!("mutation($input: DraftOrderInput!) { draftOrderCreate(input: $input) { userErrors { message } } }", input = { lineItems: [{ quantity: 1 }, { quantity: big }] })) + .await + .unwrap_err(), + shopify + .execute(graphql!("mutation($input: DraftOrderInput!) { draftOrderCreate(input: $input) { userErrors { message } } }", input = { + lineItems: [{ quantity: 1, weight: { unit: KILOGRAMS, value: nan } }], + })) + .await + .unwrap_err(), + shopify + .execute(graphql!("mutation($input: DraftOrderInput!) { draftOrderCreate(input: $input) { userErrors { message } } }", input = { + lineItems: [for quantity in quantities => { quantity: quantity }], + })) + .await + .unwrap_err(), + shopify + .execute(graphql!("mutation($input: DraftOrderInput!) { draftOrderCreate(input: $input) { userErrors { message } } }", input = { + lineItems: [for (i, weight) in weights.iter().enumerate() => { + quantity: i, + weight?: weight.map(|value| input!(WeightInput { unit: GRAMS, value: value })), + }], + })) + .await + .unwrap_err(), + shopify + .execute(graphql!("mutation($input: DraftOrderInput!) { draftOrderCreate(input: $input) { userErrors { message } } }", input = { lineItems: [line_item.clone()] })) + .await + .unwrap_err(), + shopify + .execute(graphql!("mutation($webPixel: WebPixelInput!) { webPixelCreate(webPixel: $webPixel) { userErrors { message } } }", webPixel = pixel.clone())) + .await + .unwrap_err(), + shopify + .execute(graphql!( + "mutation($id: ID!, $discount: DiscountAutomaticBasicInput!) { discountAutomaticBasicUpdate(id: $id, automaticBasicDiscount: $discount) { userErrors { message } } }", + id = "gid://shopify/DiscountAutomaticNode/1", + discount = { customerGets: { value: { percentage: f64::INFINITY }, items: { all: true } } }, + )) + .await + .unwrap_err(), + shopify + .execute(recent_products::Variables { first: big, sort_key: None }) + .await + .unwrap_err(), + shopify + .execute(graphql!( + "query($first: Int!) { products(first: $first) { nodes { id } } }", + first = u64::MAX, + )) + .await + .unwrap_err(), + ]; + let shown: Vec = errors.iter().map(ToString::to_string).collect(); + assert_eq!( + shown, + [ + "invalid value at `$input.lineItems[1].quantity`: Int out of 32-bit range", + "invalid value at `$input.lineItems[0].weight.value`: not a finite Float", + "invalid value at `$input.lineItems[2].quantity`: Int out of 32-bit range", + "invalid value at `$input.lineItems[2].weight.value`: not a finite Float", + "invalid value at `$input.lineItems[0].quantity`: Int out of 32-bit range", + "invalid value at `$webPixel.settings`: null for a non-null JSON field", + "invalid value at `$discount.customerGets.value.percentage`: not a finite Float", + "invalid value at `$first`: Int out of 32-bit range", + "invalid value at `$first`: Int out of 32-bit range", + ] + ); + for error in &errors { + assert!(matches!( + error, + shopify_api::Error::InvalidValue { detail: None, .. } + )); + let debug = format!("{error:?}"); + assert!( + !debug.contains("1099511627776") && !debug.contains("NaN"), + "{debug}" + ); + } + assert!(mock.requests().is_empty()); + + // Serialized on its own, an input object fails the same way. + let error = serde_json::to_string(&line_item).unwrap_err(); + assert_eq!( + error.to_string(), + "invalid value at `DraftOrderLineItemInput.quantity`: Int out of 32-bit range" + ); + assert_eq!( + format!("{pixel:?}"), + "invalid value at `WebPixelInput.settings`: null for a non-null JSON field" + ); +} + +/// The bounds are allowed, and nulls inside `JSON`. +#[test] +fn values_at_the_bounds_are_sent() { + let line_item = input!(DraftOrderLineItemInput { + quantity: i64::from(i32::MAX), + weight: { unit: GRAMS, value: f64::MAX }, + }); + let pixel = input!(WebPixelInput { + settings: json!({ "a": null }) + }); + let discount = input!(DiscountCustomerGetsValueInput { percentage?: Some(f64::MIN_POSITIVE) }); + let constants = input!(DraftOrderLineItemInput { + quantity: -2_147_483_648, + title: "t", + requiresShipping: true, + weight: { unit: GRAMS, value: 2 }, + }); + assert_eq!( + serde_json::to_value(&constants).unwrap(), + json!({ "quantity": i32::MIN, "title": "t", "requiresShipping": true, "weight": { "unit": "GRAMS", "value": 2 } }) + ); + let tags = input!(ProductUpdateInput { tags: ["t"; 40] }); + assert_eq!( + serde_json::to_value(&tags).unwrap()["tags"], + json!(vec!["t"; 40]) + ); + assert_eq!( + serde_json::to_value((&line_item, &pixel, &discount)).unwrap(), + json!([ + { "quantity": i32::MAX, "weight": { "unit": "GRAMS", "value": f64::MAX } }, + { "settings": { "a": null } }, + { "percentage": f64::MIN_POSITIVE }, + ]) + ); +} + +/// Only integer literals, negated, in parentheses or in a list `[…]`, are +/// checked when the crate compiles: what `Some(…)` calls depends on what +/// the name resolves to. The other forms are checked when the value is +/// built. +mod int_forms { + use shopify_api::{Error, InvalidValueReason, graphql, input}; + + fn normalize(n: i64) -> i32 { + (n - 2_147_483_648) as i32 + } + use normalize as Some; + + #[test] + fn a_function_named_some_is_the_callers() { + let value = input!(DraftOrderLineItemInput { + quantity: Some(2_147_483_648i64) + }); + assert_eq!( + serde_json::to_value(value).unwrap(), + serde_json::json!({ "quantity": 0 }) + ); + } + + #[test] + fn repeats_vec_and_option_are_checked_when_built() { + let out_of_range = |body: shopify_api::Result| { + matches!( + body, + Err(Error::InvalidValue { + reason: InvalidValueReason::IntOutOfRange, + .. + }) + ) + }; + assert!(out_of_range( + graphql!( + "query($n: Int!) { products(first: $n) { nodes { id } } }", + n = { [2_147_483_648i64; 1][0] } + ) + .body() + )); + assert!(out_of_range( + graphql!( + "query($n: Int) { products(first: $n) { nodes { id } } }", + n = ::core::option::Option::Some(3_000_000_000i64), + ) + .body() + )); + assert!(out_of_range( + graphql!( + "mutation($input: DraftOrderInput!) { draftOrderCreate(input: $input) { userErrors { message } } }", + input = { lineItems: [{ quantity: vec![2_147_483_648i64][0] }] }, + ) + .body() + )); + } +} + +/// A suffixed literal its type cannot hold is the value the compiler gives +/// it under `allow(overflowing_literals)`, checked when it is built. +#[test] +#[allow(overflowing_literals, reason = "a literal that wraps to `-1`")] +fn a_wrapping_suffixed_literal_is_its_rust_value() { + let value = input!(DraftOrderLineItemInput { + quantity: 0xffff_ffff_i32 + }); + assert_eq!( + serde_json::to_value(value).unwrap(), + json!({ "quantity": -1 }) + ); +} + +/// Names like the ones the macros generate, or generated before, given to +/// the caller's locals, closures, functions, constants and trait methods: +/// the values sent are the caller's. +mod hygiene { + #![allow( + non_upper_case_globals, + non_snake_case, + dead_code, + reason = "names and items that look like the generated ones" + )] + + use serde_json::{Value, json}; + use shopify_api::{graphql, input}; + + /// A trait method by value for every type, named like the methods the + /// generated code calls. + trait Capture: Sized { + fn check(self, _: &str) -> &'static str { + "captured" + } + fn optional(self, _: Option<&str>) -> Option<&'static str> { + Some("captured") + } + fn push(self, _: &str) {} + fn build(self, _: A, _: B) -> &'static str { + "captured" + } + fn variable(self, _: &str, _: V) -> Self { + self + } + fn __literal_variable(self, _: &str, _: V) -> Self { + self + } + } + impl Capture for T {} + + fn json(value: impl serde::Serialize) -> Value { + serde_json::to_value(value).unwrap() + } + + #[test] + fn locals_and_closures() { + let __shopify_api_check1 = |text: &str| format!("closure:{text}"); + let __shopify_api_check3 = |text: &str| format!("closure:{text}"); + let __shopify_api_optional1 = |text: &str| Some(format!("closure:{text}")); + let __shopify_api_checks = "local"; + let __shopify_api_items = vec!["local"]; + let __shopify_api_variable_0 = "local"; + let check = |text: &str| format!("closure:{text}"); + let Checks = "local"; + let literal = "local"; + let value0 = |text: &str| format!("closure:{text}"); + let V1 = "local"; + let value = input!(ProductUpdateInput { + title: __shopify_api_check3("a"), + vendor: __shopify_api_check1("b"), + handle: check("c"), + productType: __shopify_api_checks, + descriptionHtml: __shopify_api_variable_0, + templateSuffix?: __shopify_api_optional1("d"), + tags: [for tag in &__shopify_api_items => Checks.to_string() + tag + literal + V1], + seo: { title: value0("e"), description: literal }, + }); + assert_eq!( + json(&value), + json!({ + "title": "closure:a", + "vendor": "closure:b", + "handle": "closure:c", + "productType": "local", + "descriptionHtml": "local", + "templateSuffix": "closure:d", + "tags": ["locallocallocallocal"], + "seo": { "title": "closure:e", "description": "local" }, + }) + ); + + let operation = graphql!( + "mutation($product: ProductUpdateInput!, $media: [CreateMediaInput!], $first: Int) { productUpdate(product: $product, media: $media) { product { variants(first: $first) { nodes { id } } } userErrors { message } } }", + product = { title: __shopify_api_check3("e"), tags: __shopify_api_items.clone() }, + media = [for alt in [__shopify_api_variable_0] => { originalSource: check(alt), mediaContentType: IMAGE, alt: alt }], + first = __shopify_api_items.len(), + ); + assert_eq!( + crate::variables(&operation), + json!({ + "product": { "title": "closure:e", "tags": ["local"] }, + "media": [{ "originalSource": "closure:local", "mediaContentType": "IMAGE", "alt": "local" }], + "first": 1, + }) + ); + } + + mod items { + use super::*; + + const __shopify_api_check1: &str = "const"; + const __shopify_api_checks: &str = "const"; + const __shopify_api_items: [&str; 1] = ["const"]; + const __shopify_api_variable_0: &str = "const"; + const Checks: &str = "const"; + const checks: &str = "const"; + const items: &str = "const"; + const literal: &str = "const"; + const value0: &str = "const"; + const V1: &str = "const"; + const value69: &str = "const"; + fn leaf(text: &str) -> String { + format!("fn:{text}") + } + static __shopify_api_optional1: &str = "static"; + fn __shopify_api_check2(text: &str) -> String { + format!("fn:{text}") + } + fn check(text: &str) -> String { + format!("fn:{text}") + } + fn optional(text: Option<&str>) -> Option { + text.map(|text| format!("fn:{text}")) + } + + /// Seventy values, each a constant named like a generated one: the + /// macro numbers its own names past any count, and every value sent + /// is the caller's. + #[test] + fn seventy_values() { + let value = input!(ProductUpdateInput { + tags: [ + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1, + __shopify_api_check1 + ] + }); + assert_eq!(json(&value)["tags"], json!(vec!["const"; 70])); + } + + #[test] + fn functions_constants_and_statics() { + let value = input!(ProductUpdateInput { + title: __shopify_api_check2("a"), + vendor: check("b"), + handle: __shopify_api_check1, + productType: __shopify_api_checks, + descriptionHtml: Checks, + templateSuffix?: optional(Some(__shopify_api_optional1)), + tags: [for tag in __shopify_api_items => check(tag)], + seo: { title: leaf(literal), description: value0.to_string() + V1 }, + }); + assert_eq!( + json(&value), + json!({ + "title": "fn:a", + "vendor": "fn:b", + "handle": "const", + "productType": "const", + "descriptionHtml": "const", + "templateSuffix": "fn:static", + "tags": ["fn:const"], + "seo": { "title": "fn:const", "description": "constconst" }, + }) + ); + let operation = graphql!( + "mutation($product: ProductUpdateInput!, $media: [CreateMediaInput!], $first: Int) { productUpdate(product: $product, media: $media) { product { variants(first: $first) { nodes { id } } } userErrors { message } } }", + product = { title: __shopify_api_variable_0, tags: [for tag in [checks, items] => tag] }, + first = __shopify_api_items.len(), + ); + assert_eq!( + crate::variables(&operation), + json!({ "product": { "title": "const", "tags": ["const", "const"] }, "first": 1 }) + ); + } + } + + enum Stage { + Ready, + } + use Stage::Ready as ready; + + /// Any pattern, whatever it binds: nothing, a name that starts with a + /// capital, a unit variant renamed in lower case, a generated name. + #[test] + fn the_pattern_of_a_for_is_the_callers() { + let value = json(input!(ProductUpdateInput { + tags: [for _ in 0..2 => "sale"], + collectionsToJoin: [for (ready, id) in [(ready, "1")] => id], + collectionsToLeave: [for ref Item in [String::from("a")] => Item], + redirectNewHandle: true, + })); + assert_eq!( + value, + json!({ "tags": ["sale", "sale"], "collectionsToJoin": ["1"], "collectionsToLeave": ["a"], "redirectNewHandle": true }) + ); + let value = json(input!(ProductUpdateInput { + tags: [for __shopify_api_collected in [["a", "b"]] => __shopify_api_collected[1]], + })); + assert_eq!(value, json!({ "tags": ["b"] })); + let operation = graphql!( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }", + product = { tags: [for _ in [()] => "x"], metafields: [for Item in ["k"] => { key: Item, value: "v", namespace: "n", type: "single_line_text_field" }] }, + ); + assert_eq!( + crate::variables(&operation), + json!({ "product": { "tags": ["x"], "metafields": [{ "key": "k", "value": "v", "namespace": "n", "type": "single_line_text_field" }] } }) + ); + } + + struct Product { + title: &'static str, + } + + impl Product { + const SUFFIX: &'static str = "suffix"; + + /// In a method, where `Self` and `self` are the caller's. + fn input(&self) -> Value { + json(input!(ProductUpdateInput { + title: self.title, + templateSuffix: Self::SUFFIX, + tags: [for tag in [Self::SUFFIX] => tag], + })) + } + } + + #[test] + fn self_and_self_type_are_the_callers() { + assert_eq!( + Product { title: "t" }.input(), + json!({ "title": "t", "templateSuffix": "suffix", "tags": ["suffix"] }) + ); + } +} diff --git a/crates/shopify_api/tests/live.rs b/crates/shopify_api/tests/live.rs new file mode 100644 index 0000000..fe539bd --- /dev/null +++ b/crates/shopify_api/tests/live.rs @@ -0,0 +1,286 @@ +//! Against a real development store. Ignored by default: `mise run test:live` +//! runs them, with `SHOPIFY_TEST_SHOP` and either `SHOPIFY_TEST_ACCESS_TOKEN` +//! or `SHOPIFY_TEST_CLIENT_ID` and `SHOPIFY_TEST_CLIENT_SECRET`. The token +//! needs `read_products` and `write_products`: the typed bulk test creates a +//! product tagged `shopify-api-live-test` when the store has none of the +//! shape it reads, and reuses it on later runs. +#![cfg(feature = "rustls")] + +use std::collections::HashMap; +use std::time::Duration; + +use serde_json::Value; +use shopify_api::bulk::{BulkOperationStatus, BulkOperationsFilter, BulkWaitOptions}; +use shopify_api::{Auth, Shopify, graphql}; + +graphql! { + /// Two levels of nested connections, two sibling connections under a + /// product, and the nodes of an interface (`Media`). + mod live_catalog = bulk("{ + products { edges { node { + id title + variants { edges { node { + id sku + metafields { edges { node { id namespace key value } } } + } } } + media { edges { node { id mediaContentType ... on MediaImage { alt } } } } + } } } + }"); + + mod seed_fixture = "mutation SeedLiveFixture($input: ProductSetInput!) { + productSet(input: $input, synchronous: true) { + product { id } + userErrors { field message } + } + }"; +} + +/// The tag of the product the typed bulk test creates. +const FIXTURE_TAG: &str = "shopify-api-live-test"; + +/// A small image, stable for years, that Shopify can fetch. +const FIXTURE_IMAGE: &str = + "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"; + +fn live() -> Shopify { + let env = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty()); + let shop = env("SHOPIFY_TEST_SHOP").expect("SHOPIFY_TEST_SHOP"); + let auth = match ( + env("SHOPIFY_TEST_ACCESS_TOKEN"), + env("SHOPIFY_TEST_CLIENT_ID"), + env("SHOPIFY_TEST_CLIENT_SECRET"), + ) { + (Some(token), _, _) => Auth::access_token(token), + (None, Some(id), Some(secret)) => Auth::client_credentials(id, secret), + _ => panic!( + "set SHOPIFY_TEST_ACCESS_TOKEN, or SHOPIFY_TEST_CLIENT_ID and SHOPIFY_TEST_CLIENT_SECRET" + ), + }; + Shopify::new(shop, auth).expect("a valid shop") +} + +#[tokio::test] +#[ignore = "calls a real store: mise run test:live"] +async fn reads_the_shop_with_a_typed_query() { + let data = live() + .execute(graphql!( + "query Shop { shop { name myshopifyDomain currencyCode } }" + )) + .await + .unwrap(); + assert!(!data.shop.name.is_empty()); + assert!(data.shop.myshopify_domain.ends_with(".myshopify.com")); +} + +#[tokio::test] +#[ignore = "calls a real store: mise run test:live"] +async fn the_answer_carries_the_cost() { + let response = live() + .execute_response(graphql!("{ products(first: 1) { nodes { id } } }")) + .await + .unwrap(); + let cost = response.cost().expect("Shopify reports the cost"); + assert!(cost.throttle_status.maximum_available > 0.0); +} + +#[tokio::test] +#[ignore = "calls a real store: mise run test:live"] +async fn downloads_the_schema_through_the_shop() { + let schema = live().download_admin_schema().await.unwrap(); + assert!(schema.pointer("/data/__schema/types").is_some()); +} + +#[tokio::test] +#[ignore = "calls a real store: mise run test:live"] +async fn runs_a_bulk_query_to_its_end() { + let shopify = live(); + let operation = shopify + .start_bulk_query("{ products { edges { node { id title } } } }") + .await + .unwrap(); + let listed = shopify + .bulk_operations(BulkOperationsFilter::new().first(5)) + .await + .unwrap(); + assert!(listed.items.iter().any(|listed| listed.id == operation.id)); + + let operation = shopify + .wait_for_bulk_operation( + &operation.id, + BulkWaitOptions::new().timeout(Duration::from_secs(180)), + ) + .await + .unwrap(); + assert_eq!(operation.status, BulkOperationStatus::Completed); + if let Some(url) = operation.url { + let rows: Vec = shopify.download_bulk_results(&url).await.unwrap(); + assert!(rows.iter().all(|row| row.get("id").is_some())); + } +} + +/// Starts `live_catalog`, waits for it, and reads its results twice: as +/// `BulkItems` and as raw JSONL lines. +async fn run_live_catalog(shopify: &Shopify) -> (Vec, Vec) { + let started = shopify + .start_bulk_query(live_catalog::operation()) + .await + .unwrap(); + let operation = shopify + .wait_for_bulk_operation( + &started.id, + BulkWaitOptions::new().timeout(Duration::from_secs(600)), + ) + .await + .unwrap(); + assert_eq!( + operation.status, + BulkOperationStatus::Completed, + "{operation:?}" + ); + let Some(url) = operation.url else { + return (Vec::new(), Vec::new()); + }; + let items = shopify + .download_bulk_items(&url) + .await + .unwrap() + .collect() + .await + .expect("the typed reader places every line: Shopify kept the alias and the order"); + let lines = shopify.download_bulk_results(&url).await.unwrap(); + (items, lines) +} + +fn has_the_shape(items: &[live_catalog::Item]) -> bool { + items.iter().any(|product| { + !product.media.is_empty() + && product + .variants + .iter() + .any(|variant| !variant.metafields.is_empty()) + }) +} + +async fn seed_fixture(shopify: &Shopify) { + let metafield = |value: &str| { + shopify_api::input!(MetafieldInput { + namespace: "shopify_api_test", + key: "note", + type: "single_line_text_field", + value: value, + }) + }; + let small = metafield("small"); + let medium = metafield("medium"); + let data = shopify + .execute(seed_fixture::Variables { + input: shopify_api::input!(ProductSetInput { + title: "shopify_api live test", + tags: [FIXTURE_TAG], + productOptions: [{ name: "Size", values: [{ name: "S" }, { name: "M" }] }], + variants: [ + { + optionValues: [{ optionName: "Size", name: "S" }], + price: "1.00", + metafields: [small], + }, + { + optionValues: [{ optionName: "Size", name: "M" }], + price: "1.00", + metafields: [medium], + }, + ], + files: [{ originalSource: FIXTURE_IMAGE, contentType: IMAGE, alt: "fixture" }], + }), + }) + .await + .unwrap(); + let payload = data.product_set.expect("productSet answered"); + assert!(payload.user_errors.is_empty(), "{:?}", payload.user_errors); +} + +/// What the typed reader relies on and Shopify's guide does not show: the +/// `_shopifyApiTypename: __typename` alias is kept in the JSONL, and the +/// order of `groupObjects` (each object right after its parent) holds at the +/// second level too. The items are compared with a regrouping of the raw +/// lines by `__parentId` alone. +#[tokio::test] +#[ignore = "calls a real store: mise run test:live"] +async fn a_typed_bulk_query_regroups_two_levels_and_sibling_connections() { + let shopify = live(); + let (mut items, mut lines) = run_live_catalog(&shopify).await; + if !has_the_shape(&items) { + seed_fixture(&shopify).await; + // The image is fetched in the background: wait until it is listed. + for _ in 0..20 { + (items, lines) = run_live_catalog(&shopify).await; + if has_the_shape(&items) { + break; + } + tokio::time::sleep(Duration::from_secs(15)).await; + } + } + assert!( + has_the_shape(&items), + "no product with an image and a variant metafield, even after creating one tagged `{FIXTURE_TAG}`" + ); + + // The raw lines, regrouped by `__parentId` alone. + let id = |line: &Value| line["id"].as_str().unwrap().to_string(); + let mut products = Vec::new(); + let mut kind_of = HashMap::new(); + let mut children: HashMap)>> = HashMap::new(); + for line in &lines { + match line.get("__parentId").and_then(Value::as_str) { + None => { + kind_of.insert(id(line), "Product"); + products.push(id(line)); + } + Some(parent) => { + let typename = line + .get("_shopifyApiTypename") + .and_then(Value::as_str) + .map(str::to_string); + if kind_of.get(parent) == Some(&"Product") { + // Two connections under a product: the alias tells them apart. + assert!(typename.is_some(), "no `_shopifyApiTypename`: {line}"); + if typename.as_deref() == Some("ProductVariant") { + kind_of.insert(id(line), "ProductVariant"); + } + } else { + // Alone under its variant: not aliased. + assert_eq!(kind_of.get(parent), Some(&"ProductVariant"), "{line}"); + assert!(typename.is_none(), "{line}"); + } + children + .entry(parent.to_string()) + .or_default() + .push((id(line), typename)); + } + } + } + + let ids = |list: &[(String, Option)], variants: bool| -> Vec { + list.iter() + .filter(|(_, typename)| (typename.as_deref() == Some("ProductVariant")) == variants) + .map(|(id, _)| id.clone()) + .collect() + }; + let none = Vec::new(); + assert_eq!( + items.iter().map(|item| item.id.clone()).collect::>(), + products + ); + for product in &items { + let below = children.get(&product.id).unwrap_or(&none); + let variants: Vec = product.variants.iter().map(|v| v.id.clone()).collect(); + assert_eq!(variants, ids(below, true), "{}", product.id); + let media: Vec = product.media.iter().map(|m| m.id.clone()).collect(); + assert_eq!(media, ids(below, false), "{}", product.id); + for variant in &product.variants { + let below = children.get(&variant.id).unwrap_or(&none); + let metafields: Vec = variant.metafields.iter().map(|m| m.id.clone()).collect(); + assert_eq!(metafields, ids(below, false), "{}", variant.id); + } + } +} diff --git a/crates/shopify_api/tests/no_implicit_prelude.rs b/crates/shopify_api/tests/no_implicit_prelude.rs new file mode 100644 index 0000000..415d9c1 --- /dev/null +++ b/crates/shopify_api/tests/no_implicit_prelude.rs @@ -0,0 +1,55 @@ +//! The code `graphql!` and `input!` write for modules, variables of scalars +//! and literals of constants names everything by its full path: it compiles +//! without the prelude. A Rust expression in a literal needs the +//! `diagnostic` namespace, which `no_implicit_prelude` hides. +#![no_implicit_prelude] + +extern crate shopify_api; +extern crate std; + +shopify_api::graphql! { + mod products = "query Products($first: Int!, $query: String) { products(first: $first, query: $query) { nodes { id title } } }" +} + +#[test] +fn modules_variables_and_constants_compile_without_the_prelude() { + let variables = products::Variables { + first: 2, + query: ::std::option::Option::None, + }; + let operation = products::operation(variables); + ::std::assert_eq!( + operation.variable_json("first").unwrap(), + ::std::option::Option::Some("2") + ); + ::std::assert_eq!( + operation.variable_json("query").unwrap(), + ::std::option::Option::None + ); + let inline = shopify_api::graphql!( + "query($first: Int!, $query: String) { products(first: $first, query: $query) { nodes { id } } }", + first = 3, + query = "title:shirt", + ); + ::std::assert_eq!( + inline.variable_json("first").unwrap(), + ::std::option::Option::Some("3") + ); + ::std::assert_eq!( + inline.variable_json("query").unwrap(), + ::std::option::Option::Some(r#""title:shirt""#) + ); + let product = shopify_api::input!(ProductUpdateInput { title: "a", status: ACTIVE, tags: ["b"], seo: { title: "s" } }); + let literal = shopify_api::graphql!( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }", + product = { title: "a", status: ACTIVE, descriptionHtml: null }, + ); + ::std::assert_eq!( + ::shopify_api::__private::serde_json::to_string(&product).unwrap(), + r#"{"title":"a","status":"ACTIVE","tags":["b"],"seo":{"title":"s"}}"# + ); + ::std::assert_eq!( + literal.variable_json("product").unwrap(), + ::std::option::Option::Some(r#"{"title":"a","status":"ACTIVE","descriptionHtml":null}"#) + ); +} diff --git a/crates/shopify_api/tests/oauth.rs b/crates/shopify_api/tests/oauth.rs new file mode 100644 index 0000000..3572cc2 --- /dev/null +++ b/crates/shopify_api/tests/oauth.rs @@ -0,0 +1,319 @@ +//! The token requests of OAuth and of the token exchange. +#![cfg(all(feature = "testing", feature = "oauth"))] + +use serde_json::json; +use shopify_api::oauth::{RequestedToken, ShopifyApp}; +use shopify_api::testing::MockTransport; +use shopify_api::transport::HttpResponse; +use shopify_api::{Error, OAuthErrorCode}; + +fn app(mock: &MockTransport) -> ShopifyApp { + ShopifyApp::new("client-id", "client-secret").with_transport(mock.clone()) +} + +fn now() -> i64 { + chrono::Utc::now().timestamp() +} + +#[tokio::test] +async fn the_code_of_a_verified_callback_becomes_a_token() { + let mock = MockTransport::new(); + mock.push_json(json!({ "access_token": "shpat_1", "scope": "read_products,write_orders" })); + let app = app(&mock); + + let query = format!( + "code=abc&shop=my-shop.myshopify.com&state=s1×tamp={}", + now() + ); + let signature = app.sign_query(&query).unwrap(); + let callback = app + .verify_query(&format!("{query}&hmac={signature}")) + .unwrap(); + let token = app.exchange_code(&callback).await.unwrap(); + + assert_eq!(token.access_token, "shpat_1"); + assert_eq!(token.scopes(), ["read_products", "write_orders"]); + let request = mock.last_request().unwrap(); + assert_eq!( + request.url, + "https://my-shop.myshopify.com/admin/oauth/access_token" + ); + assert_eq!( + request.json().unwrap(), + json!({ "client_id": "client-id", "client_secret": "client-secret", "code": "abc" }) + ); +} + +#[tokio::test] +async fn a_session_token_becomes_an_expiring_token_and_a_client_that_refreshes_it() { + let mock = MockTransport::new(); + mock.push_json(json!({ + "access_token": "shpat_1", + "scope": "read_products", + "expires_in": 3600, + "refresh_token": "shprt_1", + "refresh_token_expires_in": 7_776_000, + })); + let app = app(&mock); + let now = now(); + let bearer = app.sign_session_token(&json!({ + "iss": "https://my-shop.myshopify.com/admin", + "dest": "https://my-shop.myshopify.com", + "aud": "client-id", + "sub": "42", + "exp": now + 60, + "nbf": now, + })); + + let session = app.verify_session_token(&bearer).unwrap(); + let token = app + .exchange_session_token(&session, RequestedToken::ExpiringOffline) + .await + .unwrap(); + assert_eq!(token.refresh_token.as_deref(), Some("shprt_1")); + assert_eq!( + mock.last_request().unwrap().json().unwrap(), + json!({ + "client_id": "client-id", + "client_secret": "client-secret", + "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange", + "subject_token": bearer, + "subject_token_type": "urn:ietf:params:oauth:token-type:id_token", + "requested_token_type": "urn:shopify:params:oauth:token-type:offline-access-token", + "expiring": "1", + }) + ); + + // The client of that token sends it, through the app's transport. + mock.push_data(json!({ "shop": { "name": "My shop" } })); + let shopify = app.client(session.shop(), token).unwrap(); + let data = shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(data["shop"]["name"], "My shop"); + assert_eq!( + mock.graphql_requests()[0].access_token.as_deref(), + Some("shpat_1") + ); +} + +#[tokio::test] +async fn an_online_token_names_its_staff_member() { + let mock = MockTransport::new(); + mock.push(HttpResponse::json( + 200, + &json!({ + "access_token": "shpua_1", + "scope": "read_products", + "expires_in": 86_399, + "associated_user_scope": "read_products", + "associated_user": { "id": 902541635, "first_name": "Ada", "email": "ada@example.com", "account_owner": true }, + }), + )); + let app = app(&mock); + let now = now(); + let bearer = app.sign_session_token(&json!({ + "iss": "https://my-shop.myshopify.com/admin", + "dest": "https://my-shop.myshopify.com", + "aud": "client-id", + "exp": now + 60, + })); + let session = app.verify_session_token(&bearer).unwrap(); + + let token = app + .exchange_session_token(&session, RequestedToken::Online) + .await + .unwrap(); + let user = token.associated_user.unwrap(); + assert_eq!(user.id, 902541635); + assert_eq!(user.first_name.as_deref(), Some("Ada")); + assert_eq!(user.account_owner, Some(true)); +} + +#[test] +fn a_checkout_extension_session_token_verifies_on_its_own_path() { + let app = ShopifyApp::new("client-id", "client-secret"); + let now = now(); + // As a checkout UI extension sends it: `dest` without `https://`, no `iss`, a customer. + let bearer = app.sign_session_token(&json!({ + "dest": "store-name.myshopify.com", + "aud": "client-id", + "exp": now + 60, + "nbf": now, + "iat": now, + "jti": "6c992878-dbaf-48d1-bb9d-6d9b59814fd1", + "sub": "gid://shopify/Customer/1", + })); + let session = app.verify_extension_session_token(&bearer).unwrap(); + assert_eq!(session.shop().as_str(), "store-name.myshopify.com"); + assert_eq!(session.customer(), Some("gid://shopify/Customer/1")); + assert!(app.verify_session_token(&bearer).is_err()); + + // A bare handle, or another host, is still not a shop. + for dest in ["store-name", "store-name.example.com", "https://store-name"] { + let bearer = + app.sign_session_token(&json!({ "dest": dest, "aud": "client-id", "exp": now + 60 })); + assert!( + app.verify_extension_session_token(&bearer).is_err(), + "{dest}" + ); + } +} + +/// The reproduction of the review of 1.0: the token any buyer gets from +/// `shopify.sessionToken.get()` in a checkout UI extension (no `iss`, no `sid`, +/// no `sub`, `dest` without `https://`) must not pass as an admin session, +/// which an app trusts to load the stored offline token of `shop()`. +#[test] +fn a_buyer_checkout_token_is_not_an_admin_session() { + let app = ShopifyApp::new("client-id", "client-secret"); + let now = now(); + let checkout = app.sign_session_token(&json!({ + "dest": "victim.myshopify.com", "aud": "client-id", "exp": now + 300, "nbf": now - 1, + "iat": now, "jti": "x" + })); + assert_eq!( + app.verify_session_token(&checkout).unwrap_err().to_string(), + "verification failed: the `dest` of the session token is not the admin of a shop" + ); + let extension = app.verify_extension_session_token(&checkout).unwrap(); + assert_eq!(extension.shop().as_str(), "victim.myshopify.com"); + assert_eq!(extension.customer(), None); + + // With `https://` added to `dest`, it still has no `iss`. + let checkout = app.sign_session_token(&json!({ + "dest": "https://victim.myshopify.com", "aud": "client-id", "exp": now + 300, + })); + assert!(app.verify_session_token(&checkout).is_err()); + + // The admin token of the same shop verifies on both paths. + let admin = app.sign_session_token(&json!({ + "iss": "https://victim.myshopify.com/admin", "dest": "https://victim.myshopify.com", + "aud": "client-id", "sub": "42", "sid": "s", "exp": now + 60, "nbf": now - 1 + })); + let session = app.verify_session_token(&admin).unwrap(); + assert_eq!(session.shop().as_str(), "victim.myshopify.com"); + assert_eq!(session.user_id(), Some("42")); + assert_eq!(session.session_id(), Some("s")); +} + +/// `iss` was compared as a prefix: a host that starts with the shop's passed. +#[test] +fn an_issuer_that_only_starts_with_the_shop_is_refused() { + let app = ShopifyApp::new("client-id", "client-secret"); + let now = now(); + let token = app.sign_session_token(&json!({ + "iss": "https://s.myshopify.com.evil.example/admin", "dest": "https://s.myshopify.com", + "aud": "client-id", "exp": now + 60, + })); + assert!(app.verify_session_token(&token).is_err()); + assert!(app.verify_extension_session_token(&token).is_err()); +} + +#[derive(Default, Clone)] +struct Saved(std::sync::Arc>>); + +impl shopify_api::TokenStore for Saved { + fn save<'a>( + &'a self, + shop: &'a shopify_api::ShopDomain, + token: &'a shopify_api::TokenData, + ) -> shopify_api::transport::BoxFuture<'a, Result<(), Box>> + { + Box::pin(async move { + self.0 + .lock() + .unwrap() + .push((shop.to_string(), token.clone())); + Ok(()) + }) + } +} + +#[tokio::test] +async fn the_clients_of_an_app_save_their_renewed_tokens() { + let mock = MockTransport::new(); + mock.push_json( + json!({ "access_token": "shpat_2", "expires_in": 3600, "refresh_token": "shprt_2" }), + ); + mock.push_data(json!({ "shop": { "name": "My shop" } })); + let saved = Saved::default(); + let app = app(&mock).with_token_store(saved.clone()); + + let mut token = shopify_api::TokenData::new("shpat_1"); + token.expires_at = Some(chrono::Utc::now()); + token.refresh_token = Some("shprt_1".to_string()); + let shop = shopify_api::ShopDomain::new("my-shop").unwrap(); + let shopify = app.client(&shop, token).unwrap(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + + let saved = saved.0.lock().unwrap(); + assert_eq!(saved.len(), 1); + assert_eq!(saved[0].0, "my-shop.myshopify.com"); + assert_eq!(saved[0].1.refresh_token.as_deref(), Some("shprt_2")); +} + +#[tokio::test] +async fn a_refused_code_exchange_has_its_status_and_code() { + let mock = MockTransport::new(); + mock.push(HttpResponse::json( + 400, + &json!({ "error": "invalid_request", "error_description": "The authorization code was not found or was already used" }), + )); + let app = app(&mock); + let query = format!( + "code=abc&shop=my-shop.myshopify.com&state=s1×tamp={}", + now() + ); + let signature = app.sign_query(&query).unwrap(); + let callback = app + .verify_query(&format!("{query}&hmac={signature}")) + .unwrap(); + + let error = app.exchange_code(&callback).await.unwrap_err(); + assert_eq!( + error.to_string(), + "authentication failed: the token endpoint of my-shop.myshopify.com answered 400 (invalid_request)" + ); + assert!(matches!( + error, + Error::Auth { + status: Some(400), + oauth_code: Some(OAuthErrorCode::InvalidRequest), + held: false, + .. + } + )); +} + +#[tokio::test] +async fn a_refused_token_exchange_has_its_status_and_code() { + for (status, body, code) in [ + ( + 400, + r#"{"error": "invalid_subject_token"}"#, + Some(OAuthErrorCode::InvalidSubjectToken), + ), + (502, "Bad Gateway", None), + ] { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(status, body.to_string())); + let app = app(&mock); + let now = now(); + let bearer = app.sign_session_token(&json!({ + "iss": "https://my-shop.myshopify.com/admin", + "dest": "https://my-shop.myshopify.com", + "aud": "client-id", + "sub": "42", + "exp": now + 60, + "nbf": now, + })); + let session = app.verify_session_token(&bearer).unwrap(); + + let error = app + .exchange_session_token(&session, RequestedToken::Offline) + .await + .unwrap_err(); + assert_eq!(error.token_endpoint_status(), Some(status), "{error:?}"); + assert_eq!(error.oauth_code(), code); + assert!(!error.is_held_auth_failure()); + } +} diff --git a/crates/shopify_api/tests/pagination.rs b/crates/shopify_api/tests/pagination.rs new file mode 100644 index 0000000..8f354eb --- /dev/null +++ b/crates/shopify_api/tests/pagination.rs @@ -0,0 +1,99 @@ +//! Cursor pagination with typed operations. +#![cfg(feature = "testing")] + +use serde_json::json; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::{Page, graphql}; + +#[tokio::test] +async fn collects_every_page_following_the_cursor() { + let mock = MockTransport::new(); + for (ids, next, cursor) in [ + (vec![1, 2], true, Some("c2")), + (vec![3, 4], true, Some("c4")), + (vec![5], false, None), + ] { + let nodes: Vec<_> = ids + .iter() + .map(|id| json!({ "id": format!("gid://shopify/Product/{id}"), "title": format!("P{id}") })) + .collect(); + mock.push_data(json!({ "products": { + "nodes": nodes, + "pageInfo": { "hasNextPage": next, "endCursor": cursor }, + } })); + } + let shopify = client(&mock); + + let products = shopify + .paginate( + |after| { + graphql!( + "query Products($after: String) { + products(first: 2, after: $after) { + nodes { id title } + pageInfo { hasNextPage endCursor } + } + }", + after = after, + ) + }, + |data| { + let page_info = data.products.page_info; + Page::new( + data.products.nodes, + page_info.has_next_page, + page_info.end_cursor, + ) + }, + ) + .await + .unwrap(); + + let titles: Vec<&str> = products + .iter() + .map(|product| product.title.as_str()) + .collect(); + assert_eq!(titles, ["P1", "P2", "P3", "P4", "P5"]); + let cursors: Vec<_> = mock + .graphql_requests() + .into_iter() + .map(|request| request.variables.get("after").cloned()) + .collect(); + assert_eq!( + cursors, + [Some(json!(null)), Some(json!("c2")), Some(json!("c4"))] + ); +} + +#[tokio::test] +async fn a_cursor_that_does_not_move_stops_the_loop() { + let mock = MockTransport::new(); + mock.respond_with(|_| { + Ok(shopify_api::transport::HttpResponse::json( + 200, + &json!({ "data": { "products": { "nodes": [], "pageInfo": { "hasNextPage": true, "endCursor": "same" } } } }), + )) + }); + let shopify = client(&mock); + + let error = shopify + .paginate( + |after| { + graphql!( + "query($after: String) { products(first: 2, after: $after) { nodes { id } pageInfo { hasNextPage endCursor } } }", + after = after, + ) + }, + |data| { + let page_info = data.products.page_info; + Page::new(data.products.nodes, page_info.has_next_page, page_info.end_cursor) + }, + ) + .await + .unwrap_err(); + assert!( + error.to_string().contains("the cursor does not move"), + "{error}" + ); + assert_eq!(mock.requests().len(), 2); +} diff --git a/crates/shopify_api/tests/retry.rs b/crates/shopify_api/tests/retry.rs new file mode 100644 index 0000000..e10f70c --- /dev/null +++ b/crates/shopify_api/tests/retry.rs @@ -0,0 +1,299 @@ +//! What the client sends again, and what it does not. +#![cfg(feature = "testing")] + +use std::time::Duration; + +use serde_json::json; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::transport::{HttpResponse, TransportError}; +use shopify_api::{Error, RetryPolicy, Shopify}; + +fn shop() -> serde_json::Value { + json!({ "shop": { "name": "x" } }) +} + +#[tokio::test] +async fn a_throttled_request_is_sent_again() { + let mock = MockTransport::new(); + mock.push_throttled().push_throttled().push_data(shop()); + let shopify = client(&mock); + + let data = shopify + .execute(shopify_api::graphql!("{ shop { name } }")) + .await + .unwrap(); + assert_eq!(data.shop.name, "x"); + assert_eq!(mock.requests().len(), 3); +} + +#[tokio::test(start_paused = true)] +async fn a_throttled_request_waits_for_its_cost() { + let mock = MockTransport::new(); + // 10 requested, 0 available, 100 per second: 0.1 s, and a little more. + mock.push_throttled().push_data(shop()); + let shopify = Shopify::builder("test-shop") + .access_token("t") + .transport(mock.clone()) + .build() + .unwrap(); + + let started = tokio::time::Instant::now(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(started.elapsed(), Duration::from_millis(200)); +} + +#[tokio::test] +async fn throttling_that_lasts_ends_in_an_error_with_the_cost() { + let mock = MockTransport::new(); + for _ in 0..5 { + mock.push_throttled(); + } + let shopify = client(&mock); + + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + let Error::Throttled { retries, cost, .. } = error else { + panic!("throttled: {error:?}"); + }; + assert_eq!(retries, 4); + assert_eq!(cost.unwrap().requested_query_cost, 10.0); + assert_eq!(mock.requests().len(), 5); +} + +#[tokio::test(start_paused = true)] +async fn a_429_waits_for_its_retry_after() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "2.0")) + .push_data(shop()); + let shopify = Shopify::builder("test-shop") + .access_token("t") + .transport(mock.clone()) + .build() + .unwrap(); + + let started = tokio::time::Instant::now(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(started.elapsed(), Duration::from_secs(2)); +} + +#[tokio::test] +async fn a_query_is_sent_again_after_a_server_error_or_a_network_failure() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(502, "Bad Gateway")) + .push_error(TransportError::timeout("timed out")) + .push_data(shop()); + let shopify = client(&mock); + + shopify + .graphql("query { shop { name } }", ()) + .await + .unwrap(); + assert_eq!(mock.requests().len(), 3); +} + +#[tokio::test] +async fn a_mutation_is_not_sent_again_when_it_may_have_run() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(502, "Bad Gateway")); + let shopify = client(&mock); + + let mutation = "mutation { tagsAdd(id: \"gid://shopify/Order/1\", tags: [\"a\"]) { userErrors { message } } }"; + let error = shopify.graphql(mutation, ()).await.unwrap_err(); + assert_eq!(error.status(), Some(502)); + assert_eq!(mock.requests().len(), 1); + + mock.clear(); + mock.push_error(TransportError::new("connection reset")); + let error = shopify.graphql(mutation, ()).await.unwrap_err(); + assert!(matches!(error, Error::Transport { .. }), "{error:?}"); + assert_eq!(mock.requests().len(), 1); + + // A throttled mutation did not run: it goes again. + mock.clear(); + mock.push_throttled() + .push_data(json!({ "tagsAdd": { "userErrors": [] } })); + shopify.graphql(mutation, ()).await.unwrap(); + assert_eq!(mock.requests().len(), 2); +} + +#[tokio::test] +async fn no_retry_policy_sends_once() { + let mock = MockTransport::new(); + mock.push_throttled(); + let shopify = client(&mock).with_retry(RetryPolicy::none()); + + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!( + matches!(error, Error::Throttled { retries: 0, .. }), + "{error:?}" + ); + assert_eq!(mock.requests().len(), 1); +} + +#[tokio::test] +async fn waits_shopify_cannot_mean_do_not_panic() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "-5")) + .push_json(json!({ + "errors": [{ "message": "Throttled", "extensions": { "code": "THROTTLED" } }], + "extensions": { "cost": { + "requestedQueryCost": 10, + "throttleStatus": { "maximumAvailable": 2000.0, "currentlyAvailable": 0, "restoreRate": 1e-320 }, + } }, + })) + .push_data(shop()); + let shopify = client(&mock); + + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(mock.requests().len(), 3); + + // Too long to wait for: the caller gets it. + mock.clear(); + mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "1e300")); + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!( + matches!( + error, + Error::Throttled { + retry_after: Some(Duration::MAX), + .. + } + ), + "{error:?}" + ); +} + +/// `max_delay` caps the backoff the client computes, not the wait Shopify asks for. +#[tokio::test(start_paused = true)] +async fn a_429_waits_for_a_retry_after_longer_than_the_longest_backoff() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "120")) + .push_data(shop()); + let shopify = Shopify::builder("test-shop") + .access_token("t") + .transport(mock.clone()) + .build() + .unwrap(); + + let started = tokio::time::Instant::now(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(started.elapsed(), Duration::from_secs(120)); + assert_eq!(mock.requests().len(), 2); +} + +/// A wait longer than `max_retry_after` is not slept through: the caller gets it. +#[tokio::test(start_paused = true)] +async fn a_retry_after_beyond_the_limit_is_returned_as_a_throttle_error() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "600")); + let shopify = Shopify::builder("test-shop") + .access_token("t") + .transport(mock.clone()) + .retry(RetryPolicy::new(4).with_max_retry_after(Duration::from_secs(300))) + .build() + .unwrap(); + + let started = tokio::time::Instant::now(); + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert_eq!(started.elapsed(), Duration::ZERO); + let Error::Throttled { + retries, + retry_after, + .. + } = error + else { + panic!("throttled: {error:?}"); + }; + assert_eq!(retries, 0); + assert_eq!(retry_after, Some(Duration::from_secs(600))); + assert_eq!(mock.requests().len(), 1); +} + +/// A comment that ends with a bare `\r` still hides nothing: the mutation +/// after it is sent once. +#[tokio::test] +async fn a_mutation_after_a_comment_ended_by_a_carriage_return_is_not_sent_again() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(502, "Bad Gateway")) + .push_data(json!({ "tagsAdd": { "userErrors": [] } })); + let shopify = client(&mock); + + let mutation = "# comment\rmutation { tagsAdd(id: \"gid://shopify/Order/1\", tags: [\"a\"]) { userErrors { message } } }"; + let error = shopify.graphql(mutation, ()).await.unwrap_err(); + assert_eq!(error.status(), Some(502)); + assert_eq!(mock.requests().len(), 1); +} + +/// The test client retries a `429` at once, whatever its `Retry-After`; one +/// beyond the limit still ends in an error. +#[tokio::test(start_paused = true)] +async fn the_test_client_does_not_wait_for_a_retry_after() { + let mock = MockTransport::new(); + mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "300")) + .push_data(shop()); + let shopify = client(&mock); + + let started = tokio::time::Instant::now(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(started.elapsed(), Duration::ZERO); + assert_eq!(mock.requests().len(), 2); + + mock.clear(); + mock.push(HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", "301")); + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!( + matches!(error, Error::Throttled { retry_after: Some(wait), .. } if wait == Duration::from_secs(301)), + "{error:?}" + ); + assert_eq!(started.elapsed(), Duration::ZERO); +} + +fn http_date_in(seconds: i64) -> String { + (chrono::Utc::now() + chrono::Duration::seconds(seconds)) + .format("%a, %d %b %Y %H:%M:%S GMT") + .to_string() +} + +/// A `Retry-After` may be an HTTP date: the client waits until then. +#[tokio::test(start_paused = true)] +async fn a_429_waits_until_its_retry_after_date() { + let mock = MockTransport::new(); + mock.push( + HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", http_date_in(120)), + ) + .push_data(shop()); + let shopify = Shopify::builder("test-shop") + .access_token("t") + .transport(mock.clone()) + .build() + .unwrap(); + + let started = tokio::time::Instant::now(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + // The date has whole seconds: up to one less than asked. + let elapsed = started.elapsed(); + assert!( + elapsed > Duration::from_secs(118) && elapsed <= Duration::from_secs(120), + "{elapsed:?}" + ); + + // Past: sent again at once. Beyond `max_retry_after`: the caller gets it. + mock.clear(); + mock.push( + HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", http_date_in(-60)), + ) + .push_data(shop()); + let started = tokio::time::Instant::now(); + shopify.graphql("{ shop { name } }", ()).await.unwrap(); + assert_eq!(started.elapsed(), Duration::ZERO); + + mock.clear(); + mock.push( + HttpResponse::new(429, "Too Many Requests").with_header("Retry-After", http_date_in(600)), + ); + let error = shopify.graphql("{ shop { name } }", ()).await.unwrap_err(); + assert!( + matches!(error, Error::Throttled { retry_after: Some(wait), .. } if wait > Duration::from_secs(590)), + "{error:?}" + ); + assert_eq!(started.elapsed(), Duration::ZERO); +} diff --git a/crates/shopify_api/tests/schema_override.rs b/crates/shopify_api/tests/schema_override.rs new file mode 100644 index 0000000..4c3325b --- /dev/null +++ b/crates/shopify_api/tests/schema_override.rs @@ -0,0 +1,269 @@ +//! Which schema `graphql!` takes for a library of the workspace, with +//! `schema` in its `[package.metadata.shopify_api]`, across cargo commands +//! that share a target directory: cargo reuses a compiled crate whatever +//! command built it, so the schema must not depend on which one did, nor on +//! where the package is. +//! +//! Builds a small workspace with cargo, offline, in `CARGO_TARGET_TMPDIR`. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::{Mutex, MutexGuard}; + +/// Internal to this repository's tests: it would apply to the probes too. +const TEST_SCHEMA_ENV: &str = "SHOPIFY_API_INTERNAL_TEST_SCHEMA"; + +fn schema(version: &str) -> String { + format!( + r#"{{"format": 2, "apiVersion": "{version}", "query": "Q", "types": {{"Q": {{"o": {{"f": {{"f": "String"}}}}}}, "String": "s"}}}}"# + ) +} + +/// A workspace of `app`, which prints the API version of `library`, a path +/// dependency whose default schema file is 2026-04, and +/// `schemas/override.json` in it, of 2026-07, which the `schema` key of +/// `library` may name. An `override.json` outside the library, of 2026-07 +/// too, is one it may not name. +struct Workspace { + root: PathBuf, + target: PathBuf, + /// The tests share a target directory, where `cargo run` of one would + /// run the binary another just built. + _alone: MutexGuard<'static, ()>, +} + +impl Workspace { + fn new(name: &str) -> Self { + static ONE_AT_A_TIME: Mutex<()> = Mutex::new(()); + let alone = ONE_AT_A_TIME + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let tmp = Path::new(env!("CARGO_TARGET_TMPDIR")); + let root = tmp.join(name); + let _ = std::fs::remove_dir_all(&root); + let shopify_api = env!("CARGO_MANIFEST_DIR"); + let write = |path: &str, contents: &str| { + let path = root.join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, contents).unwrap(); + }; + write( + "Cargo.toml", + "[workspace]\nresolver = \"3\"\nmembers = [\"app\", \"library\"]\n", + ); + // The versions the workspace of shopify_api locks, all downloaded. + let lock = Path::new(shopify_api).join("../../Cargo.lock"); + write("Cargo.lock", &std::fs::read_to_string(lock).unwrap()); + write( + "app/Cargo.toml", + "[package]\nname = \"probe_app\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\ + [dependencies]\nprobe_library = { path = \"../library\" }\n", + ); + write( + "app/src/main.rs", + "fn main() { print!(\"{}\", probe_library::probe::API_VERSION); }\n", + ); + write( + "library/src/lib.rs", + "shopify_api::graphql! { pub mod probe = \"{ f }\"; }\n", + ); + write("library/graphql/admin.schema.json", &schema("2026-04")); + write("library/schemas/override.json", &schema("2026-07")); + write("override.json", &schema("2026-07")); + // Shared by the tests: later runs build only the probes again. + let target = tmp.join("schema_override_target"); + let workspace = Self { + root, + target, + _alone: alone, + }; + workspace.library_metadata(""); + workspace + } + + /// Writes the `Cargo.toml` of `library`, with these lines in its + /// `[package.metadata.shopify_api]`. + fn library_metadata(&self, lines: &str) { + let shopify_api = env!("CARGO_MANIFEST_DIR"); + let manifest = format!( + "[package]\nname = \"probe_library\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\ + [dependencies]\nshopify_api = {{ path = '{shopify_api}', default-features = false }}\n\ + [package.metadata.shopify_api]\n{lines}" + ); + std::fs::write(self.root.join("library/Cargo.toml"), manifest).unwrap(); + } + + fn with_override(&self) { + self.library_metadata("schema = \"schemas/override.json\"\n"); + } + + fn cargo(&self, args: &[&str]) -> Output { + self.cargo_with_test_schema(args, "") + } + + /// `cargo`, with the internal test variable set to `test_schema`. + fn cargo_with_test_schema(&self, args: &[&str], test_schema: &str) -> Output { + let mut command = Command::new(std::env::var_os("CARGO").unwrap_or("cargo".into())); + command + .args(args) + .arg("--offline") + .arg("--quiet") + .arg("--manifest-path") + .arg(self.root.join("Cargo.toml")) + .env("CARGO_TARGET_DIR", &self.target) + .env_remove("CARGO_PRIMARY_PACKAGE"); + // Empty is no file: the `[env]` of this repository's cargo config, + // which the probes are under, sets the variable only when it is unset. + command.env(TEST_SCHEMA_ENV, test_schema); + command.output().unwrap() + } + + fn succeed(&self, args: &[&str]) -> String { + let output = self.cargo(args); + assert!( + output.status.success(), + "cargo {args:?} failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() + } + + fn app_version(&self) -> String { + self.succeed(&["run", "-p", "probe_app"]) + } + + fn fail(&self, args: &[&str]) -> String { + let output = self.cargo(args); + let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + assert!(!output.status.success(), "cargo {args:?} succeeded"); + stderr + } + + fn touch_library(&self) { + let source = self.root.join("library/src/lib.rs"); + let mut text = std::fs::read_to_string(&source).unwrap(); + text.push('\n'); + std::fs::write(source, text).unwrap(); + } +} + +/// The key applies to the library whether cargo was asked to build it or +/// only the app, and in any order. An edit of `Cargo.toml` alone compiles +/// the library again. +#[test] +fn the_key_chooses_the_schema_whatever_cargo_built_first() { + let workspace = Workspace::new("key"); + workspace.with_override(); + workspace.succeed(&["build", "-p", "probe_library"]); + assert_eq!(workspace.app_version(), "2026-07"); + workspace.touch_library(); + assert_eq!(workspace.app_version(), "2026-07"); + // Without the key: the default file, though the library was built last + // with it, and as the package cargo was asked to build. + workspace.library_metadata(""); + assert_eq!(workspace.app_version(), "2026-04"); + workspace.succeed(&["build", "-p", "probe_library"]); + assert_eq!(workspace.app_version(), "2026-04"); + workspace.with_override(); + assert_eq!(workspace.app_version(), "2026-07"); + + // `api-version` is followed too: a pin the file does not hold is an + // error for a library built as a dependency, which never downloads. + workspace.library_metadata("api-version = \"2026-07\"\nschema = \"schemas/override.json\"\n"); + assert_eq!(workspace.app_version(), "2026-07"); + workspace.library_metadata("api-version = \"2026-10\"\nschema = \"schemas/override.json\"\n"); + let stderr = workspace.fail(&["run", "-p", "probe_app"]); + assert!( + stderr.contains("override.json` holds the Admin API 2026-07"), + "{stderr}" + ); + assert!(stderr.contains("shopify-api schema download"), "{stderr}"); +} + +/// A `.cargo-ok` above the workspace makes its packages look like a cargo +/// checkout. That changes nothing to the schema chosen: only a missing file +/// is then a compile error rather than a download. +#[test] +fn an_unrelated_cargo_ok_above_does_not_change_the_schema() { + let workspace = Workspace::new("cargo_ok_above"); + std::fs::write(workspace.root.join(".cargo-ok"), "not cargo's").unwrap(); + workspace.with_override(); + workspace.succeed(&["build", "-p", "probe_library"]); + assert_eq!(workspace.app_version(), "2026-07"); + workspace.library_metadata(""); + assert_eq!(workspace.app_version(), "2026-04"); + + std::fs::remove_file(workspace.root.join("library/graphql/admin.schema.json")).unwrap(); + let stderr = workspace.fail(&["build", "-p", "probe_library"]); + assert!(stderr.contains("admin.schema.json` is missing"), "{stderr}"); + assert!(stderr.contains("shopify-api schema download"), "{stderr}"); + assert!(!stderr.contains("cannot download"), "{stderr}"); +} + +/// A packaged library (a `Cargo.toml.orig` next to its `Cargo.toml`) takes +/// the file its key names too, even when cargo is asked to build it, and +/// never downloads one it lacks. +#[test] +fn a_packaged_library_takes_its_key_and_never_downloads() { + let workspace = Workspace::new("packaged_library"); + let library = workspace.root.join("library"); + workspace.with_override(); + std::fs::copy(library.join("Cargo.toml"), library.join("Cargo.toml.orig")).unwrap(); + workspace.succeed(&["build", "-p", "probe_library"]); + assert_eq!(workspace.app_version(), "2026-07"); + + std::fs::remove_file(library.join("schemas/override.json")).unwrap(); + let stderr = workspace.fail(&["build", "-p", "probe_library"]); + assert!(stderr.contains("override.json` is missing"), "{stderr}"); + assert!(!stderr.contains("cannot download"), "{stderr}"); +} + +/// A file outside the package is refused, though it exists: `cargo package` +/// would not ship it, and the packaged crate would look for it elsewhere. +#[test] +fn a_schema_outside_the_package_is_a_compile_error() { + let workspace = Workspace::new("outside"); + let absolute = workspace.root.join("override.json"); + // A literal string, as `library_metadata` writes the path of shopify_api. + let absolute = format!("'{}'", absolute.display()); + for path in [ + "\"../override.json\"", + "\"schemas/../../override.json\"", + "\"./D:/override.json\"", + &absolute, + ] { + workspace.library_metadata(&format!("schema = {path}\n")); + let stderr = workspace.fail(&["build", "-p", "probe_library"]); + assert!( + stderr.contains("must name a file inside the package"), + "{stderr}" + ); + assert!(stderr.contains("`cargo package` ships"), "{stderr}"); + } + workspace.library_metadata("schema = \"schemas/../schemas/override.json\"\n"); + assert_eq!(workspace.app_version(), "2026-07"); +} + +/// The internal test variable of this repository applies to `shopify_api` +/// and its `trybuild` projects only: a user's crate, here the library, +/// keeps its own schema, even when the variable names a file, or one that +/// does not exist. +#[test] +fn the_internal_test_schema_does_not_reach_other_packages() { + let workspace = Workspace::new("internal_test_schema"); + let elsewhere = workspace.root.join("override.json"); + for test_schema in [elsewhere.to_str().unwrap(), "missing.json"] { + workspace.touch_library(); + let output = workspace.cargo_with_test_schema(&["run", "-p", "probe_app"], test_schema); + assert!( + output.status.success(), + "{test_schema}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + String::from_utf8_lossy(&output.stdout), + "2026-04", + "{test_schema}" + ); + } +} diff --git a/crates/shopify_api/tests/ui/block_string_unicode_indent.rs b/crates/shopify_api/tests/ui/block_string_unicode_indent.rs new file mode 100644 index 0000000..58321d9 --- /dev/null +++ b/crates/shopify_api/tests/ui/block_string_unicode_indent.rs @@ -0,0 +1,4 @@ +fn main() { + // Lines indented with U+00A0 (two bytes) and U+2003 (three bytes): `graphql-parser` would panic. + let _ = shopify_api::graphql!("query { products(first: 1, query: \"\"\"\n\u{a0}a\n\u{2003}b\"\"\") { nodes { id } } }"); +} diff --git a/crates/shopify_api/tests/ui/block_string_unicode_indent.stderr b/crates/shopify_api/tests/ui/block_string_unicode_indent.stderr new file mode 100644 index 0000000..ec67528 --- /dev/null +++ b/crates/shopify_api/tests/ui/block_string_unicode_indent.stderr @@ -0,0 +1,6 @@ +error: This block string indents its lines with different Unicode whitespace, which the GraphQL parser this crate uses cannot read. Indent it with spaces or tabs, or write it as a quoted string (line 1, column 35) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/block_string_unicode_indent.rs:3:35 + | +3 | let _ = shopify_api::graphql!("query { products(first: 1, query: \"\"\"\n\u{a0}a\n\u{2003}b\"\"\") { nodes { id } } }"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_aliased_id.rs b/crates/shopify_api/tests/ui/bulk_aliased_id.rs new file mode 100644 index 0000000..d9d9c4f --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_aliased_id.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { productId: id variants { edges { node { sku } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_aliased_id.stderr b/crates/shopify_api/tests/ui/bulk_aliased_id.stderr new file mode 100644 index 0000000..9c29362 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_aliased_id.stderr @@ -0,0 +1,6 @@ +error: The nodes of `products` have the nested connection `variants`: select their `id`, without an alias or a directive, in this `node { … }`. Shopify refuses the query otherwise, and places each nested line under its parent by that `id` (line 1, column 22) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_aliased_id.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { productId: id variants { edges { node { sku } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_block_string_unicode_indent.rs b/crates/shopify_api/tests/ui/bulk_block_string_unicode_indent.rs new file mode 100644 index 0000000..49a4649 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_block_string_unicode_indent.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products(query: \"\"\"\n\u{a0}a\n\u{2003}b\"\"\") { edges { node { id } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_block_string_unicode_indent.stderr b/crates/shopify_api/tests/ui/bulk_block_string_unicode_indent.stderr new file mode 100644 index 0000000..ef7b62d --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_block_string_unicode_indent.stderr @@ -0,0 +1,6 @@ +error: This block string indents its lines with different Unicode whitespace, which the GraphQL parser this crate uses cannot read. Indent it with spaces or tabs, or write it as a quoted string (line 1, column 19) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_block_string_unicode_indent.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products(query: \"\"\"\n\u{a0}a\n\u{2003}b\"\"\") { edges { node { id } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_connection_in_fragment.rs b/crates/shopify_api/tests/ui/bulk_connection_in_fragment.rs new file mode 100644 index 0000000..8eb1bbc --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_in_fragment.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id ... on Product { variants { edges { node { sku } } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_connection_in_fragment.stderr b/crates/shopify_api/tests/ui/bulk_connection_in_fragment.stderr new file mode 100644 index 0000000..73e85ab --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_in_fragment.stderr @@ -0,0 +1,6 @@ +error: The connection `variants` is inside a fragment: in a bulk query, a nested connection is written right in the `node { … }` of its parent connection (line 1, column 49) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_connection_in_fragment.rs:2:40 + | +2 | ...i::graphql!(bulk("{ products { edges { node { id ... on Product { variants { edges { node { sku } } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_connection_nodes.rs b/crates/shopify_api/tests/ui/bulk_connection_nodes.rs new file mode 100644 index 0000000..7548595 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_nodes.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { nodes { id } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_connection_nodes.stderr b/crates/shopify_api/tests/ui/bulk_connection_nodes.stderr new file mode 100644 index 0000000..2004eef --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_nodes.stderr @@ -0,0 +1,6 @@ +error: A connection of a bulk query selects `edges { node { … } }` and nothing else, as Shopify documents it (`products`): Shopify does not document `nodes` for bulk queries (line 1, column 14) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_connection_nodes.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { nodes { id } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_connection_page_info.rs b/crates/shopify_api/tests/ui/bulk_connection_page_info.rs new file mode 100644 index 0000000..1e43a22 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_page_info.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id } } pageInfo { hasNextPage } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_connection_page_info.stderr b/crates/shopify_api/tests/ui/bulk_connection_page_info.stderr new file mode 100644 index 0000000..eeb4e93 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_page_info.stderr @@ -0,0 +1,6 @@ +error: A connection of a bulk query selects `edges { node { … } }` and nothing else, as Shopify documents it (`products`): `pageInfo` is refused beside `edges` (line 1, column 36) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_connection_page_info.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { id } } pageInfo { hasNextPage } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_connection_under_object.rs b/crates/shopify_api/tests/ui/bulk_connection_under_object.rs new file mode 100644 index 0000000..4721a72 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_under_object.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ orders { edges { node { id customer { orders { edges { node { id } } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_connection_under_object.stderr b/crates/shopify_api/tests/ui/bulk_connection_under_object.stderr new file mode 100644 index 0000000..6e1095c --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_connection_under_object.stderr @@ -0,0 +1,6 @@ +error: The connection `orders` is under `customer`, which is not a connection: in a bulk query, a nested connection is written right in the `node { … }` of its parent connection (line 1, column 41) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_connection_under_object.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ orders { edges { node { id customer { orders { edges { node { id } } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_enum_value.rs b/crates/shopify_api/tests/ui/bulk_enum_value.rs new file mode 100644 index 0000000..bc3ea71 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_enum_value.rs @@ -0,0 +1,6 @@ +fn main() { + let _ = shopify_api::graphql!( + bulk("query($sort: ProductSortKeys) { products(sortKey: $sort) { edges { node { id } } } }"), + sort = TITEL, + ); +} diff --git a/crates/shopify_api/tests/ui/bulk_enum_value.stderr b/crates/shopify_api/tests/ui/bulk_enum_value.stderr new file mode 100644 index 0000000..743dc31 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_enum_value.stderr @@ -0,0 +1,6 @@ +error: `TITEL` is not a value of the enum `ProductSortKeys` (did you mean `TITLE`?): `$sort` takes `CREATED_AT`, `ID`, `INVENTORY_TOTAL`, `PRODUCT_TYPE`, `PUBLISHED_AT`, `RELEVANCE`, `TITLE`, `UPDATED_AT` or `VENDOR` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_enum_value.rs:4:16 + | +4 | sort = TITEL, + | ^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_form.rs b/crates/shopify_api/tests/ui/bulk_form.rs new file mode 100644 index 0000000..a1baa70 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_form.rs @@ -0,0 +1,5 @@ +shopify_api::graphql! { + mod nested = bulk(bulk("{ products { edges { node { id } } } }")); +} + +fn main() {} diff --git a/crates/shopify_api/tests/ui/bulk_form.stderr b/crates/shopify_api/tests/ui/bulk_form.stderr new file mode 100644 index 0000000..ddd5133 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_form.stderr @@ -0,0 +1,5 @@ +error: `bulk(…)` takes the operation as a string literal or `file("path.graphql")` + --> tests/ui/bulk_form.rs:2:23 + | +2 | mod nested = bulk(bulk("{ products { edges { node { id } } } }")); + | ^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_id_alias_beside_connection.rs b/crates/shopify_api/tests/ui/bulk_id_alias_beside_connection.rs new file mode 100644 index 0000000..a36ef88 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_id_alias_beside_connection.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id: handle variants { edges { node { sku } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_id_alias_beside_connection.stderr b/crates/shopify_api/tests/ui/bulk_id_alias_beside_connection.stderr new file mode 100644 index 0000000..aefdad4 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_id_alias_beside_connection.stderr @@ -0,0 +1,6 @@ +error: `id: handle` is refused on the nodes of `products`, which have the nested connection `variants`: each nested line is placed under its parent by the `id` of that parent. Give `handle` another alias (line 1, column 29) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_id_alias_beside_connection.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { id: handle variants { edges { node { sku } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_missing_id.rs b/crates/shopify_api/tests/ui/bulk_missing_id.rs new file mode 100644 index 0000000..37da153 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_missing_id.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { title variants { edges { node { sku } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_missing_id.stderr b/crates/shopify_api/tests/ui/bulk_missing_id.stderr new file mode 100644 index 0000000..d0bc03e --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_missing_id.stderr @@ -0,0 +1,6 @@ +error: The nodes of `products` have the nested connection `variants`: select their `id`, without an alias or a directive, in this `node { … }`. Shopify refuses the query otherwise, and places each nested line under its parent by that `id` (line 1, column 22) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_missing_id.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { title variants { edges { node { sku } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_mutation_of_a_bulk_operation.rs b/crates/shopify_api/tests/ui/bulk_mutation_of_a_bulk_operation.rs new file mode 100644 index 0000000..f6a6296 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_mutation_of_a_bulk_operation.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("mutation { bulkOperationRunQuery(query: \"{ shop { name } }\", groupObjects: false) { userErrors { message } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_mutation_of_a_bulk_operation.stderr b/crates/shopify_api/tests/ui/bulk_mutation_of_a_bulk_operation.stderr new file mode 100644 index 0000000..d435856 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_mutation_of_a_bulk_operation.stderr @@ -0,0 +1,6 @@ +error: Shopify does not run `bulkOperationRunQuery` in a bulk mutation (line 1, column 12) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_mutation_of_a_bulk_operation.rs:2:40 + | +2 | ...l!(bulk("mutation { bulkOperationRunQuery(query: \"{ shop { name } }\", groupObjects: false) { userErrors { message } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_mutation_two_fields.rs b/crates/shopify_api/tests/ui/bulk_mutation_two_fields.rs new file mode 100644 index 0000000..2e1932e --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_mutation_two_fields.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("mutation { a: tagsAdd(id: \"gid://shopify/Product/1\", tags: [\"x\"]) { userErrors { message } } b: tagsAdd(id: \"gid://shopify/Product/2\", tags: [\"x\"]) { userErrors { message } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_mutation_two_fields.stderr b/crates/shopify_api/tests/ui/bulk_mutation_two_fields.stderr new file mode 100644 index 0000000..4e26585 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_mutation_two_fields.stderr @@ -0,0 +1,6 @@ +error: A bulk mutation selects one top-level field: Shopify runs one per operation (line 1, column 94) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_mutation_two_fields.rs:2:40 + | +2 | ...lk("mutation { a: tagsAdd(id: \"gid://shopify/Product/1\", tags: [\"x\"]) { userErrors { message } } b: tagsAdd(id: \"gid://shopify/Product/2\", tags: [\"x\"]) { userErrors { message } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_not_node.rs b/crates/shopify_api/tests/ui/bulk_not_node.rs new file mode 100644 index 0000000..55dd0a6 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_not_node.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ deletionEvents { edges { node { occurredAt } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_not_node.stderr b/crates/shopify_api/tests/ui/bulk_not_node.stderr new file mode 100644 index 0000000..d3f0165 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_not_node.stderr @@ -0,0 +1,6 @@ +error: Shopify bulk queries read connections of `Node` objects: the nodes of `deletionEvents`, `DeletionEvent`, do not all implement `Node` (line 1, column 3) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_not_node.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ deletionEvents { edges { node { occurredAt } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_pagination_argument.rs b/crates/shopify_api/tests/ui/bulk_pagination_argument.rs new file mode 100644 index 0000000..8c866b8 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_pagination_argument.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products(first: 10) { edges { node { id } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_pagination_argument.stderr b/crates/shopify_api/tests/ui/bulk_pagination_argument.stderr new file mode 100644 index 0000000..dd6c91c --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_pagination_argument.stderr @@ -0,0 +1,6 @@ +error: Shopify ignores `first` in a bulk query and returns every object of `products`: remove it (line 1, column 3) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_pagination_argument.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products(first: 10) { edges { node { id } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_reserved_alias.rs b/crates/shopify_api/tests/ui/bulk_reserved_alias.rs new file mode 100644 index 0000000..4ac3d1c --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_reserved_alias.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { __parentId: id } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_reserved_alias.stderr b/crates/shopify_api/tests/ui/bulk_reserved_alias.stderr new file mode 100644 index 0000000..32e71ed --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_reserved_alias.stderr @@ -0,0 +1,6 @@ +error: `__parentId` cannot be an alias in a bulk query: the lines of its results hold `__parentId`, and `_shopifyApiTypename` where this crate selects `__typename` to place them (line 1, column 29) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_reserved_alias.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { __parentId: id } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_reserved_alias_top_level.rs b/crates/shopify_api/tests/ui/bulk_reserved_alias_top_level.rs new file mode 100644 index 0000000..fa5eb4a --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_reserved_alias_top_level.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ _shopifyApiTypename: products { edges { node { id } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_reserved_alias_top_level.stderr b/crates/shopify_api/tests/ui/bulk_reserved_alias_top_level.stderr new file mode 100644 index 0000000..186c9aa --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_reserved_alias_top_level.stderr @@ -0,0 +1,6 @@ +error: `_shopifyApiTypename` cannot be an alias in a bulk query: the lines of its results hold `__parentId`, and `_shopifyApiTypename` where this crate selects `__typename` to place them (line 1, column 3) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_reserved_alias_top_level.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ _shopifyApiTypename: products { edges { node { id } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_reserved_prefix_constant.rs b/crates/shopify_api/tests/ui/bulk_reserved_prefix_constant.rs new file mode 100644 index 0000000..96c1a91 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_reserved_prefix_constant.rs @@ -0,0 +1,7 @@ +// A constant named like a binding of the generated code: a compile error, not a change of meaning. +#![allow(non_upper_case_globals)] +const __shopify_api_parent: usize = 0; + +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id variants { edges { node { sku } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_reserved_prefix_constant.stderr b/crates/shopify_api/tests/ui/bulk_reserved_prefix_constant.stderr new file mode 100644 index 0000000..f95f7f8 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_reserved_prefix_constant.stderr @@ -0,0 +1,31 @@ +error[E0308]: mismatched types + --> tests/ui/bulk_reserved_prefix_constant.rs:6:13 + | +3 | const __shopify_api_parent: usize = 0; + | --------------------------------- constant defined here +... +6 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { id variants { edges { node { sku } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | expected `Option<(usize, usize)>`, found `usize` + | expected due to this + | `__shopify_api_parent` is interpreted as a constant, not a new binding + | + = note: expected enum `Option<(usize, usize)>` + found type `usize` + = note: this error originates in the macro `shopify_api::graphql` (in Nightly builds, run with -Z macro-backtrace for more info) +help: introduce a new binding instead + | +6 - let _ = shopify_api::graphql!(bulk("{ products { edges { node { id variants { edges { node { sku } } } } } } }")); +6 + let _ = other___shopify_api_parent; + | + +error[E0308]: mismatched types + --> tests/ui/bulk_reserved_prefix_constant.rs:6:13 + | +6 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { id variants { edges { node { sku } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `usize`, found `Option<_>` + | + = note: expected type `usize` + found enum `Option<_>` + = note: this error originates in the macro `shopify_api::graphql` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/bulk_same_type_siblings.rs b/crates/shopify_api/tests/ui/bulk_same_type_siblings.rs new file mode 100644 index 0000000..184f93b --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_same_type_siblings.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id custom: metafields(namespace: \"custom\") { edges { node { key } } } other: metafields(namespace: \"other\") { edges { node { key } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_same_type_siblings.stderr b/crates/shopify_api/tests/ui/bulk_same_type_siblings.stderr new file mode 100644 index 0000000..b11a692 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_same_type_siblings.stderr @@ -0,0 +1,6 @@ +error: `custom` and `other`, connections of each node of `products`, may both return `Metafield`: their lines in the results could not be told apart. Query one of them in another bulk query (line 1, column 99) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_same_type_siblings.rs:2:40 + | +2 | ...lk("{ products { edges { node { id custom: metafields(namespace: \"custom\") { edges { node { key } } } other: metafields(namespace: \"other\") { edges { node { key } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_start_not_a_query.rs b/crates/shopify_api/tests/ui/bulk_start_not_a_query.rs new file mode 100644 index 0000000..c057e9c --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_start_not_a_query.rs @@ -0,0 +1,8 @@ +// Anything but a bulk query text or a typed bulk query gets the message of +// `StartBulkQuery`, not one about `From`. +use shopify_api::{Auth, Shopify}; + +fn main() { + let shopify = Shopify::new("my-shop", Auth::access_token("shpat_x")).unwrap(); + let _ = shopify.start_bulk_query(42u32); +} diff --git a/crates/shopify_api/tests/ui/bulk_start_not_a_query.stderr b/crates/shopify_api/tests/ui/bulk_start_not_a_query.stderr new file mode 100644 index 0000000..cd0305d --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_start_not_a_query.stderr @@ -0,0 +1,31 @@ +error[E0277]: `u32` is not a bulk query to start + --> tests/ui/bulk_start_not_a_query.rs:7:21 + | +7 | let _ = shopify.start_bulk_query(42u32); + | ^^^^^^^^^^^^^^^^ ----- `u32` doesn't satisfy the trait bound + | | + | a `&str`, a `String`, `GroupObjects(…)`, or a `graphql!(bulk(…))` query or its `Variables` + | + = help: the trait `StartBulkQuery>` is not implemented for `u32` +help: the following other types implement trait `StartBulkQuery` + --> src/bulk.rs + | + | impl StartBulkQuery for &str {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&str` +... + | impl StartBulkQuery for String {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `String` +... + | impl StartBulkQuery for &String {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&String` +... + | impl> StartBulkQuery for GroupObjects {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `GroupObjects` +note: required by a bound in `bulk::::start_bulk_query` + --> src/bulk.rs + | + | pub async fn start_bulk_query( + | ---------------- required by a bound in this associated function + | &self, + | query: impl StartBulkQuery, + | ^^^^^^^^^^^^^^^^^ required by this bound in `bulk::::start_bulk_query` diff --git a/crates/shopify_api/tests/ui/bulk_string_escape.rs b/crates/shopify_api/tests/ui/bulk_string_escape.rs new file mode 100644 index 0000000..595d66f --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_string_escape.rs @@ -0,0 +1,4 @@ +fn main() { + // `graphql-parser` reads `\b` as U+0010, and the bulk text is written back from what it read. + let _ = shopify_api::graphql!(bulk(r#"{ products(query: "a\bb") { edges { node { id } } } }"#)); +} diff --git a/crates/shopify_api/tests/ui/bulk_string_escape.stderr b/crates/shopify_api/tests/ui/bulk_string_escape.stderr new file mode 100644 index 0000000..57ab65c --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_string_escape.stderr @@ -0,0 +1,6 @@ +error: This string would not reach Shopify as written: the GraphQL parser this crate uses reads it otherwise, and a bulk query is sent as the text it read. Write `\u0008` rather than `\b` (line 1, column 19) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_string_escape.rs:3:40 + | +3 | let _ = shopify_api::graphql!(bulk(r#"{ products(query: "a\bb") { edges { node { id } } } }"#)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_too_deep.rs b/crates/shopify_api/tests/ui/bulk_too_deep.rs new file mode 100644 index 0000000..5450f59 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_too_deep.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id collections { edges { node { id products { edges { node { id variants { edges { node { sku } } } } } } } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_too_deep.stderr b/crates/shopify_api/tests/ui/bulk_too_deep.stderr new file mode 100644 index 0000000..d0b3fae --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_too_deep.stderr @@ -0,0 +1,6 @@ +error: Connections nest 2 levels deep at most below the top-level one in a bulk query: `variants` is level 3 (line 1, column 93) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_too_deep.rs:2:40 + | +2 | ...lk("{ products { edges { node { id collections { edges { node { id products { edges { node { id variants { edges { node { sku } } } } } } } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_too_many_connections.rs b/crates/shopify_api/tests/ui/bulk_too_many_connections.rs new file mode 100644 index 0000000..495fdb9 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_too_many_connections.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id variants { edges { node { sku } } } media { edges { node { alt } } } collections { edges { node { title } } } metafields { edges { node { key } } } sellingPlanGroups { edges { node { name } } } } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_too_many_connections.stderr b/crates/shopify_api/tests/ui/bulk_too_many_connections.stderr new file mode 100644 index 0000000..4606112 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_too_many_connections.stderr @@ -0,0 +1,6 @@ +error: A bulk query has 5 connections at most: `sellingPlanGroups` is connection number 6 (line 1, column 180) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_too_many_connections.rs:2:40 + | +2 | ...lk("{ products { edges { node { id variants { edges { node { sku } } } media { edges { node { alt } } } collections { edges { node { title } } } metafields { edges { node { key } } } sellingPlanGroups { edges { node { name } } } } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_top_level_nodes.rs b/crates/shopify_api/tests/ui/bulk_top_level_nodes.rs new file mode 100644 index 0000000..8845660 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_top_level_nodes.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ nodes(ids: [\"gid://shopify/Product/1\"]) { id } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_top_level_nodes.stderr b/crates/shopify_api/tests/ui/bulk_top_level_nodes.stderr new file mode 100644 index 0000000..dab5718 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_top_level_nodes.stderr @@ -0,0 +1,6 @@ +error: `nodes` cannot be the top-level field of a bulk query: select a connection, such as `products` (line 1, column 3) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_top_level_nodes.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ nodes(ids: [\"gid://shopify/Product/1\"]) { id } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_top_level_not_a_connection.rs b/crates/shopify_api/tests/ui/bulk_top_level_not_a_connection.rs new file mode 100644 index 0000000..036aec0 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_top_level_not_a_connection.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ shop { name } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_top_level_not_a_connection.stderr b/crates/shopify_api/tests/ui/bulk_top_level_not_a_connection.stderr new file mode 100644 index 0000000..5c4bdad --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_top_level_not_a_connection.stderr @@ -0,0 +1,6 @@ +error: The top-level field of a bulk query is a connection: `shop` is `Shop!`. Run it as an ordinary query, or select a connection such as `products` (line 1, column 3) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_top_level_not_a_connection.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ shop { name } }")); + | ^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_two_top_level_fields.rs b/crates/shopify_api/tests/ui/bulk_two_top_level_fields.rs new file mode 100644 index 0000000..4ce3b50 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_two_top_level_fields.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { id } } } orders { edges { node { id } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_two_top_level_fields.stderr b/crates/shopify_api/tests/ui/bulk_two_top_level_fields.stderr new file mode 100644 index 0000000..ce50dea --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_two_top_level_fields.stderr @@ -0,0 +1,6 @@ +error: A bulk query selects one top-level field: Shopify runs one per operation (line 1, column 38) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_two_top_level_fields.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { id } } } orders { edges { node { id } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_typename_key.rs b/crates/shopify_api/tests/ui/bulk_typename_key.rs new file mode 100644 index 0000000..b33fc54 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_typename_key.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!(bulk("{ products { edges { node { _shopifyApiTypename: title } } } }")); +} diff --git a/crates/shopify_api/tests/ui/bulk_typename_key.stderr b/crates/shopify_api/tests/ui/bulk_typename_key.stderr new file mode 100644 index 0000000..54626dd --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_typename_key.stderr @@ -0,0 +1,6 @@ +error: `_shopifyApiTypename` cannot be an alias in a bulk query: the lines of its results hold `__parentId`, and `_shopifyApiTypename` where this crate selects `__typename` to place them (line 1, column 29) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/bulk_typename_key.rs:2:40 + | +2 | let _ = shopify_api::graphql!(bulk("{ products { edges { node { _shopifyApiTypename: title } } } }")); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/bulk_variable_unknown.rs b/crates/shopify_api/tests/ui/bulk_variable_unknown.rs new file mode 100644 index 0000000..ca92070 --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_variable_unknown.rs @@ -0,0 +1,6 @@ +fn main() { + let _ = shopify_api::graphql!( + bulk("query($q: String) { products(query: $q) { edges { node { id } } } }"), + filter = "x", + ); +} diff --git a/crates/shopify_api/tests/ui/bulk_variable_unknown.stderr b/crates/shopify_api/tests/ui/bulk_variable_unknown.stderr new file mode 100644 index 0000000..0289c9f --- /dev/null +++ b/crates/shopify_api/tests/ui/bulk_variable_unknown.stderr @@ -0,0 +1,5 @@ +error: The operation has no variable `$filter`: it declares $q + --> tests/ui/bulk_variable_unknown.rs:4:9 + | +4 | filter = "x", + | ^^^^^^ diff --git a/crates/shopify_api/tests/ui/crate_path_dollar_crate.rs b/crates/shopify_api/tests/ui/crate_path_dollar_crate.rs new file mode 100644 index 0000000..828f1b0 --- /dev/null +++ b/crates/shopify_api/tests/ui/crate_path_dollar_crate.rs @@ -0,0 +1,12 @@ +// `$crate` means nothing in the text serde's derive reads the path from. +pub use shopify_api as runtime; + +macro_rules! shop_id { + () => { + shopify_api::graphql!(crate = $crate::runtime, "{ shop { id } }") + }; +} + +fn main() { + let _ = shop_id!(); +} diff --git a/crates/shopify_api/tests/ui/crate_path_dollar_crate.stderr b/crates/shopify_api/tests/ui/crate_path_dollar_crate.stderr new file mode 100644 index 0000000..9381187 --- /dev/null +++ b/crates/shopify_api/tests/ui/crate_path_dollar_crate.stderr @@ -0,0 +1,10 @@ +error: `crate = $crate::…` cannot reach serde's derive: write the absolute path, `crate = ::my_framework::shopify_api` + --> tests/ui/crate_path_dollar_crate.rs:6:39 + | + 6 | shopify_api::graphql!(crate = $crate::runtime, "{ shop { id } }") + | ^^^^^^ +... +11 | let _ = shop_id!(); + | ---------- in this macro invocation + | + = note: this error originates in the macro `shop_id` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/deprecated_field_denied.rs b/crates/shopify_api/tests/ui/deprecated_field_denied.rs new file mode 100644 index 0000000..4d2ba36 --- /dev/null +++ b/crates/shopify_api/tests/ui/deprecated_field_denied.rs @@ -0,0 +1,5 @@ +#![deny(deprecated)] + +fn main() { + let _ = shopify_api::graphql!("{ product(id: \"gid://shopify/Product/1\") { bodyHtml } }"); +} diff --git a/crates/shopify_api/tests/ui/deprecated_field_denied.stderr b/crates/shopify_api/tests/ui/deprecated_field_denied.stderr new file mode 100644 index 0000000..7495888 --- /dev/null +++ b/crates/shopify_api/tests/ui/deprecated_field_denied.stderr @@ -0,0 +1,11 @@ +error: use of deprecated constant `main::_::SHOPIFY_DEPRECATION`: `Product.bodyHtml` is deprecated in the Shopify Admin API 2026-10: Use `descriptionHtml` instead. (line 1, column 44 of the operation) + --> tests/ui/deprecated_field_denied.rs:4:35 + | +4 | let _ = shopify_api::graphql!("{ product(id: \"gid://shopify/Product/1\") { bodyHtml } }"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: the lint level is defined here + --> tests/ui/deprecated_field_denied.rs:1:9 + | +1 | #![deny(deprecated)] + | ^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/input_unknown_type.rs b/crates/shopify_api/tests/ui/input_unknown_type.rs new file mode 100644 index 0000000..db0dd7a --- /dev/null +++ b/crates/shopify_api/tests/ui/input_unknown_type.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::input!(MetafieldSetInput { ownerId: "gid://shopify/Product/1", key: "color", value: "blue" }); +} diff --git a/crates/shopify_api/tests/ui/input_unknown_type.stderr b/crates/shopify_api/tests/ui/input_unknown_type.stderr new file mode 100644 index 0000000..dcdfd2e --- /dev/null +++ b/crates/shopify_api/tests/ui/input_unknown_type.stderr @@ -0,0 +1,6 @@ +error: The schema has no input object `MetafieldSetInput` (did you mean `MetafieldsSetInput`?) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/input_unknown_type.rs:2:33 + | +2 | let _ = shopify_api::input!(MetafieldSetInput { ownerId: "gid://shopify/Product/1", key: "color", value: "blue" }); + | ^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/integer_out_of_range.rs b/crates/shopify_api/tests/ui/integer_out_of_range.rs new file mode 100644 index 0000000..f5cdd9a --- /dev/null +++ b/crates/shopify_api/tests/ui/integer_out_of_range.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("{ products(first: 3000000000) { nodes { title } } }"); +} diff --git a/crates/shopify_api/tests/ui/integer_out_of_range.stderr b/crates/shopify_api/tests/ui/integer_out_of_range.stderr new file mode 100644 index 0000000..cf90e49 --- /dev/null +++ b/crates/shopify_api/tests/ui/integer_out_of_range.stderr @@ -0,0 +1,6 @@ +error: The integer is outside the range of `Int`, a 32-bit integer, given for argument `first` of `QueryRoot.products` (line 1, column 3) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/integer_out_of_range.rs:2:35 + | +2 | let _ = shopify_api::graphql!("{ products(first: 3000000000) { nodes { title } } }"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_deprecated_field_denied.rs b/crates/shopify_api/tests/ui/literal_deprecated_field_denied.rs new file mode 100644 index 0000000..d73b996 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_deprecated_field_denied.rs @@ -0,0 +1,5 @@ +#![deny(deprecated)] + +fn main() { + let _ = shopify_api::input!(ProductVariantsBulkInput { barcode: "1234", price: "10.00" }); +} diff --git a/crates/shopify_api/tests/ui/literal_deprecated_field_denied.stderr b/crates/shopify_api/tests/ui/literal_deprecated_field_denied.stderr new file mode 100644 index 0000000..b7ab067 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_deprecated_field_denied.stderr @@ -0,0 +1,11 @@ +error: use of deprecated constant `main::_::SHOPIFY_DEPRECATION`: `ProductVariantsBulkInput.barcode` is deprecated in the Shopify Admin API 2026-10: Use `barcodes` instead. + --> tests/ui/literal_deprecated_field_denied.rs:4:60 + | +4 | let _ = shopify_api::input!(ProductVariantsBulkInput { barcode: "1234", price: "10.00" }); + | ^^^^^^^ + | +note: the lint level is defined here + --> tests/ui/literal_deprecated_field_denied.rs:1:9 + | +1 | #![deny(deprecated)] + | ^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_duplicate_field.rs b/crates/shopify_api/tests/ui/literal_duplicate_field.rs new file mode 100644 index 0000000..696a451 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_duplicate_field.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", title: "Shirt", title: "Hat" }); +} diff --git a/crates/shopify_api/tests/ui/literal_duplicate_field.stderr b/crates/shopify_api/tests/ui/literal_duplicate_field.stderr new file mode 100644 index 0000000..eac21cd --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_duplicate_field.stderr @@ -0,0 +1,6 @@ +error: The field `title` of `ProductUpdateInput` is given twice + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_duplicate_field.rs:2:101 + | +2 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", title: "Shirt", title: "Hat" }); + | ^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_int_out_of_range.rs b/crates/shopify_api/tests/ui/literal_int_out_of_range.rs new file mode 100644 index 0000000..3940d7a --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_int_out_of_range.rs @@ -0,0 +1,7 @@ +fn main() { + let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: 2_147_483_648_i64 }); + let _ = shopify_api::graphql!( + "query($first: Int!) { products(first: $first) { nodes { id } } }", + first = -2_147_483_649, + ); +} diff --git a/crates/shopify_api/tests/ui/literal_int_out_of_range.stderr b/crates/shopify_api/tests/ui/literal_int_out_of_range.stderr new file mode 100644 index 0000000..fd01a4c --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_int_out_of_range.stderr @@ -0,0 +1,13 @@ +error: The integer is outside the range of `Int`, a 32-bit integer, given for `quantity` of `DraftOrderLineItemInput` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_int_out_of_range.rs:2:69 + | +2 | let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: 2_147_483_648_i64 }); + | ^^^^^^^^^^^^^^^^^ + +error: The integer is outside the range of `Int`, a 32-bit integer, given for `$first` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_int_out_of_range.rs:5:18 + | +5 | first = -2_147_483_649, + | ^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.rs b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.rs new file mode 100644 index 0000000..388b533 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.rs @@ -0,0 +1,7 @@ +use shopify_api::{Maybe, input}; + +fn main() { + let item = input!(InventoryTransferLineItemInput { inventoryItemId: "gid://shopify/InventoryItem/1", quantity: 2 }); + let line_items: Maybe> = Maybe::Value(vec![item]); + let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); +} diff --git a/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr new file mode 100644 index 0000000..509134e --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_maybe_non_null_with_default.stderr @@ -0,0 +1,26 @@ +error[E0277]: `lineItems` of `InventoryTransferCreateInput` is non-null (`[InventoryTransferLineItemInput!]!`): `lineItems?:` takes an `Option`, not a `Maybe`, whose `Null` it refuses + --> tests/ui/literal_maybe_non_null_with_default.rs:6:63 + | +6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); + | --------------------------------------------------^^^^^^^^^^--- + | | | + | | an `Option`: `None` leaves the field out + | required by a bound introduced by this call + | + = help: the trait `__ShopifyApiNoNull4_c2392f79` is not implemented for `Vec>` +help: this trait has no implementations, consider adding one + --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 + | +6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required for `Maybe>>` to implement `__ShopifyApiOptional4_c2392f79` + --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 + | +6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required by a bound in `Checks::build` + --> tests/ui/literal_maybe_non_null_with_default.rs:6:13 + | +6 | let _ = input!(InventoryTransferCreateInput { lineItems?: line_items }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` + = note: this error originates in the macro `input` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/literal_missing_required.rs b/crates/shopify_api/tests/ui/literal_missing_required.rs new file mode 100644 index 0000000..6367406 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_missing_required.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::input!(MetafieldsSetInput { ownerId: "gid://shopify/Product/1", namespace: "custom" }); +} diff --git a/crates/shopify_api/tests/ui/literal_missing_required.stderr b/crates/shopify_api/tests/ui/literal_missing_required.stderr new file mode 100644 index 0000000..b3b7e05 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_missing_required.stderr @@ -0,0 +1,6 @@ +error: Input object `MetafieldsSetInput` requires the fields `key: String!` and `value: String!`: add them + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_missing_required.rs:2:52 + | +2 | let _ = shopify_api::input!(MetafieldsSetInput { ownerId: "gid://shopify/Product/1", namespace: "custom" }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_null_on_non_null.rs b/crates/shopify_api/tests/ui/literal_null_on_non_null.rs new file mode 100644 index 0000000..07e0e94 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_null_on_non_null.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::input!(MetafieldsSetInput { ownerId: null, key: "color", value: "blue" }); +} diff --git a/crates/shopify_api/tests/ui/literal_null_on_non_null.stderr b/crates/shopify_api/tests/ui/literal_null_on_non_null.stderr new file mode 100644 index 0000000..fcc76b1 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_null_on_non_null.stderr @@ -0,0 +1,6 @@ +error: `null` is not allowed for `ownerId` of `MetafieldsSetInput`, of type `ID!` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_null_on_non_null.rs:2:63 + | +2 | let _ = shopify_api::input!(MetafieldsSetInput { ownerId: null, key: "color", value: "blue" }); + | ^^^^ diff --git a/crates/shopify_api/tests/ui/literal_object_for_scalar.rs b/crates/shopify_api/tests/ui/literal_object_for_scalar.rs new file mode 100644 index 0000000..ec3c703 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_object_for_scalar.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", title: { value: "Shirt" } }); +} diff --git a/crates/shopify_api/tests/ui/literal_object_for_scalar.stderr b/crates/shopify_api/tests/ui/literal_object_for_scalar.stderr new file mode 100644 index 0000000..cf47500 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_object_for_scalar.stderr @@ -0,0 +1,6 @@ +error: `title` of `ProductUpdateInput` expects a `String`, not an object + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_object_for_scalar.rs:2:92 + | +2 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", title: { value: "Shirt" } }); + | ^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_one_of.rs b/crates/shopify_api/tests/ui/literal_one_of.rs new file mode 100644 index 0000000..7ede229 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_one_of.rs @@ -0,0 +1,9 @@ +fn main() { + let handle: Option<&str> = Some("shirt"); + let _ = shopify_api::input!(ProductSetIdentifiers { id: "gid://shopify/Product/1", handle: "shirt" }); + let _ = shopify_api::input!(ProductSetIdentifiers {}); + let _ = shopify_api::input!(ProductSetIdentifiers { handle?: handle }); + let _ = shopify_api::input!(ProductSetIdentifiers { handle: null }); + let _ = shopify_api::input!(ProductSetIdentifiers { handle: handle }); + let _ = shopify_api::input!(ProductSetIdentifiers { handle: shopify_api::Maybe::<&str>::Null }); +} diff --git a/crates/shopify_api/tests/ui/literal_one_of.stderr b/crates/shopify_api/tests/ui/literal_one_of.stderr new file mode 100644 index 0000000..26bd76e --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_one_of.stderr @@ -0,0 +1,61 @@ +error: `ProductSetIdentifiers` is a oneOf input: give exactly one of `customId`, `handle` or `id`, not null: `id` is given already + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_one_of.rs:3:88 + | +3 | let _ = shopify_api::input!(ProductSetIdentifiers { id: "gid://shopify/Product/1", handle: "shirt" }); + | ^^^^^^ + +error: `ProductSetIdentifiers` is a oneOf input: give exactly one of `customId`, `handle` or `id`, not null + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_one_of.rs:4:55 + | +4 | let _ = shopify_api::input!(ProductSetIdentifiers {}); + | ^^ + +error: `ProductSetIdentifiers` is a oneOf input: give exactly one of `customId`, `handle` or `id`, not null: write `handle: …`, not `handle?:` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_one_of.rs:5:63 + | +5 | let _ = shopify_api::input!(ProductSetIdentifiers { handle?: handle }); + | ^ + +error: `ProductSetIdentifiers` is a oneOf input: give exactly one of `customId`, `handle` or `id`, not null: `handle: null` is not one + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_one_of.rs:6:65 + | +6 | let _ = shopify_api::input!(ProductSetIdentifiers { handle: null }); + | ^^^^ + +error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Option<&str>` + --> tests/ui/literal_one_of.rs:7:65 + | +7 | let _ = shopify_api::input!(ProductSetIdentifiers { handle: handle }); + | ^^^^^^ + | | + | `Option<&str>` doesn't satisfy the trait bound + | `String`, `&str`, `&String` or `Cow` + | + = help: the trait `main::__ShopifyApiExpect1_c23935b5` is not implemented for `Option<&str>` +note: required by a bound in `main::Checks::build` + --> tests/ui/literal_one_of.rs:7:13 + | +7 | let _ = shopify_api::input!(ProductSetIdentifiers { handle: handle }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `handle` of `ProductSetIdentifiers` expects a `String`, not `Maybe<&str>` + --> tests/ui/literal_one_of.rs:8:65 + | +8 | let _ = shopify_api::input!(ProductSetIdentifiers { handle: shopify_api::Maybe::<&str>::Null }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | `Maybe<&str>` doesn't satisfy the trait bound + | `String`, `&str`, `&String` or `Cow` + | + = help: the trait `main::__ShopifyApiExpect1_c23935b5` is not implemented for `Maybe<&str>` +note: required by a bound in `main::Checks::build` + --> tests/ui/literal_one_of.rs:8:13 + | +8 | let _ = shopify_api::input!(ProductSetIdentifiers { handle: shopify_api::Maybe::<&str>::Null }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/literal_option_in_field.rs b/crates/shopify_api/tests/ui/literal_option_in_field.rs new file mode 100644 index 0000000..106e256 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_option_in_field.rs @@ -0,0 +1,4 @@ +fn main() { + let vendor: Option = None; + let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); +} diff --git a/crates/shopify_api/tests/ui/literal_option_in_field.stderr b/crates/shopify_api/tests/ui/literal_option_in_field.stderr new file mode 100644 index 0000000..9b3c698 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_option_in_field.stderr @@ -0,0 +1,17 @@ +error[E0277]: `vendor` of `ProductUpdateInput` expects a `String`, not `Option` + --> tests/ui/literal_option_in_field.rs:3:93 + | +3 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); + | ^^^^^^ + | | + | `Option` doesn't satisfy the trait bound + | `String`, `&str`, `&String` or `Cow` + | + = help: the trait `__ShopifyApiExpect1_c1d682ad` is not implemented for `Option` + = note: `vendor?: value` takes an `Option`, `None` leaving the field out; `vendor: null` sends `null` +note: required by a bound in `Checks::build` + --> tests/ui/literal_option_in_field.rs:3:13 + | +3 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", vendor: vendor }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/literal_optional_required.rs b/crates/shopify_api/tests/ui/literal_optional_required.rs new file mode 100644 index 0000000..b0bc236 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_optional_required.rs @@ -0,0 +1,4 @@ +fn main() { + let owner: Option<&str> = None; + let _ = shopify_api::input!(MetafieldsSetInput { ownerId?: owner, key: "color", value: "blue" }); +} diff --git a/crates/shopify_api/tests/ui/literal_optional_required.stderr b/crates/shopify_api/tests/ui/literal_optional_required.stderr new file mode 100644 index 0000000..8367366 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_optional_required.stderr @@ -0,0 +1,6 @@ +error: `ownerId` of `MetafieldsSetInput` is required (`ID!`): it cannot be left out, so `?:` does not apply; write `ownerId: …` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_optional_required.rs:3:61 + | +3 | let _ = shopify_api::input!(MetafieldsSetInput { ownerId?: owner, key: "color", value: "blue" }); + | ^ diff --git a/crates/shopify_api/tests/ui/literal_raw_outside_enum.rs b/crates/shopify_api/tests/ui/literal_raw_outside_enum.rs new file mode 100644 index 0000000..7b09838 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_raw_outside_enum.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", title: raw("Shirt") }); +} diff --git a/crates/shopify_api/tests/ui/literal_raw_outside_enum.stderr b/crates/shopify_api/tests/ui/literal_raw_outside_enum.stderr new file mode 100644 index 0000000..d8511a6 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_raw_outside_enum.stderr @@ -0,0 +1,6 @@ +error: `raw(…)` is only for a value of an enum: `title` of `ProductUpdateInput` expects a `String` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_raw_outside_enum.rs:2:92 + | +2 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", title: raw("Shirt") }); + | ^^^ diff --git a/crates/shopify_api/tests/ui/literal_reserved_prefix_constant.rs b/crates/shopify_api/tests/ui/literal_reserved_prefix_constant.rs new file mode 100644 index 0000000..983b5ea --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_reserved_prefix_constant.rs @@ -0,0 +1,8 @@ +// A constant named like a binding of the generated code: a compile error, not a change of meaning. +#![allow(non_upper_case_globals)] +const __shopify_api_value0: &str = ""; + +fn main() { + let title = String::from("Shirt"); + let _ = shopify_api::input!(ProductInput { title: title }); +} diff --git a/crates/shopify_api/tests/ui/literal_reserved_prefix_constant.stderr b/crates/shopify_api/tests/ui/literal_reserved_prefix_constant.stderr new file mode 100644 index 0000000..d8794ab --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_reserved_prefix_constant.stderr @@ -0,0 +1,21 @@ +error[E0308]: mismatched types + --> tests/ui/literal_reserved_prefix_constant.rs:7:13 + | +3 | const __shopify_api_value0: &str = ""; + | -------------------------------- constant defined here +... +7 | let _ = shopify_api::input!(ProductInput { title: title }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | expected type parameter `V2`, found `&str` + | expected due to this + | `__shopify_api_value0` is interpreted as a constant, not a new binding + | + = note: expected type parameter `V2` + found reference `&'static str` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) +help: introduce a new binding instead + | +7 - let _ = shopify_api::input!(ProductInput { title: title }); +7 + let _ = other___shopify_api_value0; + | diff --git a/crates/shopify_api/tests/ui/literal_unknown_enum_value.rs b/crates/shopify_api/tests/ui/literal_unknown_enum_value.rs new file mode 100644 index 0000000..8790d49 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_unknown_enum_value.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", status: ACTIV }); +} diff --git a/crates/shopify_api/tests/ui/literal_unknown_enum_value.stderr b/crates/shopify_api/tests/ui/literal_unknown_enum_value.stderr new file mode 100644 index 0000000..d217d02 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_unknown_enum_value.stderr @@ -0,0 +1,6 @@ +error: `ACTIV` is not a value of the enum `ProductStatus` (did you mean `ACTIVE`?): `status` of `ProductUpdateInput` takes `ACTIVE`, `ARCHIVED`, `DRAFT` or `UNLISTED` + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_unknown_enum_value.rs:2:93 + | +2 | let _ = shopify_api::input!(ProductUpdateInput { id: "gid://shopify/Product/1", status: ACTIV }); + | ^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_unknown_field.rs b/crates/shopify_api/tests/ui/literal_unknown_field.rs new file mode 100644 index 0000000..5a45097 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_unknown_field.rs @@ -0,0 +1,6 @@ +fn main() { + let _ = shopify_api::graphql!( + "mutation($product: ProductUpdateInput!) { productUpdate(product: $product) { userErrors { message } } }", + product = { id: "gid://shopify/Product/1", titel: "Shirt" }, + ); +} diff --git a/crates/shopify_api/tests/ui/literal_unknown_field.stderr b/crates/shopify_api/tests/ui/literal_unknown_field.stderr new file mode 100644 index 0000000..7f8b7b8 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_unknown_field.stderr @@ -0,0 +1,6 @@ +error: Input object `ProductUpdateInput` has no field `titel` (did you mean `title`?) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/literal_unknown_field.rs:4:52 + | +4 | product = { id: "gid://shopify/Product/1", titel: "Shirt" }, + | ^^^^^ diff --git a/crates/shopify_api/tests/ui/literal_wrong_input_type.rs b/crates/shopify_api/tests/ui/literal_wrong_input_type.rs new file mode 100644 index 0000000..3c00671 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_wrong_input_type.rs @@ -0,0 +1,7 @@ +fn main() { + let seo = vec![shopify_api::input!(SEOInput { title: "Shirt" })]; + let _ = shopify_api::graphql!( + "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", + metafields = seo, + ); +} diff --git a/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr new file mode 100644 index 0000000..8073484 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_wrong_input_type.stderr @@ -0,0 +1,43 @@ +error[E0277]: an item of `$metafields` expects a `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })` + --> tests/ui/literal_wrong_input_type.rs:5:22 + | +3 | let _ = shopify_api::graphql!( + | _____________- +4 | | "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", +5 | | metafields = seo, + | | ^^^ build it with `input!(MetafieldsSetInput { … })` +6 | | ); + | |_____- required by a bound introduced by this call + | + = help: the trait `__ShopifyApiExpect2_c1d68407` is not implemented for `InputObject<2493993284262097346>` +help: the following other types implement trait `__ShopifyApiExpect2_c1d68407` + --> tests/ui/literal_wrong_input_type.rs:3:13 + | +3 | let _ = shopify_api::graphql!( + | _____________^ +4 | | "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", +5 | | metafields = seo, +6 | | ); + | | ^ + | | | + | |_____`&InputObject<960560859991546817>` + | `InputObject<960560859991546817>` +note: required for `Vec>` to implement `__ShopifyApiExpect1_c1d68407` + --> tests/ui/literal_wrong_input_type.rs:3:13 + | +3 | let _ = shopify_api::graphql!( + | _____________^ +4 | | "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", +5 | | metafields = seo, +6 | | ); + | |_____^ +note: required by a bound in `Checks::build` + --> tests/ui/literal_wrong_input_type.rs:3:13 + | +3 | let _ = shopify_api::graphql!( + | _____________^ +4 | | "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }", +5 | | metafields = seo, +6 | | ); + | |_____^ required by this bound in `Checks::build` + = note: this error originates in the macro `shopify_api::graphql` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/literal_wrong_scalar.rs b/crates/shopify_api/tests/ui/literal_wrong_scalar.rs new file mode 100644 index 0000000..bef69c7 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_wrong_scalar.rs @@ -0,0 +1,5 @@ +fn main() { + let count = 2_u8; + let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: "2", title: count, requiresShipping: 1 }); + let _ = shopify_api::input!(WeightInput { unit: GRAMS, value: 2_u64 }); +} diff --git a/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr new file mode 100644 index 0000000..2a69e54 --- /dev/null +++ b/crates/shopify_api/tests/ui/literal_wrong_scalar.stderr @@ -0,0 +1,70 @@ +error[E0277]: `quantity` of `DraftOrderLineItemInput` expects an `Int`, not `&str` + --> tests/ui/literal_wrong_scalar.rs:3:69 + | +3 | let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: "2", title: count, requiresShipping: 1 }); + | ^^^ + | | + | `&'static str` doesn't satisfy the trait bound + | any integer type + | + = help: the trait `main::__ShopifyApiExpect1_c1d69cb4` is not implemented for `&str` +note: required by a bound in `main::Checks::build` + --> tests/ui/literal_wrong_scalar.rs:3:13 + | +3 | let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: "2", title: count, requiresShipping: 1 }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `title` of `DraftOrderLineItemInput` expects a `String`, not `u8` + --> tests/ui/literal_wrong_scalar.rs:3:81 + | +3 | let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: "2", title: count, requiresShipping: 1 }); + | ^^^^^ + | | + | `u8` doesn't satisfy the trait bound + | `String`, `&str`, `&String` or `Cow` + | + = help: the trait `__ShopifyApiExpect3_c1d69cb4` is not implemented for `u8` + = note: `title?: value` takes an `Option`, `None` leaving the field out; `title: null` sends `null` +note: required by a bound in `main::Checks::build` + --> tests/ui/literal_wrong_scalar.rs:3:13 + | +3 | let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: "2", title: count, requiresShipping: 1 }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `requiresShipping` of `DraftOrderLineItemInput` expects a `Boolean`, not `{integer}` + --> tests/ui/literal_wrong_scalar.rs:3:106 + | +3 | let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: "2", title: count, requiresShipping: 1 }); + | ^ + | | + | `{integer}` doesn't satisfy the trait bound + | `bool` + | + = help: the trait `__ShopifyApiExpect5_c1d69cb4` is not implemented for `{integer}` + = note: `requiresShipping?: value` takes an `Option`, `None` leaving the field out; `requiresShipping: null` sends `null` +note: required by a bound in `main::Checks::build` + --> tests/ui/literal_wrong_scalar.rs:3:13 + | +3 | let _ = shopify_api::input!(DraftOrderLineItemInput { quantity: "2", title: count, requiresShipping: 1 }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: `value` of `WeightInput` expects a `Float`, not `u64` + --> tests/ui/literal_wrong_scalar.rs:4:67 + | +4 | let _ = shopify_api::input!(WeightInput { unit: GRAMS, value: 2_u64 }); + | ^^^^^ + | | + | `u64` doesn't satisfy the trait bound + | `f64`, `f32`, `i32` or `u32` + | + = help: the trait `main::__ShopifyApiExpect1_c1d69cb4` is not implemented for `u64` + = note: `u64` implements similarly named trait `main::__ShopifyApiExpect1_c1d69cb4`, but not `main::__ShopifyApiExpect1_c1d69cb4` +note: required by a bound in `main::Checks::build` + --> tests/ui/literal_wrong_scalar.rs:4:13 + | +4 | let _ = shopify_api::input!(WeightInput { unit: GRAMS, value: 2_u64 }); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Checks::build` + = note: this error originates in the macro `shopify_api::input` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/ui/missing_file.rs b/crates/shopify_api/tests/ui/missing_file.rs new file mode 100644 index 0000000..5cd195d --- /dev/null +++ b/crates/shopify_api/tests/ui/missing_file.rs @@ -0,0 +1,5 @@ +shopify_api::graphql! { + mod orders = file("graphql/missing.graphql"); +} + +fn main() {} diff --git a/crates/shopify_api/tests/ui/missing_file.stderr b/crates/shopify_api/tests/ui/missing_file.stderr new file mode 100644 index 0000000..610c77f --- /dev/null +++ b/crates/shopify_api/tests/ui/missing_file.stderr @@ -0,0 +1,5 @@ +error: Cannot read `graphql/missing.graphql`, relative to the Cargo.toml of the crate: No such file or directory (os error 2) + --> tests/ui/missing_file.rs:2:23 + | +2 | mod orders = file("graphql/missing.graphql"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/missing_variable.rs b/crates/shopify_api/tests/ui/missing_variable.rs new file mode 100644 index 0000000..116726e --- /dev/null +++ b/crates/shopify_api/tests/ui/missing_variable.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("query($id: ID!) { product(id: $id) { title } }"); +} diff --git a/crates/shopify_api/tests/ui/missing_variable.stderr b/crates/shopify_api/tests/ui/missing_variable.stderr new file mode 100644 index 0000000..098176f --- /dev/null +++ b/crates/shopify_api/tests/ui/missing_variable.stderr @@ -0,0 +1,5 @@ +error: Variable `$id: ID!` needs a value: add `id = …` after the operation + --> tests/ui/missing_variable.rs:2:35 + | +2 | let _ = shopify_api::graphql!("query($id: ID!) { product(id: $id) { title } }"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/same_name_alias_field_order.rs b/crates/shopify_api/tests/ui/same_name_alias_field_order.rs new file mode 100644 index 0000000..e5e1ea1 --- /dev/null +++ b/crates/shopify_api/tests/ui/same_name_alias_field_order.rs @@ -0,0 +1,7 @@ +// An alias spelled like its field, with the fields of an input object in +// another order: Shopify (GraphQL Ruby) refuses it with `fieldConflict`. +fn main() { + let _ = shopify_api::graphql!( + r#"mutation { draftOrderCreate:draftOrderCreate(input:{note:"x" tags:["y"]}){draftOrder{id}} draftOrderCreate:draftOrderCreate(input:{tags:["y"] note:"x"}){draftOrder{id}} }"# + ); +} diff --git a/crates/shopify_api/tests/ui/same_name_alias_field_order.stderr b/crates/shopify_api/tests/ui/same_name_alias_field_order.stderr new file mode 100644 index 0000000..276f7de --- /dev/null +++ b/crates/shopify_api/tests/ui/same_name_alias_field_order.stderr @@ -0,0 +1,6 @@ +error: `draftOrderCreate` is selected twice with the fields of an input object in another order (`(input: {note: "x", tags: ["y"]})`), which Shopify refuses; write them in the same order, or give one of them an alias (line 1, column 91) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/same_name_alias_field_order.rs:5:9 + | +5 | ... r#"mutation { draftOrderCreate:draftOrderCreate(input:{note:"x" tags:["y"]}){draftOrder{id}} draftOrderCreate:draftOrderCreate(input:{tags:["y"] note:"x"}){draftOrder{id}} }"# + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/subscription.rs b/crates/shopify_api/tests/ui/subscription.rs new file mode 100644 index 0000000..42ecf22 --- /dev/null +++ b/crates/shopify_api/tests/ui/subscription.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("subscription { shop { name } }"); +} diff --git a/crates/shopify_api/tests/ui/subscription.stderr b/crates/shopify_api/tests/ui/subscription.stderr new file mode 100644 index 0000000..dafecce --- /dev/null +++ b/crates/shopify_api/tests/ui/subscription.stderr @@ -0,0 +1,6 @@ +error: Subscriptions are not supported (line 1, column 1) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/subscription.rs:2:35 + | +2 | let _ = shopify_api::graphql!("subscription { shop { name } }"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/syntax_error.rs b/crates/shopify_api/tests/ui/syntax_error.rs new file mode 100644 index 0000000..3820079 --- /dev/null +++ b/crates/shopify_api/tests/ui/syntax_error.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("{ shop { name }"); +} diff --git a/crates/shopify_api/tests/ui/syntax_error.stderr b/crates/shopify_api/tests/ui/syntax_error.stderr new file mode 100644 index 0000000..de5157d --- /dev/null +++ b/crates/shopify_api/tests/ui/syntax_error.stderr @@ -0,0 +1,6 @@ +error: Invalid GraphQL: Parse error at 1:16 Unexpected end of input Expected } + (checked against the Shopify Admin API 2026-10) + --> tests/ui/syntax_error.rs:2:35 + | +2 | let _ = shopify_api::graphql!("{ shop { name }"); + | ^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/unknown_enum_value.rs b/crates/shopify_api/tests/ui/unknown_enum_value.rs new file mode 100644 index 0000000..a1c45e4 --- /dev/null +++ b/crates/shopify_api/tests/ui/unknown_enum_value.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("{ orders(first: 1, sortKey: CREATED) { nodes { id } } }"); +} diff --git a/crates/shopify_api/tests/ui/unknown_enum_value.stderr b/crates/shopify_api/tests/ui/unknown_enum_value.stderr new file mode 100644 index 0000000..2b0b1f8 --- /dev/null +++ b/crates/shopify_api/tests/ui/unknown_enum_value.stderr @@ -0,0 +1,6 @@ +error: `CREATED` is not a value of the enum `OrderSortKeys` (did you mean `CREATED_AT`?) (in argument `sortKey` of `QueryRoot.orders`) (line 1, column 3) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/unknown_enum_value.rs:2:35 + | +2 | let _ = shopify_api::graphql!("{ orders(first: 1, sortKey: CREATED) { nodes { id } } }"); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/unknown_field.rs b/crates/shopify_api/tests/ui/unknown_field.rs new file mode 100644 index 0000000..9dd2626 --- /dev/null +++ b/crates/shopify_api/tests/ui/unknown_field.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("{ shop { nam } }"); +} diff --git a/crates/shopify_api/tests/ui/unknown_field.stderr b/crates/shopify_api/tests/ui/unknown_field.stderr new file mode 100644 index 0000000..ad34093 --- /dev/null +++ b/crates/shopify_api/tests/ui/unknown_field.stderr @@ -0,0 +1,6 @@ +error: Type `Shop` has no field `nam` (did you mean `name`?) (line 1, column 10) + (checked against the Shopify Admin API 2026-10) + --> tests/ui/unknown_field.rs:2:35 + | +2 | let _ = shopify_api::graphql!("{ shop { nam } }"); + | ^^^^^^^^^^^^^^^^^^ diff --git a/crates/shopify_api/tests/ui/unknown_variable.rs b/crates/shopify_api/tests/ui/unknown_variable.rs new file mode 100644 index 0000000..36802b9 --- /dev/null +++ b/crates/shopify_api/tests/ui/unknown_variable.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("query($id: ID!) { product(id: $id) { title } }", id = "1", first = 2); +} diff --git a/crates/shopify_api/tests/ui/unknown_variable.stderr b/crates/shopify_api/tests/ui/unknown_variable.stderr new file mode 100644 index 0000000..ec5cdf5 --- /dev/null +++ b/crates/shopify_api/tests/ui/unknown_variable.stderr @@ -0,0 +1,5 @@ +error: The operation has no variable `$first`: it declares $id + --> tests/ui/unknown_variable.rs:2:95 + | +2 | let _ = shopify_api::graphql!("query($id: ID!) { product(id: $id) { title } }", id = "1", first = 2); + | ^^^^^ diff --git a/crates/shopify_api/tests/ui/unselected_field.rs b/crates/shopify_api/tests/ui/unselected_field.rs new file mode 100644 index 0000000..4dd7e6f --- /dev/null +++ b/crates/shopify_api/tests/ui/unselected_field.rs @@ -0,0 +1,6 @@ +async fn email(shopify: &shopify_api::Shopify) -> shopify_api::Result { + let data = shopify.execute(shopify_api::graphql!("{ shop { name } }")).await?; + Ok(data.shop.email) +} + +fn main() {} diff --git a/crates/shopify_api/tests/ui/unselected_field.stderr b/crates/shopify_api/tests/ui/unselected_field.stderr new file mode 100644 index 0000000..074c770 --- /dev/null +++ b/crates/shopify_api/tests/ui/unselected_field.stderr @@ -0,0 +1,7 @@ +error[E0609]: no field `email` on type `DataShop` + --> tests/ui/unselected_field.rs:3:18 + | +3 | Ok(data.shop.email) + | ^^^^^ unknown field + | + = note: available field is: `name` diff --git a/crates/shopify_api/tests/ui/wrong_value_type.rs b/crates/shopify_api/tests/ui/wrong_value_type.rs new file mode 100644 index 0000000..132b55a --- /dev/null +++ b/crates/shopify_api/tests/ui/wrong_value_type.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = shopify_api::graphql!("query($first: Int!) { products(first: $first) { nodes { id } } }", first = "ten"); +} diff --git a/crates/shopify_api/tests/ui/wrong_value_type.stderr b/crates/shopify_api/tests/ui/wrong_value_type.stderr new file mode 100644 index 0000000..de3c286 --- /dev/null +++ b/crates/shopify_api/tests/ui/wrong_value_type.stderr @@ -0,0 +1,29 @@ +error[E0277]: `&str` is not a value for a GraphQL variable of Rust type `i64` + --> tests/ui/wrong_value_type.rs:2:111 + | +2 | let _ = shopify_api::graphql!("query($first: Int!) { products(first: $first) { nodes { id } } }", first = "ten"); + | ^^^^^ the variable expects a value convertible to `i64` + | + = help: the trait `IntoVariable` is not implemented for `&str` +help: `&str` implements trait `IntoVariable` + --> src/graphql/operation.rs + | + | impl IntoVariable<$target> for $source { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `IntoVariable` +... + | impl IntoVariable> for $source { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `IntoVariable>` +... + | / into_variable!(String: + | | String => |value| value, + | | &str => |value| value.to_string(), + | | &String => |value| value.clone(), + | | Cow<'_, str> => |value| value.into_owned(), + | | ); + | |_- in this macro invocation +note: required by a bound in `Operation::::variable` + --> src/graphql/operation.rs + | + | pub fn variable>(self, name: &str, value: V) -> Self { + | ^^^^^^^^^^^^^^^ required by this bound in `Operation::::variable` + = note: this error originates in the macro `into_variable` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/crates/shopify_api/tests/webhooks.rs b/crates/shopify_api/tests/webhooks.rs new file mode 100644 index 0000000..3c3d38b --- /dev/null +++ b/crates/shopify_api/tests/webhooks.rs @@ -0,0 +1,404 @@ +//! Webhook subscriptions against a scripted Shopify. +#![cfg(all(feature = "testing", feature = "webhooks"))] + +use serde_json::{Value, json}; +use shopify_api::testing::{MockTransport, client}; +use shopify_api::webhooks::WebhookSubscriptionSpec; + +fn subscription(id: u32, topic: &str, uri: &str) -> Value { + json!({ + "id": format!("gid://shopify/WebhookSubscription/{id}"), + "topic": topic, + "uri": uri, + "format": "JSON", + "filter": null, + "includeFields": [], + "metafieldNamespaces": [], + "name": null, + "createdAt": "2026-10-01T00:00:00Z", + "updatedAt": "2026-10-01T00:00:00Z", + "apiVersion": { "handle": "2026-10" }, + }) +} + +#[tokio::test] +async fn sync_keeps_updates_creates_then_deletes() { + let mock = MockTransport::new(); + // Two pages of existing subscriptions. + mock.push_data(json!({ "webhookSubscriptions": { + "nodes": [subscription(1, "ORDERS_CREATE", "https://example.com/hooks")], + "pageInfo": { "hasNextPage": true, "endCursor": "c1" }, + } })); + mock.push_data(json!({ "webhookSubscriptions": { + "nodes": [ + subscription(2, "PRODUCTS_UPDATE", "https://old.example.com/hooks"), + subscription(3, "PRODUCTS_UPDATE", "https://example.com/hooks"), + ], + "pageInfo": { "hasNextPage": false, "endCursor": "c2" }, + } })); + let mut updated = subscription(3, "PRODUCTS_UPDATE", "https://example.com/hooks"); + updated["includeFields"] = json!(["id"]); + mock.push_data(json!({ "webhookSubscriptionUpdate": { "webhookSubscription": updated, "userErrors": [] } })); + mock.push_data(json!({ "webhookSubscriptionCreate": { + "webhookSubscription": subscription(4, "APP_UNINSTALLED", "https://example.com/hooks"), + "userErrors": [], + } })); + mock.push_data(json!({ "webhookSubscriptionDelete": { + "deletedWebhookSubscriptionId": "gid://shopify/WebhookSubscription/2", + "userErrors": [], + } })); + let shopify = client(&mock); + + let report = shopify + .sync_webhook_subscriptions(&[ + WebhookSubscriptionSpec::new("orders/create", "https://example.com/hooks"), + WebhookSubscriptionSpec::new("products/update", "https://example.com/hooks") + .include_fields(["id"]), + WebhookSubscriptionSpec::new("app/uninstalled", "https://example.com/hooks"), + ]) + .await + .unwrap(); + + assert_eq!(report.kept.len(), 1); + assert_eq!(report.updated[0].include_fields, ["id"]); + assert_eq!(report.created[0].topic, "APP_UNINSTALLED"); + assert_eq!(report.created[0].api_version, "2026-10"); + assert_eq!(report.deleted, ["gid://shopify/WebhookSubscription/2"]); + + let sent = mock.graphql_requests(); + let names: Vec<_> = sent + .iter() + .map(|request| request.operation_name.clone().unwrap()) + .collect(); + // Nothing is deleted before what replaces it exists. + assert_eq!( + names, + [ + "WebhookSubscriptions", + "WebhookSubscriptions", + "WebhookSubscriptionUpdate", + "WebhookSubscriptionCreate", + "WebhookSubscriptionDelete", + ] + ); + assert_eq!(sent[1].variables, json!({ "after": "c1" })); + // An update sends every option, so that it replaces the old ones. + assert_eq!( + sent[2].variables, + json!({ + "id": "gid://shopify/WebhookSubscription/3", + "webhookSubscription": { + "uri": "https://example.com/hooks", + "format": "JSON", + "filter": "", + "includeFields": ["id"], + "metafieldNamespaces": [], + }, + }) + ); + assert_eq!( + sent[3].variables, + json!({ + "topic": "APP_UNINSTALLED", + "webhookSubscription": { "uri": "https://example.com/hooks", "format": "JSON" }, + }) + ); +} + +/// Only JSON webhooks verify: an XML subscription of a desired topic and +/// address is updated to JSON, not kept. +#[tokio::test] +async fn sync_updates_an_xml_subscription_to_json() { + let mock = MockTransport::new(); + let mut xml = subscription(1, "ORDERS_CREATE", "https://example.com/hooks"); + xml["format"] = json!("XML"); + mock.push_data(json!({ "webhookSubscriptions": { + "nodes": [xml], + "pageInfo": { "hasNextPage": false, "endCursor": null }, + } })); + mock.push_data(json!({ "webhookSubscriptionUpdate": { + "webhookSubscription": subscription(1, "ORDERS_CREATE", "https://example.com/hooks"), + "userErrors": [], + } })); + let shopify = client(&mock); + + let report = shopify + .sync_webhook_subscriptions(&[WebhookSubscriptionSpec::new( + "orders/create", + "https://example.com/hooks", + )]) + .await + .unwrap(); + + assert!(report.kept.is_empty()); + assert_eq!(report.updated[0].format, "JSON"); + let sent = mock.graphql_requests(); + assert_eq!( + sent[1].operation_name.as_deref(), + Some("WebhookSubscriptionUpdate") + ); + assert_eq!(sent[1].variables["webhookSubscription"]["format"], "JSON"); +} + +#[tokio::test] +async fn a_refused_subscription_returns_the_user_errors() { + let mock = MockTransport::new(); + mock.push_data(json!({ "webhookSubscriptionCreate": { + "webhookSubscription": null, + "userErrors": [{ "field": ["webhookSubscription", "callbackUrl"], "message": "Address is invalid" }], + } })); + let shopify = client(&mock); + + let error = shopify + .create_webhook_subscription(&WebhookSubscriptionSpec::new( + "ORDERS_CREATE", + "http://localhost", + )) + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + "webhookSubscriptionCreate refused: webhookSubscription.callbackUrl: Address is invalid" + ); +} + +mod verification { + use shopify_api::webhooks::{Webhook, sign, verify_hmac}; + + const SECRET: &str = "hush"; + + fn headers(signature: &str, topic: &str, shop: &str) -> Vec<(String, String)> { + vec![ + ("X-Shopify-Hmac-Sha256".into(), signature.into()), + ("X-Shopify-Topic".into(), topic.into()), + ("X-Shopify-Shop-Domain".into(), shop.into()), + ] + } + + fn refusal(signature: &str, body: &[u8]) -> String { + let result = Webhook::verify( + headers(signature, "shop/redact", "victim.myshopify.com"), + body, + SECRET, + ); + assert!(!verify_hmac(SECRET, body, signature)); + result.unwrap_err().to_string() + } + + /// The other texts the client secret signs, which an installer of the + /// app reads, never pass for a webhook. + #[cfg(feature = "oauth")] + mod forgeries { + use base64::Engine; + use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; + use serde_json::json; + use shopify_api::oauth::ShopifyApp; + + use super::*; + + const NOT_A_WEBHOOK: &str = "verification failed: the body of the webhook does not start with `{`: only JSON webhooks verify"; + + #[test] + fn the_hmac_of_a_launch_query_is_not_a_webhook_signature() { + let app = ShopifyApp::new("client-id", SECRET); + // Sorted, nothing to escape: the message signed is the query itself. + let query = "host=YWRtaW4&shop=attacker.myshopify.com×tamp=1700000000"; + let hmac = app.sign_query(query).unwrap(); + let signature = STANDARD.encode(hex::decode(hmac).unwrap()); + assert_eq!(refusal(&signature, query.as_bytes()), NOT_A_WEBHOOK); + } + + #[test] + fn the_signature_of_a_session_token_is_not_a_webhook_signature() { + let app = ShopifyApp::new("client-id", SECRET); + let token = app.sign_session_token(&json!({ + "dest": "https://attacker.myshopify.com", + "aud": "client-id", + "exp": 1, + })); + let (signed, signature) = token.rsplit_once('.').unwrap(); + let signature = STANDARD.encode(URL_SAFE_NO_PAD.decode(signature).unwrap()); + assert_eq!(refusal(&signature, signed.as_bytes()), NOT_A_WEBHOOK); + } + + /// The parameters of an app proxy request are the storefront's: a + /// name that sorts first can open a JSON object after a tab, a + /// whitespace `Webhook::verify` does not skip. + #[test] + fn an_app_proxy_request_that_reads_as_json_after_a_tab_is_not_a_webhook() { + let app = ShopifyApp::new("client-id", SECRET); + let query = "%09%7B%22x%22%3A%22=&logged_in_customer_id=&path_prefix=%2Fapps%2Fx\ + &shop=attacker.myshopify.com×tamp=1700000000\ + &z=%22%2C%22shop_domain%22%3A%22victim.myshopify.com%22%7D"; + let message = "\t{\"x\":\"=logged_in_customer_id=path_prefix=/apps/xshop=attacker.myshopify.comtimestamp=1700000000z=\",\"shop_domain\":\"victim.myshopify.com\"}"; + let payload: serde_json::Value = serde_json::from_str(message).unwrap(); + assert_eq!(payload["shop_domain"], "victim.myshopify.com"); + let signature = app.sign_app_proxy(query).unwrap(); + let signature = STANDARD.encode(hex::decode(signature).unwrap()); + assert_eq!( + sign(SECRET, message.as_bytes()), + signature, + "the message signed" + ); + assert_eq!(refusal(&signature, message.as_bytes()), NOT_A_WEBHOOK); + } + + /// Or a JSON array, which is not an object. + #[test] + fn an_app_proxy_request_is_not_a_webhook() { + let app = ShopifyApp::new("client-id", SECRET); + let query = "%5B%22=&logged_in_customer_id=&path_prefix=%2Fapps%2Fx\ + &shop=attacker.myshopify.com×tamp=1700000000&z=%22%5D"; + let message = "[\"=logged_in_customer_id=path_prefix=/apps/xshop=attacker.myshopify.comtimestamp=1700000000z=\"]"; + assert!(serde_json::from_str::(message).is_ok()); + let signature = app.sign_app_proxy(query).unwrap(); + let signature = STANDARD.encode(hex::decode(signature).unwrap()); + assert_eq!( + sign(SECRET, message.as_bytes()), + signature, + "the message signed" + ); + assert_eq!(refusal(&signature, message.as_bytes()), NOT_A_WEBHOOK); + } + + /// `<` sorts before letters: a parameter named `"; + let signature = app.sign_app_proxy(query).unwrap(); + let signature = STANDARD.encode(hex::decode(signature).unwrap()); + assert_eq!( + sign(SECRET, message.as_bytes()), + signature, + "the message signed" + ); + assert_eq!(refusal(&signature, message.as_bytes()), NOT_A_WEBHOOK); + + // The same text as the sorted `key=value` pairs of a launch query. + let launch = + "=&shop=attacker.myshopify.com×tamp=1700000000"; + assert_eq!( + refusal(&sign(SECRET, launch.as_bytes()), launch.as_bytes()), + NOT_A_WEBHOOK + ); + } + } + + #[test] + fn only_bodies_that_start_with_a_brace_verify() { + for body in [&b"{\"id\":1}"[..], b"{}", b"{ }\n"] { + assert!( + Webhook::verify( + headers(&sign(SECRET, body), "orders/create", "a"), + body, + SECRET + ) + .is_ok() + ); + assert!(verify_hmac(SECRET, body, &sign(SECRET, body))); + } + for body in [ + &b""[..], + b" ", + b"[1]", + b"a=1", + b"eyJhbGciOiJIUzI1NiJ9.e30", + b"", + b" ", + // JSON objects, but not first: nothing is skipped before the `{`. + b" {}", + b"\t{}", + b"\n{}", + b"\r\n{}", + b"\xEF\xBB\xBF{}", + ] { + refusal(&sign(SECRET, body), body); + } + } + + #[test] + fn headers_without_x_and_in_any_case_are_read() { + let body = br#"{"id":1}"#; + let signature = sign(SECRET, body); + let headers = [ + ("shopify-hmac-sha256", signature.as_str()), + ("Shopify-Topic", "orders/create"), + ("SHOPIFY-SHOP-DOMAIN", "a.myshopify.com"), + ("shopify-api-version", "2026-10"), + ("shopify-webhook-id", "w1"), + ]; + let webhook = Webhook::verify(headers, &body[..], SECRET).unwrap(); + assert_eq!(webhook.topic(), "orders/create"); + assert_eq!(webhook.shop().as_str(), "a.myshopify.com"); + assert_eq!(webhook.api_version(), Some("2026-10")); + assert_eq!(webhook.webhook_id(), Some("w1")); + } + + /// axum's and actix's `HeaderMap` is `http`'s, which reqwest re-exports. + #[cfg(feature = "rustls")] + #[test] + fn a_header_map_goes_in_as_it_is() { + use shopify_api::transport::reqwest_0_13::reqwest::header::{HeaderMap, HeaderValue}; + + let body = br#"{"id":1}"#; + let mut map = HeaderMap::new(); + map.insert( + "x-shopify-hmac-sha256", + HeaderValue::from_str(&sign(SECRET, body)).unwrap(), + ); + map.insert("x-shopify-topic", HeaderValue::from_static("orders/create")); + map.insert( + "x-shopify-shop-domain", + HeaderValue::from_static("a.myshopify.com"), + ); + // A value that is not UTF-8 is not Shopify's: ignored. + map.insert("x-other", HeaderValue::from_bytes(&[0xff]).unwrap()); + let webhook = Webhook::verify(&map, body.to_vec(), SECRET).unwrap(); + assert_eq!(webhook.shop().as_str(), "a.myshopify.com"); + } + + #[test] + fn debug_shows_the_length_of_the_body_not_the_body() { + let body = br#"{"email":"ada@example.com"}"#; + let webhook = Webhook::verify( + headers(&sign(SECRET, body), "customers/create", "a"), + &body[..], + SECRET, + ) + .unwrap(); + let shown = format!("{webhook:?}"); + assert!(!shown.contains("ada@example.com"), "{shown}"); + assert!(shown.contains("[27 bytes]"), "{shown}"); + } + + #[test] + fn a_destructive_webhook_checks_the_shop_of_its_payload() { + let verified = |body: &str, shop: &str| { + Webhook::verify( + headers(&sign(SECRET, body.as_bytes()), "shop/redact", shop), + body.as_bytes(), + SECRET, + ) + .unwrap() + .verify_payload_shop() + }; + let redact = r#"{"shop_id":1,"shop_domain":"a.myshopify.com"}"#; + assert!(verified(redact, "a.myshopify.com").is_ok()); + assert_eq!( + verified(redact, "victim.myshopify.com") + .unwrap_err() + .to_string(), + "verification failed: the payload of the webhook does not name the shop of its headers" + ); + let uninstalled = + r#"{"id":1,"domain":"shop.example.com","myshopify_domain":"a.myshopify.com"}"#; + assert!(verified(uninstalled, "a").is_ok()); + assert!(verified(r#"{"id":1}"#, "a").is_err()); + assert!(verified("{not json", "a").is_err()); + } +} diff --git a/crates/shopify_api_graphql/Cargo.toml b/crates/shopify_api_graphql/Cargo.toml new file mode 100644 index 0000000..30ba996 --- /dev/null +++ b/crates/shopify_api_graphql/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "shopify_api_graphql" +description = "Internal to shopify_api, no semver guarantee: checks Shopify Admin GraphQL operations against the schema and generates their Rust types for its `graphql!` macro. Depend on `shopify_api` instead." +documentation = "https://docs.rs/shopify_api_graphql" +keywords = ["shopify", "graphql", "codegen"] +categories = ["development-tools", "api-bindings"] +readme = "README.md" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +include = ["src/**", "Cargo.toml", "README.md", "LICENSE.txt"] + +[dependencies] +graphql-parser.workspace = true +proc-macro2.workspace = true +quote.workspace = true +serde.workspace = true +serde_json.workspace = true +toml.workspace = true +ureq = { workspace = true, optional = true } + +[features] +## `project::download_public_schema`, `project::download_schema_file` and `project::up_to_date_schema`. +download = ["dep:ureq"] + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] + +[lints] +workspace = true diff --git a/crates/shopify_api_graphql/LICENSE.txt b/crates/shopify_api_graphql/LICENSE.txt new file mode 120000 index 0000000..1ef648f --- /dev/null +++ b/crates/shopify_api_graphql/LICENSE.txt @@ -0,0 +1 @@ +../../LICENSE.txt \ No newline at end of file diff --git a/crates/shopify_api_graphql/README.md b/crates/shopify_api_graphql/README.md new file mode 100644 index 0000000..90f2d2c --- /dev/null +++ b/crates/shopify_api_graphql/README.md @@ -0,0 +1,17 @@ +# shopify_api_graphql + +The compile-time half of [`shopify_api`](https://crates.io/crates/shopify_api)'s +`graphql!` and `input!` macros: it reads Shopify's Admin GraphQL schema, +checks an operation against it, generates the Rust types of its variables and +of its result, and checks the input values written in Rust. + +**It is an implementation detail, with no semver guarantee**: any release may +change its items. `shopify_api` depends on it with an exact `=` version. +Depend on [`shopify_api`](https://crates.io/crates/shopify_api) and use its +`graphql!` and `input!` macros instead. It is a separate crate so that the +macros and the `shopify-api` command line share it. + +It bundles no schema: it reads the version a crate pins in +`[package.metadata.shopify_api]` of its `Cargo.toml`, else the one of its +schema file, downloads that version's schema (`download` feature), and stores +it in a compact form (one line per type, no descriptions). diff --git a/crates/shopify_api_graphql/src/analyze.rs b/crates/shopify_api_graphql/src/analyze.rs new file mode 100644 index 0000000..78d0a8e --- /dev/null +++ b/crates/shopify_api_graphql/src/analyze.rs @@ -0,0 +1,1482 @@ +//! Checks a GraphQL operation against a schema and describes the shape of +//! its variables and of its result. +//! +//! # Stricter than the specification, on purpose +//! +//! Where Shopify's server (GraphQL Ruby) refuses what the specification +//! accepts, the analyzer refuses it too, so that an operation it accepts is +//! one Shopify runs. One response key selected twice must have the fields of +//! each input object of its arguments in the same order: the specification +//! says input fields are unordered (`{a: 1, b: 2}` is `{b: 2, a: 1}`), but +//! GraphQL Ruby compares their text and answers `fieldConflict`. An alias +//! spelled like its field (`draftOrderCreate: draftOrderCreate(...)`) is an +//! alias all the same. When the order cannot be read, the operation is +//! refused rather than guessed. + +mod input_objects; + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::fmt; + +use graphql_parser::Pos; +use graphql_parser::query as ast; + +use crate::schema::{Field, InputValue, Schema, TypeDef, TypeRef}; + +type Document<'a> = ast::Document<'a, String>; +type SelectionSet<'a> = ast::SelectionSet<'a, String>; +type Value<'a> = ast::Value<'a, String>; +type Directive<'a> = ast::Directive<'a, String>; + +/// An operation that does not parse or does not fit the schema. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Error { + pub message: String, + /// Line and column in the operation text, both starting at 1. + pub position: Option<(usize, usize)>, +} + +impl fmt::Display for Error { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.position { + Some((line, column)) => { + write!(formatter, "{} (line {line}, column {column})", self.message) + } + None => formatter.write_str(&self.message), + } + } +} + +impl std::error::Error for Error {} + +type Result = std::result::Result; + +fn error_at(position: Pos, message: impl Into) -> Result { + Err(Error { + message: message.into(), + position: Some((position.line, position.column)), + }) +} + +fn error(message: impl Into) -> Result { + Err(Error { + message: message.into(), + position: None, + }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OperationKind { + Query, + Mutation, +} + +/// How a scalar travels in JSON. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum Scalar { + /// `String`, `ID`, enum values, and Shopify's string-encoded scalars such + /// as `DateTime`, `Decimal`, `Money`, `URL` and `UnsignedInt64`. + String, + Int, + Float, + Boolean, + /// `JSON`: any value. + Json, +} + +impl Scalar { + /// How the scalar, or the enum, of this name travels. + pub(crate) fn of(name: &str) -> Self { + match name { + "Int" => Self::Int, + "Float" => Self::Float, + "Boolean" => Self::Boolean, + "JSON" => Self::Json, + _ => Self::String, + } + } +} + +/// What a variable holds, lists and nullability set aside. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum VariableBase { + Scalar(Scalar), + Enum, + /// An input object, named by the variable's type. + Input, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Variable { + pub name: String, + pub ty: TypeRef, + pub has_default: bool, + pub base: VariableBase, +} + +impl Variable { + /// The operation cannot run without a value for this variable. + pub fn is_required(&self) -> bool { + self.ty.is_non_null() && !self.has_default + } +} + +/// The fields selected on an object, interface or union. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Selection { + /// The type the fields are selected on: of the first place, when one + /// response key names fields of different types (see `types`). + pub type_name: String, + pub fields: Vec, + /// Every type the fields are selected on, `type_name` first. More than + /// one when a response key names fields of different object, interface or + /// union types below two exclusive object types (`price` is + /// `Product.priceRangeV2` and `Order.totalPriceSet`): the fields are then + /// those of every place, each conditional unless every place selects it. + pub types: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct SelectedField { + /// The key of the field in the response: its alias, or its name. + pub key: String, + pub ty: TypeRef, + /// The field may be absent: it is selected in a fragment that does not + /// always apply, or under `@include` / `@skip`. + pub conditional: bool, + pub base: FieldBase, + /// A connection of a bulk query, read as the list of its nodes: absent + /// from the line of its parent, filled from the lines that follow. + pub connection: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum FieldBase { + Scalar(Scalar), + Object(Selection), +} + +/// A deprecated field, argument, input field or enum value that an +/// operation uses. `graphql!` turns each one into a compiler warning. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Deprecation { + /// What is deprecated: `Product.bodyHtml`, `Collection.image(maxWidth:)`, + /// `CollectionInput.publications` or `OrderSortKeys.CREATED_AT`. + pub coordinate: String, + /// Shopify's reason, which usually names what replaces it. + pub reason: String, + /// Line and column in the operation text, both starting at 1. + pub position: (usize, usize), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Operation { + pub kind: OperationKind, + pub name: Option, + pub variables: Vec, + pub data: Selection, + /// What the operation uses that the schema deprecates, in the order of the text. + pub deprecations: Vec, +} + +/// Parses `source`, after refusing the block strings the parser panics on. +pub(crate) fn parse(source: &str) -> Result> { + if let Some(position) = crate::source::unreadable_block_strings(source) { + return error_at( + position, + "This block string indents its lines with different Unicode whitespace, which the GraphQL parser this crate uses cannot read. Indent it with spaces or tabs, or write it as a quoted string", + ); + } + graphql_parser::parse_query(source).or_else(|parse_error| { + let text = parse_error.to_string(); + let detail = text.strip_prefix("query parse error: ").unwrap_or(&text); + error(format!( + "Invalid GraphQL: {}", + detail.trim().replace('\n', " ") + )) + }) +} + +/// Parses `source`, checks it against `schema` and returns its shape. +/// +/// `source` contains exactly one query or mutation, and the fragments it uses. +pub fn analyze(schema: &Schema, source: &str) -> Result { + let document = parse(source)?; + + // Checked on the text: the parser keeps only the last of the two. + if let Some((field, position)) = input_objects::duplicate_field(source) { + return error_at( + position, + format!("The input field `{field}` is given twice in the same input object"), + ); + } + + let mut operations = Vec::new(); + let mut fragments = BTreeMap::new(); + for definition in &document.definitions { + match definition { + ast::Definition::Operation(operation) => operations.push(operation), + ast::Definition::Fragment(fragment) => { + if fragments.insert(fragment.name.as_str(), fragment).is_some() { + return error_at( + fragment.position, + format!("Fragment `{}` is defined twice", fragment.name), + ); + } + } + } + } + let operation = match operations.as_slice() { + [operation] => *operation, + [] => return error("The document contains no query or mutation"), + [_, second, ..] => { + return error_at( + operation_position(second), + "The document contains several operations; `graphql!` takes one", + ); + } + }; + + let (kind, name, definitions, directives, selection_set, position) = match operation { + ast::OperationDefinition::SelectionSet(set) => ( + OperationKind::Query, + None, + &[][..], + &[][..], + set, + set.span.0, + ), + ast::OperationDefinition::Query(query) => ( + OperationKind::Query, + query.name.clone(), + &query.variable_definitions[..], + &query.directives[..], + &query.selection_set, + query.position, + ), + ast::OperationDefinition::Mutation(mutation) => ( + OperationKind::Mutation, + mutation.name.clone(), + &mutation.variable_definitions[..], + &mutation.directives[..], + &mutation.selection_set, + mutation.position, + ), + ast::OperationDefinition::Subscription(subscription) => { + return error_at(subscription.position, "Subscriptions are not supported"); + } + }; + let root = match kind { + OperationKind::Query => schema.query.as_str(), + OperationKind::Mutation => match &schema.mutation { + Some(mutation) => mutation.as_str(), + None => return error_at(position, "The schema has no mutations"), + }, + }; + + let mut analyzer = Analyzer { + schema, + source, + argument_orders: HashMap::new(), + fragments, + variables: Vec::new(), + used_variables: BTreeSet::new(), + null_defaults: BTreeSet::new(), + used_fragments: BTreeSet::new(), + fragment_stack: Vec::new(), + deprecations: Vec::new(), + }; + + for definition in definitions { + let ty = type_ref(&definition.var_type); + let base = match schema.get(ty.name()) { + Some(TypeDef::Scalar) => VariableBase::Scalar(Scalar::of(ty.name())), + Some(TypeDef::Enum { .. }) => VariableBase::Enum, + Some(TypeDef::Input { .. }) => VariableBase::Input, + Some(other) => { + return error_at( + definition.position, + format!( + "Variable `${}` cannot have the type `{ty}`: `{}` is {}, not an input type", + definition.name, + ty.name(), + other.kind_name() + ), + ); + } + None => { + return error_at( + definition.position, + format!( + "Variable `${}` has the unknown type `{}`{}", + definition.name, + ty.name(), + did_you_mean(ty.name(), schema.types.keys().map(String::as_str)) + ), + ); + } + }; + if analyzer + .variables + .iter() + .any(|declared| declared.name == definition.name) + { + return error_at( + definition.position, + format!("Variable `${}` is declared twice", definition.name), + ); + } + analyzer.variables.push(Variable { + name: definition.name.clone(), + ty: ty.clone(), + has_default: definition.default_value.is_some(), + base, + }); + if let Some(default) = &definition.default_value { + if matches!(default, ast::Value::Null) { + analyzer.null_defaults.insert(definition.name.clone()); + } + // The parser refuses a variable here. + let expected = InputValue::of(ty); + let place = format!("the default value of `${}`", definition.name); + analyzer.check_value(default, &expected, &place, definition.position)?; + } + } + + let location = match kind { + OperationKind::Query => "QUERY", + OperationKind::Mutation => "MUTATION", + }; + analyzer.check_directives(directives, location)?; + let data = analyzer.selection( + &[SubSet { + set: selection_set, + conditional: false, + lineage: Vec::new(), + parent: root.to_string(), + }], + position, + )?; + + if let Some(unused) = analyzer + .variables + .iter() + .find(|variable| !analyzer.used_variables.contains(&variable.name)) + { + return error(format!( + "Variable `${}` is declared but never used", + unused.name + )); + } + if let Some((unused, fragment)) = analyzer + .fragments + .iter() + .find(|(name, _)| !analyzer.used_fragments.contains(**name)) + { + return error_at( + fragment.position, + format!("Fragment `{unused}` is defined but never used"), + ); + } + + let mut deprecations = analyzer.deprecations; + deprecations.sort_by(|left, right| { + (left.position, &left.coordinate).cmp(&(right.position, &right.coordinate)) + }); + deprecations.dedup(); + Ok(Operation { + kind, + name, + variables: analyzer.variables, + data, + deprecations, + }) +} + +fn operation_position(operation: &ast::OperationDefinition<'_, String>) -> Pos { + match operation { + ast::OperationDefinition::SelectionSet(set) => set.span.0, + ast::OperationDefinition::Query(query) => query.position, + ast::OperationDefinition::Mutation(mutation) => mutation.position, + ast::OperationDefinition::Subscription(subscription) => subscription.position, + } +} + +fn type_ref(ty: &ast::Type<'_, String>) -> TypeRef { + match ty { + ast::Type::NamedType(name) => TypeRef::Named(name.clone()), + ast::Type::ListType(inner) => TypeRef::List(Box::new(type_ref(inner))), + ast::Type::NonNullType(inner) => TypeRef::NonNull(Box::new(type_ref(inner))), + } +} + +/// A field being assembled from every place that selects its response key. +struct Pending<'a> { + key: String, + field: String, + ty: TypeRef, + /// Where the key was selected: on which parent type, which field, with + /// which arguments. + origins: Vec>, + /// The field may be absent from a value of the parent. + conditional: bool, + /// The subfields selected at each place that selects some. + sets: Vec>, + /// The selections of the parent (see [`Analyzer::selection`]) that select + /// the field unconditionally. + unconditional_in: BTreeSet, + position: Pos, +} + +/// The selection set of a field at one place. +struct SubSet<'a> { + set: &'a SelectionSet<'a>, + /// The place may be absent while the value is present. + conditional: bool, + /// The [`Lineage`] of the place. + lineage: Lineage, + /// The type the set is selected on: the field's type at that place, which + /// may differ from one place to another (see [`Selection::types`]). + parent: String, +} + +/// The parent type of a place and of each field above it, from the root: +/// two places whose lineages differ by two object types at some depth are +/// never both in one answer. +type Lineage = Vec; + +/// One place a response key is selected at. +struct Origin<'a> { + /// Its parent type last. + lineage: Lineage, + field: String, + /// The type of the field there. + ty: TypeRef, + arguments: &'a [(String, Value<'a>)], + position: Pos, + /// The field has a selection set there. + selects: bool, +} + +/// How the arguments of two places that select one response key compare. +enum Arguments { + Same, + Different, + /// Equal, but the fields of an input object come in another order. + Reordered, +} + +/// Which of the sets merged into one selection a field comes from. +#[derive(Clone, Copy)] +struct Place { + index: usize, + /// The set may be absent while the value is present. + uncertain: bool, +} + +/// Two values written alike, as Shopify compares the arguments of two fields +/// (GraphQL Ruby's `fieldConflict`): of the same kind (`1` is not `1.0`, `"A"` +/// is not `A`), equal, with lists in the same order. Input objects are +/// compared field by field here; the order of their fields, which the parser +/// does not keep, is compared on the text (see [`Analyzer::same_arguments`]). +fn same_value(left: &Value<'_>, right: &Value<'_>) -> bool { + use ast::Value as V; + match (left, right) { + (V::Variable(left), V::Variable(right)) + | (V::String(left), V::String(right)) + | (V::Enum(left), V::Enum(right)) => left == right, + (V::Int(left), V::Int(right)) => left.as_i64() == right.as_i64(), + // `-0.0` is not `0.0`; `1.0` is `1.00`. + (V::Float(left), V::Float(right)) => left.to_bits() == right.to_bits(), + (V::Boolean(left), V::Boolean(right)) => left == right, + (V::Null, V::Null) => true, + (V::List(left), V::List(right)) => { + left.len() == right.len() + && left + .iter() + .zip(right) + .all(|(left, right)| same_value(left, right)) + } + (V::Object(left), V::Object(right)) => { + left.len() == right.len() + && left.iter().all(|(name, left)| { + right.get(name).is_some_and(|right| same_value(left, right)) + }) + } + _ => false, + } +} + +/// Holds an input object of two fields or more, whose order matters. +fn has_ordered_object(value: &Value<'_>) -> bool { + match value { + ast::Value::Object(fields) => fields.len() > 1 || fields.values().any(has_ordered_object), + ast::Value::List(items) => items.iter().any(has_ordered_object), + _ => false, + } +} + +/// The arguments of a field for a message, each value written with its kind. +fn arguments_text(arguments: &[(String, Value<'_>)]) -> String { + let written: Vec = arguments + .iter() + .map(|(name, value)| format!("{name}: {}", value_text(value))) + .collect(); + written.join(", ") +} + +fn value_text(value: &Value<'_>) -> String { + match value { + ast::Value::Variable(name) => format!("${name}"), + ast::Value::Int(number) => number.as_i64().unwrap_or_default().to_string(), + ast::Value::Float(number) => format!("{number:?}"), + ast::Value::String(text) => format!("{text:?}"), + ast::Value::Boolean(value) => value.to_string(), + ast::Value::Null => "null".to_string(), + ast::Value::Enum(name) => name.clone(), + ast::Value::List(items) => { + let items: Vec = items.iter().map(value_text).collect(); + format!("[{}]", items.join(", ")) + } + ast::Value::Object(fields) => { + let fields: Vec = fields + .iter() + .map(|(name, value)| format!("{name}: {}", value_text(value))) + .collect(); + format!("{{{}}}", fields.join(", ")) + } + } +} + +/// The arguments of a field and the order of their input fields, by name. +type ArgumentOrders<'a> = Option)>>; + +struct Analyzer<'a> { + schema: &'a Schema, + source: &'a str, + /// [`input_objects::argument_orders`] of the fields compared so far, by + /// position. + argument_orders: HashMap<(usize, usize), ArgumentOrders<'a>>, + fragments: BTreeMap<&'a str, &'a ast::FragmentDefinition<'a, String>>, + /// The declared variables, in the order of the operation. + variables: Vec, + used_variables: BTreeSet, + /// The variables whose default value is `null`: it does not stand in for + /// a value where `null` is not allowed. + null_defaults: BTreeSet, + used_fragments: BTreeSet<&'a str>, + fragment_stack: Vec<&'a str>, + deprecations: Vec, +} + +impl<'a> Analyzer<'a> { + fn deprecated(&mut self, coordinate: String, reason: Option<&String>, position: Pos) { + if let Some(reason) = reason { + self.deprecations.push(Deprecation { + coordinate, + reason: reason.clone(), + position: (position.line, position.column), + }); + } + } + + /// Resolves the merged selection sets of one value of type `parent`. + /// + /// Each set comes with whether the place that selected it may be absent + /// while the value is present. When one place is always there, what the + /// others select is conditional. When none is, any of them may be the + /// one that is there: a subfield is then certain only if every place + /// selects it. + fn selection(&mut self, sets: &[SubSet<'a>], position: Pos) -> Result { + let mut types: Vec = Vec::new(); + for sub in sets { + if !types.contains(&sub.parent) { + types.push(sub.parent.clone()); + } + } + let any_certain = sets.iter().any(|sub| !sub.conditional); + let mut pending = Vec::new(); + for (index, sub) in sets.iter().enumerate() { + let place = Place { + index, + // Several places that may each be the one there: what each + // brings below its fields is only there with it. + uncertain: !any_certain && sets.len() > 1, + }; + self.collect( + &sub.parent, + sub.set, + any_certain && sub.conditional, + place, + &sub.lineage, + &mut pending, + )?; + } + if !any_certain && sets.len() > 1 { + for field in &mut pending { + field.conditional |= field.unconditional_in.len() < sets.len(); + } + } + if pending.is_empty() { + return error_at( + position, + format!("The selection on `{}` is empty", types.join("` and `")), + ); + } + + let mut fields = Vec::new(); + for field in pending { + let named = field.ty.name(); + let base = match self.schema.get(named) { + Some(definition) if definition.is_composite() => { + // Every place selects subfields, not only one of them. + if let Some(bare) = field.origins.iter().find(|origin| !origin.selects) { + return error_at( + bare.position, + format!( + "Field `{}` has the type `{}`: select the subfields you need, `{} {{ … }}`", + bare.field, bare.ty, bare.field + ), + ); + } + FieldBase::Object(self.selection(&field.sets, field.position)?) + } + Some(_) => { + if let Some(selecting) = field.origins.iter().find(|origin| origin.selects) { + return error_at( + selecting.position, + format!( + "Field `{}` has the type `{}`, which has no subfields", + selecting.field, selecting.ty + ), + ); + } + FieldBase::Scalar(Scalar::of(named)) + } + None => { + return error_at( + field.position, + format!("The schema does not define the type `{named}`"), + ); + } + }; + fields.push(SelectedField { + key: field.key, + ty: field.ty, + conditional: field.conditional, + base, + connection: false, + }); + } + + Ok(Selection { + type_name: types[0].clone(), + fields, + types, + }) + } + + /// Collects the fields `set` selects on `parent`, from `place` among + /// the sets [`Analyzer::selection`] merges. + fn collect( + &mut self, + parent: &str, + set: &'a SelectionSet<'a>, + conditional: bool, + place: Place, + lineage: &[String], + pending: &mut Vec>, + ) -> Result<()> { + for item in &set.items { + match item { + ast::Selection::Field(field) => { + let conditional = + conditional | self.check_directives(&field.directives, "FIELD")?; + let ty = self.field_type(parent, field)?; + let key = field.alias.as_ref().unwrap_or(&field.name).clone(); + let selects = !field.selection_set.items.is_empty(); + let origin = |lineage| Origin { + lineage, + field: field.name.clone(), + ty: ty.clone(), + arguments: &field.arguments, + position: field.position, + selects, + }; + let origin_lineage: Lineage = lineage + .iter() + .cloned() + .chain([parent.to_string()]) + .collect(); + let sets = selects.then(|| SubSet { + set: &field.selection_set, + conditional: conditional || place.uncertain, + lineage: origin_lineage.clone(), + parent: ty.name().to_string(), + }); + + match pending.iter_mut().find(|existing| existing.key == key) { + Some(existing) => { + // SameResponseShape: the answer holds one value + // under the key, of one shape. Below, the + // subfields of every place merge and are checked + // the same way. + if !self.same_shape(&existing.ty, &ty) { + return error_at( + field.position, + format!( + "`{key}` is selected twice with different fields or types (`{}: {}` and `{}: {ty}`); give one of them an alias", + existing.field, existing.ty, field.name + ), + ); + } + // FieldsInSetCanMerge: on two different object + // types, never both there, the fields and their + // arguments may differ, and so may those below + // them; elsewhere they may not. + for origin in &existing.origins { + if !self.exclusive(&origin.lineage, &origin_lineage) { + if origin.field != field.name { + return error_at( + field.position, + format!( + "`{key}` is selected twice with different fields or types (`{}: {}` and `{}: {ty}`); give one of them an alias", + origin.field, existing.ty, field.name + ), + ); + } + match self.same_arguments(origin, field) { + Arguments::Same => {} + Arguments::Different => { + return error_at( + field.position, + format!( + "`{key}` is selected twice with different arguments (`({})` and `({})`); give one of them an alias", + arguments_text(origin.arguments), + arguments_text(&field.arguments) + ), + ); + } + Arguments::Reordered => { + return error_at( + field.position, + format!( + "`{key}` is selected twice with the fields of an input object in another order (`({})`), which Shopify refuses; write them in the same order, or give one of them an alias", + arguments_text(&field.arguments) + ), + ); + } + } + } + } + existing.origins.push(origin(origin_lineage)); + existing.conditional &= conditional; + existing.sets.extend(sets); + if !conditional { + existing.unconditional_in.insert(place.index); + } + } + None => pending.push(Pending { + key, + field: field.name.clone(), + ty: ty.clone(), + origins: vec![origin(origin_lineage)], + conditional, + sets: sets.into_iter().collect(), + unconditional_in: (!conditional) + .then_some(place.index) + .into_iter() + .collect(), + position: field.position, + }), + } + } + ast::Selection::InlineFragment(fragment) => { + let conditional = conditional + | self.check_directives(&fragment.directives, "INLINE_FRAGMENT")?; + let (target, always) = match &fragment.type_condition { + Some(ast::TypeCondition::On(condition)) => ( + condition.as_str(), + self.fragment_always_applies(parent, condition, fragment.position)?, + ), + None => (parent, true), + }; + self.collect( + target, + &fragment.selection_set, + conditional | !always, + place, + lineage, + pending, + )?; + } + ast::Selection::FragmentSpread(spread) => { + let conditional = conditional + | self.check_directives(&spread.directives, "FRAGMENT_SPREAD")?; + let name = spread.fragment_name.as_str(); + let Some(fragment) = self.fragments.get(name).copied() else { + return error_at( + spread.position, + format!( + "Fragment `{name}` is not defined{}; a `graphql!` document contains the fragments it uses", + did_you_mean(name, self.fragments.keys().copied()) + ), + ); + }; + if self.fragment_stack.contains(&name) { + return error_at( + spread.position, + format!("Fragment `{name}` includes itself"), + ); + } + self.used_fragments.insert(fragment.name.as_str()); + self.check_directives(&fragment.directives, "FRAGMENT_DEFINITION")?; + + let ast::TypeCondition::On(condition) = &fragment.type_condition; + let always = + self.fragment_always_applies(parent, condition, spread.position)?; + self.fragment_stack.push(fragment.name.as_str()); + let collected = self.collect( + condition, + &fragment.selection_set, + conditional | !always, + place, + lineage, + pending, + ); + self.fragment_stack.pop(); + collected?; + } + } + } + Ok(()) + } + + /// Whether `field` gives the arguments `origin` gave. + fn same_arguments( + &mut self, + origin: &Origin<'a>, + field: &'a ast::Field<'a, String>, + ) -> Arguments { + let (left, right) = (origin.arguments, &field.arguments); + let same = left.len() == right.len() + && left.iter().all(|(name, left)| { + right + .iter() + .find(|(given, _)| given == name) + .is_some_and(|(_, right)| same_value(left, right)) + }); + if !same { + return Arguments::Different; + } + if !left.iter().any(|(_, value)| has_ordered_object(value)) { + return Arguments::Same; + } + let left = self.argument_orders(origin.position, &origin.field); + let right = self.argument_orders(field.position, &field.name); + match (left, right) { + (Some(left), Some(right)) + if left.iter().all(|(name, order)| { + right + .iter() + .any(|(given, other)| given == name && order == other) + }) => + { + Arguments::Same + } + // The text cannot be read back: refuse rather than send what + // Shopify may refuse. + _ => Arguments::Reordered, + } + } + + fn argument_orders(&mut self, position: Pos, name: &str) -> ArgumentOrders<'a> { + let source = self.source; + self.argument_orders + .entry((position.line, position.column)) + .or_insert_with(|| input_objects::argument_orders(source, position, name)) + .clone() + } + + /// SameResponseShape, for the types of two fields: the same lists and + /// nullability, the same scalar or enum, or two types with subfields, + /// whose selections [`Analyzer::selection`] then merges. + fn same_shape(&self, left: &TypeRef, right: &TypeRef) -> bool { + match (left, right) { + (TypeRef::NonNull(left), TypeRef::NonNull(right)) + | (TypeRef::List(left), TypeRef::List(right)) => self.same_shape(left, right), + (TypeRef::Named(left), TypeRef::Named(right)) => { + let composite = + |name: &str| self.schema.get(name).is_some_and(TypeDef::is_composite); + left == right || (composite(left) && composite(right)) + } + _ => false, + } + } + + /// An object type, as opposed to an interface or a union. + fn is_object(&self, name: &str) -> bool { + matches!(self.schema.get(name), Some(TypeDef::Object { .. })) + } + + /// Two places never both in one answer: at some depth, their parents are + /// two different object types. + fn exclusive(&self, left: &[String], right: &[String]) -> bool { + left.iter() + .zip(right) + .any(|(left, right)| left != right && self.is_object(left) && self.is_object(right)) + } + + /// Whether every value of type `parent` matches a fragment on `condition`. + /// Fails when none can. + fn fragment_always_applies( + &self, + parent: &str, + condition: &str, + position: Pos, + ) -> Result { + match self.schema.get(condition) { + Some(definition) if definition.is_composite() => {} + Some(definition) => { + return error_at( + position, + format!( + "A fragment cannot be on `{condition}`, which is {}", + definition.kind_name() + ), + ); + } + None => { + return error_at( + position, + format!( + "A fragment is on the unknown type `{condition}`{}", + did_you_mean(condition, self.schema.possible_types(parent).into_iter()) + ), + ); + } + } + let of_parent = self.schema.possible_types(parent); + let of_condition = self.schema.possible_types(condition); + if !of_parent.iter().any(|ty| of_condition.contains(ty)) { + return error_at( + position, + format!("A fragment on `{condition}` never applies to a `{parent}`"), + ); + } + Ok(of_parent.iter().all(|ty| of_condition.contains(ty))) + } + + /// The type of `field` on `parent`, after checking its arguments. + fn field_type(&mut self, parent: &str, field: &'a ast::Field<'a, String>) -> Result { + if field.name == "__typename" { + if let Some((argument, _)) = field.arguments.first() { + return error_at( + field.position, + format!("Field `__typename` has no argument `{argument}`"), + ); + } + return Ok(TypeRef::NonNull(Box::new(TypeRef::Named( + "String".to_string(), + )))); + } + + let fields = match self.schema.get(parent) { + Some(TypeDef::Object { fields, .. } | TypeDef::Interface { fields, .. }) => fields, + Some(TypeDef::Union { possible_types }) => { + return error_at( + field.position, + format!( + "`{parent}` is a union: select `{}` inside a fragment such as `... on {} {{ {} }}`", + field.name, + possible_types.first().map_or("Type", String::as_str), + field.name + ), + ); + } + _ => { + return error_at( + field.position, + format!("`{parent}` has no fields to select"), + ); + } + }; + let Some(definition) = fields.get(&field.name) else { + return error_at( + field.position, + format!( + "Type `{parent}` has no field `{}`{}", + field.name, + did_you_mean(&field.name, fields.keys().map(String::as_str)) + ), + ); + }; + self.deprecated( + format!("{parent}.{}", field.name), + definition.deprecation.as_ref(), + field.position, + ); + self.check_arguments(parent, field, definition)?; + Ok(definition.ty.clone()) + } + + fn check_arguments( + &mut self, + parent: &str, + field: &'a ast::Field<'a, String>, + definition: &Field, + ) -> Result<()> { + for (index, (name, value)) in field.arguments.iter().enumerate() { + if field.arguments[..index] + .iter() + .any(|(earlier, _)| earlier == name) + { + return error_at( + field.position, + format!( + "Field `{parent}.{}` is given the argument `{name}` twice", + field.name + ), + ); + } + let Some(argument) = definition.args.get(name) else { + return error_at( + field.position, + format!( + "Field `{parent}.{}` has no argument `{name}`{}", + field.name, + did_you_mean(name, definition.args.keys().map(String::as_str)) + ), + ); + }; + self.deprecated( + format!("{parent}.{}({name}:)", field.name), + argument.deprecation.as_ref(), + field.position, + ); + let place = format!("argument `{name}` of `{parent}.{}`", field.name); + self.check_value(value, argument, &place, field.position)?; + } + for (name, argument) in &definition.args { + if argument.is_required() && !field.arguments.iter().any(|(given, _)| given == name) { + return error_at( + field.position, + format!( + "Field `{parent}.{}` requires the argument `{name}: {}`", + field.name, argument.ty + ), + ); + } + } + Ok(()) + } + + /// Checks the directives written at `location` (`FIELD`, `QUERY`…) + /// against those of the schema. Returns whether they make the selection + /// conditional: `@include` and `@skip`. + fn check_directives( + &mut self, + directives: &'a [Directive<'a>], + location: &str, + ) -> Result { + let schema = self.schema; + let mut conditional = false; + for (index, directive) in directives.iter().enumerate() { + let name = directive.name.as_str(); + let Some(definition) = schema.directive(name) else { + return error_at( + directive.position, + format!( + "The schema has no directive `@{name}`{}", + did_you_mean(name, schema.directives.keys().map(String::as_str)) + .replacen('`', "`@", 1) + ), + ); + }; + if !definition + .locations + .iter() + .any(|allowed| allowed == location) + { + let place = location.to_lowercase().replace('_', " "); + return error_at( + directive.position, + format!("`@{name}` cannot be written on a {place}"), + ); + } + if !definition.repeatable + && directives[..index] + .iter() + .any(|earlier| earlier.name == name) + { + return error_at( + directive.position, + format!("`@{name}` is written twice at the same place"), + ); + } + for (position, (argument, value)) in directive.arguments.iter().enumerate() { + if directive.arguments[..position] + .iter() + .any(|(earlier, _)| earlier == argument) + { + return error_at( + directive.position, + format!("`@{name}` is given the argument `{argument}` twice"), + ); + } + let Some(expected) = definition.args.get(argument) else { + return error_at( + directive.position, + format!( + "`@{name}` has no argument `{argument}`{}", + did_you_mean(argument, definition.args.keys().map(String::as_str)) + ), + ); + }; + let place = format!("argument `{argument}` of `@{name}`"); + self.check_value(value, expected, &place, directive.position)?; + } + if let Some((missing, expected)) = + definition.args.iter().find(|(argument, expected)| { + expected.is_required() + && !directive + .arguments + .iter() + .any(|(given, _)| given == *argument) + }) + { + return error_at( + directive.position, + format!( + "`@{name}` requires the argument `{missing}: {}`", + expected.ty + ), + ); + } + conditional |= matches!(name, "include" | "skip"); + } + Ok(conditional) + } + + /// Marks the variables of a value whose type is not known. + fn mark_variables(&mut self, value: &Value<'a>, position: Pos) -> Result<()> { + match value { + ast::Value::Variable(name) => { + self.variable(name, position)?; + } + ast::Value::List(items) => { + for item in items { + self.mark_variables(item, position)?; + } + } + ast::Value::Object(fields) => { + for item in fields.values() { + self.mark_variables(item, position)?; + } + } + _ => {} + } + Ok(()) + } + + /// The declared variable of this name, which is thereby used. + fn variable(&mut self, name: &str, position: Pos) -> Result<&Variable> { + let Some(variable) = self.variables.iter().find(|variable| variable.name == name) else { + let declared = self.variables.iter().map(|variable| variable.name.as_str()); + return error_at( + position, + format!( + "Variable `${name}` is not declared{}", + did_you_mean(name, declared) + ), + ); + }; + self.used_variables.insert(name.to_string()); + Ok(variable) + } + + /// The rule of a `@oneOf` input object: exactly one field, whose value is + /// not `null`, nor a variable that may be. + fn check_one_of( + &mut self, + named: &str, + fields: &BTreeMap, + given: &BTreeMap>, + place: &str, + position: Pos, + ) -> Result<()> { + let names: Vec = fields.keys().map(|key| format!("`{key}`")).collect(); + let rule = format!( + "`{named}` is a oneOf input: give exactly one of {}, not null (in {place})", + crate::literal::join(&names, "or") + ); + let mut entries = given.iter(); + let (Some((name, value)), None) = (entries.next(), entries.next()) else { + return error_at(position, rule); + }; + match value { + ast::Value::Null => error_at(position, format!("{rule}: `{name}: null` is not one")), + ast::Value::Variable(variable) => { + let ty = self.variable(variable, position)?.ty.clone(); + if ty.is_non_null() { + return Ok(()); + } + error_at( + position, + format!( + "{rule}: `${variable}` is of type `{ty}`, which may be null; declare it `{ty}!`" + ), + ) + } + _ => Ok(()), + } + } + + /// Checks a literal or a variable given where `expected` is wanted. + fn check_value( + &mut self, + value: &Value<'a>, + expected: &InputValue, + place: &str, + position: Pos, + ) -> Result<()> { + let inner = expected.ty.nullable(); + // A custom scalar, `JSON` among them, defines its own literals: an object + // or a list is a value of it, not an input object or a list of the schema. + if let TypeRef::Named(name) = inner + && !matches!(value, ast::Value::Variable(_) | ast::Value::Null) + && !matches!(name.as_str(), "Int" | "Float" | "String" | "Boolean" | "ID") + && matches!(self.schema.get(name), Some(TypeDef::Scalar)) + { + return self.mark_variables(value, position); + } + match value { + ast::Value::Variable(name) => { + let null_default = self.null_defaults.contains(name); + let variable = self.variable(name, position)?; + if !variable_fits(variable, null_default, expected) { + return error_at( + position, + format!( + "Variable `${name}` of type `{}` cannot be used for {place}, which expects `{}`", + variable.ty, expected.ty + ), + ); + } + } + ast::Value::Null => { + if expected.ty.is_non_null() { + return error_at( + position, + format!( + "`null` is not allowed for {place}, of type `{}`", + expected.ty + ), + ); + } + } + ast::Value::List(items) => { + // GraphQL accepts a single value where a list is expected, not the opposite. + let TypeRef::List(item_type) = inner else { + return error_at( + position, + format!("A list is given for {place}, of type `{}`", expected.ty), + ); + }; + let item = InputValue::of((**item_type).clone()); + for value in items { + self.check_value(value, &item, place, position)?; + } + } + ast::Value::Object(given) => { + let named = inner.name(); + let Some(TypeDef::Input { fields, one_of }) = self.schema.get(named) else { + return error_at( + position, + format!("An object is given for {place}, of type `{}`", expected.ty), + ); + }; + if *one_of { + self.check_one_of(named, fields, given, place, position)?; + } + for (name, value) in given { + let Some(field) = fields.get(name) else { + return error_at( + position, + format!( + "Input type `{named}` has no field `{name}`{} (in {place})", + did_you_mean(name, fields.keys().map(String::as_str)) + ), + ); + }; + self.deprecated( + format!("{named}.{name}"), + field.deprecation.as_ref(), + position, + ); + self.check_value( + value, + field, + &format!("field `{name}` of `{named}`"), + position, + )?; + } + if let Some((missing, field)) = fields + .iter() + .find(|(name, field)| field.is_required() && !given.contains_key(*name)) + { + return error_at( + position, + format!( + "Input type `{named}` requires the field `{missing}: {}` (in {place})", + field.ty + ), + ); + } + } + ast::Value::Enum(given) => match self.schema.get(inner.name()) { + Some(TypeDef::Enum { values, deprecated }) + if matches!(inner, TypeRef::Named(_)) => + { + if !values.contains(given) { + return error_at( + position, + format!( + "`{given}` is not a value of the enum `{}`{} (in {place})", + inner.name(), + did_you_mean(given, values.iter().map(String::as_str)) + ), + ); + } + let reason = deprecated.get(given).cloned(); + self.deprecated( + format!("{}.{given}", inner.name()), + reason.as_ref(), + position, + ); + } + // A single value where a list of enum values is expected. + Some(TypeDef::Enum { .. }) => { + let item = InputValue::of(TypeRef::Named(inner.name().to_string())); + self.check_value(value, &item, place, position)?; + } + _ => { + return error_at( + position, + format!( + "The enum value `{given}` is given for {place}, of type `{}`", + expected.ty + ), + ); + } + }, + ast::Value::Int(number) if inner.name() == "Int" && !fits_int(number) => { + return error_at( + position, + format!( + "The integer is outside the range of `Int`, a 32-bit integer, given for {place}" + ), + ); + } + literal => { + let given = match literal { + ast::Value::Int(_) => "an integer", + ast::Value::Float(_) => "a float", + ast::Value::String(_) => "a string", + _ => "a boolean", + }; + let accepted = match (inner.name(), literal) { + ("Int", ast::Value::Int(_)) => true, + ("Float", ast::Value::Int(_) | ast::Value::Float(_)) => true, + ("String", ast::Value::String(_)) => true, + ("Boolean", ast::Value::Boolean(_)) => true, + ("ID", ast::Value::String(_) | ast::Value::Int(_)) => true, + ("Int" | "Float" | "String" | "Boolean" | "ID", _) => false, + // Custom scalars define their own literals; enums and input objects do not accept these. + (name, _) => matches!(self.schema.get(name), Some(TypeDef::Scalar)), + }; + if !accepted { + return error_at( + position, + format!("{given} is given for {place}, of type `{}`", expected.ty), + ); + } + } + } + Ok(()) + } +} + +/// `Int` is a signed 32-bit integer in GraphQL. +fn fits_int(number: &ast::Number) -> bool { + number + .as_i64() + .is_some_and(|number| i32::try_from(number).is_ok()) +} + +/// The rule of the GraphQL specification for using a variable at a location +/// ("All Variable Usages Are Allowed"). `null_default`: the default value of +/// the variable is `null`. +fn variable_fits(variable: &Variable, null_default: bool, location: &InputValue) -> bool { + fn compatible(variable: &TypeRef, location: &TypeRef) -> bool { + match (variable, location) { + (TypeRef::NonNull(variable), TypeRef::NonNull(location)) => { + compatible(variable, location) + } + (_, TypeRef::NonNull(_)) => false, + (TypeRef::NonNull(variable), location) => compatible(variable, location), + (TypeRef::List(variable), TypeRef::List(location)) => compatible(variable, location), + (TypeRef::Named(variable), TypeRef::Named(location)) => variable == location, + _ => false, + } + } + if location.ty.is_non_null() && !variable.ty.is_non_null() { + // A nullable variable is accepted when a default value other than + // `null` fills the gap. + return ((variable.has_default && !null_default) || location.has_default) + && compatible(&variable.ty, location.ty.nullable()); + } + compatible(&variable.ty, &location.ty) +} + +/// ` (did you mean `x`?)` for the candidate closest to `name`, or nothing. +pub(crate) fn did_you_mean<'a>(name: &str, candidates: impl Iterator) -> String { + let lowered = name.to_lowercase(); + // Half of the name may differ, within three edits: `frist` → `first`, `CREATED` → `CREATED_AT`. + let limit = (name.len() / 2).clamp(1, 3); + candidates + .map(|candidate| { + ( + edit_distance(&lowered, &candidate.to_lowercase()), + candidate, + ) + }) + .filter(|(distance, _)| *distance <= limit) + .min() + .map(|(_, candidate)| format!(" (did you mean `{candidate}`?)")) + .unwrap_or_default() +} + +fn edit_distance(left: &str, right: &str) -> usize { + let right: Vec = right.chars().collect(); + let mut row: Vec = (0..=right.len()).collect(); + for (i, a) in left.chars().enumerate() { + let mut previous = row[0]; + row[0] = i + 1; + for (j, b) in right.iter().enumerate() { + let substitution = previous + usize::from(a != *b); + previous = row[j + 1]; + row[j + 1] = substitution.min(previous + 1).min(row[j] + 1); + } + } + row[right.len()] +} diff --git a/crates/shopify_api_graphql/src/analyze/input_objects.rs b/crates/shopify_api_graphql/src/analyze/input_objects.rs new file mode 100644 index 0000000..84f629f --- /dev/null +++ b/crates/shopify_api_graphql/src/analyze/input_objects.rs @@ -0,0 +1,363 @@ +//! What the parser loses of input objects, read from the text itself. +//! +//! The parser keeps input objects in a map, so of `{ title: "a", title: "b" }` +//! (invalid: Input Object Field Uniqueness) the analyzer only sees the second +//! `title`, and `{ a: 1, b: 2 }` looks like `{ b: 2, a: 1 }`, which Shopify +//! tells apart when it compares the arguments of two fields. + +use std::collections::HashSet; + +use graphql_parser::Pos; + +/// The first input field given twice in one input object of `source`, with +/// its position. `source` already parsed: anything unexpected ends the scan. +pub(super) fn duplicate_field(source: &str) -> Option<(&str, Pos)> { + let mut lexer = Lexer::new(source); + let mut frames: Vec> = Vec::new(); + let mut previous: Option> = None; + while let Some((token, start)) = lexer.next() { + match token { + Token::Punctuator(b'{') => { + // A value follows `:` (an argument or a field of an input + // object) or `=` (a default value), or stands in a list. + let object = matches!(previous, Some(Token::Punctuator(b':' | b'='))) + || matches!(frames.last(), Some(Frame::List)); + frames.push(if object { + Frame::Object(HashSet::new()) + } else { + Frame::Other + }); + } + Token::Punctuator(b'[') => frames.push(Frame::List), + Token::Punctuator(b'(') => frames.push(Frame::Other), + Token::Punctuator(b'}' | b']' | b')') => { + frames.pop()?; + } + Token::Name(name) => { + // In an input object, a name is a field unless it is the value + // of one (an enum value, `true`, `null`) or of a variable. + if let Some(Frame::Object(fields)) = frames.last_mut() + && !matches!(previous, Some(Token::Punctuator(b':' | b'$'))) + && !fields.insert(name) + { + return Some((name, position_of(source, start))); + } + } + _ => {} + } + previous = Some(token); + } + None +} + +/// The order of the input fields of each argument of the field at `field` +/// (its position as the parser gives it): for each argument, by name, the +/// brackets of its value and the names of the input fields in the order of +/// the text. Two values the parser holds equal have their fields in the same +/// order when these are equal. +/// +/// `None` when the text at `field` is not the field `name`. +pub(super) fn argument_orders<'a>( + source: &'a str, + field: Pos, + name: &str, +) -> Option)>> { + let mut lexer = Lexer::new(source); + // The field starts with its alias or its name. + let first = loop { + let at = lexer.pos; + let (token, _) = lexer.next()?; + if at == field { + break token; + } + if (at.line, at.column) > (field.line, field.column) { + return None; + } + }; + let Token::Name(first) = first else { + return None; + }; + let mut after = lexer.next(); + // `alias: name`, the alias spelled like the name or not: the colon says + // which it is. + if after.map(|(token, _)| token) == Some(Token::Punctuator(b':')) { + if lexer.next().map(|(token, _)| token) != Some(Token::Name(name)) { + return None; + } + after = lexer.next(); + } else if first != name { + return None; + } + let mut arguments = Vec::new(); + if after.map(|(token, _)| token) != Some(Token::Punctuator(b'(')) { + return Some(arguments); + } + // The arguments: `Other`; in their values, objects and lists. + let mut frames: Vec> = vec![Frame::Other]; + let mut previous: Option> = None; + while let Some((token, _)) = lexer.next() { + let order = match token { + Token::Punctuator(b'{') => { + frames.push(Frame::Object(HashSet::new())); + Some("{") + } + Token::Punctuator(b'[') => { + frames.push(Frame::List); + Some("[") + } + Token::Punctuator(close @ (b'}' | b']' | b')')) => { + frames.pop()?; + if frames.is_empty() { + return Some(arguments); + } + Some(if close == b'}' { "}" } else { "]" }) + } + // A name is an argument or an input field unless it is a value. + Token::Name(name) if !matches!(previous, Some(Token::Punctuator(b':' | b'$'))) => { + match frames.last() { + Some(Frame::Other) => { + arguments.push((name, Vec::new())); + None + } + Some(Frame::Object(_)) => Some(name), + _ => None, + } + } + _ => None, + }; + if let Some(order) = order { + arguments.last_mut()?.1.push(order); + } + previous = Some(token); + } + None +} + +enum Frame<'a> { + /// An input object, with the fields given so far. + Object(HashSet<&'a str>), + List, + /// A selection set or arguments. + Other, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Token<'a> { + Name(&'a str), + Punctuator(u8), + /// A string, a number, or a punctuator of no use here. + Other, +} + +struct Lexer<'a> { + text: &'a str, + position: usize, + /// The position of the next token as the parser counts it: a tab is 8 + /// columns, `\r` none, a name or a number one per byte, a string one per + /// character. + pos: Pos, +} + +impl<'a> Lexer<'a> { + fn new(text: &'a str) -> Self { + let mut lexer = Self { + text, + position: 0, + pos: Pos { line: 1, column: 1 }, + }; + lexer.skip_ignored(); + lexer + } + + /// The next token and where it starts, `None` at the end. + fn next(&mut self) -> Option<(Token<'a>, usize)> { + let rest = &self.text.as_bytes()[self.position..]; + let &first = rest.first()?; + let start = self.position; + let (token, length) = match first { + b'A'..=b'Z' | b'a'..=b'z' | b'_' => { + let length = rest + .iter() + .position(|byte| !(byte.is_ascii_alphanumeric() || *byte == b'_')) + .unwrap_or(rest.len()); + (Token::Name(&self.text[start..start + length]), length) + } + b'"' if rest.starts_with(b"\"\"\"") => { + // A block string: its only escape is `\"""`. + let mut index = 3; + loop { + let tail = rest.get(index..).filter(|tail| !tail.is_empty())?; + if tail.starts_with(b"\\\"\"\"") { + index += 4; + } else if tail.starts_with(b"\"\"\"") { + break; + } else { + index += 1; + } + } + (Token::Other, index + 3) + } + b'"' => { + let mut index = 1; + loop { + match rest.get(index)? { + b'\\' => index += 2, + b'"' => break, + _ => index += 1, + } + } + (Token::Other, index + 1) + } + b'{' | b'}' | b'(' | b')' | b'[' | b']' | b':' | b'=' | b'$' => { + (Token::Punctuator(first), 1) + } + b'0'..=b'9' | b'-' => { + let length = rest + .iter() + .position(|byte| { + !(byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'+' | b'-')) + }) + .unwrap_or(rest.len()); + (Token::Other, length) + } + _ => { + let length = self.text[start..].chars().next().map_or(1, char::len_utf8); + (Token::Other, length) + } + }; + let text = &self.text[start..start + length]; + if first == b'"' && length >= 6 && text.starts_with("\"\"\"") { + let lines = text.matches('\n').count(); + if lines > 0 { + let last = text.rfind('\n').map_or(0, |index| index + 1); + self.pos.line += lines; + self.pos.column = text[last..].chars().count() + 1; + } else { + self.pos.column += text.chars().count(); + } + } else if first == b'"' { + self.pos.column += text.chars().count(); + } else { + self.pos.column += length; + } + self.position += length; + self.skip_ignored(); + Some((token, start)) + } + + /// Skips white space, line terminators, commas, comments and byte order + /// marks, counting lines and columns as the parser does. + fn skip_ignored(&mut self) { + loop { + let rest = &self.text.as_bytes()[self.position..]; + match rest.first() { + Some(b' ' | b',') => { + self.position += 1; + self.pos.column += 1; + } + Some(b'\t') => { + self.position += 1; + self.pos.column += 8; + } + Some(b'\n') => { + self.position += 1; + self.pos.line += 1; + self.pos.column = 1; + } + Some(b'\r') => self.position += 1, + Some(0xEF) if rest.starts_with("\u{feff}".as_bytes()) => self.position += 3, + Some(b'#') => { + // The parser ends a comment with its line terminator. + match rest.iter().position(|byte| matches!(byte, b'\n' | b'\r')) { + Some(end) => { + self.position += end + 1; + self.pos.line += 1; + self.pos.column = 1; + } + None => self.position += rest.len(), + } + } + _ => return, + } + } + } +} + +/// The line and column of the byte `offset` of `source`, both from 1. +fn position_of(source: &str, offset: usize) -> Pos { + let before = &source[..offset]; + let line_start = before.rfind(['\n', '\r']).map_or(0, |index| index + 1); + Pos { + line: before.matches('\n').count() + before.matches('\r').count() + - before.matches("\r\n").count() + + 1, + column: before[line_start..].chars().count() + 1, + } +} + +#[cfg(test)] +mod tests { + use super::duplicate_field; + + fn duplicate(source: &str) -> Option<(&str, usize, usize)> { + duplicate_field(source).map(|(name, position)| (name, position.line, position.column)) + } + + #[test] + fn finds_a_field_given_twice_in_one_input_object() { + assert_eq!( + duplicate(r#"mutation { a(x: {id: "1", title: "old", title: "new"}) { id } }"#), + Some(("title", 1, 41)) + ); + // In a list, nested, in a default value, in a directive, on a later line. + assert_eq!( + duplicate("{ a(x: [{b: 1}, {b: 1, b: 2}]) { id } }"), + Some(("b", 1, 24)) + ); + assert_eq!(duplicate("{ a(x: {b: {c: 1, c: 2}}) }"), Some(("c", 1, 19))); + assert_eq!( + duplicate("query($x: In = {a: 1\n a: 2}) { a }"), + Some(("a", 2, 2)) + ); + assert_eq!(duplicate("{ a @d(x: {k: 1, k: 1}) }"), Some(("k", 1, 18))); + } + + #[test] + fn leaves_distinct_fields_and_selections_alone() { + for source in [ + // The same name in sibling objects, in a nested one, or as a value. + "{ a(x: [{b: 1}, {b: 2}]) { b b } }", + "{ a(x: {b: {b: 1}, c: B}) { id } }", + "{ a(x: {b: B, B: b, c: $b, d: null, null: true}) { id } }", + // Selection sets repeat fields legally. + "{ a { id id } b: a { id } }", + "query($x: [In!] = [{a: 1}]) { a(x: $x) { a a } }", + // Names in strings, block strings and comments are not fields. + r#"{ a(x: {b: "b: 1, b: 2", c: """ b: \""" b: """}) { id } }"#, + "{ a(x: {b: 1 # b: 2\n}) { id } }", + ] { + assert_eq!(duplicate(source), None, "{source}"); + } + } + + #[test] + fn a_large_input_object_is_scanned_in_linear_time() { + // A quadratic scan takes about 50 s on this object in a debug build. + let fields: Vec = (0..100_000) + .map(|index| format!("f{index}: {index}")) + .collect(); + let source = format!("{{ a(x: {{{}}}) {{ id }} }}", fields.join(", ")); + let started = std::time::Instant::now(); + assert_eq!(duplicate(&source), None); + let duplicated = format!("{{ a(x: {{{}, f99999: 0}}) {{ id }} }}", fields.join(", ")); + assert_eq!( + duplicate(&duplicated).map(|(name, ..)| name), + Some("f99999") + ); + assert!( + started.elapsed() < std::time::Duration::from_secs(5), + "{:?}", + started.elapsed() + ); + } +} diff --git a/crates/shopify_api_graphql/src/bulk.rs b/crates/shopify_api_graphql/src/bulk.rs new file mode 100644 index 0000000..e24cf09 --- /dev/null +++ b/crates/shopify_api_graphql/src/bulk.rs @@ -0,0 +1,1334 @@ +//! Bulk operations: Shopify's rules for the query of +//! `bulkOperationRunQuery` and the mutation of `bulkOperationRunMutation`, +//! checked on top of [`analyze`](crate::analyze()), and what a typed bulk +//! query needs at run time: the text it sends, and where each line of its +//! results goes. +//! +//! The rules follow Shopify's guide for API 2026-10 +//! (). Where it +//! is silent, what it does not show is refused: +//! +//! - one top-level field, a connection, not `node` or `nodes`; +//! - at most five connections, nested at most two levels below it; +//! - each connection selected as `edges { node { … } }` and nothing else: +//! no `nodes`, `cursor`, `pageInfo`, and no `first`, `last`, `after` or +//! `before`, which Shopify ignores; +//! - the nodes of a connection implement `Node`; +//! - a nested connection written in the `node { … }` of its parent, not in +//! a fragment or under another field; +//! - an object with nested connections selects `id`, without an alias, +//! and no other field under the key `id`; +//! - two connections of one object that may return the same type are +//! refused: their lines could not be told apart. +//! +//! A bulk query takes no variables. Its variables are written into its text +//! as GraphQL literals at run time: the text is kept as [`Part`]s, with the +//! argument lists that hold a variable apart. + +mod strings; + +use std::collections::{BTreeMap, BTreeSet}; + +use graphql_parser::Pos; +use graphql_parser::query as ast; +use proc_macro2::{Span, TokenStream}; +use quote::{format_ident, quote}; + +use crate::analyze::{Error, FieldBase, Operation, OperationKind, SelectedField, Selection}; +use crate::codegen::{field_idents, item_types}; +use crate::schema::{Field, Schema, TypeDef, TypeRef}; + +type Document<'a> = ast::Document<'a, String>; +type SelectionSet<'a> = ast::SelectionSet<'a, String>; +type Value<'a> = ast::Value<'a, String>; +type Fragments<'a> = BTreeMap<&'a str, &'a ast::FragmentDefinition<'a, String>>; + +/// The most connections a bulk query may have, its top-level one included. +pub const MAX_CONNECTIONS: usize = 5; +/// How many levels of connections a bulk query may nest below its top-level one. +pub const MAX_DEPTH: usize = 2; + +/// The name of the type generated for each top-level object of a bulk query. +pub const ITEM_TYPE: &str = "Item"; + +/// The alias of the `__typename` written on the nodes of the connections +/// that share a parent, which tells their lines apart. The lines are routed +/// by it alone: a `__typename` the query selects is left as written. +pub const TYPENAME_KEY: &str = "_shopifyApiTypename"; + +/// Arguments Shopify ignores in a bulk query: it reads every object. +const PAGINATION: [&str; 4] = ["first", "last", "after", "before"]; + +fn error_at(position: Pos, message: impl Into) -> Result { + Err(Error { + message: message.into(), + position: Some((position.line, position.column)), + }) +} + +fn error(message: impl Into) -> Result { + Err(Error { + message: message.into(), + position: None, + }) +} + +/// A checked bulk query. +#[derive(Debug, Clone)] +#[non_exhaustive] +pub struct BulkQuery { + /// The selection on the nodes of the top-level connection, each nested + /// connection made a list of its nodes ([`SelectedField::connection`]). + pub item: Selection, + /// The nested connections of the top-level nodes, in the order of their + /// fields in [`BulkQuery::item`]. + pub connections: Vec, + /// The text sent, variables apart. + pub parts: Vec, + /// The default value of each variable that has one, as GraphQL text. + pub defaults: BTreeMap, +} + +/// A nested connection, and where its lines go. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Connection { + /// Its response key. + pub key: String, + /// The object types its nodes may be, which their `__typename` names. + pub types: Vec, + /// The connections of its nodes. + pub connections: Vec, +} + +/// A piece of the text of a bulk query. +#[derive(Debug, Clone, PartialEq)] +#[non_exhaustive] +pub enum Part { + Text(String), + /// `(name: value, …)` where a value holds a variable. An argument whose + /// variable has no value and no default is left out, and the + /// parentheses with the last one. + Arguments(Vec), +} + +#[derive(Debug, Clone, PartialEq)] +#[non_exhaustive] +pub struct Argument { + pub name: String, + pub value: ValuePart, +} + +#[derive(Debug, Clone, PartialEq)] +#[non_exhaustive] +pub enum ValuePart { + /// A constant, as GraphQL text. + Text(String), + Variable(String), + List(Vec), + /// An input object: a field whose variable has no value is left out. + Object(Vec), +} + +/// The object types a value of `name` may be, sorted. +fn concrete_types(schema: &Schema, name: &str) -> Vec { + let mut types: Vec = schema + .possible_types(name) + .into_iter() + .map(str::to_string) + .collect(); + types.sort(); + types.dedup(); + types +} + +fn fields_of<'s>(schema: &'s Schema, name: &str) -> Option<&'s BTreeMap> { + match schema.get(name) { + Some(TypeDef::Object { fields, .. } | TypeDef::Interface { fields, .. }) => Some(fields), + _ => None, + } +} + +/// The node type of a connection type: an object with `edges { node }` +/// and `pageInfo`, as Shopify's connections are. +pub fn connection_node<'s>(schema: &'s Schema, name: &str) -> Option<&'s str> { + let Some(TypeDef::Object { fields, .. }) = schema.get(name) else { + return None; + }; + if !fields.contains_key("pageInfo") { + return None; + } + let edge = fields.get("edges")?.ty.name(); + let Some(TypeDef::Object { fields: edge, .. }) = schema.get(edge) else { + return None; + }; + Some(edge.get("node")?.ty.name()) +} + +/// Every value of `name` implements `Node`. +fn implements_node(schema: &Schema, name: &str) -> bool { + let types = schema.possible_types(name); + !types.is_empty() + && types.iter().all(|ty| { + matches!(schema.get(ty), Some(TypeDef::Object { interfaces, .. }) if interfaces.iter().any(|interface| interface == "Node")) + }) +} + +fn parse(source: &str) -> Result, Error> { + // `analyze` read it first: a failure here is not expected. + crate::analyze::parse(source) +} + +/// The operation and the fragments of a document `analyze` accepted. +fn parts_of<'a>( + document: &'a Document<'a>, +) -> (&'a ast::OperationDefinition<'a, String>, Fragments<'a>) { + let mut operation = None; + let mut fragments = BTreeMap::new(); + for definition in &document.definitions { + match definition { + ast::Definition::Operation(found) => operation = Some(found), + ast::Definition::Fragment(fragment) => { + fragments.insert(fragment.name.as_str(), fragment); + } + } + } + ( + operation.expect("`analyze` accepted one operation"), + fragments, + ) +} + +fn selection_set<'a>(operation: &'a ast::OperationDefinition<'a, String>) -> &'a SelectionSet<'a> { + match operation { + ast::OperationDefinition::SelectionSet(set) => set, + ast::OperationDefinition::Query(query) => &query.selection_set, + ast::OperationDefinition::Mutation(mutation) => &mutation.selection_set, + ast::OperationDefinition::Subscription(subscription) => &subscription.selection_set, + } +} + +fn set_position(set: &SelectionSet<'_>) -> Pos { + set.span.0 +} + +fn item_position(item: &ast::Selection<'_, String>) -> Pos { + match item { + ast::Selection::Field(field) => field.position, + ast::Selection::InlineFragment(fragment) => fragment.position, + ast::Selection::FragmentSpread(spread) => spread.position, + } +} + +/// The only field of a top-level selection, or an error that says why. +fn top_level_field<'a>( + set: &'a SelectionSet<'a>, + what: &str, +) -> Result<&'a ast::Field<'a, String>, Error> { + match set.items.as_slice() { + [ast::Selection::Field(field)] => Ok(field), + [_, second, ..] => error_at( + item_position(second), + format!("A bulk {what} selects one top-level field: Shopify runs one per operation"), + ), + [other] => error_at( + item_position(other), + format!("A bulk {what} selects one top-level field, not a fragment"), + ), + [] => error_at( + set_position(set), + format!("A bulk {what} selects one top-level field"), + ), + } +} + +/// Checks the bulk rules of a query `analyze` accepted, and describes +/// what runs it. +pub fn analyze_bulk_query( + schema: &Schema, + source: &str, + operation: &Operation, +) -> Result { + if operation.kind != OperationKind::Query { + return error("A bulk query is a query"); + } + strings::check(source)?; + let document = parse(source)?; + let (definition, fragments) = parts_of(&document); + let mut checker = Checker { + schema, + fragments: &fragments, + count: 0, + typename: BTreeSet::new(), + }; + checker.variables(definition)?; + + let top = top_level_field(selection_set(definition), "query")?; + Checker::check_key(top)?; + if top.name == "node" || top.name == "nodes" { + return error_at( + top.position, + format!( + "`{}` cannot be the top-level field of a bulk query: select a connection, such as `products`", + top.name + ), + ); + } + let ty = fields_of(schema, &schema.query) + .and_then(|fields| fields.get(&top.name)) + .map(|field| field.ty.clone()) + .ok_or_else(|| Error { + message: format!("The query root has no field `{}`", top.name), + position: Some((top.position.line, top.position.column)), + })?; + if connection_node(schema, ty.name()).is_none() || matches!(ty.nullable(), TypeRef::List(_)) { + return error_at( + top.position, + format!( + "The top-level field of a bulk query is a connection: `{}` is `{ty}`. Run it as an ordinary query, or select a connection such as `products`", + top.name + ), + ); + } + let top_connection = checker.connection(top, &schema.query, 0)?; + + let data_field = operation + .data + .fields + .first() + .expect("the selection is not empty"); + let item = item_selection(schema, connection_nodes(data_field)); + + let mut printer = Printer { + typename: &checker.typename, + parts: Vec::new(), + text: String::new(), + }; + printer.operation(definition); + for fragment in fragments.values() { + printer.text.push(' '); + printer.fragment(fragment); + } + let parts = printer.finish(); + + let mut defaults = BTreeMap::new(); + if let ast::OperationDefinition::Query(query) = definition { + for variable in &query.variable_definitions { + if let Some(default) = &variable.default_value { + defaults.insert(variable.name.clone(), constant_text(default)); + } + } + } + + Ok(BulkQuery { + item, + connections: top_connection.connections, + parts, + defaults, + }) +} + +/// Checks the bulk rules of a mutation `analyze` accepted: one mutation +/// field, not a bulk operation itself, with at most one connection. +pub fn check_bulk_mutation( + schema: &Schema, + source: &str, + operation: &Operation, +) -> Result<(), Error> { + if operation.kind != OperationKind::Mutation { + return error("A bulk mutation is a mutation"); + } + let document = parse(source)?; + let (definition, fragments) = parts_of(&document); + let top = top_level_field(selection_set(definition), "mutation")?; + if matches!( + top.name.as_str(), + "bulkOperationRunMutation" | "bulkOperationRunQuery" + ) { + return error_at( + top.position, + format!("Shopify does not run `{}` in a bulk mutation", top.name), + ); + } + let root = schema.mutation.as_deref().unwrap_or_default(); + let ty = fields_of(schema, root) + .and_then(|fields| fields.get(&top.name)) + .map(|field| field.ty.name().to_string()) + .unwrap_or_default(); + let mut found = Vec::new(); + find_connections(schema, &fragments, &top.selection_set, &ty, &mut found, 0); + if let [first, second, ..] = found.as_slice() { + return error_at( + second.1, + format!( + "The mutation of a bulk operation selects one connection at most (`{}`), Shopify's limit: `{}` is a second one", + first.0, second.0 + ), + ); + } + Ok(()) +} + +/// The connection fields selected in `set`, at any depth, with where they are. +fn find_connections<'a>( + schema: &Schema, + fragments: &Fragments<'a>, + set: &'a SelectionSet<'a>, + parent: &str, + found: &mut Vec<(String, Pos)>, + depth: usize, +) { + // Fragments do not nest without end: `analyze` refused that. + if depth > 64 { + return; + } + for item in &set.items { + match item { + ast::Selection::Field(field) => { + let Some(ty) = fields_of(schema, parent) + .and_then(|fields| fields.get(&field.name)) + .map(|field| field.ty.name().to_string()) + else { + continue; + }; + if connection_node(schema, &ty).is_some() { + found.push((field.name.clone(), field.position)); + } + find_connections( + schema, + fragments, + &field.selection_set, + &ty, + found, + depth + 1, + ); + } + ast::Selection::InlineFragment(fragment) => { + let target = match &fragment.type_condition { + Some(ast::TypeCondition::On(name)) => name.as_str(), + None => parent, + }; + find_connections( + schema, + fragments, + &fragment.selection_set, + target, + found, + depth + 1, + ); + } + ast::Selection::FragmentSpread(spread) => { + if let Some(fragment) = fragments.get(spread.fragment_name.as_str()) { + let ast::TypeCondition::On(target) = &fragment.type_condition; + find_connections( + schema, + fragments, + &fragment.selection_set, + target, + found, + depth + 1, + ); + } + } + } + } +} + +struct Checker<'a, 's> { + schema: &'s Schema, + fragments: &'a Fragments<'a>, + /// The connections seen so far. + count: usize, + /// The `node` fields whose selection gains `__typename`, aliased [`TYPENAME_KEY`]. + typename: BTreeSet<(usize, usize)>, +} + +impl<'a> Checker<'a, '_> { + /// The variables are written into the text: a `JSON` value has no + /// GraphQL literal this crate can write for sure. + fn variables(&self, definition: &ast::OperationDefinition<'_, String>) -> Result<(), Error> { + let ast::OperationDefinition::Query(query) = definition else { + return Ok(()); + }; + for variable in &query.variable_definitions { + let mut seen = BTreeSet::new(); + let name = base_name(&variable.var_type); + if reaches_json(self.schema, name, &mut seen) { + return error_at( + variable.position, + format!( + "Variable `${}` may hold a `JSON` value, which a bulk query cannot take: Shopify takes no variables for a bulk query, and this crate writes them into its text as GraphQL literals", + variable.name + ), + ); + } + } + Ok(()) + } + + /// Checks a connection field of `parent` and what it selects, `depth` + /// levels below the top-level one. + fn connection( + &mut self, + field: &'a ast::Field<'a, String>, + parent: &str, + depth: usize, + ) -> Result { + self.count += 1; + if self.count > MAX_CONNECTIONS { + return error_at( + field.position, + format!( + "A bulk query has {MAX_CONNECTIONS} connections at most: `{}` is connection number {}", + field.name, self.count + ), + ); + } + if depth > MAX_DEPTH { + return error_at( + field.position, + format!( + "Connections nest {MAX_DEPTH} levels deep at most below the top-level one in a bulk query: `{}` is level {depth}", + field.name + ), + ); + } + if let Some(directive) = field.directives.first() { + return error_at( + directive.position, + format!( + "A connection of a bulk query cannot have directives such as `@{}`: Shopify writes its nodes on lines of their own", + directive.name + ), + ); + } + if let Some((argument, _)) = field + .arguments + .iter() + .find(|(name, _)| PAGINATION.contains(&name.as_str())) + { + return error_at( + field.position, + format!( + "Shopify ignores `{argument}` in a bulk query and returns every object of `{}`: remove it", + field.name + ), + ); + } + let shape = format!( + "A connection of a bulk query selects `edges {{ node {{ … }} }}` and nothing else, as Shopify documents it (`{}`)", + field.name + ); + let edges = only_field(&field.selection_set, "edges", &shape)?; + let node = only_field(&edges.selection_set, "node", &shape)?; + + let ty = self.field_type(parent, field).unwrap_or_default(); + let node_type = connection_node(self.schema, &ty) + .unwrap_or_default() + .to_string(); + if !implements_node(self.schema, &node_type) { + return error_at( + field.position, + format!( + "Shopify bulk queries read connections of `Node` objects: the nodes of `{}`, `{node_type}`, do not all implement `Node`", + field.name + ), + ); + } + + let children = self.node_selection(&node.selection_set, &node_type, depth)?; + if let Some(child) = children.first() { + if let Some(other) = self.aliased_id(&node.selection_set, 0) { + return error_at( + other.position, + format!( + "`id: {}` is refused on the nodes of `{}`, which have the nested connection `{}`: each nested line is placed under its parent by the `id` of that parent. Give `{}` another alias", + other.name, field.name, child.name, other.name + ), + ); + } + let has_id = node.selection_set.items.iter().any(|item| { + matches!(item, ast::Selection::Field(id) if id.name == "id" && id.alias.is_none() && id.directives.is_empty()) + }); + if !has_id { + return error_at( + node.position, + format!( + "The nodes of `{}` have the nested connection `{}`: select their `id`, without an alias or a directive, in this `node {{ … }}`. Shopify refuses the query otherwise, and places each nested line under its parent by that `id`", + field.name, child.name + ), + ); + } + } + if children.len() > 1 { + for (index, later) in children.iter().enumerate() { + for earlier in &children[..index] { + if let Some(shared) = earlier + .connection + .types + .iter() + .find(|ty| later.connection.types.contains(ty)) + { + return error_at( + later.position, + format!( + "`{}` and `{}`, connections of each node of `{}`, may both return `{shared}`: their lines in the results could not be told apart. Query one of them in another bulk query", + earlier.connection.key, later.connection.key, field.name + ), + ); + } + } + } + for child in &children { + self.typename.insert((child.node.line, child.node.column)); + } + } + Ok(Connection { + key: field.alias.as_ref().unwrap_or(&field.name).clone(), + types: concrete_types(self.schema, &node_type), + connections: children.into_iter().map(|child| child.connection).collect(), + }) + } + + /// The type name of `field` on `parent`. + fn field_type(&self, parent: &str, field: &ast::Field<'_, String>) -> Option { + fields_of(self.schema, parent) + .and_then(|fields| fields.get(&field.name)) + .map(|definition| definition.ty.name().to_string()) + } + + fn field_definition(&self, parent: &str, field: &ast::Field<'_, String>) -> Option<&Field> { + fields_of(self.schema, parent).and_then(|fields| fields.get(&field.name)) + } + + /// A field other than `id` aliased `id` in `set` or its fragments. + fn aliased_id( + &self, + set: &'a SelectionSet<'a>, + depth: usize, + ) -> Option<&'a ast::Field<'a, String>> { + // Fragments do not nest without end: `analyze` refused that. + if depth > 64 { + return None; + } + set.items.iter().find_map(|item| match item { + ast::Selection::Field(field) => { + (field.alias.as_deref() == Some("id") && field.name != "id").then_some(field) + } + ast::Selection::InlineFragment(fragment) => { + self.aliased_id(&fragment.selection_set, depth + 1) + } + ast::Selection::FragmentSpread(spread) => self + .fragments + .get(spread.fragment_name.as_str()) + .and_then(|fragment| self.aliased_id(&fragment.selection_set, depth + 1)), + }) + } + + /// Refuses an alias Shopify or this crate writes in the lines. + fn check_key(field: &ast::Field<'_, String>) -> Result<(), Error> { + if let Some(alias) = &field.alias + && (alias.starts_with("__") || alias == TYPENAME_KEY) + { + return error_at( + field.position, + format!( + "`{alias}` cannot be an alias in a bulk query: the lines of its results hold `__parentId`, and `{TYPENAME_KEY}` where this crate selects `__typename` to place them" + ), + ); + } + Ok(()) + } + + /// Checks what a `node { … }` selects, and returns its connections. + fn node_selection( + &mut self, + set: &'a SelectionSet<'a>, + node_type: &str, + depth: usize, + ) -> Result, Error> { + let mut children = Vec::new(); + for item in &set.items { + match item { + ast::Selection::Field(field) => { + Self::check_key(field)?; + let Some(definition) = self.field_definition(node_type, field) else { + continue; + }; + let ty = definition.ty.clone(); + if connection_node(self.schema, ty.name()).is_some() { + if !matches!(ty.nullable(), TypeRef::Named(_)) { + return error_at( + field.position, + format!( + "`{}` is a list of connections, which a bulk query cannot read", + field.name + ), + ); + } + let connection = self.connection(field, node_type, depth + 1)?; + let node = only_field(&field.selection_set, "edges", "") + .and_then(|edges| only_field(&edges.selection_set, "node", "")) + .map(|node| node.position) + .unwrap_or(field.position); + children.push(Child { + name: field.name.clone(), + position: field.position, + node, + connection, + }); + } else if !field.selection_set.items.is_empty() { + self.plain(&field.selection_set, ty.name(), &field.name, false)?; + } + } + ast::Selection::InlineFragment(fragment) => { + let target = match &fragment.type_condition { + Some(ast::TypeCondition::On(name)) => name.as_str(), + None => node_type, + }; + self.plain(&fragment.selection_set, target, "", true)?; + } + ast::Selection::FragmentSpread(spread) => { + if let Some(fragment) = self.fragments.get(spread.fragment_name.as_str()) { + let ast::TypeCondition::On(target) = &fragment.type_condition; + self.plain(&fragment.selection_set, target, "", true)?; + } + } + } + } + Ok(children) + } + + /// Checks a selection that may hold no connection: under the field + /// `under`, or in a fragment. + fn plain( + &self, + set: &'a SelectionSet<'a>, + parent: &str, + under: &str, + fragment: bool, + ) -> Result<(), Error> { + for item in &set.items { + match item { + ast::Selection::Field(field) => { + Self::check_key(field)?; + let Some(definition) = self.field_definition(parent, field) else { + continue; + }; + let ty = definition.ty.name().to_string(); + if connection_node(self.schema, &ty).is_some() { + let place = if fragment { + "inside a fragment".to_string() + } else { + format!("under `{under}`, which is not a connection") + }; + return error_at( + field.position, + format!( + "The connection `{}` is {place}: in a bulk query, a nested connection is written right in the `node {{ … }}` of its parent connection", + field.name + ), + ); + } + if !field.selection_set.items.is_empty() { + let under = if fragment { under } else { &field.name }; + self.plain(&field.selection_set, &ty, under, fragment)?; + } + } + ast::Selection::InlineFragment(inline) => { + let target = match &inline.type_condition { + Some(ast::TypeCondition::On(name)) => name.as_str(), + None => parent, + }; + self.plain(&inline.selection_set, target, under, true)?; + } + ast::Selection::FragmentSpread(spread) => { + if let Some(definition) = self.fragments.get(spread.fragment_name.as_str()) { + let ast::TypeCondition::On(target) = &definition.type_condition; + self.plain(&definition.selection_set, target, under, true)?; + } + } + } + } + Ok(()) + } +} + +/// A nested connection, with where its field and its `node` are. +struct Child { + name: String, + position: Pos, + node: Pos, + connection: Connection, +} + +/// The single field `name` of `set`, without alias, arguments or directives. +fn only_field<'a>( + set: &'a SelectionSet<'a>, + name: &str, + shape: &str, +) -> Result<&'a ast::Field<'a, String>, Error> { + match set.items.as_slice() { + [ast::Selection::Field(field)] + if field.name == name + && field.alias.is_none() + && field.arguments.is_empty() + && field.directives.is_empty() => + { + Ok(field) + } + [ast::Selection::Field(field), ..] if field.name == "nodes" => error_at( + field.position, + format!("{shape}: Shopify does not document `nodes` for bulk queries"), + ), + [item] => error_at( + item_position(item), + format!("{shape}: write `{name}`, without alias, arguments or directives"), + ), + [first, second, ..] => { + let other = if matches!(first, ast::Selection::Field(field) if field.name == name) { + second + } else { + first + }; + error_at( + item_position(other), + format!("{shape}: {} is refused beside `{name}`", item_name(other)), + ) + } + [] => error_at(set_position(set), shape.to_string()), + } +} + +/// A selection as a message names it. +fn item_name(item: &ast::Selection<'_, String>) -> String { + match item { + ast::Selection::Field(field) => format!("`{}`", field.name), + ast::Selection::InlineFragment(_) | ast::Selection::FragmentSpread(_) => { + "a fragment".to_string() + } + } +} + +fn base_name<'t>(ty: &'t ast::Type<'_, String>) -> &'t str { + match ty { + ast::Type::NamedType(name) => name, + ast::Type::ListType(inner) | ast::Type::NonNullType(inner) => base_name(inner), + } +} + +/// A value of input type `name` may hold a `JSON` value. +fn reaches_json<'s>(schema: &'s Schema, name: &'s str, seen: &mut BTreeSet<&'s str>) -> bool { + if name == "JSON" { + return true; + } + match schema.get(name) { + Some(TypeDef::Input { fields, .. }) if seen.insert(name) => fields + .values() + .any(|field| reaches_json(schema, field.ty.name(), seen)), + _ => false, + } +} + +/// The selection on the nodes of a connection field of the analyzed operation. +fn connection_nodes(field: &SelectedField) -> &Selection { + let FieldBase::Object(connection) = &field.base else { + unreachable!("a connection has subfields"); + }; + let FieldBase::Object(edge) = &connection.fields[0].base else { + unreachable!("`edges` has subfields"); + }; + let FieldBase::Object(node) = &edge.fields[0].base else { + unreachable!("`node` has subfields"); + }; + node +} + +/// `selection` with each connection made the list of its nodes. +fn item_selection(schema: &Schema, selection: &Selection) -> Selection { + let mut item = selection.clone(); + for field in &mut item.fields { + if let Some(node) = connection_node(schema, field.ty.name()) { + let nodes = item_selection(schema, connection_nodes(field)); + field.ty = TypeRef::NonNull(Box::new(TypeRef::List(Box::new(TypeRef::NonNull( + Box::new(TypeRef::Named(node.to_string())), + ))))); + field.base = FieldBase::Object(nodes); + field.conditional = false; + field.connection = true; + } + } + item +} + +/// A constant value as GraphQL text. +fn constant_text(value: &Value<'_>) -> String { + match value { + ast::Value::Variable(name) => format!("${name}"), + ast::Value::Int(number) => number.as_i64().unwrap_or_default().to_string(), + // `Debug` keeps a `.` or an exponent: `1.0`, `1e300`. + ast::Value::Float(number) => format!("{number:?}"), + ast::Value::String(text) => string_literal(text), + ast::Value::Boolean(value) => value.to_string(), + ast::Value::Null => "null".to_string(), + ast::Value::Enum(name) => name.clone(), + ast::Value::List(items) => { + let items: Vec = items.iter().map(constant_text).collect(); + format!("[{}]", items.join(", ")) + } + ast::Value::Object(fields) => { + let fields: Vec = fields + .iter() + .map(|(name, value)| format!("{name}: {}", constant_text(value))) + .collect(); + format!("{{{}}}", fields.join(", ")) + } + } +} + +/// A string as a GraphQL string literal: JSON's escapes are GraphQL's. +pub fn string_literal(text: &str) -> String { + serde_json::to_string(text).expect("a string serializes") +} + +fn has_variable(value: &Value<'_>) -> bool { + match value { + ast::Value::Variable(_) => true, + ast::Value::List(items) => items.iter().any(has_variable), + ast::Value::Object(fields) => fields.values().any(has_variable), + _ => false, + } +} + +fn value_part(value: &Value<'_>) -> ValuePart { + match value { + ast::Value::Variable(name) => ValuePart::Variable(name.clone()), + ast::Value::List(items) if items.iter().any(has_variable) => { + ValuePart::List(items.iter().map(value_part).collect()) + } + ast::Value::Object(fields) if fields.values().any(has_variable) => ValuePart::Object( + fields + .iter() + .map(|(name, value)| Argument { + name: name.clone(), + value: value_part(value), + }) + .collect(), + ), + constant => ValuePart::Text(constant_text(constant)), + } +} + +/// Writes a document back as text, without its variable definitions, with +/// `__typename` aliased [`TYPENAME_KEY`] where the lines need it. +struct Printer<'c> { + typename: &'c BTreeSet<(usize, usize)>, + parts: Vec, + text: String, +} + +impl Printer<'_> { + fn finish(mut self) -> Vec { + if !self.text.is_empty() { + self.parts.push(Part::Text(std::mem::take(&mut self.text))); + } + self.parts + } + + fn operation(&mut self, definition: &ast::OperationDefinition<'_, String>) { + let (name, directives, set) = match definition { + ast::OperationDefinition::SelectionSet(set) => (None, &[][..], set), + ast::OperationDefinition::Query(query) => ( + query.name.as_deref(), + &query.directives[..], + &query.selection_set, + ), + ast::OperationDefinition::Mutation(mutation) => ( + mutation.name.as_deref(), + &mutation.directives[..], + &mutation.selection_set, + ), + ast::OperationDefinition::Subscription(subscription) => ( + subscription.name.as_deref(), + &subscription.directives[..], + &subscription.selection_set, + ), + }; + if name.is_some() || !directives.is_empty() { + self.text.push_str("query"); + if let Some(name) = name { + self.text.push(' '); + self.text.push_str(name); + } + self.directives(directives); + self.text.push(' '); + } + self.selection_set(set, false); + } + + fn fragment(&mut self, fragment: &ast::FragmentDefinition<'_, String>) { + let ast::TypeCondition::On(condition) = &fragment.type_condition; + self.text + .push_str(&format!("fragment {} on {condition}", fragment.name)); + self.directives(&fragment.directives); + self.text.push(' '); + self.selection_set(&fragment.selection_set, false); + } + + fn selection_set(&mut self, set: &SelectionSet<'_>, typename: bool) { + self.text.push('{'); + if typename { + self.text.push(' '); + self.text.push_str(TYPENAME_KEY); + self.text.push_str(": __typename"); + } + for item in &set.items { + self.text.push(' '); + match item { + ast::Selection::Field(field) => { + if let Some(alias) = &field.alias { + self.text.push_str(alias); + self.text.push_str(": "); + } + self.text.push_str(&field.name); + self.arguments(&field.arguments); + self.directives(&field.directives); + if !field.selection_set.items.is_empty() { + self.text.push(' '); + let typename = self + .typename + .contains(&(field.position.line, field.position.column)); + self.selection_set(&field.selection_set, typename); + } + } + ast::Selection::InlineFragment(fragment) => { + self.text.push_str("..."); + if let Some(ast::TypeCondition::On(condition)) = &fragment.type_condition { + self.text.push_str(" on "); + self.text.push_str(condition); + } + self.directives(&fragment.directives); + self.text.push(' '); + self.selection_set(&fragment.selection_set, false); + } + ast::Selection::FragmentSpread(spread) => { + self.text.push_str("..."); + self.text.push_str(&spread.fragment_name); + self.directives(&spread.directives); + } + } + } + self.text.push_str(" }"); + } + + fn directives(&mut self, directives: &[ast::Directive<'_, String>]) { + for directive in directives { + self.text.push_str(" @"); + self.text.push_str(&directive.name); + self.arguments(&directive.arguments); + } + } + + fn arguments(&mut self, arguments: &[(String, Value<'_>)]) { + if arguments.is_empty() { + return; + } + if arguments.iter().any(|(_, value)| has_variable(value)) { + if !self.text.is_empty() { + self.parts.push(Part::Text(std::mem::take(&mut self.text))); + } + self.parts.push(Part::Arguments( + arguments + .iter() + .map(|(name, value)| Argument { + name: name.clone(), + value: value_part(value), + }) + .collect(), + )); + return; + } + let written: Vec = arguments + .iter() + .map(|(name, value)| format!("{name}: {}", constant_text(value))) + .collect(); + self.text.push('('); + self.text.push_str(&written.join(", ")); + self.text.push(')'); + } +} + +// ─── Code ──────────────────────────────────────────────────────────── + +/// The name of the `static` that holds the template of a bulk query. +pub fn template_ident() -> proc_macro2::Ident { + proc_macro2::Ident::new("__SHOPIFY_API_BULK_TEMPLATE", Span::mixed_site()) +} + +/// The item types of a bulk query, their `BulkItem` implementation, and the +/// `static` [`template_ident`] of its text. `krate` is the path of the +/// `shopify_api` crate in the generated code. +pub fn query_items( + schema: &Schema, + operation: &Operation, + bulk: &BulkQuery, + krate: &TokenStream, +) -> TokenStream { + let types = item_types(&bulk.item, ITEM_TYPE, krate); + let private = quote!(#krate::__private::bulk); + let item = format_ident!("{}", ITEM_TYPE); + + // Where each line goes. + let connections = connections_tokens(&bulk.connections, &private); + let parent = proc_macro2::Ident::new("__shopify_api_parent", Span::mixed_site()); + let slot = proc_macro2::Ident::new("__shopify_api_slot", Span::mixed_site()); + let line = proc_macro2::Ident::new("__shopify_api_line", Span::mixed_site()); + let number = proc_macro2::Ident::new("__shopify_api_number", Span::mixed_site()); + let child = proc_macro2::Ident::new("__shopify_api_child", Span::mixed_site()); + let mut arms = Vec::new(); + let top = field_idents(&bulk.item); + for (index, connection) in bulk.connections.iter().enumerate() { + let field = ident_of(&top, &connection.key); + arms.push(quote! { + (::core::option::Option::None, #index) => #private::push(&mut self.#field, #line, #number), + }); + if connection.connections.is_empty() { + continue; + } + let nested = nested_selection(&bulk.item, &connection.key); + let below = field_idents(nested); + for (inner, grandchild) in connection.connections.iter().enumerate() { + let inner_field = ident_of(&below, &grandchild.key); + arms.push(quote! { + (::core::option::Option::Some((#index, #child)), #inner) => match self.#field.get_mut(#child) { + ::core::option::Option::Some(#child) => #private::push(&mut #child.#inner_field, #line, #number), + ::core::option::Option::None => ::core::result::Result::Err(#private::unplaced()), + }, + }); + } + } + + let template = template_tokens(schema, operation, bulk, &private); + let template_ident = template_ident(); + let (parts_ident, variables_ident) = template_parts_idents(); + quote! { + #types + + impl #private::BulkItem for #item { + const CONNECTIONS: &'static [#private::BulkConnection] = #connections; + + fn __attach( + &mut self, + #parent: ::core::option::Option<(usize, usize)>, + #slot: usize, + #line: &[u8], + #number: usize, + ) -> #krate::__private::Result { + match (#parent, #slot) { + #(#arms)* + _ => ::core::result::Result::Err(#private::unplaced()), + } + } + } + + #template + + static #template_ident: #private::BulkTemplate = #private::BulkTemplate { + parts: #parts_ident, + variables: #variables_ident, + }; + } +} + +fn ident_of<'i>(idents: &'i [(String, proc_macro2::Ident)], key: &str) -> &'i proc_macro2::Ident { + &idents + .iter() + .find(|(field, _)| field == key) + .expect("a connection is a field of its parent") + .1 +} + +/// The selection on the nodes of the connection `key` of `item`. +fn nested_selection<'s>(item: &'s Selection, key: &str) -> &'s Selection { + match item + .fields + .iter() + .find(|field| field.key == key) + .map(|field| &field.base) + { + Some(FieldBase::Object(selection)) => selection, + _ => unreachable!("a connection has subfields"), + } +} + +fn connections_tokens(connections: &[Connection], private: &TokenStream) -> TokenStream { + let items = connections.iter().map(|connection| { + let key = &connection.key; + let types = &connection.types; + let nested = connections_tokens(&connection.connections, private); + quote! { + #private::BulkConnection { + key: #key, + types: &[#(#types),*], + connections: #nested, + } + } + }); + quote!(&[#(#items),*]) +} + +/// The parts and the variables of the text, as `static`s named +/// `__SHOPIFY_API_BULK_PARTS` and `__SHOPIFY_API_BULK_VARIABLES`, with one +/// `static` per input object whose fields hold enums. +fn template_tokens( + schema: &Schema, + operation: &Operation, + bulk: &BulkQuery, + private: &TokenStream, +) -> TokenStream { + let names: Vec<&str> = operation + .variables + .iter() + .map(|variable| variable.name.as_str()) + .collect(); + let parts = bulk.parts.iter().map(|part| match part { + Part::Text(text) => quote!(#private::BulkPart::Text(#text)), + Part::Arguments(arguments) => { + let arguments = arguments_tokens(arguments, &names, private); + quote!(#private::BulkPart::Arguments(#arguments)) + } + }); + let mut inputs = BTreeMap::new(); + let variables: Vec = operation + .variables + .iter() + .map(|variable| { + let name = &variable.name; + let ty = type_tokens(schema, &variable.ty, private, &mut inputs); + let default = match bulk.defaults.get(name) { + Some(text) => quote!(::core::option::Option::Some(#text)), + None => quote!(::core::option::Option::None), + }; + quote! { + #private::BulkVariable { name: #name, ty: #ty, default: #default } + } + }) + .collect(); + let statics = inputs.into_iter().filter_map(|(name, fields)| { + let fields = fields?; + let ident = input_ident(&name); + let count = fields.len(); + let fields = fields.into_iter().map(|(field, ty)| quote!((#field, #ty))); + Some(quote! { + static #ident: [(&str, #private::BulkType); #count] = [#(#fields),*]; + }) + }); + let (parts_ident, variables_ident) = template_parts_idents(); + quote! { + #(#statics)* + static #parts_ident: &[#private::BulkPart] = &[#(#parts),*]; + static #variables_ident: &[#private::BulkVariable] = &[#(#variables),*]; + } +} + +/// The `static`s of the parts and of the variables of the text. +fn template_parts_idents() -> (proc_macro2::Ident, proc_macro2::Ident) { + ( + proc_macro2::Ident::new("__SHOPIFY_API_BULK_PARTS", Span::mixed_site()), + proc_macro2::Ident::new("__SHOPIFY_API_BULK_VARIABLES", Span::mixed_site()), + ) +} + +fn input_ident(name: &str) -> proc_macro2::Ident { + proc_macro2::Ident::new( + &format!("__SHOPIFY_API_BULK_INPUT_{name}"), + Span::mixed_site(), + ) +} + +fn arguments_tokens(arguments: &[Argument], names: &[&str], private: &TokenStream) -> TokenStream { + let items = arguments.iter().map(|argument| { + let name = &argument.name; + let value = value_tokens(&argument.value, names, private); + quote!(#private::BulkArgument { name: #name, value: #value }) + }); + quote!(&[#(#items),*]) +} + +fn value_tokens(value: &ValuePart, names: &[&str], private: &TokenStream) -> TokenStream { + match value { + ValuePart::Text(text) => quote!(#private::BulkValue::Text(#text)), + ValuePart::Variable(name) => { + let index = names + .iter() + .position(|declared| declared == name) + .expect("`analyze` checked that the variable is declared"); + quote!(#private::BulkValue::Variable(#index)) + } + ValuePart::List(items) => { + let items = items.iter().map(|item| value_tokens(item, names, private)); + quote!(#private::BulkValue::List(&[#(#items),*])) + } + ValuePart::Object(fields) => { + let fields = arguments_tokens(fields, names, private); + quote!(#private::BulkValue::Object(#fields)) + } + } +} + +/// Input objects by name: the fields that hold enums, with their type, or +/// `None` while they are being written. +type Inputs = BTreeMap>>; + +/// Where the enums of a value of type `ty` are, which are written bare. +fn type_tokens( + schema: &Schema, + ty: &TypeRef, + private: &TokenStream, + inputs: &mut Inputs, +) -> TokenStream { + match ty { + TypeRef::NonNull(inner) => type_tokens(schema, inner, private, inputs), + TypeRef::List(item) => { + let item = type_tokens(schema, item, private, inputs); + quote!(#private::BulkType::List(&#item)) + } + TypeRef::Named(name) => match schema.get(name) { + Some(TypeDef::Enum { .. }) => quote!(#private::BulkType::Enum), + Some(TypeDef::Input { fields, .. }) + if reaches_enum(schema, name, &mut BTreeSet::new()) => + { + if !inputs.contains_key(name) { + inputs.insert(name.clone(), None); + let written = fields + .iter() + .filter(|(_, field)| { + reaches_enum(schema, field.ty.name(), &mut BTreeSet::new()) + }) + .map(|(field, input)| { + ( + field.clone(), + type_tokens(schema, &input.ty, private, inputs), + ) + }) + .collect(); + inputs.insert(name.clone(), Some(written)); + } + let ident = input_ident(name); + quote!(#private::BulkType::Input(&#ident)) + } + _ => quote!(#private::BulkType::Plain), + }, + } +} + +/// A value of input type `name` may hold an enum value. +fn reaches_enum<'s>(schema: &'s Schema, name: &'s str, seen: &mut BTreeSet<&'s str>) -> bool { + match schema.get(name) { + Some(TypeDef::Enum { .. }) => true, + Some(TypeDef::Input { fields, .. }) if seen.insert(name) => fields + .values() + .any(|field| reaches_enum(schema, field.ty.name(), seen)), + _ => false, + } +} diff --git a/crates/shopify_api_graphql/src/bulk/strings.rs b/crates/shopify_api_graphql/src/bulk/strings.rs new file mode 100644 index 0000000..2bbe195 --- /dev/null +++ b/crates/shopify_api_graphql/src/bulk/strings.rs @@ -0,0 +1,166 @@ +//! The strings of a bulk query read as GraphQL reads them. +//! +//! A bulk query is sent as text written back from what `graphql-parser` +//! read, which decodes some strings unlike GraphQL: `\b` as U+0010, not +//! U+0008, and block strings split and indented with Unicode whitespace and +//! without a lone `\r` as a line break. Its values carry no position, and +//! the fields of an input object are kept sorted, so the text of a string +//! cannot be found back for its value. Each string of the source is +//! decoded here as the GraphQL specification does, and a string the +//! parser reads otherwise is refused. + +use super::error_at; +use crate::analyze::Error; +use crate::source::{Lexer, unreadable_block_string}; + +/// Refuses a string or block string of `source` that `graphql-parser` +/// does not read as GraphQL does. +pub(super) fn check(source: &str) -> Result<(), Error> { + let mut lexer = Lexer::new(source); + while let Some((position, token)) = lexer.next_string() { + let expected = if token.starts_with("\"\"\"") { + block_string(&token[3..token.len() - 3]) + } else { + quoted_string(&token[1..token.len() - 1]) + }; + if expected.is_some() && expected == parsed(token) { + continue; + } + let advice = if token.starts_with("\"\"\"") { + "Write it as a quoted string, with escapes" + } else if token.contains("\\b") { + "Write `\\u0008` rather than `\\b`" + } else { + "Write the characters it holds with `\\uXXXX` escapes" + }; + return error_at( + position, + format!( + "This string would not reach Shopify as written: the GraphQL parser this crate uses reads it otherwise, and a bulk query is sent as the text it read. {advice}" + ), + ); + } + Ok(()) +} + +/// The string the token is for `graphql-parser`. +fn parsed(token: &str) -> Option { + use graphql_parser::query::{Definition, OperationDefinition, Selection, Value}; + if unreadable_block_string(token) { + return None; + } + let source = format!("{{ f(a: {token}) }}"); + let document = graphql_parser::parse_query::(&source).ok()?; + let Some(Definition::Operation(OperationDefinition::SelectionSet(set))) = + document.definitions.into_iter().next() + else { + return None; + }; + let Some(Selection::Field(field)) = set.items.into_iter().next() else { + return None; + }; + match field.arguments.into_iter().next() { + Some((_, Value::String(value))) => Some(value), + _ => None, + } +} + +/// The value of a quoted string, as the specification reads it. +fn quoted_string(body: &str) -> Option { + let mut value = String::with_capacity(body.len()); + let mut characters = body.chars(); + while let Some(character) = characters.next() { + match character { + '\\' => { + let escaped = match characters.next()? { + '"' => '"', + '\\' => '\\', + '/' => '/', + 'b' => '\u{8}', + 'f' => '\u{c}', + 'n' => '\n', + 'r' => '\r', + 't' => '\t', + 'u' => { + let hex: String = characters.by_ref().take(4).collect(); + if hex.len() != 4 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return None; + } + char::from_u32(u32::from_str_radix(&hex, 16).ok()?)? + } + _ => return None, + }; + value.push(escaped); + } + // A line terminator ends a line, not a string. + '\n' | '\r' => return None, + other => value.push(other), + } + } + Some(value) +} + +/// The value of a block string, as the specification reads it. +fn block_string(body: &str) -> Option { + let raw = body.replace("\\\"\"\"", "\"\"\""); + let raw = raw.replace("\r\n", "\n").replace('\r', "\n"); + let lines: Vec<&str> = raw.split('\n').collect(); + let indent = |line: &str| line.len() - line.trim_start_matches([' ', '\t']).len(); + let common = lines + .iter() + .skip(1) + .filter(|line| indent(line) < line.len()) + .map(|line| indent(line)) + .min(); + let lines: Vec<&str> = lines + .iter() + .enumerate() + .map(|(index, line)| match common { + Some(common) if index > 0 => line.get(common..).unwrap_or(""), + _ => line, + }) + .collect(); + let blank = |line: &&str| line.trim_start_matches([' ', '\t']).is_empty(); + let first = lines.iter().position(|line| !blank(line)); + let last = lines.iter().rposition(|line| !blank(line)); + match (first, last) { + (Some(first), Some(last)) => Some(lines[first..=last].join("\n")), + _ => Some(String::new()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn comments_hide_quotes() { + assert!(check("# \"\\b\"\n{ f }").is_ok()); + assert!(check("{ f(a: \"# \\b\") }").is_err()); + } + + #[test] + fn the_parser_is_checked_for_every_escape() { + for escape in [ + r"\u0008", r#"\""#, r"\\", r"\/", r"\f", r"\n", r"\r", r"\t", r"\u00e9", r"\uFFFF", + ] { + let source = format!("{{ f(a: \"x{escape}y\") }}"); + assert!(check(&source).is_ok(), "{escape}"); + } + let error = check("{ f(a: \"x\\by\") }").unwrap_err(); + assert!(error.message.contains("`\\u0008`"), "{}", error.message); + assert_eq!(error.position, Some((1, 8))); + } + + #[test] + fn block_strings_follow_the_specification() { + assert_eq!( + block_string("\n a\n b\n \\\"\"\"\n "), + Some("a\n b\n\"\"\"".to_string()) + ); + assert_eq!(block_string("a\rb"), Some("a\nb".to_string())); + assert!(check("{ f(a: \"\"\"\n a\n b\n \"\"\") }").is_ok()); + assert!(check("{ f(a: \"\"\"a\rb\"\"\") }").is_err()); + assert!(check("{ f(a: \"\"\"\n\u{a0}a\n\u{a0}b\"\"\") }").is_err()); + } +} diff --git a/crates/shopify_api_graphql/src/codegen.rs b/crates/shopify_api_graphql/src/codegen.rs new file mode 100644 index 0000000..7922965 --- /dev/null +++ b/crates/shopify_api_graphql/src/codegen.rs @@ -0,0 +1,481 @@ +//! Rust types for the result and the variables of an analyzed operation. + +use std::collections::BTreeSet; + +use proc_macro2::{Ident, Span, TokenStream}; +use quote::{quote, quote_spanned}; + +use crate::analyze::{ + FieldBase, Operation, Scalar, SelectedField, Selection, Variable, VariableBase, +}; +use crate::schema::{Schema, TypeDef, TypeRef}; + +/// The name of the type generated for the `data` of an operation. +pub const DATA_TYPE: &str = "Data"; +/// The name of the type generated for the variables of an operation. +pub const VARIABLES_TYPE: &str = "Variables"; + +/// Identifiers that cannot be written `r#name`. +const UNRAWABLE: [&str; 5] = ["self", "Self", "super", "crate", "_"]; +const KEYWORDS: &[&str] = &[ + "abstract", "as", "async", "await", "become", "box", "break", "const", "continue", "do", "dyn", + "else", "enum", "extern", "false", "final", "fn", "for", "gen", "if", "impl", "in", "let", + "loop", "macro", "match", "mod", "move", "mut", "override", "priv", "pub", "ref", "return", + "static", "struct", "trait", "true", "try", "type", "typeof", "unsafe", "unsized", "use", + "virtual", "where", "while", "yield", +]; + +/// `lineItems` → `line_items`, `__typename` → `typename`, `HTMLBody` → `html_body`. +fn snake_case(name: &str) -> String { + let characters: Vec = name.trim_matches('_').chars().collect(); + let mut snake = String::new(); + for (index, character) in characters.iter().enumerate() { + if character.is_uppercase() { + let after_lower = index > 0 + && (characters[index - 1].is_lowercase() || characters[index - 1].is_ascii_digit()); + let before_lower = index > 0 + && characters[index - 1].is_uppercase() + && characters + .get(index + 1) + .is_some_and(|next| next.is_lowercase()); + if (after_lower || before_lower) && !snake.ends_with('_') { + snake.push('_'); + } + snake.extend(character.to_lowercase()); + } else { + snake.push(*character); + } + } + if snake.is_empty() || snake.starts_with(|first: char| first.is_ascii_digit()) { + snake.insert(0, '_'); + } + snake +} + +/// `lineItems` → `LineItems`, `line_items` → `LineItems`, `__typename` → `Typename`. +fn pascal_case(name: &str) -> String { + let mut pascal = String::new(); + let mut capitalize = true; + for character in name.chars() { + if character == '_' { + capitalize = true; + } else if capitalize { + pascal.extend(character.to_uppercase()); + capitalize = false; + } else { + pascal.push(character); + } + } + pascal +} + +/// The Rust field for a GraphQL name: snake case, raw when it is a keyword, +/// with the `serde` attribute that restores the name when it differs. +fn field_ident(name: &str, taken: &mut BTreeSet) -> (Ident, Option) { + let mut snake = snake_case(name); + if UNRAWABLE.contains(&snake.as_str()) { + snake.push('_'); + } + while !taken.insert(snake.clone()) { + snake.push('_'); + } + let rename = (snake != name).then(|| quote!(#[serde(rename = #name)])); + let ident = if KEYWORDS.contains(&snake.as_str()) { + Ident::new_raw(&snake, Span::call_site()) + } else { + Ident::new(&snake, Span::call_site()) + }; + (ident, rename) +} + +fn scalar_type(scalar: Scalar, krate: &TokenStream) -> TokenStream { + match scalar { + Scalar::String => quote!(::std::string::String), + Scalar::Int => quote!(::core::primitive::i64), + Scalar::Float => quote!(::core::primitive::f64), + Scalar::Boolean => quote!(::core::primitive::bool), + Scalar::Json => quote!(#krate::__private::serde_json::Value), + } +} + +/// Wraps `base` in the `Option`s and `Vec`s of a GraphQL type. +fn wrap(ty: &TypeRef, base: &TokenStream) -> TokenStream { + match ty { + TypeRef::NonNull(inner) => wrap_non_null(inner, base), + nullable => { + let inner = wrap_non_null(nullable, base); + quote!(::core::option::Option<#inner>) + } + } +} + +fn wrap_non_null(ty: &TypeRef, base: &TokenStream) -> TokenStream { + match ty { + TypeRef::Named(_) => base.clone(), + TypeRef::NonNull(inner) => wrap_non_null(inner, base), + TypeRef::List(item) => { + let item = wrap(item, base); + quote!(::std::vec::Vec<#item>) + } + } +} + +/// The path of `serde` in the generated code, as `#[serde(crate = "…")]` takes it. +fn serde_path(krate: &TokenStream) -> String { + format!("{krate}::__private::serde").replace(' ', "") +} + +// ─── Result ────────────────────────────────────────────────────────── + +struct DataTypes<'a> { + krate: &'a TokenStream, + names: BTreeSet, + items: Vec, +} + +impl DataTypes<'_> { + fn object(&mut self, selection: &Selection, name: String) -> Ident { + let mut name = name; + while !self.names.insert(name.clone()) { + name.push('_'); + } + let ident = Ident::new(&name, Span::call_site()); + + let mut taken = BTreeSet::new(); + let fields: Vec = selection + .fields + .iter() + .map(|field| self.field(field, &name, &mut taken)) + .collect(); + + let krate = self.krate; + let serde = serde_path(krate); + let on = selection.types.join("` or `"); + let doc = if name == DATA_TYPE { + format!(" The `data` of the operation, selected on `{on}`.") + } else if name == crate::bulk::ITEM_TYPE { + format!( + " A top-level object of the bulk query, with the objects of its nested connections, selected on `{on}`." + ) + } else { + format!(" Selection on `{on}`.") + }; + self.items.push(quote! { + #[doc = #doc] + #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq, #krate::__private::serde::Serialize, #krate::__private::serde::Deserialize)] + #[serde(crate = #serde)] + #[allow(dead_code, reason = "the caller may read only some fields")] + pub struct #ident { + #(#fields)* + } + }); + ident + } + + fn field( + &mut self, + field: &SelectedField, + parent: &str, + taken: &mut BTreeSet, + ) -> TokenStream { + let (ident, rename) = field_ident(&field.key, taken); + let base = match &field.base { + FieldBase::Scalar(scalar) => scalar_type(*scalar, self.krate), + FieldBase::Object(selection) => { + let nested = self.object(selection, format!("{parent}{}", pascal_case(&field.key))); + quote!(#nested) + } + }; + let optional = field.conditional || !field.ty.is_non_null(); + let ty = if field.conditional && field.ty.is_non_null() { + let inner = wrap(&field.ty, &base); + quote!(::core::option::Option<#inner>) + } else { + wrap(&field.ty, &base) + }; + + let default = (optional || field.connection).then(|| quote!(#[serde(default)])); + let doc = format!(" `{}: {}`", field.key, field.ty); + quote! { + #[doc = #doc] + #rename + #default + pub #ident: #ty, + } + } +} + +/// The public structs describing the `data` of `operation`: [`DATA_TYPE`] and +/// one struct per nested selection, named after its path (`DataOrdersNodes`). +/// +/// `krate` is the path of the `shopify_api` crate in the generated code. +pub fn data_types(operation: &Operation, krate: &TokenStream) -> TokenStream { + let mut types = DataTypes { + krate, + names: BTreeSet::new(), + items: Vec::new(), + }; + types.object(&operation.data, DATA_TYPE.to_string()); + let items = types.items; + quote!(#(#items)*) +} + +/// The structs of the items of a bulk query: `name`, and one struct per +/// nested selection, named after its path (`ItemVariants`). +pub fn item_types(selection: &Selection, name: &str, krate: &TokenStream) -> TokenStream { + let mut types = DataTypes { + krate, + names: BTreeSet::new(), + items: Vec::new(), + }; + types.object(selection, name.to_string()); + let items = types.items; + quote!(#(#items)*) +} + +/// The Rust fields of the struct of `selection`, by response key, as +/// [`item_types`] and [`data_types`] name them. +pub(crate) fn field_idents(selection: &Selection) -> Vec<(String, Ident)> { + let mut taken = BTreeSet::new(); + selection + .fields + .iter() + .map(|field| (field.key.clone(), field_ident(&field.key, &mut taken).0)) + .collect() +} + +// ─── Variables ─────────────────────────────────────────────────────── + +/// The Rust type a variable value is converted to, or `None` when the variable +/// holds an input object, which is an [`InputObject`](https://docs.rs/shopify_api/latest/shopify_api/struct.InputObject.html). +pub fn variable_type(variable: &Variable, krate: &TokenStream) -> Option { + let base = match variable.base { + VariableBase::Scalar(scalar) => scalar_type(scalar, krate), + VariableBase::Enum => scalar_type(Scalar::String, krate), + VariableBase::Input => return None, + }; + Some(wrap(&variable.ty, &base)) +} + +/// The `TYPE` of `shopify_api::InputObject` for the input object +/// `name`: the 64-bit FNV-1a hash of the name, the same in every crate. +pub fn input_object_id(name: &str) -> u64 { + name.bytes().fold(0xcbf2_9ce4_8422_2325, |hash, byte| { + (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3) + }) +} + +/// A compiler warning at `span` that gives `note`: the use of a +/// `#[deprecated]` constant. +pub fn deprecation_warning(span: Span, note: &str) -> TokenStream { + quote_spanned! {span=> + const _: () = { + #[deprecated(note = #note)] + const SHOPIFY_DEPRECATION: () = (); + SHOPIFY_DEPRECATION + }; + } +} + +/// The input objects a value of input type `name` may hold, `name` included. +fn reachable_inputs<'a>(schema: &'a Schema, name: &'a str, found: &mut BTreeSet<&'a str>) { + if let Some(TypeDef::Input { fields, .. }) = schema.get(name) + && found.insert(name) + { + for field in fields.values() { + reachable_inputs(schema, field.ty.name(), found); + } + } +} + +/// [`VARIABLES_TYPE`], `operation(variables)`, `From` for the +/// operation, and a type alias, named as in the schema, for each input object +/// the variables may hold. +/// +/// `constructor` builds the operation without its variables; `krate` is the +/// path of the `shopify_api` crate in the generated code. +pub fn variables_types( + schema: &Schema, + operation: &Operation, + krate: &TokenStream, + constructor: &TokenStream, +) -> TokenStream { + let data = Ident::new(DATA_TYPE, Span::call_site()); + let target = quote!(#krate::__private::Operation<#data>); + variables_types_for( + schema, + operation, + krate, + constructor, + &target, + "`Shopify::execute`", + ) +} + +/// [`variables_types`] for an operation of type `target`, which `runner` +/// runs: a bulk query or a bulk mutation. +pub fn variables_types_for( + schema: &Schema, + operation: &Operation, + krate: &TokenStream, + constructor: &TokenStream, + target: &TokenStream, + runner: &str, +) -> TokenStream { + let mut inputs = BTreeSet::new(); + for variable in &operation.variables { + reachable_inputs(schema, variable.ty.name(), &mut inputs); + } + let aliases = inputs.iter().map(|name| { + let ident = Ident::new(name, Span::call_site()); + let id = input_object_id(name); + let doc = format!(" The input object `{name}`: build it with `input!({name} {{ … }})`."); + quote! { + #[doc = #doc] + #[allow(dead_code, reason = "the caller may not name every input object")] + pub type #ident = #krate::__private::InputObject<#id>; + } + }); + + let mut taken = BTreeSet::new(); + let mut fields = Vec::new(); + let mut setters = Vec::new(); + for variable in &operation.variables { + let base = match variable.base { + VariableBase::Scalar(scalar) => scalar_type(scalar, krate), + VariableBase::Enum => scalar_type(Scalar::String, krate), + VariableBase::Input => { + let ident = Ident::new(variable.ty.name(), Span::call_site()); + quote!(#ident) + } + }; + let (ident, rename) = field_ident(&variable.name, &mut taken); + let key = &variable.name; + let doc = format!(" `${key}: {}`", variable.ty); + if variable.is_required() { + let ty = wrap(&variable.ty, &base); + fields.push(quote! { + #[doc = #doc] + #rename + pub #ident: #ty, + }); + setters.push(quote! { + let operation = operation.__variable(#key, variables.#ident); + }); + } else { + // `wrap` of a nullable type is already an `Option`. + let ty = wrap(variable.ty.nullable(), &base); + fields.push(quote! { + #[doc = #doc] + #rename + #[serde(skip_serializing_if = "::core::option::Option::is_none")] + pub #ident: #ty, + }); + // `None` leaves the variable out. A non-null variable with a + // default takes its value out of the `Some`, checked as non-null. + let value = if variable.ty.is_non_null() { + quote!(::core::option::Option::Some(value)) + } else { + quote!(value @ ::core::option::Option::Some(_)) + }; + setters.push(quote! { + let operation = match variables.#ident { + #value => operation.__variable(#key, value), + ::core::option::Option::None => operation, + }; + }); + } + } + + // `Default` only when it cannot leave out a required variable; + // `InputObject` has no `PartialEq`. + let mut derives = vec![ + quote!(::core::fmt::Debug), + quote!(::core::clone::Clone), + quote!(#krate::__private::serde::Serialize), + ]; + if inputs.is_empty() { + derives.push(quote!(::core::cmp::PartialEq)); + } + if !operation.variables.iter().any(Variable::is_required) { + derives.push(quote!(::core::default::Default)); + } + let serde = serde_path(krate); + let variables = Ident::new(VARIABLES_TYPE, Span::call_site()); + let struct_doc = format!( + " The variables of the operation; those left to `None` are not sent. {runner} runs it." + ); + let operation_doc = format!(" The operation with its variables, for {runner}."); + quote! { + #(#aliases)* + + #[doc = #struct_doc] + #[derive(#(#derives),*)] + #[serde(crate = #serde)] + pub struct #variables { + #(#fields)* + } + + #[doc = #operation_doc] + pub fn operation(variables: #variables) -> #target { + let operation = #constructor; + #(#setters)* + operation + } + + impl ::core::convert::From<#variables> for #target { + fn from(variables: #variables) -> Self { + operation(variables) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn converts_names() { + for (name, snake, pascal) in [ + ("id", "id", "Id"), + ("lineItems", "line_items", "LineItems"), + ("totalPriceSet", "total_price_set", "TotalPriceSet"), + ("__typename", "typename", "Typename"), + ("HTMLBody", "html_body", "HTMLBody"), + ("sku2", "sku2", "Sku2"), + ("address1", "address1", "Address1"), + ("already_snake", "already_snake", "AlreadySnake"), + ("iOS", "i_os", "IOS"), + ("2fa", "_2fa", "2fa"), + ] { + assert_eq!(snake_case(name), snake, "{name}"); + assert_eq!(pascal_case(name), pascal, "{name}"); + } + } + + #[test] + fn field_identifiers_avoid_keywords_and_duplicates() { + let mut taken = BTreeSet::new(); + let mut field = |name: &str| { + let (ident, rename) = field_ident(name, &mut taken); + ( + ident.to_string(), + rename.map(|attribute| attribute.to_string()), + ) + }; + // A raw identifier still has the name of the field: nothing to restore. + assert_eq!(field("type"), ("r#type".to_string(), None)); + assert_eq!(field("id"), ("id".to_string(), None)); + let renamed = |key: &str| Some(format!("# [serde (rename = \"{key}\")]")); + assert_eq!(field("self"), ("self_".to_string(), renamed("self"))); + assert_eq!( + field("lineItems"), + ("line_items".to_string(), renamed("lineItems")) + ); + assert_eq!( + field("line_items"), + ("line_items_".to_string(), renamed("line_items")) + ); + } +} diff --git a/crates/shopify_api_graphql/src/lib.rs b/crates/shopify_api_graphql/src/lib.rs new file mode 100644 index 0000000..8993aea --- /dev/null +++ b/crates/shopify_api_graphql/src/lib.rs @@ -0,0 +1,70 @@ +//! Compile-time support for the typed Shopify Admin GraphQL operations of +//! [`shopify_api`](https://docs.rs/shopify_api). +//! +//! **An implementation detail of `shopify_api_macros` and of the +//! `shopify-api` command, with no semver guarantee**: any release may change +//! its items. `shopify_api` depends on it with an exact `=` version. Depend on +//! [`shopify_api`](https://crates.io/crates/shopify_api), whose `graphql!` +//! and `input!` macros use it, not on this crate. +//! +//! `analyze` checks an operation against a `Schema` and describes the shape +//! of its variables and of its result; `codegen` turns that description into +//! Rust types. `literal` checks the values written in Rust for input types +//! (`{ title: "x" }`) and writes the code that sends them. `project` finds +//! the API version and the schema file of a crate, and downloads that +//! version's schema (with the `download` feature). No schema is bundled. +//! +//! `SHOPIFY_API_INTERNAL_TEST_SCHEMA` (`project::TEST_SCHEMA_ENV`) is +//! internal to this repository's tests, not part of the API: a schema file +//! `graphql!` then uses for `shopify_api` and the projects `trybuild` +//! compiles for it (`project::TEST_SCHEMA_PACKAGES`), and no other package. +#![forbid(unsafe_code)] +#![cfg_attr(docsrs, feature(doc_cfg))] + +#[doc(hidden)] +pub mod analyze; +#[doc(hidden)] +pub mod bulk; +#[doc(hidden)] +pub mod codegen; +#[doc(hidden)] +pub mod literal; +#[doc(hidden)] +pub mod project; +mod restrict; +#[doc(hidden)] +pub mod schema; +mod source; + +#[doc(hidden)] +pub use analyze::{ + Deprecation, Error, FieldBase, Operation, OperationKind, Scalar, SelectedField, Selection, + Variable, VariableBase, analyze, +}; +#[doc(hidden)] +pub use project::{ + PROJECT_SCHEMA_PATH, SchemaSource, TEST_SCHEMA_ENV, TEST_SCHEMA_PACKAGES, latest_api_version, + schema_source, test_schema_applies, +}; +#[doc(hidden)] +pub use schema::{Field, INTROSPECTION_QUERY, InputValue, Schema, SchemaError, TypeDef, TypeRef}; + +/// The oldest Admin API version `shopify_api` calls. +#[doc(hidden)] +pub const MINIMUM_API_VERSION: &str = "2026-04"; + +/// Whether `version` is an Admin API version `shopify_api` calls: a quarterly +/// release such as `2026-10`, from [`MINIMUM_API_VERSION`] on, or `unstable`. +#[doc(hidden)] +pub fn is_supported_api_version(version: &str) -> bool { + if version == "unstable" { + return true; + } + let bytes = version.as_bytes(); + let well_formed = bytes.len() == 7 + && bytes[4] == b'-' + && bytes[..4].iter().chain(&bytes[5..]).all(u8::is_ascii_digit) + && matches!(&version[5..], "01" | "04" | "07" | "10"); + // Same length and form: the text orders as the dates do. + well_formed && version >= MINIMUM_API_VERSION +} diff --git a/crates/shopify_api_graphql/src/literal.rs b/crates/shopify_api_graphql/src/literal.rs new file mode 100644 index 0000000..2abd15e --- /dev/null +++ b/crates/shopify_api_graphql/src/literal.rs @@ -0,0 +1,1345 @@ +//! Values written in Rust for an input type: the variables of an inline +//! `graphql!`, and `input!`. The macros parse them into [`Value`]s; +//! [`Literals`] checks each one against the type expected where it stands +//! and writes the code that sends it. +//! +//! What a value means depends on that type: +//! +//! - `null` is `null`, where the type is nullable; +//! - `{ field: value, field?: option, … }` is an object where an input object +//! is expected, every field checked; +//! - `[value, …]` and `[for pattern in iterable if condition => value]` are +//! lists where a list is expected; +//! - a lone identifier is a value of the enum where an enum is expected, +//! `raw(string)` a value nothing checks; +//! - anything else is a Rust expression, whose type rustc checks with a +//! trait written for the place: it names the GraphQL type when it refuses +//! one. An `Option` is refused in a field: `field?:` leaves the field out +//! when it is `None`, `field: null` sends `null`. + +use std::collections::BTreeMap; +use std::fmt; + +use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream, TokenTree}; +use quote::{format_ident, quote, quote_spanned}; + +use crate::analyze::{Scalar, Variable, did_you_mean}; +use crate::codegen::{deprecation_warning, input_object_id, variable_type}; +use crate::schema::{InputValue, Schema, TypeDef, TypeRef}; + +/// A value, as the macros parse it. +#[derive(Debug, Clone)] +pub enum Value { + /// `null`. + Null(Span), + /// `raw(value)`, `keyword` being the span of `raw`. + Raw { + keyword: Span, + value: Expr, + }, + /// A lone identifier: a value of the enum where an enum is expected, a + /// Rust variable elsewhere. + Ident(Ident), + Object(Object), + List(List), + For(Box), + /// Any other Rust expression. + Rust(Expr), +} + +/// A Rust expression, and where to point at it. +#[derive(Debug, Clone)] +pub struct Expr { + pub tokens: TokenStream, + pub span: Span, +} + +/// `{ field: value, … }`. +#[derive(Debug, Clone)] +pub struct Object { + /// Of the braces. + pub span: Span, + pub fields: Vec, +} + +#[derive(Debug, Clone)] +pub struct Field { + /// The name of the GraphQL field, `type` included. + pub name: String, + pub name_span: Span, + /// The span of the `?` of `field?: value`. + pub optional: Option, + pub value: Value, +} + +/// `[value, …]`. +#[derive(Debug, Clone)] +pub struct List { + /// Of the brackets. + pub span: Span, + pub items: Vec, + /// The same text read as a Rust array expression, when it is one. + pub rust: Option, +} + +/// `[for pattern in iterable if filter => item]`. +#[derive(Debug, Clone)] +pub struct For { + /// Of the brackets. + pub span: Span, + pub pattern: TokenStream, + pub iterable: TokenStream, + pub filter: Option, + pub item: Value, +} + +/// A value that does not fit the schema, and the token at fault. +#[derive(Debug, Clone)] +pub struct Error { + pub span: Span, + pub message: String, +} + +impl fmt::Display for Error { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.message) + } +} + +impl std::error::Error for Error {} + +fn error(span: Span, message: impl Into) -> Result { + Err(Error { + span, + message: message.into(), + }) +} + +/// How an inline variable is set on the operation. +#[derive(Debug, Clone)] +pub enum VariableValue { + /// A Rust expression converted to `ty` by `IntoVariable`, as + /// `Operation::variable::` does. + Converted { ty: TokenStream, value: Expr }, + /// An expression of the JSON of the value, for + /// `Operation::__literal_variable`. + Literal(TokenStream), +} + +/// Where a value stands, for messages. +#[derive(Clone)] +enum Site { + Variable(String), + Field { name: String, parent: String }, + Item(Box), +} + +impl fmt::Display for Site { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Variable(name) => write!(formatter, "`${name}`"), + Self::Field { name, parent } => write!(formatter, "`{name}` of `{parent}`"), + Self::Item(site) => write!(formatter, "an item of {site}"), + } + } +} + +/// What a value of a type may be: an `Option` stands for a nullable +/// variable or list item, not for a field. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Place { + Variable, + Field, + Item, +} + +/// Checks values against a schema and writes their code. +/// +/// No name the code declares is in scope where a Rust expression of a value +/// is evaluated, so that none captures or shadows a name of the caller's. +/// The Rust expressions of a value are the arguments of one method, which +/// builds the value; the method, and the traits that check each argument, +/// are declared in a block of their own, the receiver of the call. A +/// constant (`"text"`, `12`, `true`) is written in place, with nothing to +/// check. Its locals and parameters are `__shopify_api_…` names, on +/// mixed-site spans: a constant of the caller's of one of these names could +/// only make the code fail to compile (E0530), never change what it sends. +pub struct Literals<'a> { + schema: &'a Schema, + krate: TokenStream, + items: Vec, + count: usize, + /// Of the names of the traits, from the crate being compiled: rustc + /// points at a trait of the same name in another crate otherwise. + suffix: u32, +} + +impl fmt::Debug for Literals<'_> { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("Literals") + .field("api_version", &self.schema.api_version) + .field("items", &self.items.len()) + .finish() + } +} + +impl<'a> Literals<'a> { + /// `krate` is the path of the `shopify_api` crate in the generated code. + pub fn new(schema: &'a Schema, krate: TokenStream) -> Self { + Self { + schema, + krate, + items: Vec::new(), + count: 0, + suffix: crate_suffix(), + } + } + + /// The warnings the code written so far gives: unnamed constants. + pub fn finish(self) -> TokenStream { + let items = self.items; + quote!(#(#items)*) + } + + /// The value of an inline variable. A Rust expression for a scalar, a + /// list of scalars, or `raw(…)` for an enum, converts as it always did + /// (`IntoVariable`, an `Option` sending `null`); anything else is written + /// as JSON when the operation is built. + pub fn variable(&mut self, variable: &Variable, value: &Value) -> Result { + let ty = &variable.ty; + let site = Site::Variable(variable.name.clone()); + let scalar = matches!(self.schema.get(ty.name()), Some(TypeDef::Scalar)); + if scalar { + match value { + Value::Rust(expr) => self.int_literals(&expr.tokens, ty, &site)?, + Value::List(List { + rust: Some(rust), .. + }) => self.int_literals(&rust.tokens, ty, &site)?, + _ => {} + } + } + let rust_type = variable_type(variable, &self.krate); + let convert = |value: Expr| { + rust_type + .clone() + .map(|ty| VariableValue::Converted { ty, value }) + }; + let converted = match value { + Value::Rust(expr) if scalar => convert(expr.clone()), + Value::Ident(ident) if scalar => convert(ident_expr(ident)), + Value::List(List { + items, + rust: Some(rust), + .. + }) if scalar + && items + .iter() + .all(|item| matches!(item, Value::Rust(_) | Value::Ident(_))) => + { + convert(rust.clone()) + } + Value::Raw { keyword, value } => { + self.enum_only(ty, *keyword, &site)?; + convert(value.clone()) + } + _ => None, + }; + if let Some(converted) = converted { + return Ok(converted); + } + let mut build = Build::default(); + let body = self.value(value, ty, &site, Place::Variable, &mut build)?; + Ok(VariableValue::Literal(build.finish(body, &self.krate))) + } + + /// `input!(name { … })`: an `InputObject` of the input object `name`. + pub fn input_object( + &mut self, + name: &str, + span: Span, + object: &Object, + ) -> Result { + let schema = self.schema; + let (fields, one_of) = match schema.get(name) { + Some(TypeDef::Input { fields, one_of }) => (fields, *one_of), + Some(other) => { + return error( + span, + format!( + "`{name}` is {}, not an input object: `input!` builds the input objects of the schema", + other.kind_name() + ), + ); + } + None => { + let inputs = schema + .types + .iter() + .filter(|(_, definition)| matches!(definition, TypeDef::Input { .. })) + .map(|(name, _)| name.as_str()); + return error( + span, + format!( + "The schema has no input object `{name}`{}", + did_you_mean(name, inputs) + ), + ); + } + }; + let mut build = Build::default(); + let body = self.object(name, fields, one_of, object, &mut build)?; + let json = build.finish(body, &self.krate); + let krate = &self.krate; + let id = input_object_id(name); + Ok(quote_spanned! {span=> + #krate::__private::InputObject::<#id>::__new(#name, #json) + }) + } + + /// The code that builds a value of type `ty` from the arguments it adds + /// to `build`. + fn value( + &mut self, + value: &Value, + ty: &TypeRef, + site: &Site, + place: Place, + build: &mut Build, + ) -> Result { + let krate = self.krate.clone(); + let inner = ty.nullable(); + match value { + Value::Null(span) => { + if ty.is_non_null() { + return error( + *span, + format!("`null` is not allowed for {site}, of type `{ty}`"), + ); + } + Ok(quote_spanned!(*span=> ())) + } + Value::Raw { keyword, value } => { + self.enum_only(ty, *keyword, site)?; + let tokens = argument(value); + let arg = quote_spanned!(value.span=> #krate::__private::literal::raw(#tokens)); + Ok(build.argument(None, quote!(::std::string::String), arg)) + } + Value::Ident(ident) => match self.enum_values(inner) { + Some((name, values, deprecated)) => { + self.enum_value(ident, name, values, deprecated, site) + } + None => self.expression(&ident_expr(ident), ty, site, place, build), + }, + Value::Object(object) => match self.input_fields(inner) { + Some((name, fields, one_of)) => self.object(name, fields, one_of, object, build), + None => error( + object.span, + format!("{site} expects {}, not an object", self.what(ty)), + ), + }, + Value::List(list) => match (inner, &list.rust) { + (TypeRef::List(item), _) => { + let site = Site::Item(Box::new(site.clone())); + let mut items = Vec::new(); + for value in &list.items { + items.push(self.value(value, item, &site, Place::Item, build)?); + } + let nested = items + .iter() + .rev() + .fold(quote!(()), |rest, item| quote!((#item, #rest))); + Ok(quote!(literal::List(#nested))) + } + (_, Some(rust)) => self.expression(rust, ty, site, place, build), + (_, None) => error( + list.span, + format!("{site} expects {}, not a list", self.what(ty)), + ), + }, + Value::For(comprehension) => { + let TypeRef::List(item) = inner else { + return error( + comprehension.span, + format!("{site} expects {}, not a list", self.what(ty)), + ); + }; + let site = Site::Item(Box::new(site.clone())); + let mut each = Build::default(); + let value = self.value(&comprehension.item, item, &site, Place::Item, &mut each)?; + let value = each.finish(value, &krate); + let For { + pattern, + iterable, + filter, + .. + } = &**comprehension; + // A generated name may meet a user item only in a compile + // error (a constant in a pattern, E0530), never in a silent + // change of meaning: mixed-site, no user expression sees it. + let items = Ident::new("__shopify_api_collected", Span::mixed_site()); + // Each item is written in its turn of the loop, so that it may + // borrow what the loop gives. + let push = + quote!(#krate::__private::literal::Collected::push(&mut #items, #value);); + let body = match filter { + Some(filter) => quote!(if #filter { #push }), + None => push, + }; + let list = quote! {{ + let mut #items = <#krate::__private::literal::Collected as ::core::default::Default>::default(); + for #pattern in #iterable { #body } + #items + }}; + Ok(build.argument(None, quote!(#krate::__private::literal::Collected), list)) + } + Value::Rust(expr) => self.expression(expr, ty, site, place, build), + } + } + + /// The fields of an object literal, for the input object `name`, a + /// `@oneOf` one when `one_of`. + fn object( + &mut self, + name: &str, + definitions: &BTreeMap, + one_of: bool, + object: &Object, + build: &mut Build, + ) -> Result { + let one_of_rule = || { + let fields: Vec = definitions.keys().map(|key| format!("`{key}`")).collect(); + format!( + "`{name}` is a oneOf input: give exactly one of {}, not null", + join(&fields, "or") + ) + }; + let mut given: Vec<&str> = Vec::new(); + let mut fields = Vec::new(); + for field in &object.fields { + let key = field.name.as_str(); + let Some(definition) = definitions.get(key) else { + return error( + field.name_span, + format!( + "Input object `{name}` has no field `{key}`{}", + did_you_mean(key, definitions.keys().map(String::as_str)) + ), + ); + }; + if given.contains(&key) { + return error( + field.name_span, + format!("The field `{key}` of `{name}` is given twice"), + ); + } + if one_of { + if let Some(first) = given.first() { + return error( + field.name_span, + format!("{}: `{first}` is given already", one_of_rule()), + ); + } + if let Some(question) = field.optional { + return error( + question, + format!("{}: write `{key}: …`, not `{key}?:`", one_of_rule()), + ); + } + if let Value::Null(span) = field.value { + return error(span, format!("{}: `{key}: null` is not one", one_of_rule())); + } + } + given.push(key); + if let Some(reason) = &definition.deprecation { + let note = format!( + "`{name}.{key}` is deprecated in the Shopify Admin API {}: {reason}", + self.schema.api_version + ); + self.items.push(deprecation_warning(field.name_span, ¬e)); + } + let site = Site::Field { + name: key.to_string(), + parent: name.to_string(), + }; + let code = match field.optional { + Some(question) => { + if definition.is_required() { + return error( + question, + format!( + "{site} is required (`{}`): it cannot be left out, so `?:` does not apply; write `{key}: …`", + definition.ty + ), + ); + } + let value = self.optional(field, definition, &site, build)?; + quote!(literal::Optional(#key, #value)) + } + None => { + // The field of a oneOf input is nullable in the schema, and + // takes a value that is not null. + let ty = match one_of { + true => TypeRef::NonNull(Box::new(definition.ty.nullable().clone())), + false => definition.ty.clone(), + }; + let value = self.value(&field.value, &ty, &site, Place::Field, build)?; + quote!(literal::Field(#key, #value)) + } + }; + fields.push(code); + } + if one_of && given.is_empty() { + return error(object.span, one_of_rule()); + } + let missing: Vec = definitions + .iter() + .filter(|(key, definition)| definition.is_required() && !given.contains(&key.as_str())) + .map(|(key, definition)| format!("`{key}: {}`", definition.ty)) + .collect(); + if !missing.is_empty() { + let (fields, them) = if missing.len() == 1 { + ("field", "it") + } else { + ("fields", "them") + }; + return error( + object.span, + format!( + "Input object `{name}` requires the {fields} {}: add {them}", + join(&missing, "and") + ), + ); + } + let nested = fields + .iter() + .rev() + .fold(quote!(()), |rest, field| quote!((#field, #rest))); + Ok(quote!(literal::Object(#nested))) + } + + /// `field?: value`, the field being optional: `Maybe` of the value. + fn optional( + &mut self, + field: &Field, + definition: &InputValue, + site: &Site, + build: &mut Build, + ) -> Result { + let krate = self.krate.clone(); + let key = &field.name; + // Non-null with a default: absent is fine, `null` is not. + let null_refused = definition.ty.is_non_null(); + let expr = match &field.value { + Value::Raw { keyword, value } => { + self.enum_only(&definition.ty, *keyword, site)?; + let tokens = argument(value); + let convert = if null_refused { + quote!(raw_option) + } else { + quote!(raw_optional) + }; + let arg = + quote_spanned!(value.span=> #krate::__private::literal::#convert(#tokens)); + return Ok(build.argument( + None, + quote!(#krate::__private::Maybe<::std::string::String>), + arg, + )); + } + Value::Rust(expr) => expr.clone(), + Value::Ident(ident) => ident_expr(ident), + Value::Null(span) => { + return error(*span, format!("`{key}?: null` is `{key}: null`")); + } + Value::Object(Object { span, .. }) | Value::List(List { span, .. }) => { + return error(*span, literal_after_question(key)); + } + Value::For(comprehension) => { + return error(comprehension.span, literal_after_question(key)); + } + }; + if self.is_enum(&definition.ty) { + return error( + expr.span, + format!( + "{site} holds a value of the enum `{}`: for a string known at run time, write `{key}?: raw(…)`, with an `Option` of it", + definition.ty.name() + ), + ); + } + + self.int_literals(&expr.tokens, &definition.ty, site)?; + let kind = self.kind(&definition.ty); + let value_bound = self.expect(&definition.ty, Place::Field, site, &kind, build); + let n = self.next(); + let bound = self.name("Optional", n); + let what = escape(&self.what(&definition.ty)); + let (message, label, maybe_bound) = if null_refused { + let no_null = self.name("NoNull", n); + let refusal = escape(&format!( + "{site} is non-null (`{}`): `{key}?:` takes an `Option`, not a `Maybe`, whose `Null` it refuses", + definition.ty + )); + build.items.push(quote! { + #[diagnostic::on_unimplemented(message = #refusal, label = "an `Option`: `None` leaves the field out")] + trait #no_null {} + }); + ( + format!("`{key}?:` takes an `Option` of {what}, not `{{Self}}`"), + "`None` leaves the field out".to_string(), + quote!(#value_bound + #no_null), + ) + } else { + ( + format!( + "`{key}?:` takes an `Option` or a `shopify_api::Maybe` of {what}, not `{{Self}}`" + ), + "`None` and `Maybe::Absent` leave the field out, `Maybe::Null` sends `null`" + .to_string(), + quote!(#value_bound), + ) + }; + // `OptionalValue` as a supertrait: one refusal, which names the field. + build.items.push(quote! { + #[diagnostic::on_unimplemented(message = #message, label = #label)] + trait #bound: literal::OptionalValue<#kind> {} + impl #bound for ::core::option::Option {} + impl #bound for #krate::__private::Maybe {} + }); + let generic = format_ident!("V{n}"); + let value = build.argument( + Some(quote!(#generic: #bound)), + quote!(#generic), + argument(&expr), + ); + Ok(quote! { + literal::optional::<#kind, _>( + literal::OptionalValue::<#kind>::into_maybe(#value) + ) + }) + } + + /// A Rust expression for a value of type `ty`, checked by a trait. + fn expression( + &mut self, + expr: &Expr, + ty: &TypeRef, + site: &Site, + place: Place, + build: &mut Build, + ) -> Result { + if self.is_enum(ty) { + let name = ty.name(); + let message = match ty.nullable() { + TypeRef::List(_) => format!( + "{site} expects a list of values of the enum `{name}`: write them bare, `[{}, …]`, or `[for value in … => raw(value)]` for strings known at run time", + self.first_value(name) + ), + _ => format!( + "{site} expects a value of the enum `{name}`: write it bare, as `{}`, or `raw(…)` for a string known at run time", + self.first_value(name) + ), + }; + return error(expr.span, message); + } + self.int_literals(&expr.tokens, ty, site)?; + let kind = self.kind(ty); + if let Some(constant) = self.constant(expr, ty) { + return Ok(constant); + } + let bound = self.expect(ty, place, site, &kind, build); + let generic = format_ident!("V{}", self.next()); + let value = build.argument( + Some(quote!(#generic: #bound)), + quote!(#generic), + argument(expr), + ); + Ok(quote!(literal::leaf::<#kind, _>(#value))) + } + + /// A literal that has the type `ty` whatever its context, written in + /// place: a string for a string scalar, an integer for an `Int` (checked + /// already) or a `Float`, a float for a `Float`, `true` or `false`. + fn constant(&self, expr: &Expr, ty: &TypeRef) -> Option { + let TypeRef::Named(name) = ty.nullable() else { + return None; + }; + if !matches!(self.schema.get(name), Some(TypeDef::Scalar)) { + return None; + } + let trees: Vec = expr.tokens.clone().into_iter().collect(); + let literal = match trees.as_slice() { + [TokenTree::Ident(ident)] if ident == "true" || ident == "false" => { + return (Scalar::of(name) == Scalar::Boolean).then(|| expr.tokens.clone()); + } + [TokenTree::Literal(literal)] => literal.to_string(), + [TokenTree::Punct(minus), TokenTree::Literal(literal)] if minus.as_char() == '-' => { + literal.to_string() + } + _ => return None, + }; + let tokens = &expr.tokens; + match (Scalar::of(name), number(&literal)) { + (Scalar::String, _) + if literal.starts_with('"') + || literal.starts_with("r\"") + || literal.starts_with("r#") => + { + (!trees.iter().any(|tree| matches!(tree, TokenTree::Punct(_)))) + .then(|| tokens.clone()) + } + (Scalar::Int, Some(Number::Int(suffix))) + if suffix.is_empty() || INT_TYPES.contains(&suffix) => + { + Some(quote!(literal::leaf::(#tokens))) + } + ( + Scalar::Float, + Some(Number::Int("" | "i32" | "u32") | Number::Float("" | "f32" | "f64")), + ) => Some(quote!(literal::leaf::(#tokens))), + _ => None, + } + } + + /// The trait a Rust expression of type `ty` must implement at `place`, + /// whose refusal names the GraphQL type. + fn expect( + &mut self, + ty: &TypeRef, + place: Place, + site: &Site, + kind: &TokenStream, + build: &mut Build, + ) -> Ident { + let n = self.next(); + let bound = self.name("Expect", n); + let krate = self.krate.clone(); + let what = self.what(ty); + let mut label = accepted(self.schema, ty.nullable()); + let mut impls = Vec::new(); + let mut note = None; + let inner = ty.nullable(); + if !ty.is_non_null() && place != Place::Field { + label.push_str(", or an `Option` of it, `None` sending `null`"); + let non_null = TypeRef::NonNull(Box::new(inner.clone())); + let value = self.expect(&non_null, place, site, kind, build); + impls.push(quote!(impl #bound for V {})); + impls.push(quote!(impl #bound for ::core::option::Option {})); + } else { + match inner { + TypeRef::List(item) => { + let item = self.expect( + item, + Place::Item, + &Site::Item(Box::new(site.clone())), + kind, + build, + ); + impls.push(quote! { + impl #bound for ::std::vec::Vec {} + impl<'a, V: #item> #bound for &'a ::std::vec::Vec {} + impl<'a, V: #item> #bound for &'a [V] {} + impl #bound for [V; N] {} + }); + } + TypeRef::Named(name) => match self.schema.get(name) { + Some(TypeDef::Input { .. }) => { + let id = input_object_id(name); + impls.push(quote! { + impl #bound for #krate::__private::InputObject<#id> {} + impl<'a> #bound for &'a #krate::__private::InputObject<#id> {} + }); + } + // One impl for the types of the scalar: the refusal is this + // trait's, which names the place. + _ => impls.push(quote! { + #[diagnostic::do_not_recommend] + impl> #bound for V {} + }), + }, + TypeRef::NonNull(_) => unreachable!("`nullable` removes the `!`"), + } + if place == Place::Field { + if self.is_scalar(inner) { + note = self.option_note(ty, site); + } else { + impls.push(self.no_option(&bound, ty, site, kind)); + } + } + } + // The type of an `InputObject` is a hash: the message names the + // expected GraphQL type and leaves the given one to rustc's help. + let given = if self.holds_input(ty) { + "" + } else { + ", not `{Self}`" + }; + let message = format!( + "{} expects {}{given}", + escape(&site.to_string()), + escape(&what) + ); + let label = escape(&label); + let note = note.map(|note: String| { + let note = escape(¬e); + quote!(, note = #note) + }); + // `Validate` as a supertrait: what a value is checked for when it is + // built follows from its type being accepted. + build.items.push(quote! { + #[diagnostic::on_unimplemented(message = #message, label = #label #note)] + trait #bound: literal::Validate<#kind> {} + #(#impls)* + }); + bound + } + + /// What to write for an `Option` in a nullable field of a scalar, whose + /// check takes the types of the scalar only: shown with any refusal. + fn option_note(&self, ty: &TypeRef, site: &Site) -> Option { + let Site::Field { name, .. } = site else { + return None; + }; + (!ty.is_non_null()).then(|| { + format!( + "`{name}?: value` takes an `Option`, `None` leaving the field out; `{name}: null` sends `null`" + ) + }) + } + + fn is_scalar(&self, ty: &TypeRef) -> bool { + matches!(ty, TypeRef::Named(name) if matches!(self.schema.get(name), Some(TypeDef::Scalar))) + } + + /// Refuses an `Option` in a field, saying what to write instead: sending + /// `null` for `None` would clear the field. + fn no_option( + &mut self, + bound: &Ident, + ty: &TypeRef, + site: &Site, + kind: &TokenStream, + ) -> TokenStream { + let n = self.next(); + let no_option = self.name("NoOption", n); + let Site::Field { name, .. } = site else { + unreachable!("a field has a field site") + }; + let what = self.what(ty); + let (message, label) = if ty.is_non_null() { + ( + format!("{site} is required (`{ty}`): it takes {what}, not an `Option`"), + "the field is required: give a value".to_string(), + ) + } else { + ( + format!( + "{site} takes {what}, not an `Option`: write `{name}?: value` to leave the field out when it is `None`, or `{name}: null` to send `null`" + ), + format!("`{name}: None` would send `null`, which clears the field"), + ) + }; + let (message, label) = (escape(&message), escape(&label)); + quote! { + #[diagnostic::on_unimplemented(message = #message, label = #label)] + trait #no_option: literal::Validate<#kind> {} + impl #bound for ::core::option::Option {} + } + } + + /// A value of the enum `name`, written bare. + fn enum_value( + &mut self, + ident: &Ident, + name: &str, + values: &[String], + deprecated: &BTreeMap, + site: &Site, + ) -> Result { + let given = unraw(ident); + if !values.contains(&given) { + let listed: Vec = values + .iter() + .take(LISTED_VALUES) + .map(|value| format!("`{value}`")) + .collect(); + let mut list = join(&listed, "or"); + if values.len() > LISTED_VALUES { + list = format!("{}, … ({} values)", listed.join(", "), values.len()); + } + let run_time = if given.chars().any(char::is_lowercase) { + format!("; for a string known at run time, write `raw({given})`") + } else { + String::new() + }; + return error( + ident.span(), + format!( + "`{given}` is not a value of the enum `{name}`{}: {site} takes {list}{run_time}", + did_you_mean(&given, values.iter().map(String::as_str)) + ), + ); + } + if let Some(reason) = deprecated.get(&given) { + let note = format!( + "`{name}.{given}` is deprecated in the Shopify Admin API {}: {reason}", + self.schema.api_version + ); + self.items.push(deprecation_warning(ident.span(), ¬e)); + } + Ok(quote_spanned!(ident.span()=> #given)) + } + + /// Refuses `raw(…)` where no enum value is expected. + fn enum_only(&self, ty: &TypeRef, keyword: Span, site: &Site) -> Result<(), Error> { + if self.enum_values(ty.nullable()).is_some() { + return Ok(()); + } + error( + keyword, + format!( + "`raw(…)` is only for a value of an enum: {site} expects {}", + self.what(ty) + ), + ) + } + + fn enum_values( + &self, + ty: &TypeRef, + ) -> Option<(&'a str, &'a [String], &'a BTreeMap)> { + let schema = self.schema; + match ty { + TypeRef::Named(name) => match schema.get(name) { + Some(TypeDef::Enum { values, deprecated }) => { + let (name, _) = schema.types.get_key_value(name)?; + Some((name.as_str(), values.as_slice(), deprecated)) + } + _ => None, + }, + _ => None, + } + } + + /// The name, the fields and whether it is `@oneOf`, of an input object. + fn input_fields( + &self, + ty: &TypeRef, + ) -> Option<(&'a str, &'a BTreeMap, bool)> { + let schema = self.schema; + match ty { + TypeRef::Named(name) => match schema.get(name) { + Some(TypeDef::Input { fields, one_of }) => { + let (name, _) = schema.types.get_key_value(name)?; + Some((name.as_str(), fields, *one_of)) + } + _ => None, + }, + _ => None, + } + } + + /// What a Rust expression of type `ty` is checked for when it is built: + /// the `Int`, `Float` or non-null `JSON` its innermost type is. + fn kind(&self, ty: &TypeRef) -> TokenStream { + let (name, non_null) = innermost(ty); + let kind = match (self.schema.get(name), Scalar::of(name)) { + (Some(TypeDef::Scalar), Scalar::Int) => quote!(Int), + (Some(TypeDef::Scalar), Scalar::Float) => quote!(Float), + (Some(TypeDef::Scalar), Scalar::Boolean) => quote!(Boolean), + (Some(TypeDef::Scalar), Scalar::Json) if non_null => quote!(Json), + (Some(TypeDef::Scalar), Scalar::Json) => quote!(MaybeJson), + (Some(TypeDef::Scalar), _) => quote!(Text), + _ => quote!(Input), + }; + quote!(literal::#kind) + } + + /// Refuses an integer literal outside of the 32 bits of `Int`, where + /// the innermost type of `ty` is `Int`: written alone, negated, in + /// parentheses, or as an item of a list `[…]`. Only forms whose meaning + /// does not depend on what a name resolves to: `Some(…)` may be a + /// function of the caller's. Any other value is checked when it is built. + fn int_literals(&self, tokens: &TokenStream, ty: &TypeRef, site: &Site) -> Result<(), Error> { + if !matches!(self.schema.get(ty.name()), Some(TypeDef::Scalar)) + || Scalar::of(ty.name()) != Scalar::Int + { + return Ok(()); + } + let mut found = Vec::new(); + int_literals(tokens, &mut found); + match found + .into_iter() + .find(|(value, _)| i32::try_from(*value).is_err()) + { + Some((_, span)) => error( + span, + format!( + "The integer is outside the range of `Int`, a 32-bit integer, given for {site}" + ), + ), + None => Ok(()), + } + } + + /// The innermost type of `ty` is an input object. + fn holds_input(&self, ty: &TypeRef) -> bool { + matches!(self.schema.get(ty.name()), Some(TypeDef::Input { .. })) + } + + /// The innermost type of `ty` is an enum. + fn is_enum(&self, ty: &TypeRef) -> bool { + matches!(self.schema.get(ty.name()), Some(TypeDef::Enum { .. })) + } + + fn first_value(&self, name: &str) -> &str { + match self.schema.get(name) { + Some(TypeDef::Enum { values, .. }) => values.first().map_or("VALUE", String::as_str), + _ => "VALUE", + } + } + + /// A type in words: "a `String`", "a list of `MetafieldsSetInput`, built with …". + fn what(&self, ty: &TypeRef) -> String { + match ty.nullable() { + TypeRef::List(item) => format!("a list of {}", self.items_of(item)), + other => { + let name = other.name(); + match self.schema.get(name) { + Some(TypeDef::Input { .. }) => { + format!("a `{name}`, built with `input!({name} {{ … }})`") + } + Some(TypeDef::Enum { .. }) => format!("a value of the enum `{name}`"), + _ => { + let article = if name.starts_with(['A', 'E', 'I', 'O', 'U']) { + "an" + } else { + "a" + }; + match Scalar::of(name) { + Scalar::String if !matches!(name, "String") => { + format!("{article} `{name}` (a string)") + } + _ => format!("{article} `{name}`"), + } + } + } + } + } + } + + fn items_of(&self, ty: &TypeRef) -> String { + match ty.nullable() { + TypeRef::List(item) => format!("lists of {}", self.items_of(item)), + other => { + let name = other.name(); + match self.schema.get(name) { + Some(TypeDef::Input { .. }) => { + format!("`{name}`, built with `input!({name} {{ … }})`") + } + Some(TypeDef::Enum { .. }) => format!("values of the enum `{name}`"), + _ => format!("`{name}`"), + } + } + } + } + + fn name(&self, what: &str, n: usize) -> Ident { + format_ident!("__ShopifyApi{what}{n}_{:08x}", self.suffix) + } + + fn next(&mut self) -> usize { + self.count += 1; + self.count + } +} + +/// A hash of the name of the crate being compiled, which cargo gives the +/// macros. +fn crate_suffix() -> u32 { + let name = std::env::var("CARGO_CRATE_NAME").unwrap_or_default(); + let hash = input_object_id(&name); + (hash ^ (hash >> 32)) as u32 +} + +fn literal_after_question(key: &str) -> String { + format!( + "`{key}?:` takes a Rust expression, an `Option` or a `shopify_api::Maybe` whose `None` leaves the field out; write `{key}: …` for this value" + ) +} + +/// How many values of an enum a message lists. +const LISTED_VALUES: usize = 30; + +/// The Rust types accepted for a value of `ty`, the `!` removed. +fn accepted(schema: &Schema, ty: &TypeRef) -> String { + match ty { + TypeRef::List(_) => "a `Vec`, a slice or an array".to_string(), + other => { + let name = other.name(); + if let Some(TypeDef::Input { .. }) = schema.get(name) { + return format!("build it with `input!({name} {{ … }})`"); + } + match Scalar::of(name) { + Scalar::String => "`String`, `&str`, `&String` or `Cow`", + Scalar::Int => "any integer type", + Scalar::Float => "`f64`, `f32`, `i32` or `u32`", + Scalar::Boolean => "`bool`", + Scalar::Json => "`serde_json::Value` or `&Value`", + } + .to_string() + } + } +} + +/// The integer literals of `tokens` in the forms +/// [`Literals::int_literals`] reads, and their spans; one beyond `i128` is +/// `i128::MAX`, and one whose suffix's type cannot hold it is left out. +fn int_literals(tokens: &TokenStream, found: &mut Vec<(i128, Span)>) { + let trees: Vec = tokens.clone().into_iter().collect(); + match trees.as_slice() { + [TokenTree::Literal(literal)] => { + if let Some(value) = int_literal(&literal.to_string(), false) { + found.push((value, literal.span())); + } + } + [TokenTree::Punct(minus), TokenTree::Literal(literal)] if minus.as_char() == '-' => { + if let Some(value) = int_literal(&literal.to_string(), true) { + found.push((value, literal.span())); + } + } + [TokenTree::Group(group)] => match group.delimiter() { + Delimiter::Parenthesis | Delimiter::None => int_literals(&group.stream(), found), + Delimiter::Bracket => items(&group.stream(), found), + Delimiter::Brace => {} + }, + _ => {} + } + + fn items(tokens: &TokenStream, found: &mut Vec<(i128, Span)>) { + let mut item = TokenStream::new(); + for tree in tokens.clone() { + match &tree { + TokenTree::Punct(comma) if comma.as_char() == ',' => { + int_literals(&std::mem::take(&mut item), found); + } + _ => item.extend([tree]), + } + } + int_literals(&item, found); + } +} + +/// The value of the text of an integer literal: `2_147_483_648_i64`, +/// `0x8000_0000`, `0b1`; `None` for any other literal. +fn integer(text: &str) -> Option { + let (magnitude, _) = integer_parts(text)?; + Some(magnitude.map_or(i128::MAX, |value| { + i128::try_from(value).unwrap_or(i128::MAX) + })) +} + +/// The value of an integer literal, negated or not, when the compiler gives +/// it the value written; `None` when its suffix's type cannot hold it, as +/// `0xffff_ffff_i32`, which `allow(overflowing_literals)` makes `-1`: only +/// the value built from it is known. `isize` and `usize` are taken as 32 +/// bits, the narrowest a target may have. +fn int_literal(text: &str, negated: bool) -> Option { + let (magnitude, suffix) = integer_parts(text)?; + if let Some(suffix) = suffix { + let bits = match &suffix[1..] { + "size" => 32, + bits => bits.parse().ok()?, + }; + let largest = if suffix.starts_with('i') { + (1_u128 << (bits - 1)) - u128::from(!negated) + } else { + u128::MAX >> (128 - bits) + }; + if magnitude? > largest { + return None; + } + } + let value = integer(text)?; + Some(if negated { + value.saturating_neg() + } else { + value + }) +} + +/// The digits of an integer literal as a number, `None` beyond `u128`, and +/// its suffix; `None` for any other literal. +fn integer_parts(text: &str) -> Option<(Option, Option<&'static str>)> { + const SUFFIXES: [&str; 12] = [ + "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize", + ]; + let (radix, digits) = [(16, "0x"), (8, "0o"), (2, "0b")] + .into_iter() + .find_map(|(radix, prefix)| Some((radix, text.strip_prefix(prefix)?))) + .unwrap_or((10, text)); + let (digits, suffix) = SUFFIXES + .iter() + .find_map(|suffix| Some((digits.strip_suffix(suffix)?, Some(*suffix)))) + .unwrap_or((digits, None)); + let digits: String = digits.chars().filter(|&digit| digit != '_').collect(); + if digits.is_empty() || !digits.chars().all(|digit| digit.is_digit(radix)) { + return None; + } + Some((u128::from_str_radix(&digits, radix).ok(), suffix)) +} + +/// The innermost named type of `ty`, and whether it is non-null. +fn innermost(ty: &TypeRef) -> (&str, bool) { + match ty { + TypeRef::Named(name) => (name, false), + TypeRef::NonNull(inner) => match &**inner { + TypeRef::Named(name) => (name, true), + other => innermost(other), + }, + TypeRef::List(item) => innermost(item), + } +} + +/// The Rust expressions of a value, which are the arguments of the method +/// that builds it, and the traits that check them. +#[derive(Default)] +struct Build { + items: Vec, + generics: Vec, + params: Vec, + args: Vec, +} + +impl Build { + /// Takes `arg` as an argument of type `ty`: the name the code that + /// builds the value refers to it by. + fn argument( + &mut self, + generic: Option, + ty: TokenStream, + arg: TokenStream, + ) -> TokenStream { + let name = format_ident!( + "__shopify_api_value{}", + self.params.len(), + span = Span::mixed_site() + ); + self.generics.extend(generic); + self.params.push(quote!(#name: #ty)); + self.args.push(arg); + quote!(#name) + } + + /// The code of the JSON of the value, or of why it is refused: a + /// `Result, Invalid>`, a type that does not depend on the + /// arguments, so that a refused argument is reported once, at it. + fn finish(self, body: TokenStream, krate: &TokenStream) -> TokenStream { + let Self { + items, + generics, + params, + args, + } = self; + let json = quote!(literal::to_raw(&#body)); + // `literal`, in a block that no expression of the caller's is in. + let path = quote!(use #krate::__private::literal;); + if args.is_empty() { + return quote!({ #path #json }); + } + quote! { + ({ + #path + #(#items)* + struct Checks; + impl Checks { + #[allow(clippy::too_many_arguments, reason = "one per Rust expression of the value")] + fn build<#(#generics),*>(self, #(#params),*) -> ::core::result::Result< + ::std::boxed::Box<#krate::__private::serde_json::value::RawValue>, + literal::Invalid, + > { + #json + } + } + Checks + }) + .build(#(#args),*) + } + } +} + +const INT_TYPES: [&str; 10] = [ + "i8", "i16", "i32", "i64", "isize", "u8", "u16", "u32", "u64", "usize", +]; + +/// A number literal and its suffix. +enum Number<'a> { + Int(&'a str), + Float(&'a str), +} + +/// The kind of the number literal `text`, if it is one. +fn number(text: &str) -> Option> { + if !text.starts_with(|first: char| first.is_ascii_digit()) { + return None; + } + if integer(text).is_some() { + let suffix = INT_TYPES + .iter() + .chain(&["i128", "u128"]) + .find(|suffix| text.ends_with(*suffix)) + .copied() + .unwrap_or(""); + return Some(Number::Int(suffix)); + } + let (digits, suffix) = ["f32", "f64"] + .iter() + .find_map(|suffix| Some((text.strip_suffix(suffix)?, *suffix))) + .unwrap_or((text, "")); + digits + .chars() + .all(|character| { + character.is_ascii_digit() || matches!(character, '.' | '_' | 'e' | 'E' | '+' | '-') + }) + .then_some(Number::Float(suffix)) +} + +/// An expression of the caller's as an argument, in parentheses of the +/// macro's at its place: its braces are not a method argument of the +/// caller's to lint, and a refusal points at it. +pub fn argument(expr: &Expr) -> TokenStream { + let mut group = Group::new(Delimiter::Parenthesis, expr.tokens.clone()); + group.set_span(Span::mixed_site().located_at(expr.span)); + TokenTree::Group(group).into() +} + +fn ident_expr(ident: &Ident) -> Expr { + Expr { + tokens: quote!(#ident), + span: ident.span(), + } +} + +/// The name of an identifier, without the `r#` of a raw one. +fn unraw(ident: &Ident) -> String { + let name = ident.to_string(); + match name.strip_prefix("r#") { + Some(name) => name.to_string(), + None => name, + } +} + +/// `a`, `a and b`, `a, b and c`. +pub(crate) fn join(items: &[String], last: &str) -> String { + match items { + [] => String::new(), + [one] => one.clone(), + [init @ .., tail] => format!("{} {last} {tail}", init.join(", ")), + } +} + +/// Text for `#[diagnostic::on_unimplemented]`, where braces are placeholders. +fn escape(text: &str) -> String { + text.replace('{', "{{").replace('}', "}}") +} diff --git a/crates/shopify_api_graphql/src/project.rs b/crates/shopify_api_graphql/src/project.rs new file mode 100644 index 0000000..9196ea0 --- /dev/null +++ b/crates/shopify_api_graphql/src/project.rs @@ -0,0 +1,1797 @@ +//! The Admin API version of a crate, and the schema file that goes with it. +//! +//! A crate may pin its version, and name its schema file, in its `Cargo.toml`: +//! +//! ```toml +//! [package.metadata.shopify_api] +//! api-version = "2026-07" +//! schema = "schemas/admin-2026-07.json" +//! ``` +//! +//! `schema` must name a file inside the package, which `cargo package` +//! ships: see [`inside_package`]. Without it, the file is +//! [`PROJECT_SCHEMA_PATH`]. Without +//! `api-version`, the version is the one of that file, and the latest stable +//! one when there is no file yet. `graphql!` checks the crate's operations +//! against that schema: see [`schema_plan`] for when it is downloaded. +//! +//! Both keys belong to the package: which schema a crate is checked against +//! depends on its own `Cargo.toml` and files only, never on where it is, nor +//! on the cargo command that built it. + +use std::ffi::OsStr; +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + +use crate::{MINIMUM_API_VERSION, is_supported_api_version}; + +/// Where a crate keeps the schema of its API version, relative to its `Cargo.toml`. +pub const PROJECT_SCHEMA_PATH: &str = "graphql/admin.schema.json"; + +/// Internal to this repository's tests, not part of the API: a schema file +/// `graphql!` uses, relative to the `Cargo.toml` of the crate being +/// compiled, or absolute, as it is. This repository's `.cargo/config.toml` +/// sets it, for the projects `trybuild` compiles, which have no schema file. +/// It applies only to the packages [`TEST_SCHEMA_PACKAGES`] names, wherever +/// they are: any other package, a dependency or a user's crate, ignores it. +pub const TEST_SCHEMA_ENV: &str = "SHOPIFY_API_INTERNAL_TEST_SCHEMA"; + +/// The packages [`TEST_SCHEMA_ENV`] applies to, by `CARGO_PKG_NAME`: +/// `shopify_api` (its tests and doctests) and `shopify_api-tests`, the name +/// `trybuild` gives the projects of its compile-fail tests. +pub const TEST_SCHEMA_PACKAGES: [&str; 2] = ["shopify_api", "shopify_api-tests"]; + +/// Whether [`TEST_SCHEMA_ENV`] applies to the package named `package`. +pub fn test_schema_applies(package: Option<&str>) -> bool { + package.is_some_and(|package| TEST_SCHEMA_PACKAGES.contains(&package)) +} + +/// The `[package.metadata]` table `shopify_api` reads. +pub const METADATA_TABLE: &str = "shopify_api"; + +/// The key of the API version in [`METADATA_TABLE`]. +pub const API_VERSION_KEY: &str = "api-version"; + +/// The key of the schema file in [`METADATA_TABLE`], relative to the +/// package's `Cargo.toml` and inside the package ([`inside_package`]); +/// [`PROJECT_SCHEMA_PATH`] without it. +pub const SCHEMA_KEY: &str = "schema"; + +/// The lines to add to a `Cargo.toml` to select `version`. +pub fn metadata_snippet(version: &str) -> String { + format!("[package.metadata.{METADATA_TABLE}]\n{API_VERSION_KEY} = \"{version}\"") +} + +/// The lines to add to a `Cargo.toml` to select `version` and the schema +/// file at `path`, relative to it: `path` is written with `/` separators, as +/// a TOML string, so that any file name reads back as it is. +pub fn schema_snippet(version: &str, path: &Path) -> String { + let path = path + .components() + .map(|component| component.as_os_str().to_string_lossy()) + .collect::>() + .join("/"); + format!( + "{}\n{SCHEMA_KEY} = {}", + metadata_snippet(version), + toml::Value::from(path) + ) +} + +/// The newest stable Admin API version at `now`: Shopify releases one on the +/// first day of each quarter, named after it (`2026-10` on October 1st). +pub fn latest_api_version(now: SystemTime) -> String { + let seconds = now + .duration_since(SystemTime::UNIX_EPOCH) + .map_or(0, |since| since.as_secs()); + let (year, month) = year_and_month(seconds / 86_400); + format!("{year}-{:02}", (month - 1) / 3 * 3 + 1) +} + +/// The quarterly release before `version`: `2026-01` before `2026-04`. +pub fn previous_api_version(version: &str) -> Option { + let (year, month) = version.split_once('-')?; + let (year, month): (u32, u32) = (year.parse().ok()?, month.parse().ok()?); + let previous = match month { + 1 => format!("{}-10", year.checked_sub(1)?), + 4 | 7 | 10 => format!("{year}-{:02}", month - 3), + _ => return None, + }; + Some(previous) +} + +/// The year and month (1 to 12) of a day counted from 1970-01-01, in UTC. +fn year_and_month(days: u64) -> (u64, u64) { + // Howard Hinnant's `civil_from_days`, for days after the epoch. + let z = days + 719_468; + let era = z / 146_097; + let day_of_era = z - era * 146_097; + let year_of_era = + (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let shifted_month = (5 * day_of_year + 2) / 153; + let month = if shifted_month < 10 { + shifted_month + 3 + } else { + shifted_month - 9 + }; + let year = year_of_era + era * 400 + u64::from(month <= 2); + (year, month) +} + +/// What the `[package.metadata.shopify_api]` of a `Cargo.toml` declares. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct PackageConfig { + /// [`API_VERSION_KEY`]. + pub api_version: Option, + /// [`SCHEMA_KEY`], relative to the `Cargo.toml`, normalized by + /// [`inside_package`]. + pub schema: Option, +} + +impl PackageConfig { + /// The schema file of the package in `dir`: [`SCHEMA_KEY`], else + /// [`PROJECT_SCHEMA_PATH`]. + pub fn schema_path(&self, dir: &Path) -> PathBuf { + dir.join( + self.schema + .as_deref() + .unwrap_or(Path::new(PROJECT_SCHEMA_PATH)), + ) + } +} + +/// What the `Cargo.toml` in `manifest_dir` declares; nothing when there is none. +pub fn package_config(manifest_dir: &Path) -> Result { + let manifest = manifest_dir.join("Cargo.toml"); + let text = match std::fs::read_to_string(&manifest) { + Ok(text) => text, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + return Ok(PackageConfig::default()); + } + Err(error) => return Err(format!("cannot read `{}`: {error}", manifest.display())), + }; + config_in(&text).map_err(|error| format!("`{}`: {error}", manifest.display())) +} + +/// The Admin API version the `Cargo.toml` in `manifest_dir` declares, if any. +pub fn configured_api_version(manifest_dir: &Path) -> Result, String> { + package_config(manifest_dir).map(|config| config.api_version) +} + +/// What a `Cargo.toml` declares. +fn config_in(manifest: &str) -> Result { + let table: toml::Table = manifest.parse().map_err(|error| format!("{error}"))?; + let ours = table + .get("package") + .and_then(|package| package.get("metadata")) + .and_then(|metadata| metadata.get(METADATA_TABLE)); + let Some(ours) = ours else { + return Ok(PackageConfig::default()); + }; + Ok(PackageConfig { + api_version: api_version_in(ours.get(API_VERSION_KEY))?, + schema: schema_in(ours.get(SCHEMA_KEY))?, + }) +} + +/// The schema file [`SCHEMA_KEY`] names, if any. +fn schema_in(value: Option<&toml::Value>) -> Result, String> { + let Some(value) = value else { + return Ok(None); + }; + match value.as_str() { + Some(path) if !path.is_empty() => inside_package(path).map(Some), + _ => Err(format!( + "`{SCHEMA_KEY}` in [package.metadata.{METADATA_TABLE}] must be the path of a schema file, \ + relative to Cargo.toml, such as \"graphql/admin.schema.json\"" + )), + } +} + +/// What [`inside_package`] accepts, for the messages that refuse a path. +pub const PORTABLE_PATH: &str = "a relative path with `/` separators and portable names: \ + no `:`, `\\`, `<`, `>`, `\"`, `|`, `?`, `*` or control character, no name ending in `.` or a space, \ + and no device name such as `CON` or `NUL`"; + +/// A name that means the same file on every system. Windows reads `:` and +/// `\` as a drive and a separator, drops a final `.` or space (`x.json.` +/// opens `x.json`), refuses `<>"|?*` and control characters, and opens a +/// device for `CON`, `NUL`, `COM1`, `CONIN$`… whatever the extension. +fn portable_name(name: &str) -> bool { + if name.ends_with(['.', ' ']) + || name + .chars() + .any(|c| c.is_control() || r#":\<>"|?*"#.contains(c)) + { + return false; + } + let stem = name.split('.').next().unwrap_or(name).trim_end_matches(' '); + let stem = stem.to_ascii_uppercase(); + let numbered = |prefix: &str| { + stem.strip_prefix(prefix).is_some_and(|number| { + matches!(number, "¹" | "²" | "³") + || (number.len() == 1 && number.bytes().all(|byte| byte.is_ascii_digit())) + }) + }; + !(["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"].contains(&stem.as_str()) + || numbered("COM") + || numbered("LPT")) +} + +/// `path`, relative to a package's `Cargo.toml`, normalized, when it names a +/// file inside the package: `cargo package` ships only the package's files, +/// so a packaged crate would look for any other file at another place, and +/// fail, or find another schema there. +/// +/// `path` is portable, since a published crate may be built on any system: +/// it is read with `/` separators, and each name must mean the same file +/// everywhere ([`PORTABLE_PATH`]). +/// +/// The check is lexical: `.`, empty segments and `a/..` are removed, and the +/// path must not be absolute, nor climb above the package. A symbolic link +/// inside the package that points outside it is accepted, on purpose: +/// `cargo package` ships the content of a linked file. The path is returned +/// normalized, so that the file opened is the one checked, even when `a` in +/// `a/..` is a link to a directory; on every system, it holds only the +/// names checked, as plain components: no drive, root, `.` nor `..`. +pub fn inside_package(path: &str) -> Result { + use std::path::Component; + let refused = || { + format!( + "`{SCHEMA_KEY} = {}` in [package.metadata.{METADATA_TABLE}] must name a file inside the package, \ + as {PORTABLE_PATH}, such as \"graphql/admin.schema.json\": \ + `cargo package` ships only the package's files, and a published crate may be built on any system", + toml::Value::from(path) + ) + }; + if path.starts_with('/') { + return Err(refused()); + } + let mut names = Vec::new(); + for segment in path.split('/') { + match segment { + "" | "." => {} + ".." => { + if names.pop().is_none() { + return Err(refused()); + } + } + // Checked even when a later `..` removes it. + name if !portable_name(name) => return Err(refused()), + name => names.push(name), + } + } + if names.is_empty() { + return Err(refused()); + } + let normal: PathBuf = names.iter().collect(); + // What this system makes of the names: each one a plain component. + let plain = normal + .components() + .eq(names.iter().map(|name| Component::Normal(OsStr::new(name)))); + if !plain { + return Err(refused()); + } + Ok(normal) +} + +/// The API version [`API_VERSION_KEY`] declares, if any. +fn api_version_in(value: Option<&toml::Value>) -> Result, String> { + let Some(value) = value else { + return Ok(None); + }; + let Some(version) = value.as_str() else { + return Err(format!( + "`{API_VERSION_KEY}` in [package.metadata.{METADATA_TABLE}] must be a string, such as \"2026-10\"" + )); + }; + if !is_supported_api_version(version) { + return Err(format!( + "`{API_VERSION_KEY} = \"{version}\"` in [package.metadata.{METADATA_TABLE}] is not a version shopify_api calls: \ + a quarterly release from {MINIMUM_API_VERSION} on, such as \"2026-10\", or \"unstable\"" + )); + } + Ok(Some(version.to_string())) +} + +/// Where the schema of a crate comes from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SchemaSource { + /// A schema file, used as it is: the one [`TEST_SCHEMA_ENV`] names. + File(PathBuf), + /// The schema file of the crate, and the version its `Cargo.toml` + /// declares: see [`schema_plan`]. + Project { + /// The directory of the crate's `Cargo.toml`. + dir: PathBuf, + /// [`PackageConfig::schema_path`]. + path: PathBuf, + /// The version its `Cargo.toml` declares. + pinned: Option, + }, +} + +/// The schema `graphql!` uses for the crate in `manifest_dir`: +/// +/// 1. the file `test_schema` names, the value of [`TEST_SCHEMA_ENV`] +/// (internal to this repository's tests), for a `package` it applies to +/// ([`test_schema_applies`]); any other package ignores it; +/// 2. else the one [`SCHEMA_KEY`] names, else [`PROJECT_SCHEMA_PATH`], with +/// the version `Cargo.toml` declares. +pub fn schema_source( + manifest_dir: Option<&Path>, + test_schema: Option<&OsStr>, + package: Option<&str>, +) -> Result { + let test_schema = test_schema.filter(|value| !value.is_empty() && test_schema_applies(package)); + if let Some(named) = test_schema { + let path = match manifest_dir { + Some(dir) => dir.join(named), + None => PathBuf::from(named), + }; + if !path.is_file() { + return Err(format!( + "{TEST_SCHEMA_ENV} names `{}`, which is not a file", + path.display() + )); + } + return Ok(SchemaSource::File(path)); + } + let dir = manifest_dir + .ok_or("no Cargo.toml of a package: the schema of a crate is kept next to it")?; + let config = package_config(dir)?; + Ok(SchemaSource::Project { + path: config.schema_path(dir), + pinned: config.api_version, + dir: dir.to_path_buf(), + }) +} + +/// Whether the package in `dir` is local: the user's own source, in a +/// workspace or a path dependency outside it, rather than a packaged, +/// vendored or checked-out copy of a dependency. It only gates downloads, +/// see [`may_download`]. +/// +/// A package is not local when: +/// - its directory holds a `Cargo.toml.orig`, which cargo writes into every +/// packaged crate (registry sources, and the copy `cargo package` +/// verifies), or a `.cargo-checksum.json` (vendored); +/// - its directory or one of its ancestors holds a `.cargo-ok`, which cargo +/// writes at the root of every extracted registry source and of every git +/// checkout, where a git dependency may be a subdirectory; +/// - it is under `cargo_home`, where cargo keeps registry sources and git +/// checkouts. +/// +/// Paths are compared both as given and with symbolic links resolved, so a +/// `$CARGO_HOME`, or a `git` or `registry` directory in it, that links to +/// another disk still counts. +/// +/// These are heuristics: an unrelated `.cargo-ok` above a workspace, for +/// one, makes it look not local. That is acceptable because the answer +/// never chooses a schema: it only lets a missing or outdated file be +/// downloaded, or turns that into a compile error that names the file and +/// the command to run. A mistake makes a build fail loudly, never compile +/// against another schema. +pub fn is_local_package(dir: &Path, cargo_home: Option<&Path>) -> bool { + if dir.join("Cargo.toml.orig").exists() || dir.join(".cargo-checksum.json").exists() { + return false; + } + let dirs = both_forms(dir); + let in_cargo_checkout = dirs + .iter() + .any(|dir| dir.ancestors().any(|dir| dir.join(".cargo-ok").exists())); + if in_cargo_checkout { + return false; + } + let Some(home) = cargo_home else { + return true; + }; + let homes = both_forms(home); + !dirs + .iter() + .any(|dir| homes.iter().any(|home| dir.starts_with(home))) +} + +/// `path` made absolute, and also with symbolic links resolved when it +/// exists. +fn both_forms(path: &Path) -> Vec { + let logical = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()); + let mut forms = vec![logical]; + if let Ok(canonical) = forms[0].canonicalize() + && canonical != forms[0] + { + forms.push(canonical); + } + forms +} + +/// The directory where cargo keeps registry sources and git checkouts: +/// `$CARGO_HOME`, else `.cargo` in the home directory. +pub fn cargo_home() -> Option { + let non_empty = |name: &str| std::env::var_os(name).filter(|value| !value.is_empty()); + if let Some(home) = non_empty("CARGO_HOME") { + return Some(PathBuf::from(home)); + } + non_empty("HOME") + .or_else(|| non_empty("USERPROFILE")) + .map(|home| PathBuf::from(home).join(".cargo")) +} + +/// Whether `graphql!` may download the schema file of the package in `dir`, +/// one cargo was asked to build when `primary` (`CARGO_PRIMARY_PACKAGE`): +/// only a local one ([`is_local_package`]). +/// +/// Neither input is tracked by cargo, and neither needs to be: they decide +/// whether a missing or outdated file is downloaded or a compile error, +/// never which file is read. A compiled crate read the same file whatever +/// they were. +pub fn may_download(dir: &Path, cargo_home: Option<&Path>, primary: bool) -> bool { + primary && is_local_package(dir, cargo_home) +} + +/// What a crate's schema file holds. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SchemaFile { + Missing, + /// A schema of `version` this version of the crate reads. + Usable { + version: String, + }, + /// A file it cannot read: another format, or broken. `reason` names the + /// file; `version` is the one it holds, when it says. + Unusable { + version: Option, + reason: String, + }, +} + +/// What to do with a crate's schema file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SchemaPlan { + /// Read it as it is. + Read, + /// Download `version` into it, then read it. + Download { + version: String, + /// No version is pinned and there is no file: `version` is the + /// latest one, which may not be out yet on the first day of a quarter. + latest: bool, + }, + /// Fail the build with this message. + Refuse(String), +} + +/// What to do with `file`, the schema file at `path` of the crate in `dir`, +/// when its `Cargo.toml` pins `pinned`. +/// +/// The version of a crate is the one it pins, else the one of its file: a +/// file is never replaced by a newer version on its own, so that a build +/// gives the same result whatever the date. Without either, the crate takes +/// the latest version at `now`. +/// +/// Only a package that [`may_download`] downloads: a local one cargo was +/// asked to build. Any other uses the file it ships, and +/// refuses to build when it has none or when it is not the version its +/// `Cargo.toml` pins: its author tested its operations against that file, +/// and a registry, vendored or packaged copy is not to be written. +pub fn schema_plan( + dir: &Path, + path: &Path, + file: &SchemaFile, + pinned: Option<&str>, + may_download: bool, + now: SystemTime, +) -> SchemaPlan { + let fix = || { + format!( + "Run `shopify-api schema download` in `{}` (`cargo install shopify_api --features cli`), \ + and commit the file. A crate downloads its schema only as a local package cargo was asked to build: \ + as a dependency, packaged, vendored, under $CARGO_HOME or below a `.cargo-ok`, it uses the one it ships.", + dir.display() + ) + }; + match (file, pinned) { + (SchemaFile::Usable { .. }, None) => SchemaPlan::Read, + (SchemaFile::Usable { version }, Some(pinned)) if version == pinned => SchemaPlan::Read, + (SchemaFile::Usable { version }, Some(pinned)) if !may_download => { + SchemaPlan::Refuse(format!( + "`{}` holds the Admin API {version}, but `{}` declares {pinned}. {}", + path.display(), + dir.join("Cargo.toml").display(), + fix() + )) + } + (SchemaFile::Missing, _) if !may_download => SchemaPlan::Refuse(format!( + "`{}` is missing: `graphql!` needs the schema of the crate's API version there. {}", + path.display(), + fix() + )), + (SchemaFile::Unusable { reason, .. }, _) if !may_download => { + SchemaPlan::Refuse(format!("{reason}. {}", fix())) + } + (_, Some(pinned)) => SchemaPlan::Download { + version: pinned.to_string(), + latest: false, + }, + ( + SchemaFile::Unusable { + version: Some(version), + .. + }, + None, + ) => SchemaPlan::Download { + version: version.clone(), + latest: false, + }, + (_, None) => SchemaPlan::Download { + version: latest_api_version(now), + latest: true, + }, + } +} + +/// Shopify's public copy of the Admin schema: a GraphQL endpoint per version +/// that answers introspection without a token. +pub const PUBLIC_ADMIN_SCHEMA_ENDPOINT: &str = "https://shopify.dev/admin-graphql-direct-proxy"; + +/// Why the schema of a version could not be had. +#[cfg(feature = "download")] +#[cfg_attr(docsrs, doc(cfg(feature = "download")))] +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DownloadError { + /// Shopify has no Admin API of this version: it is not out yet, or its + /// name is wrong. Downloading it again will not help. + UnknownVersion { + /// The version asked for. + version: String, + /// What Shopify answered. + answer: String, + }, + /// Anything else: no network, an answer that is not a schema, a file + /// that cannot be written or read. + Failed(String), +} + +#[cfg(feature = "download")] +impl std::fmt::Display for DownloadError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::UnknownVersion { version, answer } => { + write!(f, "Shopify has no Admin API version {version} ({answer})") + } + Self::Failed(message) => f.write_str(message), + } + } +} + +#[cfg(feature = "download")] +impl std::error::Error for DownloadError {} + +/// The introspection result in Shopify's answer to `url`, or why there is none. +#[cfg(feature = "download")] +fn introspection_in( + version: &str, + url: &str, + status: u16, + text: &str, +) -> Result { + let failed = |error: &dyn std::fmt::Display| { + DownloadError::Failed(format!( + "cannot download the Admin schema {version} from {url}: {error}" + )) + }; + let value: Option = serde_json::from_str(text).ok(); + let message = value + .as_ref() + .and_then(|value| value.get("error")) + .and_then(serde_json::Value::as_str); + if let Some(message) = message { + // Shopify answers a version it does not have with a 400 that says so. + if status == 400 && message.to_ascii_lowercase().contains("api version") { + return Err(DownloadError::UnknownVersion { + version: version.to_string(), + answer: format!("{url} answered \"{message}\", HTTP 400"), + }); + } + return Err(failed(&format!("{message} (HTTP {status})"))); + } + if !(200..300).contains(&status) { + return Err(failed(&format!("HTTP {status}"))); + } + value.ok_or_else(|| failed(&"the answer is not JSON")) +} + +/// Downloads the Admin schema of `version` from Shopify's public endpoint. +#[cfg(feature = "download")] +#[cfg_attr(docsrs, doc(cfg(feature = "download")))] +pub fn download_public_schema(version: &str) -> Result { + use std::time::Duration; + + let url = format!("{PUBLIC_ADMIN_SCHEMA_ENDPOINT}/{version}"); + let failed = |error: &dyn std::fmt::Display| { + DownloadError::Failed(format!( + "cannot download the Admin schema {version} from {url}: {error}" + )) + }; + let agent: ureq::Agent = ureq::Agent::config_builder() + .timeout_resolve(Some(Duration::from_secs(10))) + .timeout_connect(Some(Duration::from_secs(10))) + .timeout_global(Some(Duration::from_secs(120))) + .http_status_as_error(false) + .build() + .into(); + let body = serde_json::json!({ "query": crate::INTROSPECTION_QUERY }).to_string(); + let mut response = agent + .post(&url) + .header("Accept", "application/json") + .header("Content-Type", "application/json") + .header( + "User-Agent", + concat!("shopify_api_graphql/", env!("CARGO_PKG_VERSION")), + ) + .send(body) + .map_err(|error| failed(&error))?; + let text = response + .body_mut() + .with_config() + .limit(256 * 1024 * 1024) + .read_to_string() + .map_err(|error| failed(&error))?; + let value = introspection_in(version, &url, response.status().as_u16(), &text)?; + crate::Schema::from_introspection(&value, version).map_err(|error| failed(&error)) +} + +/// Downloads the Admin schema of `version` into `path`, and returns it. +/// +/// The file is replaced in one step: a build that reads it meanwhile sees +/// the old schema or the new one, never part of one. +#[cfg(feature = "download")] +#[cfg_attr(docsrs, doc(cfg(feature = "download")))] +pub fn download_schema_file(path: &Path, version: &str) -> Result { + let schema = download_public_schema(version)?; + write_atomically(path, &schema.to_json()).map_err(DownloadError::Failed)?; + Ok(schema) +} + +/// Writes `contents` to `path` through a temporary file in the same directory. +pub fn write_atomically(path: &Path, contents: &str) -> Result<(), String> { + if let Some(parent) = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + { + std::fs::create_dir_all(parent) + .map_err(|error| format!("cannot create `{}`: {error}", parent.display()))?; + } + let mut temporary = path.as_os_str().to_owned(); + temporary.push(format!(".{}.tmp", std::process::id())); + let temporary = PathBuf::from(temporary); + std::fs::write(&temporary, contents) + .and_then(|()| std::fs::rename(&temporary, path)) + .map_err(|error| { + let _ = std::fs::remove_file(&temporary); + format!("cannot write `{}`: {error}", path.display()) + }) +} + +/// The schema of the crate in `dir`, read from `path` with `read`, after +/// downloading it when [`schema_plan`] says so, with `may_download` from +/// [`may_download()`]. `on_download` +/// is called with the file and the version before each download, to show +/// progress. +/// +/// A download is tried once per file and version in a process: when it +/// fails, the next operations of the build fail at once with the same error. +#[cfg(feature = "download")] +#[cfg_attr(docsrs, doc(cfg(feature = "download")))] +pub fn project_schema>( + dir: &Path, + path: &Path, + pinned: Option<&str>, + may_download: bool, + now: SystemTime, + read: impl Fn(&Path) -> Result, + on_download: impl Fn(&Path, &str), +) -> Result { + obtain_schema( + dir, + path, + pinned, + may_download, + now, + read, + |path, version| { + on_download(path, version); + download_schema_file(path, version).map(drop) + }, + ) +} + +/// [`project_schema`], downloading with `download`. +#[cfg(feature = "download")] +fn obtain_schema>( + dir: &Path, + path: &Path, + pinned: Option<&str>, + may_download: bool, + now: SystemTime, + read: impl Fn(&Path) -> Result, + download: impl Fn(&Path, &str) -> Result<(), DownloadError>, +) -> Result { + let (file, current) = if path.is_file() { + match read(path) { + Ok(schema) => { + let version = schema.as_ref().api_version.clone(); + (SchemaFile::Usable { version }, Some(schema)) + } + Err(reason) => { + let version = stored_api_version(path); + (SchemaFile::Unusable { version, reason }, None) + } + } + } else { + (SchemaFile::Missing, None) + }; + match schema_plan(dir, path, &file, pinned, may_download, now) { + SchemaPlan::Read => current.map_or_else(|| read(path), Ok), + SchemaPlan::Refuse(message) => Err(message), + SchemaPlan::Download { version, latest } => { + download_once(path, &version, latest, download).map_err(|error| { + let which = match (pinned, &file) { + (Some(_), _) => format!("{version}, the version Cargo.toml pins"), + (None, SchemaFile::Missing) => format!( + "the latest Admin API version, {version}: Cargo.toml pins none, and there is no schema file yet" + ), + (None, _) => format!( + "{version}, the version of the schema file, again: this version of shopify_api cannot read it" + ), + }; + download_failure(&error, path, &which, &version, now) + })?; + read(path) + } + } +} + +/// The `apiVersion` a schema file names, whatever its format. +#[cfg(feature = "download")] +fn stored_api_version(path: &Path) -> Option { + #[derive(serde::Deserialize)] + struct Header { + #[serde(rename = "apiVersion")] + api_version: String, + } + let json = std::fs::read_to_string(path).ok()?; + let header: Header = serde_json::from_str(&json).ok()?; + Some(header.api_version) +} + +/// Downloads `version` into `path` with `download`, once in the process: the +/// outcome of the first attempt is the outcome of the next ones. +/// +/// For the `latest` version, an [`DownloadError::UnknownVersion`] tries the +/// version before: a new version may not be out on its first day. +#[cfg(feature = "download")] +fn download_once( + path: &Path, + version: &str, + latest: bool, + download: impl Fn(&Path, &str) -> Result<(), DownloadError>, +) -> Result<(), DownloadError> { + type Attempts = std::collections::BTreeMap<(PathBuf, String), Result<(), DownloadError>>; + static ATTEMPTS: std::sync::Mutex = std::sync::Mutex::new(Attempts::new()); + // Held during the download: the other operations of the build wait for it. + let mut attempts = ATTEMPTS + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let key = (path.to_path_buf(), version.to_string()); + if let Some(outcome) = attempts.get(&key) { + return outcome.clone(); + } + let outcome = match download(path, version) { + Err(error @ DownloadError::UnknownVersion { .. }) if latest => { + match previous_api_version(version) { + Some(previous) => download(path, &previous), + None => Err(error), + } + } + outcome => outcome, + }; + attempts.insert(key, outcome.clone()); + outcome +} + +/// What to tell when the schema of `version`, described by `which`, cannot +/// be downloaded into `path` at `now`. +#[cfg(feature = "download")] +fn download_failure( + error: &DownloadError, + path: &Path, + which: &str, + version: &str, + now: SystemTime, +) -> String { + match error { + DownloadError::UnknownVersion { .. } => { + // On the first day of a quarter, its version may not be out yet. + let released = latest_api_version(now); + let suggested = match previous_api_version(version) { + Some(previous) if released.as_str() >= version => previous, + _ => released, + }; + format!( + "{error}: it is not out yet, or its name is wrong. \ + Declare a released version in Cargo.toml:\n\n{}", + metadata_snippet(&suggested) + ) + } + DownloadError::Failed(_) => format!( + "{error}\n`graphql!` needs the schema of {which}, in `{}`. \ + It does not use another version instead: operations go to the version they were checked against. \ + Build once with network access, or run `shopify-api schema download` in the crate's directory, \ + and commit the file.", + path.display() + ), + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + /// An empty directory removed when the test ends. + struct Project(PathBuf); + + impl Project { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir() + .join(format!("shopify-api-graphql-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + + fn write(&self, path: &str, content: &str) -> PathBuf { + let file = self.0.join(path); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, content).unwrap(); + file + } + + fn manifest(&self, version: Option<&str>) { + let mut manifest = "[package]\nname = \"app\"\n".to_string(); + if let Some(version) = version { + manifest.push_str(&format!("\n{}\n", metadata_snippet(version))); + } + self.write("Cargo.toml", &manifest); + } + } + + impl Drop for Project { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn leap(year: u64) -> bool { + (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400) + } + + /// Midnight UTC of a day. + fn day(year: u64, month: u64, day: u64) -> SystemTime { + let mut days = 0; + for y in 1970..year { + days += if leap(y) { 366 } else { 365 }; + } + let leap = leap(year); + let lengths = [ + 31, + if leap { 29 } else { 28 }, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31, + ]; + days += lengths[..(month - 1) as usize].iter().sum::() + day - 1; + SystemTime::UNIX_EPOCH + Duration::from_secs(days * 86_400) + } + + #[test] + fn the_latest_version_is_the_one_of_the_quarter() { + assert_eq!(latest_api_version(day(2026, 10, 1)), "2026-10"); + assert_eq!(latest_api_version(day(2026, 10, 22)), "2026-10"); + assert_eq!(latest_api_version(day(2026, 12, 31)), "2026-10"); + assert_eq!(latest_api_version(day(2027, 1, 1)), "2027-01"); + assert_eq!(latest_api_version(day(2027, 3, 31)), "2027-01"); + assert_eq!(latest_api_version(day(2028, 2, 29)), "2028-01"); + assert_eq!(latest_api_version(day(2028, 4, 1)), "2028-04"); + assert_eq!(latest_api_version(day(2030, 9, 30)), "2030-07"); + } + + #[test] + fn the_previous_version_is_the_quarter_before() { + assert_eq!(previous_api_version("2027-01").as_deref(), Some("2026-10")); + assert_eq!(previous_api_version("2026-10").as_deref(), Some("2026-07")); + assert_eq!(previous_api_version("2026-04").as_deref(), Some("2026-01")); + assert_eq!(previous_api_version("unstable"), None); + assert_eq!(previous_api_version("2026-05"), None); + } + + fn version_in(manifest: &str) -> Result, String> { + config_in(manifest).map(|config| config.api_version) + } + + #[test] + fn the_version_is_read_from_the_package_metadata() { + assert_eq!(version_in("[package]\nname = \"app\""), Ok(None)); + assert_eq!( + version_in("[package.metadata.shopify_api]\napi-version = \"2026-07\""), + Ok(Some("2026-07".to_string())) + ); + assert_eq!( + version_in("[package.metadata.shopify_api]\napi-version = \"unstable\""), + Ok(Some("unstable".to_string())) + ); + let old = + version_in("[package.metadata.shopify_api]\napi-version = \"2025-01\"").unwrap_err(); + assert!(old.contains("is not a version shopify_api calls"), "{old}"); + let number = version_in("[package.metadata.shopify_api]\napi-version = 2026").unwrap_err(); + assert!(number.contains("must be a string"), "{number}"); + assert!(version_in("[package").is_err()); + } + + #[test] + fn the_schema_file_is_read_from_the_package_metadata() { + let schema = |manifest: &str| config_in(manifest).map(|config| config.schema); + assert_eq!(schema("[package]\nname = \"app\""), Ok(None)); + assert_eq!( + schema("[package.metadata.shopify_api]\nschema = \"schemas/admin.json\""), + Ok(Some(PathBuf::from("schemas/admin.json"))) + ); + for wrong in ["schema = 1", "schema = \"\""] { + let error = schema(&format!("[package.metadata.shopify_api]\n{wrong}")).unwrap_err(); + assert!( + error.contains("must be the path of a schema file"), + "{error}" + ); + } + } + + #[test] + fn the_schema_snippet_reads_back_as_the_path() { + // Names `schema` accepts that TOML must still quote. `\\`, `"` and + // control characters are not portable names: `shopify-api` prints a + // note instead of a snippet for them. + for name in [ + "schemas/it's.json", + "schemas/a#b=c.json", + "schemas/[x] y.json", + "schémas/é.json", + "admin.json", + ] { + let snippet = schema_snippet("2026-07", Path::new(name)); + let config = config_in(&format!("[package]\nname = \"app\"\n\n{snippet}\n")); + assert_eq!( + config, + Ok(PackageConfig { + api_version: Some("2026-07".to_string()), + schema: Some(PathBuf::from(name)), + }), + "{snippet}" + ); + } + let nested: PathBuf = ["schemas", "admin.json"].iter().collect(); + assert!(schema_snippet("2026-07", &nested).ends_with("schema = \"schemas/admin.json\"")); + } + + #[test] + fn the_schema_file_must_be_inside_the_package() { + let schema = |path: &str| { + config_in(&format!( + "[package.metadata.shopify_api]\nschema = {}", + toml::Value::from(path) + )) + .map(|config| config.schema) + }; + let absolute = std::env::temp_dir().join("admin.schema.json"); + for outside in [ + absolute.to_str().unwrap(), + "/admin.schema.json", + "../x.json", + "a/../../x.json", + "./..", + ".", + "a/..", + ] { + let error = schema(outside).unwrap_err(); + assert!( + error.contains("must name a file inside the package"), + "{error}" + ); + assert!(error.contains(PORTABLE_PATH), "{error}"); + assert!(error.contains("`cargo package` ships"), "{error}"); + } + // Not portable, so refused on every system: a drive on Windows, even + // in the middle of the path, and a separator there. + for outside in [ + "./D:/schema.json", + "schemas/D:/schema.json", + "a/../D:/schema.json", + "./D:../schema.json", + "C:x.json", + "a\\b.json", + "schemas\\admin.json", + "a:b/x.json", + ] { + let error = schema(outside).unwrap_err(); + assert!(error.contains(PORTABLE_PATH), "{outside}: {error}"); + } + // Names Windows reads as another file, or as a device: refused on + // every system too, even when a later `..` removes them. + for alias in [ + "schema.json.", + "schema.json ", + "schemas./admin.json", + "schemas /admin.json", + "x.json./../y.json", + "xy.json", + "x\"y.json", + "x|y.json", + "x?.json", + "x*.json", + "x\ty.json", + "x\u{7f}y.json", + "CON", + "con.json", + "Nul.schema.json", + "AUX .json", + "schemas/PRN/x.json", + "COM1.json", + "lpt9", + "COM\u{b9}.json", + "CON/../x.json", + "conin$.json", + "CONOUT$", + "ConOut$ .json", + "CONIN$/../x.json", + ] { + let error = schema(alias).unwrap_err(); + assert!(error.contains(PORTABLE_PATH), "{alias:?}: {error}"); + } + #[cfg(windows)] + for outside in [ + "C:\\x.json", + "C:x.json", + "\\\\server\\share\\x.json", + "\\x.json", + ] { + assert!(schema(outside).is_err(), "{outside}"); + } + for (inside, normal) in [ + ("a/../x.json", "x.json"), + ("./graphql/x.json", "graphql/x.json"), + ("schemas/../schemas/admin.json", "schemas/admin.json"), + ("schemas//admin.json", "schemas/admin.json"), + ("schemas/admin.json/", "schemas/admin.json"), + ("console.json", "console.json"), + ("con-schema.json", "con-schema.json"), + ("COM10.json", "COM10.json"), + (".hidden/admin.json", ".hidden/admin.json"), + ("admin.schema.json", "admin.schema.json"), + ] { + assert_eq!(schema(inside), Ok(Some(PathBuf::from(normal))), "{inside}"); + } + } + + #[cfg(unix)] + #[test] + fn a_link_inside_the_package_may_point_outside_it() { + let project = Project::new("link"); + let outside = Project::new("link-target"); + let target = outside.write("admin.schema.json", "{}"); + std::fs::create_dir_all(project.0.join("schemas")).unwrap(); + std::os::unix::fs::symlink(&target, project.0.join("schemas/admin.json")).unwrap(); + project.write( + "Cargo.toml", + "[package]\nname = \"app\"\n\n[package.metadata.shopify_api]\nschema = \"schemas/admin.json\"\n", + ); + assert_eq!( + schema_source(Some(&project.0), None, None), + Ok(SchemaSource::Project { + dir: project.0.clone(), + path: project.0.join("schemas/admin.json"), + pinned: None, + }) + ); + } + + #[test] + fn the_source_is_the_crate_file_with_its_pinned_version() { + let project = Project::new("source"); + project.manifest(None); + let unpinned = SchemaSource::Project { + dir: project.0.clone(), + path: project.0.join(PROJECT_SCHEMA_PATH), + pinned: None, + }; + assert_eq!(schema_source(Some(&project.0), None, None), Ok(unpinned)); + assert!(schema_source(None, None, None).is_err()); + + project.manifest(Some("2026-07")); + assert_eq!( + schema_source(Some(&project.0), None, None), + Ok(SchemaSource::Project { + dir: project.0.clone(), + path: project.0.join(PROJECT_SCHEMA_PATH), + pinned: Some("2026-07".to_string()), + }) + ); + } + + #[test] + fn the_manifest_names_another_file_relative_to_it() { + let project = Project::new("key"); + project.write( + "Cargo.toml", + "[package]\nname = \"app\"\n\n[package.metadata.shopify_api]\n\ + api-version = \"2026-07\"\nschema = \"schemas/admin-2026-07.json\"\n", + ); + // The file need not exist: missing, it is downloaded or refused as + // the default one is. + let expected = SchemaSource::Project { + dir: project.0.clone(), + path: project.0.join("schemas/admin-2026-07.json"), + pinned: Some("2026-07".to_string()), + }; + assert_eq!( + schema_source(Some(&project.0), None, None), + Ok(expected.clone()) + ); + // An empty test variable is no variable. + assert_eq!( + schema_source(Some(&project.0), Some(OsStr::new("")), Some("shopify_api")), + Ok(expected) + ); + } + + /// The published macro honours the internal variable only for this + /// repository's own packages: a user's crate, or a dependency, keeps its + /// own schema whatever the environment holds. + #[test] + fn the_test_variable_applies_only_to_this_repository() { + let project = Project::new("foreign"); + project.manifest(Some("2026-07")); + project.write("schemas/unstable.json", "{}"); + for package in [ + None, + Some("my_app"), + Some("shopify_api_graphql"), + Some("shopify_api-tests-extra"), + Some("shopify_api_extra"), + Some("openshop"), + ] { + assert!(!test_schema_applies(package), "{package:?}"); + for named in ["schemas/unstable.json", "missing.json"] { + assert!( + matches!( + schema_source(Some(&project.0), Some(OsStr::new(named)), package), + Ok(SchemaSource::Project { .. }) + ), + "{package:?} {named}" + ); + } + } + assert!(test_schema_applies(Some("shopify_api"))); + assert!(test_schema_applies(Some("shopify_api-tests"))); + } + + #[test] + fn the_test_variable_names_a_file_for_the_packages_of_this_repository() { + let project = Project::new("named"); + project.manifest(Some("2026-07")); + let other = project.write("schemas/unstable.json", "{}"); + assert_eq!( + schema_source( + Some(&project.0), + Some(OsStr::new("schemas/unstable.json")), + Some("shopify_api") + ), + Ok(SchemaSource::File(other.clone())) + ); + assert_eq!( + schema_source(None, Some(other.as_os_str()), Some("shopify_api-tests")), + Ok(SchemaSource::File(other)) + ); + assert!(matches!( + schema_source(Some(&project.0), Some(OsStr::new("")), Some("shopify_api")), + Ok(SchemaSource::Project { .. }) + )); + assert_eq!( + schema_source( + Some(&project.0), + Some(OsStr::new("missing.json")), + Some("shopify_api") + ), + Err(format!( + "SHOPIFY_API_INTERNAL_TEST_SCHEMA names `{}`, which is not a file", + project.0.join("missing.json").display() + )) + ); + } + + fn usable(version: &str) -> SchemaFile { + SchemaFile::Usable { + version: version.to_string(), + } + } + + fn old_format(version: Option<&str>) -> SchemaFile { + SchemaFile::Unusable { + version: version.map(str::to_string), + reason: "`/crate/graphql/admin.schema.json`: Unsupported schema file format 1, \ + this version reads format 2" + .to_string(), + } + } + + fn path(dir: &Path) -> PathBuf { + dir.join(PROJECT_SCHEMA_PATH) + } + + fn download(version: &str, latest: bool) -> SchemaPlan { + SchemaPlan::Download { + version: version.to_string(), + latest, + } + } + + #[test] + fn without_a_pin_the_file_is_the_version_whatever_the_date() { + let dir = Path::new("/crate"); + let years_later = day(2031, 5, 6); + for primary in [true, false] { + assert_eq!( + schema_plan( + dir, + &path(dir), + &usable("2026-07"), + None, + primary, + years_later + ), + SchemaPlan::Read + ); + } + // No file and no pin: the first build of the crate takes the latest. + assert_eq!( + schema_plan( + dir, + &path(dir), + &SchemaFile::Missing, + None, + true, + day(2027, 2, 3) + ), + download("2027-01", true) + ); + } + + #[test] + fn the_primary_package_downloads_its_pinned_version() { + let dir = Path::new("/crate"); + let now = day(2026, 10, 22); + assert_eq!( + schema_plan( + dir, + &path(dir), + &usable("2026-07"), + Some("2026-07"), + true, + now + ), + SchemaPlan::Read + ); + assert_eq!( + schema_plan( + dir, + &path(dir), + &usable("2026-07"), + Some("2026-10"), + true, + now + ), + download("2026-10", false) + ); + assert_eq!( + schema_plan( + dir, + &path(dir), + &SchemaFile::Missing, + Some("2026-04"), + true, + now + ), + download("2026-04", false) + ); + // A file of an older format is downloaded again, for the same version. + assert_eq!( + schema_plan( + dir, + &path(dir), + &old_format(Some("2026-07")), + None, + true, + now + ), + download("2026-07", false) + ); + assert_eq!( + schema_plan( + dir, + &path(dir), + &old_format(Some("2026-07")), + Some("2026-10"), + true, + now + ), + download("2026-10", false) + ); + assert_eq!( + schema_plan(dir, &path(dir), &old_format(None), None, true, now), + download("2026-10", true) + ); + } + + #[test] + fn a_package_is_local_unless_packaged_vendored_or_under_cargo_home() { + let home = Project::new("cargo-home"); + let checkout = home.write("git/checkouts/lib-1a2b/0c9d/Cargo.toml", ""); + let checkout = checkout.parent().unwrap(); + assert!(!is_local_package(checkout, Some(&home.0))); + // Without a `CARGO_HOME`, only the files tell. + assert!(is_local_package(checkout, None)); + + let workspace = Project::new("local"); + workspace.manifest(None); + assert!(is_local_package(&workspace.0, Some(&home.0))); + assert!(is_local_package(&workspace.0, None)); + // A directory whose name starts as `CARGO_HOME`'s is not under it. + let sibling = PathBuf::from(format!("{}-sibling", home.0.display())); + assert!(is_local_package(&sibling, Some(&home.0))); + + for marker in ["Cargo.toml.orig", ".cargo-checksum.json"] { + let packaged = Project::new(&format!("packaged{marker}")); + packaged.manifest(None); + packaged.write(marker, ""); + assert!(!is_local_package(&packaged.0, Some(&home.0)), "{marker}"); + assert!(!is_local_package(&packaged.0, None), "{marker}"); + } + } + + #[cfg(unix)] + #[test] + fn a_cargo_home_through_a_symbolic_link_is_still_cargo_home() { + let real = Project::new("real-cargo-home"); + let registry = real.write("registry/src/index/lib-1.0.0/Cargo.toml", ""); + let linked = std::env::temp_dir().join(format!( + "shopify-api-graphql-linked-home-{}", + std::process::id() + )); + let _ = std::fs::remove_file(&linked); + std::os::unix::fs::symlink(&real.0, &linked).unwrap(); + assert!(!is_local_package(registry.parent().unwrap(), Some(&linked))); + let _ = std::fs::remove_file(&linked); + } + + #[test] + fn a_package_in_a_cargo_checkout_is_not_local() { + let home = Project::new("marker-home"); + // `.cargo-ok` in the package directory itself, as in a registry source. + let source = Project::new("marker-source"); + source.manifest(None); + source.write(".cargo-ok", "{\"v\":1}"); + assert!(!is_local_package(&source.0, Some(&home.0))); + assert!(!is_local_package(&source.0, None)); + + // A package nested in a git checkout, `.cargo-ok` at its root. + let checkout = Project::new("marker-checkout"); + checkout.write(".cargo-ok", ""); + let nested = checkout.write("crates/lib/Cargo.toml", ""); + let nested = nested.parent().unwrap(); + assert!(!is_local_package(nested, Some(&home.0))); + assert!(!is_local_package(nested, None)); + } + + /// `$CARGO_HOME/` links to a directory outside `$CARGO_HOME`. + #[cfg(unix)] + fn linked_cargo_home(name: &str, linked: &str) -> (Project, Project) { + let home = Project::new(&format!("{name}-home")); + let store = Project::new(&format!("{name}-store")); + let link = home.0.join(linked); + std::fs::create_dir_all(link.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink(&store.0, &link).unwrap(); + (home, store) + } + + #[cfg(unix)] + #[test] + fn a_symbolic_link_to_the_git_directory_keeps_its_packages_not_local() { + for (name, linked, below) in [ + ("linked-git", "git", "checkouts/lib-1a2b/0c9d"), + ("linked-checkouts", "git/checkouts", "lib-1a2b/0c9d"), + ] { + let (home, store) = linked_cargo_home(name, linked); + let package = home.0.join(linked).join(below).join("crates/lib"); + store.write(&format!("{below}/crates/lib/Cargo.toml"), ""); + // Without a marker, the path under `$CARGO_HOME` tells. + assert!(!is_local_package(&package, Some(&home.0)), "{name}"); + // With its symbolic links resolved, the path is outside + // `$CARGO_HOME`: the `.cargo-ok` at the checkout root tells. + let resolved = package.canonicalize().unwrap(); + assert!(!resolved.starts_with(home.0.canonicalize().unwrap())); + store.write(&format!("{below}/.cargo-ok"), ""); + assert!(!is_local_package(&package, Some(&home.0)), "{name}"); + assert!(!is_local_package(&resolved, Some(&home.0)), "{name}"); + } + } + + #[test] + fn only_a_local_primary_package_downloads() { + let home = Project::new("download-home"); + let local = Project::new("download-local"); + local.manifest(None); + assert!(may_download(&local.0, Some(&home.0), true)); + assert!(!may_download(&local.0, Some(&home.0), false)); + // Packaged: never, even when primary, as in the verification of + // `cargo package`. + local.write("Cargo.toml.orig", ""); + assert!(!may_download(&local.0, Some(&home.0), true)); + } + + #[test] + fn a_dependency_never_downloads() { + let dir = Path::new("/registry/deplib-1.0.0"); + let now = day(2026, 10, 22); + let refusal = |file: &SchemaFile, pinned: Option<&str>| match schema_plan( + dir, + &path(dir), + file, + pinned, + false, + now, + ) { + SchemaPlan::Refuse(message) => { + let fix = "Run `shopify-api schema download` in `/registry/deplib-1.0.0`"; + assert!(message.contains(fix), "{message}"); + message + } + other => panic!("{file:?}, {pinned:?}: {other:?}"), + }; + assert_eq!( + schema_plan( + dir, + &path(dir), + &usable("2026-07"), + Some("2026-07"), + false, + now + ), + SchemaPlan::Read + ); + let message = refusal(&usable("2026-07"), Some("2026-10")); + // Paths as the platform writes them: `\` before `graphql` on Windows. + let expected = format!( + "`{}` holds the Admin API 2026-07, but `{}` declares 2026-10.", + path(dir).display(), + dir.join("Cargo.toml").display() + ); + assert!(message.starts_with(&expected), "{message}"); + for pinned in [None, Some("2026-10")] { + let message = refusal(&SchemaFile::Missing, pinned); + assert!( + message.contains("admin.schema.json` is missing"), + "{message}" + ); + let message = refusal(&old_format(Some("2026-07")), pinned); + assert!( + message.contains("Unsupported schema file format 1"), + "{message}" + ); + } + } + + #[cfg(feature = "download")] + mod obtaining { + use std::cell::RefCell; + use std::sync::Arc; + + use super::*; + use crate::Schema; + + const SCHEMA: &str = r#"{"format":FORMAT,"apiVersion":"VERSION","query":"Q","types":{"Q":{"o":{"f":{"a":"Int"}}},"Int":"s"}}"#; + + fn schema(version: &str) -> String { + SCHEMA + .replace("FORMAT", &crate::schema::FORMAT.to_string()) + .replace("VERSION", version) + } + + fn read(path: &Path) -> Result, String> { + let json = std::fs::read_to_string(path).map_err(|error| error.to_string())?; + Schema::from_json(&json) + .map(Arc::new) + .map_err(|error| error.to_string()) + } + + /// The versions asked for, and what the next downloads do. + struct Network { + asked: RefCell>, + online: bool, + released: &'static [&'static str], + } + + impl Network { + fn new(online: bool, released: &'static [&'static str]) -> Self { + Self { + asked: RefCell::new(Vec::new()), + online, + released, + } + } + + fn download(&self, path: &Path, version: &str) -> Result<(), DownloadError> { + self.asked.borrow_mut().push(version.to_string()); + if !self.online { + return Err(DownloadError::Failed("offline".to_string())); + } + if !self.released.contains(&version) { + return Err(DownloadError::UnknownVersion { + version: version.to_string(), + answer: "HTTP 400".to_string(), + }); + } + write_atomically(path, &schema(version)).map_err(DownloadError::Failed) + } + + fn obtain( + &self, + project: &Project, + primary: bool, + now: SystemTime, + ) -> Result, String> { + let config = package_config(&project.0).unwrap(); + obtain_schema( + &project.0, + &config.schema_path(&project.0), + config.api_version.as_deref(), + primary, + now, + read, + |path, version| self.download(path, version), + ) + } + } + + #[test] + fn a_dependency_reads_its_file_and_never_writes_it() { + let project = Project::new("dependency"); + project.manifest(None); + let file = project.write(PROJECT_SCHEMA_PATH, &schema("2026-04")); + let network = Network::new(true, &["2026-04", "2026-07", "2026-10"]); + let schema = network.obtain(&project, false, day(2026, 10, 22)).unwrap(); + assert_eq!(schema.api_version, "2026-04"); + + project.manifest(Some("2026-10")); + let error = network + .obtain(&project, false, day(2026, 10, 22)) + .unwrap_err(); + assert!(error.contains("holds the Admin API 2026-04"), "{error}"); + assert!(network.asked.borrow().is_empty()); + assert!(read(&file).unwrap().api_version == "2026-04"); + } + + /// A package whose `Cargo.toml` names `schemas/admin.json`. + fn with_key(name: &str, version: Option<&str>) -> Project { + let project = Project::new(name); + let pin = version.map_or(String::new(), |version| { + format!("api-version = \"{version}\"\n") + }); + project.write( + "Cargo.toml", + &format!( + "[package]\nname = \"app\"\n\n[package.metadata.shopify_api]\n\ + {pin}schema = \"schemas/admin.json\"\n" + ), + ); + project + } + + #[test] + fn the_file_the_manifest_names_follows_the_rules_of_the_default_one() { + let project = with_key("key-local", None); + // The default file is not read when the key names another. + project.write(PROJECT_SCHEMA_PATH, &schema("2026-04")); + project.write("schemas/admin.json", &schema("2026-07")); + let network = Network::new(true, &["2026-07", "2026-10"]); + let now = day(2026, 10, 22); + assert_eq!( + network.obtain(&project, true, now).unwrap().api_version, + "2026-07" + ); + assert!(network.asked.borrow().is_empty()); + + // Missing: a local primary package downloads it there. + std::fs::remove_file(project.0.join("schemas/admin.json")).unwrap(); + assert_eq!( + network.obtain(&project, true, now).unwrap().api_version, + "2026-10" + ); + assert_eq!(*network.asked.borrow(), ["2026-10"]); + assert_eq!( + read(&project.0.join("schemas/admin.json")) + .unwrap() + .api_version, + "2026-10" + ); + assert_eq!( + read(&project.0.join(PROJECT_SCHEMA_PATH)) + .unwrap() + .api_version, + "2026-04" + ); + } + + #[test] + fn a_dependency_uses_the_file_its_manifest_names_and_never_downloads_it() { + let now = day(2026, 10, 22); + let network = Network::new(true, &["2026-04", "2026-07", "2026-10"]); + let project = with_key("key-dependency", Some("2026-07")); + project.write("schemas/admin.json", &schema("2026-07")); + assert_eq!( + network.obtain(&project, false, now).unwrap().api_version, + "2026-07" + ); + + // Missing: an error that names the file and the command. + std::fs::remove_file(project.0.join("schemas/admin.json")).unwrap(); + let error = network.obtain(&project, false, now).unwrap_err(); + let file = project.0.join("schemas/admin.json"); + assert!( + error.starts_with(&format!("`{}` is missing", file.display())), + "{error}" + ); + assert!( + error.contains(&format!( + "Run `shopify-api schema download` in `{}`", + project.0.display() + )), + "{error}" + ); + + // Of another version than the pinned one: an error too. + project.write("schemas/admin.json", &schema("2026-04")); + let error = network.obtain(&project, false, now).unwrap_err(); + assert!(error.contains("holds the Admin API 2026-04"), "{error}"); + assert!(network.asked.borrow().is_empty()); + } + + #[test] + fn a_failed_download_is_tried_once_and_says_what_to_do() { + let project = Project::new("offline"); + project.manifest(Some("2026-10")); + project.write(PROJECT_SCHEMA_PATH, &schema("2026-07")); + let network = Network::new(false, &[]); + for _ in 0..3 { + let error = network + .obtain(&project, true, day(2026, 10, 22)) + .unwrap_err(); + assert!(error.starts_with("offline\n`graphql!` needs the schema of 2026-10, the version Cargo.toml pins"), "{error}"); + assert!( + error.contains("It does not use another version instead"), + "{error}" + ); + } + assert_eq!(*network.asked.borrow(), ["2026-10"]); + } + + #[test] + fn a_version_shopify_does_not_have_is_named_and_a_released_one_suggested() { + let project = Project::new("unknown"); + let network = Network::new(true, &["2026-10"]); + project.manifest(Some("2027-04")); + assert_eq!( + network + .obtain(&project, true, day(2026, 10, 22)) + .unwrap_err(), + "Shopify has no Admin API version 2027-04 (HTTP 400): it is not out yet, \ + or its name is wrong. Declare a released version in Cargo.toml:\n\n\ + [package.metadata.shopify_api]\napi-version = \"2026-10\"" + ); + // On the first day of a quarter, before Shopify releases its version. + project.manifest(Some("2027-01")); + let error = network.obtain(&project, true, day(2027, 1, 1)).unwrap_err(); + assert!(error.ends_with("api-version = \"2026-10\""), "{error}"); + } + + #[test] + fn the_first_build_takes_the_latest_released_version() { + let project = Project::new("first"); + project.manifest(None); + // January 1st, before Shopify releases 2027-01. + let network = Network::new(true, &["2026-10"]); + let schema = network.obtain(&project, true, day(2027, 1, 1)).unwrap(); + assert_eq!(schema.api_version, "2026-10"); + assert_eq!(*network.asked.borrow(), ["2027-01", "2026-10"]); + + // Once 2027-01 is out, the file stays what it is. + let network = Network::new(true, &["2026-10", "2027-01"]); + let schema = network.obtain(&project, true, day(2027, 4, 2)).unwrap(); + assert_eq!(schema.api_version, "2026-10"); + assert!(network.asked.borrow().is_empty()); + } + + #[test] + fn a_file_of_an_older_format_is_downloaded_again_for_its_version() { + let project = Project::new("format"); + project.manifest(None); + let format = format!("\"format\":{}", crate::schema::FORMAT); + let old = schema("2026-07").replacen(&format, "\"format\":0", 1); + project.write(PROJECT_SCHEMA_PATH, &old); + let network = Network::new(true, &["2026-07", "2026-10"]); + let schema = network.obtain(&project, true, day(2026, 10, 22)).unwrap(); + assert_eq!(schema.api_version, "2026-07"); + assert_eq!(*network.asked.borrow(), ["2026-07"]); + } + } + + #[test] + fn files_are_replaced_in_one_step() { + let project = Project::new("atomic"); + let path = project.0.join("graphql/admin.schema.json"); + write_atomically(&path, "one").unwrap(); + write_atomically(&path, "two").unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "two"); + assert_eq!( + std::fs::read_dir(path.parent().unwrap()).unwrap().count(), + 1 + ); + } + + #[cfg(feature = "download")] + #[test] + fn a_version_shopify_does_not_have_is_told_apart() { + let url = "https://shopify.dev/admin-graphql-direct-proxy/2027-04"; + let answer = |status, text| introspection_in("2027-04", url, status, text); + let failed = |reason: &str| { + Err(DownloadError::Failed(format!( + "cannot download the Admin schema 2027-04 from {url}: {reason}" + ))) + }; + assert_eq!( + answer(400, r#"{"error":"Invalid API version"}"#), + Err(DownloadError::UnknownVersion { + version: "2027-04".to_string(), + answer: format!("{url} answered \"Invalid API version\", HTTP 400"), + }) + ); + assert_eq!( + answer(401, r#"{"error":"Unauthorized"}"#), + failed("Unauthorized (HTTP 401)") + ); + assert_eq!(answer(503, "Service Unavailable"), failed("HTTP 503")); + assert_eq!(answer(200, ""), failed("the answer is not JSON")); + assert_eq!( + answer(200, r#"{"data":{}}"#), + Ok(serde_json::json!({ "data": {} })) + ); + } +} diff --git a/crates/shopify_api_graphql/src/restrict.rs b/crates/shopify_api_graphql/src/restrict.rs new file mode 100644 index 0000000..88238b5 --- /dev/null +++ b/crates/shopify_api_graphql/src/restrict.rs @@ -0,0 +1,224 @@ +//! A schema cut down to what some operations use: the types they reach, and +//! of objects and interfaces, the fields they select. +//! +//! `shopify_api` checks its own operations against such a schema, a few +//! kilobytes instead of the whole Admin API. + +use std::collections::{BTreeMap, BTreeSet}; + +use graphql_parser::query as ast; + +use crate::schema::{Field, InputValue, Schema, TypeDef}; +use crate::{Error, analyze}; + +type Document<'a> = ast::Document<'a, String>; +type SelectionSet<'a> = ast::SelectionSet<'a, String>; + +impl Schema { + /// The part of the schema `operations` use. Each operation is checked + /// first, and is accepted by the result as by `self`, with the same shape. + pub fn restricted_to(&self, operations: &[&str]) -> Result { + let mut used = Used::default(); + for source in operations { + analyze(self, source)?; + let document: Document = + graphql_parser::parse_query(source).expect("an operation analyze accepted parses"); + used.document(self, &document); + } + Ok(used.schema(self)) + } +} + +/// What the operations reach, before the closure over types. +#[derive(Default)] +struct Used { + /// Selected fields, by object or interface. + fields: BTreeMap>, + /// Types named by variables and type conditions. + types: BTreeSet, +} + +impl Used { + fn document<'a>(&mut self, schema: &Schema, document: &'a Document<'a>) { + let fragments: BTreeMap<&str, &'a ast::FragmentDefinition<'a, String>> = document + .definitions + .iter() + .filter_map(|definition| match definition { + ast::Definition::Fragment(fragment) => Some((fragment.name.as_str(), fragment)), + ast::Definition::Operation(_) => None, + }) + .collect(); + for definition in &document.definitions { + let ast::Definition::Operation(operation) = definition else { + continue; + }; + let (root, variables, set) = match operation { + ast::OperationDefinition::SelectionSet(set) => (&schema.query, &[][..], set), + ast::OperationDefinition::Query(query) => ( + &schema.query, + &query.variable_definitions[..], + &query.selection_set, + ), + ast::OperationDefinition::Mutation(mutation) => ( + schema.mutation.as_ref().unwrap_or(&schema.query), + &mutation.variable_definitions[..], + &mutation.selection_set, + ), + ast::OperationDefinition::Subscription(_) => continue, + }; + for variable in variables { + self.types.insert(named(&variable.var_type).to_string()); + } + self.selection(schema, root, set, &fragments, &mut BTreeSet::new()); + } + } + + fn selection<'a>( + &mut self, + schema: &Schema, + parent: &str, + set: &'a SelectionSet<'a>, + fragments: &BTreeMap<&str, &'a ast::FragmentDefinition<'a, String>>, + spread: &mut BTreeSet<&'a str>, + ) { + self.types.insert(parent.to_string()); + for item in &set.items { + match item { + ast::Selection::Field(field) => { + if field.name.starts_with("__") { + continue; + } + let fields = match schema.get(parent) { + Some( + TypeDef::Object { fields, .. } | TypeDef::Interface { fields, .. }, + ) => fields, + _ => continue, + }; + let Some(definition) = fields.get(&field.name) else { + continue; + }; + self.fields + .entry(parent.to_string()) + .or_default() + .insert(field.name.clone()); + let inner = definition.ty.name(); + if schema.get(inner).is_some_and(TypeDef::is_composite) { + self.selection(schema, inner, &field.selection_set, fragments, spread); + } + } + ast::Selection::InlineFragment(fragment) => { + let condition = match &fragment.type_condition { + Some(ast::TypeCondition::On(condition)) => condition.as_str(), + None => parent, + }; + self.selection( + schema, + condition, + &fragment.selection_set, + fragments, + spread, + ); + } + ast::Selection::FragmentSpread(item) => { + let Some(fragment) = fragments.get(item.fragment_name.as_str()) else { + continue; + }; + if !spread.insert(fragment.name.as_str()) { + continue; + } + let ast::TypeCondition::On(condition) = &fragment.type_condition; + self.selection( + schema, + condition, + &fragment.selection_set, + fragments, + spread, + ); + spread.remove(fragment.name.as_str()); + } + } + } + } + + /// The schema of the used types, closed over the types they refer to. + fn schema(self, schema: &Schema) -> Schema { + let mut pending: Vec = self.types.iter().cloned().collect(); + pending.push(schema.query.clone()); + pending.extend(schema.mutation.clone()); + for directive in schema.directives.values() { + pending.extend(directive.args.values().map(|arg| arg.ty.name().to_string())); + } + let mut types = BTreeMap::new(); + while let Some(name) = pending.pop() { + if types.contains_key(&name) { + continue; + } + let Some(definition) = schema.get(&name) else { + continue; + }; + let selected = self.fields.get(&name); + let kept = |fields: &BTreeMap, pending: &mut Vec| { + let fields: BTreeMap = fields + .iter() + .filter(|(field, _)| selected.is_some_and(|selected| selected.contains(*field))) + .map(|(field, definition)| (field.clone(), definition.clone())) + .collect(); + for field in fields.values() { + pending.push(field.ty.name().to_string()); + pending.extend(field.args.values().map(|arg| arg.ty.name().to_string())); + } + fields + }; + let restricted = match definition { + TypeDef::Object { fields, interfaces } => TypeDef::Object { + fields: kept(fields, &mut pending), + interfaces: interfaces.clone(), + }, + TypeDef::Interface { + fields, + possible_types, + } => TypeDef::Interface { + fields: kept(fields, &mut pending), + possible_types: possible_types.clone(), + }, + TypeDef::Input { fields, .. } => { + pending.extend( + fields + .values() + .map(|field: &InputValue| field.ty.name().to_string()), + ); + definition.clone() + } + TypeDef::Scalar | TypeDef::Enum { .. } | TypeDef::Union { .. } => { + definition.clone() + } + }; + types.insert(name, restricted); + } + // Interfaces only among the types kept. The possible types of an + // interface or a union all stay, kept or not: they tell whether a + // fragment always applies, and so whether its fields are optional. + // Left out, `... on Product` in a `Node` would always apply. + let names: BTreeSet = types.keys().cloned().collect(); + for definition in types.values_mut() { + if let TypeDef::Object { interfaces, .. } = definition { + interfaces.retain(|name| names.contains(name)); + } + } + Schema { + api_version: schema.api_version.clone(), + query: schema.query.clone(), + mutation: schema.mutation.clone(), + types, + directives: schema.directives.clone(), + } + } +} + +/// The type a variable type names, without lists and non-null. +fn named<'a>(ty: &'a ast::Type<'a, String>) -> &'a str { + match ty { + ast::Type::NamedType(name) => name, + ast::Type::ListType(inner) | ast::Type::NonNullType(inner) => named(inner), + } +} diff --git a/crates/shopify_api_graphql/src/schema.rs b/crates/shopify_api_graphql/src/schema.rs new file mode 100644 index 0000000..7b45532 --- /dev/null +++ b/crates/shopify_api_graphql/src/schema.rs @@ -0,0 +1,1190 @@ +//! The part of a GraphQL schema that checking and typing an operation needs: +//! type kinds, fields, arguments, enum values and deprecations, without +//! descriptions. + +use std::collections::BTreeMap; +use std::fmt; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// The introspection query whose result [`Schema::from_introspection`] reads. +/// +/// It asks for deprecated fields, arguments, input fields and enum values +/// too: an operation may still use them, and `graphql!` warns when it does. +/// `isOneOf` marks the input objects that take exactly one field. +pub const INTROSPECTION_QUERY: &str = "\ +query IntrospectionQuery { + __schema { + queryType { name } + mutationType { name } + types { + kind + name + fields(includeDeprecated: true) { + name + args(includeDeprecated: true) { ...InputValue } + type { ...TypeRef } + isDeprecated + deprecationReason + } + inputFields(includeDeprecated: true) { ...InputValue } + isOneOf + interfaces { name } + enumValues(includeDeprecated: true) { name isDeprecated deprecationReason } + possibleTypes { name } + } + directives { + name + locations + isRepeatable + args(includeDeprecated: true) { ...InputValue } + } + } +} +fragment InputValue on __InputValue { + name + type { ...TypeRef } + defaultValue + isDeprecated + deprecationReason +} +fragment TypeRef on __Type { + kind name + ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } } +} +"; + +/// The version of the stored form written by [`Schema::to_json`]. +pub(crate) const FORMAT: u32 = 2; + +/// The reason GraphQL gives when a deprecation has none. +const NO_REASON: &str = "No longer supported"; + +/// A reference to a type, as written in GraphQL: `[Order!]!`. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum TypeRef { + Named(String), + List(Box), + NonNull(Box), +} + +impl TypeRef { + /// Parses `[Order!]!`. Returns `None` for malformed input. + pub fn parse(text: &str) -> Option { + let text = text.trim(); + if let Some(inner) = text.strip_suffix('!') { + return Some(Self::NonNull(Box::new(Self::parse(inner)?))); + } + if let Some(inner) = text.strip_prefix('[') { + return Some(Self::List(Box::new(Self::parse(inner.strip_suffix(']')?)?))); + } + let is_name = !text.is_empty() + && text + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_'); + is_name.then(|| Self::Named(text.to_string())) + } + + /// The innermost named type: `Order` for `[Order!]!`. + pub fn name(&self) -> &str { + match self { + Self::Named(name) => name, + Self::List(inner) | Self::NonNull(inner) => inner.name(), + } + } + + pub fn is_non_null(&self) -> bool { + matches!(self, Self::NonNull(_)) + } + + /// The same type without its outer `!`. + pub fn nullable(&self) -> &TypeRef { + match self { + Self::NonNull(inner) => inner, + other => other, + } + } +} + +impl fmt::Display for TypeRef { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Named(name) => formatter.write_str(name), + Self::List(inner) => write!(formatter, "[{inner}]"), + Self::NonNull(inner) => write!(formatter, "{inner}!"), + } + } +} + +/// An argument or an input field. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct InputValue { + pub ty: TypeRef, + /// The schema gives it a default value. + pub has_default: bool, + /// Why it is deprecated, when it is. + pub deprecation: Option, +} + +impl InputValue { + /// A value of type `ty`, without default and not deprecated. + pub fn of(ty: TypeRef) -> Self { + Self { + ty, + has_default: false, + deprecation: None, + } + } + + /// A value must be provided: the type is non-null and has no default. + pub fn is_required(&self) -> bool { + self.ty.is_non_null() && !self.has_default + } +} + +/// The places of an operation where a directive may be written. +pub const EXECUTABLE_LOCATIONS: [&str; 8] = [ + "QUERY", + "MUTATION", + "SUBSCRIPTION", + "FIELD", + "FRAGMENT_DEFINITION", + "FRAGMENT_SPREAD", + "INLINE_FRAGMENT", + "VARIABLE_DEFINITION", +]; + +/// A directive an operation may use, such as `@include` or `@idempotent`. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Directive { + /// Where it may be written: [`EXECUTABLE_LOCATIONS`] only. + pub locations: Vec, + pub args: BTreeMap, + /// It may be written more than once at the same place. + pub repeatable: bool, +} + +impl Directive { + /// `@include` and `@skip`, which every GraphQL schema has: what a schema + /// stored without its directives gets. + fn conditions() -> BTreeMap { + let condition = Directive { + locations: ["FIELD", "FRAGMENT_SPREAD", "INLINE_FRAGMENT"] + .map(str::to_string) + .to_vec(), + args: [( + "if".to_string(), + InputValue::of(TypeRef::NonNull(Box::new(TypeRef::Named( + "Boolean".to_string(), + )))), + )] + .into(), + repeatable: false, + }; + [ + ("include".to_string(), condition.clone()), + ("skip".to_string(), condition), + ] + .into() + } +} + +/// A field of an object or an interface. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Field { + pub ty: TypeRef, + pub args: BTreeMap, + /// Why it is deprecated, when it is. + pub deprecation: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum TypeDef { + Scalar, + Enum { + values: Vec, + /// The deprecated values, with their reason. + deprecated: BTreeMap, + }, + Object { + fields: BTreeMap, + interfaces: Vec, + }, + Interface { + fields: BTreeMap, + possible_types: Vec, + }, + Union { + possible_types: Vec, + }, + Input { + fields: BTreeMap, + /// A `@oneOf` input object: a value gives exactly one of its fields, + /// not `null`. + one_of: bool, + }, +} + +impl TypeDef { + /// The kind of type, with its article, for error messages. + pub fn kind_name(&self) -> &'static str { + match self { + Self::Scalar => "a scalar", + Self::Enum { .. } => "an enum", + Self::Object { .. } => "an object", + Self::Interface { .. } => "an interface", + Self::Union { .. } => "a union", + Self::Input { .. } => "an input object", + } + } + + /// Objects, interfaces and unions: types that need a selection of subfields. + pub fn is_composite(&self) -> bool { + matches!( + self, + Self::Object { .. } | Self::Interface { .. } | Self::Union { .. } + ) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Schema { + /// The Shopify API version the schema was downloaded for, such as `2026-10`. + pub api_version: String, + pub query: String, + pub mutation: Option, + pub types: BTreeMap, + /// The directives operations may use, by name. + pub directives: BTreeMap, +} + +/// A schema file or an introspection result is malformed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SchemaError(pub String); + +impl fmt::Display for SchemaError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.0) + } +} + +impl std::error::Error for SchemaError {} + +fn schema_error(message: impl Into) -> SchemaError { + SchemaError(message.into()) +} + +// ─── Stored form ───────────────────────────────────────────────────── +// +// One JSON object per type, with one-letter keys: the Admin schema has +// thousands of types, and it is parsed each time a crate using it compiles. +// +// A field is `"ID!"`, or `["OrderConnection!", { "first": "Int", "reverse": "Boolean=" }]` +// with its arguments. An input value is its type, followed by `=` when it has +// a default. Deprecations are kept apart, in `d`, by name: the reason of a +// field, of an enum value or of an input field, and `"field(argument)"` for +// an argument. + +#[derive(Serialize, Deserialize)] +struct StoredSchema { + format: u32, + #[serde(rename = "apiVersion")] + api_version: String, + query: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + mutation: Option, + #[serde(default)] + directives: BTreeMap, + types: BTreeMap, +} + +/// `{ "l": ["FIELD"], "a": { "key": "String!" } }`, with `"r": true` when repeatable. +#[derive(Serialize, Deserialize)] +struct StoredDirective { + #[serde(rename = "l")] + locations: Vec, + #[serde(rename = "a", default, skip_serializing_if = "BTreeMap::is_empty")] + args: BTreeMap, + #[serde(rename = "r", default, skip_serializing_if = "std::ops::Not::not")] + repeatable: bool, +} + +type Deprecations = BTreeMap; + +#[derive(Serialize, Deserialize)] +enum StoredType { + #[serde(rename = "s")] + Scalar, + #[serde(rename = "e")] + Enum(StoredEnum), + #[serde(rename = "o")] + Object(StoredComposite), + #[serde(rename = "n")] + Interface(StoredComposite), + #[serde(rename = "u")] + Union(Vec), + #[serde(rename = "i")] + Input(StoredInput), +} + +/// `["PAID", "PENDING"]`, or `{ "v": […], "d": { "PENDING": "reason" } }`. +#[derive(Serialize, Deserialize)] +#[serde(untagged)] +enum StoredEnum { + Plain(Vec), + WithDeprecations { v: Vec, d: Deprecations }, +} + +/// `{ "id": "ID!" }`, or `{ "f": { … }, "d": { "id": "reason" } }`, with +/// `"o": true` for a `@oneOf` input object. +#[derive(Serialize, Deserialize)] +#[serde(untagged)] +enum StoredInput { + Detailed { + f: BTreeMap, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + d: Deprecations, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + o: bool, + }, + Plain(BTreeMap), +} + +#[derive(Serialize, Deserialize)] +struct StoredComposite { + #[serde(rename = "f")] + fields: BTreeMap, + /// Interfaces of an object, possible types of an interface. + #[serde(rename = "t", default, skip_serializing_if = "Vec::is_empty")] + types: Vec, + #[serde(rename = "d", default, skip_serializing_if = "BTreeMap::is_empty")] + deprecated: Deprecations, +} + +#[derive(Serialize, Deserialize)] +#[serde(untagged)] +enum StoredField { + Plain(String), + WithArgs(String, BTreeMap), +} + +fn store_input(value: &InputValue) -> String { + if value.has_default { + format!("{}=", value.ty) + } else { + value.ty.to_string() + } +} + +fn load_input( + owner: &str, + name: &str, + text: &str, + deprecation: Option<&String>, +) -> Result { + let (ty, has_default) = match text.strip_suffix('=') { + Some(ty) => (ty, true), + None => (text, false), + }; + let ty = TypeRef::parse(ty) + .ok_or_else(|| schema_error(format!("Invalid type \"{text}\" for {owner}.{name}")))?; + Ok(InputValue { + ty, + has_default, + deprecation: deprecation.cloned(), + }) +} + +fn argument_key(field: &str, argument: &str) -> String { + format!("{field}({argument})") +} + +fn store_fields(fields: &BTreeMap) -> (BTreeMap, Deprecations) { + let mut deprecated = Deprecations::new(); + let stored = fields + .iter() + .map(|(name, field)| { + if let Some(reason) = &field.deprecation { + deprecated.insert(name.clone(), reason.clone()); + } + let ty = field.ty.to_string(); + let stored = if field.args.is_empty() { + StoredField::Plain(ty) + } else { + let args = field + .args + .iter() + .map(|(argument, value)| { + if let Some(reason) = &value.deprecation { + deprecated.insert(argument_key(name, argument), reason.clone()); + } + (argument.clone(), store_input(value)) + }) + .collect(); + StoredField::WithArgs(ty, args) + }; + (name.clone(), stored) + }) + .collect(); + (stored, deprecated) +} + +fn load_fields( + owner: &str, + fields: BTreeMap, + deprecated: &Deprecations, +) -> Result, SchemaError> { + fields + .into_iter() + .map(|(name, stored)| { + let (ty, args) = match stored { + StoredField::Plain(ty) => (ty, BTreeMap::new()), + StoredField::WithArgs(ty, args) => (ty, args), + }; + let field = Field { + ty: TypeRef::parse(&ty).ok_or_else(|| { + schema_error(format!("Invalid type \"{ty}\" for {owner}.{name}")) + })?, + args: args + .into_iter() + .map(|(argument, text)| { + let reason = deprecated.get(&argument_key(&name, &argument)); + let value = + load_input(&format!("{owner}.{name}"), &argument, &text, reason)?; + Ok((argument, value)) + }) + .collect::>()?, + deprecation: deprecated.get(&name).cloned(), + }; + Ok((name, field)) + }) + .collect() +} + +fn load_inputs( + owner: &str, + fields: BTreeMap, + deprecated: &Deprecations, +) -> Result, SchemaError> { + fields + .into_iter() + .map(|(field, text)| { + let value = load_input(owner, &field, &text, deprecated.get(&field))?; + Ok((field, value)) + }) + .collect() +} + +impl Schema { + /// Reads the form written by [`Schema::to_json`]. + pub fn from_json(json: &str) -> Result { + // Only `format`, without building the rest. Anything but an object + // that reads takes the full parse, for its error. + #[derive(Deserialize)] + struct Header { + format: Option, + } + let header = json + .trim_start() + .starts_with('{') + .then(|| serde_json::from_str::
(json).ok()) + .flatten(); + let format = match header { + Some(header) => header.format, + None => serde_json::from_str::(json) + .map_err(|error| schema_error(format!("Invalid schema file: {error}")))? + .get("format") + .cloned(), + }; + let format = format.as_ref().and_then(Value::as_u64); + if format != Some(u64::from(FORMAT)) { + return Err(schema_error(match format { + Some(format) => format!( + "Unsupported schema file format {format}, this version reads format {FORMAT}" + ), + None => "Not a schema file of shopify_api: it has no `format`".to_string(), + })); + } + let stored: StoredSchema = serde_json::from_str(json) + .map_err(|error| schema_error(format!("Invalid schema file: {error}")))?; + let types = stored + .types + .into_iter() + .map(|(name, stored)| { + let definition = match stored { + StoredType::Scalar => TypeDef::Scalar, + StoredType::Enum(StoredEnum::Plain(values)) => TypeDef::Enum { + values, + deprecated: Deprecations::new(), + }, + StoredType::Enum(StoredEnum::WithDeprecations { v, d }) => TypeDef::Enum { + values: v, + deprecated: d, + }, + StoredType::Object(object) => TypeDef::Object { + fields: load_fields(&name, object.fields, &object.deprecated)?, + interfaces: object.types, + }, + StoredType::Interface(interface) => TypeDef::Interface { + fields: load_fields(&name, interface.fields, &interface.deprecated)?, + possible_types: interface.types, + }, + StoredType::Union(possible_types) => TypeDef::Union { possible_types }, + StoredType::Input(StoredInput::Plain(fields)) => TypeDef::Input { + fields: load_inputs(&name, fields, &Deprecations::new())?, + one_of: false, + }, + StoredType::Input(StoredInput::Detailed { f, d, o }) => TypeDef::Input { + fields: load_inputs(&name, f, &d)?, + one_of: o, + }, + }; + Ok((name, definition)) + }) + .collect::>()?; + let mut directives: BTreeMap = stored + .directives + .into_iter() + .map(|(name, stored)| { + let owner = format!("@{name}"); + let args = stored + .args + .into_iter() + .map(|(argument, text)| { + let value = load_input(&owner, &argument, &text, None)?; + Ok((argument, value)) + }) + .collect::>()?; + let directive = Directive { + locations: stored.locations, + args, + repeatable: stored.repeatable, + }; + Ok((name, directive)) + }) + .collect::>()?; + if directives.is_empty() { + directives = Directive::conditions(); + } + Ok(Self { + api_version: stored.api_version, + query: stored.query, + mutation: stored.mutation, + types, + directives, + }) + } + + /// The stored form: one type per line, so that a new API version gives a readable diff. + pub fn to_json(&self) -> String { + let types: BTreeMap<&String, StoredType> = self + .types + .iter() + .map(|(name, definition)| { + let stored = match definition { + TypeDef::Scalar => StoredType::Scalar, + TypeDef::Enum { values, deprecated } if deprecated.is_empty() => { + StoredType::Enum(StoredEnum::Plain(values.clone())) + } + TypeDef::Enum { values, deprecated } => { + StoredType::Enum(StoredEnum::WithDeprecations { + v: values.clone(), + d: deprecated.clone(), + }) + } + TypeDef::Object { fields, interfaces } => { + let (fields, deprecated) = store_fields(fields); + StoredType::Object(StoredComposite { + fields, + types: interfaces.clone(), + deprecated, + }) + } + TypeDef::Interface { + fields, + possible_types, + } => { + let (fields, deprecated) = store_fields(fields); + StoredType::Interface(StoredComposite { + fields, + types: possible_types.clone(), + deprecated, + }) + } + TypeDef::Union { possible_types } => StoredType::Union(possible_types.clone()), + TypeDef::Input { fields, one_of } => { + let stored = fields + .iter() + .map(|(name, value)| (name.clone(), store_input(value))) + .collect(); + let deprecated: Deprecations = fields + .iter() + .filter_map(|(name, value)| { + Some((name.clone(), value.deprecation.clone()?)) + }) + .collect(); + StoredType::Input(if deprecated.is_empty() && !one_of { + StoredInput::Plain(stored) + } else { + StoredInput::Detailed { + f: stored, + d: deprecated, + o: *one_of, + } + }) + } + }; + (name, stored) + }) + .collect(); + + let quoted = |text: &str| Value::from(text).to_string(); + let mut json = format!( + "{{\"format\":{FORMAT},\"apiVersion\":{},\"query\":{}", + quoted(&self.api_version), + quoted(&self.query) + ); + if let Some(mutation) = &self.mutation { + json.push_str(&format!(",\"mutation\":{}", quoted(mutation))); + } + let directives: BTreeMap<&String, StoredDirective> = self + .directives + .iter() + .map(|(name, directive)| { + let stored = StoredDirective { + locations: directive.locations.clone(), + args: directive + .args + .iter() + .map(|(argument, value)| (argument.clone(), store_input(value))) + .collect(), + repeatable: directive.repeatable, + }; + (name, stored) + }) + .collect(); + let directives = serde_json::to_string(&directives).expect("directives serialize"); + json.push_str(&format!(",\n\"directives\":{directives}")); + json.push_str(",\"types\":{"); + for (index, (name, stored)) in types.iter().enumerate() { + json.push_str(if index == 0 { "\n" } else { ",\n" }); + let stored = serde_json::to_string(stored).expect("schema types serialize"); + json.push_str(&format!("{}:{stored}", quoted(name))); + } + json.push_str("\n}}\n"); + json + } + + /// Builds a schema from the answer to [`INTROSPECTION_QUERY`]: the whole + /// response, its `data`, or the `__schema` object. + pub fn from_introspection(response: &Value, api_version: &str) -> Result { + if let Some(errors) = response.get("errors").and_then(Value::as_array) + && !errors.is_empty() + { + let messages: Vec<&str> = errors + .iter() + .filter_map(|error| error.get("message").and_then(Value::as_str)) + .collect(); + return Err(schema_error(format!( + "Introspection failed: {}", + messages.join("; ") + ))); + } + let schema = response + .pointer("/data/__schema") + .or_else(|| response.get("__schema")) + .unwrap_or(response); + let name_of = |pointer: &str| { + schema + .pointer(pointer) + .and_then(Value::as_str) + .map(str::to_string) + }; + let query = name_of("/queryType/name") + .ok_or_else(|| schema_error("The introspection result has no `queryType`"))?; + let listed = schema + .get("types") + .and_then(Value::as_array) + .ok_or_else(|| schema_error("The introspection result has no `types`"))?; + + let mut types = BTreeMap::new(); + for entry in listed { + let name = text(entry, "name")?; + if name.starts_with("__") { + continue; + } + let names = |key: &str| -> Vec { + let listed = entry.get(key).and_then(Value::as_array); + listed + .into_iter() + .flatten() + .filter_map(|item| item.get("name").and_then(Value::as_str)) + .map(str::to_string) + .collect() + }; + let definition = match text(entry, "kind")? { + "SCALAR" => TypeDef::Scalar, + "ENUM" => { + let values = entry.get("enumValues").and_then(Value::as_array); + let deprecated = values + .into_iter() + .flatten() + .filter_map(|value| { + Some(( + value.get("name")?.as_str()?.to_string(), + deprecation(value)?, + )) + }) + .collect(); + TypeDef::Enum { + values: names("enumValues"), + deprecated, + } + } + "OBJECT" => TypeDef::Object { + fields: introspected_fields(entry)?, + interfaces: names("interfaces"), + }, + "INTERFACE" => TypeDef::Interface { + fields: introspected_fields(entry)?, + possible_types: names("possibleTypes"), + }, + "UNION" => TypeDef::Union { + possible_types: names("possibleTypes"), + }, + "INPUT_OBJECT" => TypeDef::Input { + fields: introspected_inputs(entry.get("inputFields"))?, + one_of: entry.get("isOneOf").and_then(Value::as_bool) == Some(true), + }, + other => { + return Err(schema_error(format!( + "Unknown kind \"{other}\" for type {name}" + ))); + } + }; + types.insert(name.to_string(), definition); + } + + if !matches!(types.get(&query), Some(TypeDef::Object { .. })) { + return Err(schema_error(format!( + "The query type `{query}` is not an object of the schema" + ))); + } + + let mut directives = BTreeMap::new(); + for entry in schema + .get("directives") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + let locations: Vec = entry + .get("locations") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .filter(|location| EXECUTABLE_LOCATIONS.contains(location)) + .map(str::to_string) + .collect(); + if locations.is_empty() { + continue; + } + let directive = Directive { + locations, + args: introspected_inputs(entry.get("args"))?, + repeatable: entry.get("isRepeatable").and_then(Value::as_bool) == Some(true), + }; + directives.insert(text(entry, "name")?.to_string(), directive); + } + if directives.is_empty() { + directives = Directive::conditions(); + } + + Ok(Self { + api_version: api_version.to_string(), + query, + mutation: name_of("/mutationType/name"), + types, + directives, + }) + } + + pub fn get(&self, name: &str) -> Option<&TypeDef> { + self.types.get(name) + } + + pub fn directive(&self, name: &str) -> Option<&Directive> { + self.directives.get(name) + } + + /// The object types a value of `name` can be at run time. + pub fn possible_types(&self, name: &str) -> Vec<&str> { + match self.types.get_key_value(name) { + Some((name, TypeDef::Object { .. })) => vec![name.as_str()], + Some(( + _, + TypeDef::Interface { possible_types, .. } | TypeDef::Union { possible_types }, + )) => possible_types.iter().map(String::as_str).collect(), + _ => Vec::new(), + } + } +} + +fn text<'a>(entry: &'a Value, key: &str) -> Result<&'a str, SchemaError> { + entry + .get(key) + .and_then(Value::as_str) + .ok_or_else(|| schema_error(format!("An introspected entry has no `{key}`"))) +} + +/// The reason of a deprecated entry, `None` when it is not deprecated. +fn deprecation(entry: &Value) -> Option { + if entry.get("isDeprecated").and_then(Value::as_bool) != Some(true) { + return None; + } + let reason = entry.get("deprecationReason").and_then(Value::as_str); + Some( + reason + .filter(|reason| !reason.trim().is_empty()) + .unwrap_or(NO_REASON) + .trim() + .to_string(), + ) +} + +fn introspected_type(value: Option<&Value>) -> Result { + let value = value.ok_or_else(|| schema_error("An introspected entry has no `type`"))?; + let inner = || introspected_type(value.get("ofType").filter(|inner| !inner.is_null())); + Ok(match text(value, "kind")? { + "NON_NULL" => TypeRef::NonNull(Box::new(inner()?)), + "LIST" => TypeRef::List(Box::new(inner()?)), + _ => TypeRef::Named(text(value, "name")?.to_string()), + }) +} + +fn introspected_inputs( + values: Option<&Value>, +) -> Result, SchemaError> { + values + .and_then(Value::as_array) + .into_iter() + .flatten() + .map(|value| { + let input = InputValue { + ty: introspected_type(value.get("type"))?, + has_default: value + .get("defaultValue") + .is_some_and(|default| !default.is_null()), + deprecation: deprecation(value), + }; + Ok((text(value, "name")?.to_string(), input)) + }) + .collect() +} + +fn introspected_fields(entry: &Value) -> Result, SchemaError> { + entry + .get("fields") + .and_then(Value::as_array) + .into_iter() + .flatten() + .map(|field| { + let definition = Field { + ty: introspected_type(field.get("type"))?, + args: introspected_inputs(field.get("args"))?, + deprecation: deprecation(field), + }; + Ok((text(field, "name")?.to_string(), definition)) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn parses_and_prints_type_references() { + for text in ["Order", "Order!", "[Order]", "[Order!]!", "[[Int!]]!"] { + assert_eq!(TypeRef::parse(text).unwrap().to_string(), text); + } + let list = TypeRef::parse("[Order!]!").unwrap(); + assert_eq!(list.name(), "Order"); + assert!(list.is_non_null()); + assert_eq!(list.nullable().to_string(), "[Order!]"); + for invalid in ["", "!", "[Order", "Order]", "Or der", "[]"] { + assert_eq!(TypeRef::parse(invalid), None, "{invalid}"); + } + } + + fn introspection() -> Value { + let named = |kind: &str, name: &str| json!({ "kind": kind, "name": name, "ofType": null }); + let non_null = |inner: Value| json!({ "kind": "NON_NULL", "name": null, "ofType": inner }); + let list = |inner: Value| json!({ "kind": "LIST", "name": null, "ofType": inner }); + json!({ "data": { "__schema": { + "queryType": { "name": "QueryRoot" }, + "mutationType": { "name": "Mutation" }, + "types": [ + { "kind": "OBJECT", "name": "QueryRoot", "interfaces": [], "fields": [{ + "name": "orders", + "type": non_null(list(non_null(named("OBJECT", "Order")))), + "isDeprecated": false, + "deprecationReason": null, + "args": [ + { "name": "first", "type": named("SCALAR", "Int"), "defaultValue": null }, + { "name": "reverse", "type": named("SCALAR", "Boolean"), "defaultValue": "false" }, + { + "name": "savedSearchId", + "type": named("SCALAR", "ID"), + "defaultValue": null, + "isDeprecated": true, + "deprecationReason": "Use `query` instead.", + }, + ], + }] }, + { "kind": "OBJECT", "name": "Mutation", "interfaces": [], "fields": [] }, + { "kind": "OBJECT", "name": "Order", "interfaces": [{ "name": "Node" }], "fields": [ + { "name": "id", "type": non_null(named("SCALAR", "ID")), "args": [] }, + { + "name": "legacyName", + "type": named("SCALAR", "String"), + "args": [], + "isDeprecated": true, + "deprecationReason": null, + }, + ] }, + { "kind": "INTERFACE", "name": "Node", "possibleTypes": [{ "name": "Order" }], "fields": [ + { "name": "id", "type": non_null(named("SCALAR", "ID")), "args": [] }, + ] }, + { "kind": "UNION", "name": "Resource", "possibleTypes": [{ "name": "Order" }] }, + { "kind": "ENUM", "name": "SortKey", "enumValues": [ + { "name": "ID", "isDeprecated": false }, + { "name": "CREATED_AT", "isDeprecated": true, "deprecationReason": "Use `ID`." }, + ] }, + { "kind": "INPUT_OBJECT", "name": "OrderInput", "inputFields": [ + { "name": "id", "type": non_null(named("SCALAR", "ID")), "defaultValue": null }, + { "name": "tags", "type": list(non_null(named("SCALAR", "String"))), "defaultValue": "[]" }, + { + "name": "note", + "type": named("SCALAR", "String"), + "defaultValue": null, + "isDeprecated": true, + "deprecationReason": "Use `notes`.", + }, + ] }, + { "kind": "INPUT_OBJECT", "name": "OrderKey", "isOneOf": true, "inputFields": [ + { "name": "id", "type": named("SCALAR", "ID"), "defaultValue": null }, + { "name": "name", "type": named("SCALAR", "String"), "defaultValue": null }, + ] }, + { "kind": "SCALAR", "name": "ID" }, + { "kind": "OBJECT", "name": "__Type", "interfaces": [], "fields": [] }, + ], + } } }) + } + + #[test] + fn reads_an_introspection_result() { + let schema = Schema::from_introspection(&introspection(), "2026-10").unwrap(); + + assert_eq!(schema.api_version, "2026-10"); + assert_eq!(schema.query, "QueryRoot"); + assert_eq!(schema.mutation.as_deref(), Some("Mutation")); + assert!(schema.get("__Type").is_none()); + + let Some(TypeDef::Object { fields, .. }) = schema.get("QueryRoot") else { + panic!("QueryRoot is an object"); + }; + let orders = &fields["orders"]; + assert_eq!(orders.ty.to_string(), "[Order!]!"); + assert!(!orders.args["first"].has_default); + assert!(orders.args["reverse"].has_default); + assert_eq!( + orders.args["savedSearchId"].deprecation.as_deref(), + Some("Use `query` instead.") + ); + assert_eq!(orders.deprecation, None); + + let Some(TypeDef::Object { fields, .. }) = schema.get("Order") else { + panic!("Order is an object"); + }; + // A deprecation without a reason gets the one GraphQL gives. + assert_eq!( + fields["legacyName"].deprecation.as_deref(), + Some("No longer supported") + ); + + let Some(TypeDef::Input { fields, one_of }) = schema.get("OrderInput") else { + panic!("OrderInput is an input object"); + }; + assert!(fields["id"].is_required()); + assert!(!fields["tags"].is_required()); + assert_eq!(fields["note"].deprecation.as_deref(), Some("Use `notes`.")); + assert!(!one_of); + assert_eq!( + schema.get("OrderKey"), + Some(&TypeDef::Input { + fields: [ + ( + "id".to_string(), + InputValue::of(TypeRef::Named("ID".to_string())) + ), + ( + "name".to_string(), + InputValue::of(TypeRef::Named("String".to_string())) + ), + ] + .into(), + one_of: true, + }) + ); + + assert_eq!(schema.possible_types("Node"), ["Order"]); + assert_eq!(schema.possible_types("Resource"), ["Order"]); + assert_eq!(schema.possible_types("Order"), ["Order"]); + assert!(schema.possible_types("SortKey").is_empty()); + assert_eq!( + schema.get("SortKey"), + Some(&TypeDef::Enum { + values: vec!["ID".to_string(), "CREATED_AT".to_string()], + deprecated: [("CREATED_AT".to_string(), "Use `ID`.".to_string())].into(), + }) + ); + } + + #[test] + fn the_stored_form_round_trips() { + let schema = Schema::from_introspection(&introspection(), "2026-10").unwrap(); + let json = schema.to_json(); + + assert_eq!(Schema::from_json(&json).unwrap(), schema); + assert!(json.starts_with("{\"format\":2,\"apiVersion\":\"2026-10\",")); + assert!(json.contains( + "\n\"OrderKey\":{\"i\":{\"f\":{\"id\":\"ID\",\"name\":\"String\"},\"o\":true}},\n" + )); + // One type per line, in name order. + assert!(json.contains( + "\n\"Order\":{\"o\":{\"f\":{\"id\":\"ID!\",\"legacyName\":\"String\"},\"t\":[\"Node\"],\"d\":{\"legacyName\":\"No longer supported\"}}},\n" + )); + assert!(json.contains("\"orders\":[\"[Order!]!\",{\"first\":\"Int\",\"reverse\":\"Boolean=\",\"savedSearchId\":\"ID\"}]")); + assert!(json.contains("\"d\":{\"orders(savedSearchId)\":\"Use `query` instead.\"}")); + assert!(json.contains("\n\"ID\":\"s\",\n")); + // The last type ends the object. + assert!(json.ends_with("\n\"SortKey\":{\"e\":{\"v\":[\"ID\",\"CREATED_AT\"],\"d\":{\"CREATED_AT\":\"Use `ID`.\"}}}\n}}\n")); + assert!(json.contains("\"OrderInput\":{\"i\":{\"f\":{\"id\":\"ID!\",\"note\":\"String\",\"tags\":\"[String!]=\"},\"d\":{\"note\":\"Use `notes`.\"}}}")); + } + + #[test] + fn keeps_the_directives_an_operation_may_use() { + let mut response = introspection(); + response["data"]["__schema"]["directives"] = json!([ + { + "name": "idempotent", + "locations": ["FIELD"], + "isRepeatable": false, + "args": [{ "name": "key", "type": { "kind": "NON_NULL", "name": null, "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } }, "defaultValue": null }], + }, + { "name": "deprecated", "locations": ["FIELD_DEFINITION", "ENUM_VALUE"], "isRepeatable": false, "args": [] }, + { "name": "tag", "locations": ["FIELD", "OBJECT"], "isRepeatable": true, "args": [] }, + ]); + let schema = Schema::from_introspection(&response, "2026-10").unwrap(); + + // A directive of the schema's definitions is left out; only executable places are kept. + assert!(schema.directive("deprecated").is_none()); + assert_eq!(schema.directive("tag").unwrap().locations, ["FIELD"]); + assert!(schema.directive("tag").unwrap().repeatable); + assert!(schema.directive("idempotent").unwrap().args["key"].is_required()); + // Without `@include` and `@skip` in the answer, none are added. + assert!(schema.directive("include").is_none()); + + let json = schema.to_json(); + assert!(json.contains("\n\"directives\":{\"idempotent\":{\"l\":[\"FIELD\"],\"a\":{\"key\":\"String!\"}},\"tag\":{\"l\":[\"FIELD\"],\"r\":true}},\"types\":{")); + assert_eq!(Schema::from_json(&json).unwrap(), schema); + + // A schema without directives has `@include` and `@skip`. + let bare = Schema::from_introspection(&introspection(), "2026-10").unwrap(); + assert_eq!( + bare.directives.keys().collect::>(), + ["include", "skip"] + ); + assert!(admin().directive("idempotent").is_some()); + } + + #[test] + fn reports_malformed_input() { + assert_eq!( + Schema::from_introspection( + &json!({ "errors": [{ "message": "Throttled" }] }), + "2026-10" + ), + Err(SchemaError("Introspection failed: Throttled".to_string())) + ); + assert_eq!( + Schema::from_introspection(&json!({ "data": { "__schema": {} } }), "2026-10"), + Err(SchemaError( + "The introspection result has no `queryType`".to_string() + )) + ); + assert_eq!( + Schema::from_introspection( + &json!({ "__schema": { "queryType": { "name": "Missing" }, "types": [] } }), + "2026-10" + ), + Err(SchemaError( + "The query type `Missing` is not an object of the schema".to_string() + )) + ); + assert!( + Schema::from_json("{") + .unwrap_err() + .0 + .starts_with("Invalid schema file: ") + ); + assert_eq!( + Schema::from_json(r#"{"apiVersion":"2026-10","query":"Q","types":{}}"#), + Err(SchemaError( + "Not a schema file of shopify_api: it has no `format`".to_string() + )) + ); + assert_eq!( + Schema::from_json(r#"[1]"#), + Err(SchemaError( + "Not a schema file of shopify_api: it has no `format`".to_string() + )) + ); + assert_eq!( + Schema::from_json(r#"{"format":9,"apiVersion":"2026-10","query":"Q","types":{}}"#), + Err(SchemaError( + "Unsupported schema file format 9, this version reads format 2".to_string() + )) + ); + assert_eq!( + Schema::from_json( + r#"{"format":2,"apiVersion":"2026-10","query":"Q","types":{"Q":{"o":{"f":{"a":"[Int"}}}}}"# + ), + Err(SchemaError("Invalid type \"[Int\" for Q.a".to_string())) + ); + } + + /// The Admin schema 2026-10 the tests of the workspace use. + fn admin() -> Schema { + Schema::from_json(include_str!("../../shopify_api/graphql/admin.schema.json")).unwrap() + } + + #[test] + fn the_test_schema_is_the_admin_api() { + let schema = admin(); + assert_eq!(schema.api_version, "2026-10"); + assert_eq!(schema.query, "QueryRoot"); + assert_eq!(schema.mutation.as_deref(), Some("Mutation")); + assert!(schema.types.len() > 1000); + } +} diff --git a/crates/shopify_api_graphql/src/source.rs b/crates/shopify_api_graphql/src/source.rs new file mode 100644 index 0000000..4c31add --- /dev/null +++ b/crates/shopify_api_graphql/src/source.rs @@ -0,0 +1,205 @@ +//! The string tokens of a GraphQL source, found without the parser. +//! +//! `graphql-parser` 0.4 panics on some block strings: it measures the +//! common indentation of their lines in bytes, over any Unicode whitespace, +//! then cuts every line at that byte, which can fall inside a character +//! (a line indented with U+00A0, two bytes, and another with U+2003, three +//! bytes). Those are refused here, before the parser reads them. + +use graphql_parser::Pos; + +/// The first block string of `source` the parser cannot read, if any, and +/// where it starts. +pub(crate) fn unreadable_block_strings(source: &str) -> Option { + let mut lexer = Lexer::new(source); + while let Some((position, token)) = lexer.next_string() { + if unreadable_block_string(token) { + return Some(position); + } + } + None +} + +/// Whether the parser panics on this string token: the same steps as its +/// `unquote_block_string`, without the cut. +pub(crate) fn unreadable_block_string(token: &str) -> bool { + let Some(body) = token + .strip_prefix("\"\"\"") + .and_then(|body| body.strip_suffix("\"\"\"")) + else { + return false; + }; + let lines = body.lines(); + let mut common = usize::MAX; + let mut first = None; + let mut last = 0; + for (index, line) in lines.clone().enumerate() { + let indent = line.len() - line.trim_start().len(); + if indent == line.len() { + continue; + } + first.get_or_insert(index); + last = index; + if index != 0 { + common = common.min(indent); + } + } + let Some(first) = first else { + return false; + }; + lines + .enumerate() + .skip(first) + .take(last - first + 1) + .any(|(index, line)| index != 0 && line.len() >= common && !line.is_char_boundary(common)) +} + +pub(crate) struct Lexer<'a> { + source: &'a str, + /// A byte offset. + at: usize, + line: usize, + column: usize, +} + +impl<'a> Lexer<'a> { + pub(crate) fn new(source: &'a str) -> Self { + Lexer { + source, + at: 0, + line: 1, + column: 1, + } + } + + fn rest(&self) -> &'a str { + &self.source[self.at..] + } + + /// Moves `bytes` on, counting lines as the parser does. + fn advance(&mut self, bytes: usize) { + let end = self.at + bytes; + for character in self.source[self.at..end].chars() { + if character == '\n' { + self.line += 1; + self.column = 1; + } else if character == '\t' { + self.column += 8; + } else { + self.column += 1; + } + } + self.at = end; + } + + /// The next string token, quotes included, and where it starts; `None` + /// at the end, or at a string that does not end. + pub(crate) fn next_string(&mut self) -> Option<(Pos, &'a str)> { + loop { + let rest = self.rest(); + let character = rest.chars().next()?; + match character { + '#' => { + let end = rest.find(['\n', '\r']).unwrap_or(rest.len()); + self.advance(end); + } + '"' => { + let position = Pos { + line: self.line, + column: self.column, + }; + let length = string_length(rest)?; + let token = &rest[..length]; + self.advance(length); + return Some((position, token)); + } + other => self.advance(other.len_utf8()), + } + } + } +} + +/// The length in bytes of the string token at the start of `rest`. +fn string_length(rest: &str) -> Option { + if let Some(body) = rest.strip_prefix("\"\"\"") { + let mut from = 0; + loop { + let end = from + body[from..].find("\"\"\"")?; + if body[..end].ends_with('\\') { + from = end + 3; + } else { + return Some(end + 6); + } + } + } + let mut escaped = false; + for (index, character) in rest.char_indices().skip(1) { + match character { + '"' if !escaped => return Some(index + 1), + _ => escaped = !escaped && character == '\\', + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strings_end_where_the_parser_ends_them() { + assert_eq!(string_length(r#""a\"b" x"#), Some(6)); + assert_eq!(string_length(r#""a\\" x"#), Some(5)); + assert_eq!(string_length(r#""""a\"""b""" x"#), Some(12)); + assert_eq!(string_length(r#""""""" x"#), Some(6)); + } + + /// Whether `graphql-parser` panics on the block string `token`. + fn parser_panics(token: &str) -> bool { + let source = format!("{{ f(a: {token}) }}"); + std::panic::catch_unwind(|| { + let _ = graphql_parser::parse_query::(&source); + }) + .is_err() + } + + #[test] + fn unreadable_block_strings_are_those_the_parser_panics_on() { + let whitespace = [ + " ", "\t", "\u{a0}", "\u{2003}", "\u{3000}", "\u{1680}", "\u{2028}", + ]; + let mut tokens = Vec::new(); + for a in whitespace { + for b in whitespace { + for c in ["", " ", "\u{a0}"] { + for line in ["x", ""] { + tokens.push(format!("\"\"\"\n{a}{c}x\n{b}{line}\n{c}{a}y\"\"\"")); + tokens.push(format!("\"\"\"x\n{a}{b}x\n{b}\n{c}{line}\"\"\"")); + } + } + } + } + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(|_| {})); + let mismatches: Vec<_> = tokens + .iter() + .filter(|token| parser_panics(token) != unreadable_block_string(token)) + .collect(); + std::panic::set_hook(previous); + assert!(mismatches.is_empty(), "{mismatches:?}"); + assert!(tokens.iter().any(|token| unreadable_block_string(token))); + } + + #[test] + fn finds_the_unreadable_block_string() { + assert_eq!( + unreadable_block_strings("{ f(a: \"\"\"\n\u{a0}a\n\u{a0}b\"\"\") }"), + None + ); + let position = unreadable_block_strings( + "# \"\"\"\n{ f(a: \"x\", b: \"\"\"\n\u{a0}a\n\u{2003}b\"\"\") }", + ) + .unwrap(); + assert_eq!((position.line, position.column), (2, 16)); + } +} diff --git a/crates/shopify_api_graphql/tests/analyze.rs b/crates/shopify_api_graphql/tests/analyze.rs new file mode 100644 index 0000000..cae0c2a --- /dev/null +++ b/crates/shopify_api_graphql/tests/analyze.rs @@ -0,0 +1,1108 @@ +//! Operations checked against the Shopify Admin schema 2026-10: what is +//! refused, with which message, and the shape of what is accepted. + +use std::sync::OnceLock; + +use shopify_api_graphql::{ + FieldBase, Operation, OperationKind, Scalar, Schema, Selection, VariableBase, analyze, +}; + +/// The Admin schema 2026-10 the tests of the workspace use. +fn admin() -> &'static Schema { + static ADMIN: OnceLock = OnceLock::new(); + ADMIN.get_or_init(|| { + Schema::from_json(include_str!("../../shopify_api/graphql/admin.schema.json")).unwrap() + }) +} + +fn check(source: &str) -> Operation { + analyze(admin(), source).unwrap_or_else(|error| panic!("{error}\n{source}")) +} + +fn refusal(source: &str) -> String { + match analyze(admin(), source) { + Ok(_) => panic!("accepted: {source}"), + Err(error) => error.to_string(), + } +} + +/// `key: Type` of each field, `?` marking those that may be absent. +fn fields(selection: &Selection) -> Vec { + selection + .fields + .iter() + .map(|field| { + format!( + "{}{}: {}", + field.key, + if field.conditional { "?" } else { "" }, + field.ty + ) + }) + .collect() +} + +fn child<'a>(selection: &'a Selection, key: &str) -> &'a Selection { + match selection + .fields + .iter() + .find(|field| field.key == key) + .map(|field| &field.base) + { + Some(FieldBase::Object(selection)) => selection, + _ => panic!("`{key}` is not a selection of `{}`", selection.type_name), + } +} + +// ─── Accepted ──────────────────────────────────────────────────────── + +#[test] +fn describes_variables_and_nested_selections() { + let operation = check( + "query Recent($first: Int!, $query: String, $sortKey: OrderSortKeys = CREATED_AT) { + orders(first: $first, query: $query, sortKey: $sortKey) { nodes { id name note } } + }", + ); + + assert_eq!(operation.kind, OperationKind::Query); + assert_eq!(operation.name.as_deref(), Some("Recent")); + let variables: Vec<(&str, String, bool, VariableBase)> = operation + .variables + .iter() + .map(|variable| { + ( + variable.name.as_str(), + variable.ty.to_string(), + variable.is_required(), + variable.base, + ) + }) + .collect(); + assert_eq!( + variables, + [ + ( + "first", + "Int!".to_string(), + true, + VariableBase::Scalar(Scalar::Int) + ), + ( + "query", + "String".to_string(), + false, + VariableBase::Scalar(Scalar::String) + ), + ( + "sortKey", + "OrderSortKeys".to_string(), + false, + VariableBase::Enum + ), + ] + ); + + assert_eq!(operation.data.type_name, "QueryRoot"); + assert_eq!(fields(&operation.data), ["orders: OrderConnection!"]); + let orders = child(&operation.data, "orders"); + assert_eq!(fields(orders), ["nodes: [Order!]!"]); + let nodes = child(orders, "nodes"); + assert_eq!(nodes.type_name, "Order"); + assert_eq!(fields(nodes), ["id: ID!", "name: String!", "note: String"]); +} + +#[test] +fn accepts_the_shorthand_query_and_mutations() { + let operation = check("{ shop { name } }"); + assert_eq!( + (operation.kind, operation.name), + (OperationKind::Query, None) + ); + + let operation = check( + "mutation($metafields: [MetafieldsSetInput!]!) { + metafieldsSet(metafields: $metafields) { userErrors { message } } + }", + ); + assert_eq!(operation.kind, OperationKind::Mutation); + assert_eq!(operation.data.type_name, "Mutation"); + assert_eq!(operation.variables[0].base, VariableBase::Input); + assert_eq!( + fields(&operation.data), + ["metafieldsSet: MetafieldsSetPayload"] + ); +} + +#[test] +fn maps_scalars_to_their_json_form() { + let operation = check( + "{ shop { name } order(id: \"gid://shopify/Order/1\") { + createdAt + subtotalLineItemsQuantity + totalWeight + confirmed + metafield(key: \"k\") { jsonValue } + totalPriceSet { shopMoney { amount } } + } }", + ); + let order = child(&operation.data, "order"); + let scalar = |selection: &Selection, key: &str| match selection + .fields + .iter() + .find(|field| field.key == key) + .map(|field| &field.base) + { + Some(FieldBase::Scalar(scalar)) => *scalar, + _ => panic!("`{key}` is not a scalar"), + }; + assert_eq!(scalar(order, "createdAt"), Scalar::String); + assert_eq!(scalar(order, "subtotalLineItemsQuantity"), Scalar::Int); + // `UnsignedInt64` travels as a string. + assert_eq!(scalar(order, "totalWeight"), Scalar::String); + assert_eq!(scalar(order, "confirmed"), Scalar::Boolean); + assert_eq!(scalar(child(order, "metafield"), "jsonValue"), Scalar::Json); + let money = child(child(order, "totalPriceSet"), "shopMoney"); + assert_eq!(scalar(money, "amount"), Scalar::String); +} + +#[test] +fn merges_selections_of_the_same_field_and_marks_conditional_ones() { + let operation = check( + "query($withTags: Boolean!, $ids: [ID!]!) { + nodes(ids: $ids) { + id + __typename + ... on Node { id } + ... on Product { title handle ...ProductBits } + ... on Order { name tags @include(if: $withTags) } + ... on HasMetafields { metafield(key: \"k\") { value } } + } + } + fragment ProductBits on Product { title vendor featuredMedia { id } }", + ); + let nodes = child(&operation.data, "nodes"); + assert_eq!(nodes.type_name, "Node"); + assert_eq!( + fields(nodes), + [ + "id: ID!", + "__typename: String!", + "title?: String!", + "handle?: String!", + "vendor?: String!", + "featuredMedia?: Media", + "name?: String!", + "tags?: [String!]!", + "metafield?: Metafield", + ] + ); + + // On the object itself, a fragment on one of its interfaces always applies. + let operation = check( + "{ shop { ... on Node { id } ... on Shop { name } ...Meta } } + fragment Meta on HasMetafields { metafield(key: \"k\") { value } }", + ); + assert_eq!( + fields(child(&operation.data, "shop")), + ["id: ID!", "name: String!", "metafield: Metafield"] + ); + + // The same field selected twice is one field with both selections. + let operation = + check("{ shop { plan { publicDisplayName } plan { partnerDevelopment } name name } }"); + let shop = child(&operation.data, "shop"); + assert_eq!(fields(shop), ["plan: ShopPlan!", "name: String!"]); + assert_eq!( + fields(child(shop, "plan")), + ["publicDisplayName: String!", "partnerDevelopment: Boolean!"] + ); +} + +#[test] +fn accepts_literals_of_every_kind() { + check( + "mutation { + metafieldsSet(metafields: [{ ownerId: \"gid://shopify/Product/1\", key: \"k\", value: \"v\", namespace: null }]) { + userErrors { message } + } + }", + ); + check( + "{ orders(first: 5, reverse: true, sortKey: UPDATED_AT, query: \"status:open\") { nodes { id } } }", + ); + // An integer where an ID is expected, and a variable with a default for a non-null argument. + check("query($id: ID = 1) { product(id: $id) { id } node(id: 2) { id } }"); + check(r#"query($id: ID = "gid://shopify/Product/1") { product(id: $id) { id } }"#); + check(r#"query($ids: [ID!] = ["gid://shopify/Product/1"]) { nodes(ids: $ids) { id } }"#); + // A single value where a list is expected. + check("{ nodes(ids: \"gid://shopify/Product/1\") { id } }"); +} + +// ─── Refused ───────────────────────────────────────────────────────── + +/// Input Object Field Uniqueness: the parser would keep one, Shopify gets both. +#[test] +fn refuses_an_input_field_given_twice() { + assert_eq!( + refusal( + r#"mutation { productUpdate(product: {id: "1", title: "old", title: "new"}) { product { id } } }"# + ), + "The input field `title` is given twice in the same input object (line 1, column 59)" + ); + check( + r#"mutation { productUpdate(product: {id: "1", title: "new"}) { product { id title } } }"#, + ); +} + +#[test] +fn a_one_of_input_takes_exactly_one_field_not_null() { + let rule = "`ProductSetIdentifiers` is a oneOf input: give exactly one of `customId`, `handle` or `id`, not null (in argument `identifier` of `Mutation.productSet`)"; + let operation = |identifier: &str| { + format!( + "mutation($id: ID, $handle: String!) {{ productSet(identifier: {identifier}, input: {{}}) {{ product {{ id }} }} }}" + ) + }; + let refused = |identifier: &str| refusal(&operation(identifier)); + assert!(refused("{}").starts_with(rule), "{}", refused("{}")); + assert!( + refused(r#"{id: "1", handle: "a"}"#).starts_with(rule), + "{}", + refused(r#"{id: "1", handle: "a"}"#) + ); + let null = refused("{id: null}"); + assert!( + null.starts_with(&format!("{rule}: `id: null` is not one")), + "{null}" + ); + let nullable = refused("{id: $id}"); + assert!( + nullable.starts_with(&format!( + "{rule}: `$id` is of type `ID`, which may be null; declare it `ID!`" + )), + "{nullable}" + ); + check(r#"mutation { productSet(identifier: {handle: "a"}, input: {}) { product { id } } }"#); + check(&operation("{handle: $handle}").replace("$id: ID, ", "")); +} + +/// Only a default other than `null` lets a nullable variable fill a non-null place. +#[test] +fn refuses_a_null_default_for_a_non_null_place() { + assert_eq!( + refusal("query($id: ID = null) { product(id: $id) { id } }"), + "Variable `$id` of type `ID` cannot be used for argument `id` of `QueryRoot.product`, which expects `ID!` (line 1, column 25)" + ); + assert!( + refusal("query($ids: [ID!] = null) { nodes(ids: $ids) { id } }") + .starts_with("Variable `$ids` of type `[ID!]` cannot be used"), + ); + // Where `null` is allowed, a `null` default is fine. + check("query($after: String = null) { products(first: 1, after: $after) { nodes { id } } }"); +} + +#[test] +fn refuses_unknown_fields_and_arguments_with_a_suggestion() { + assert_eq!( + refusal("{ orders(first: 1) { nodes { id nam } } }"), + "Type `Order` has no field `nam` (did you mean `name`?) (line 1, column 33)" + ); + assert_eq!( + refusal("{ orders(frist: 1) { nodes { id } } }"), + "Field `QueryRoot.orders` has no argument `frist` (did you mean `first`?) (line 1, column 3)" + ); + assert_eq!( + refusal("{ shop { zzzzzz } }"), + "Type `Shop` has no field `zzzzzz` (line 1, column 10)" + ); + assert_eq!( + refusal("{ shop { __typename(x: 1) } }"), + "Field `__typename` has no argument `x` (line 1, column 10)" + ); +} + +#[test] +fn refuses_missing_arguments_and_selections() { + assert_eq!( + refusal("{ product { id } }"), + "Field `QueryRoot.product` requires the argument `id: ID!` (line 1, column 3)" + ); + assert_eq!( + refusal("{ shop }"), + "Field `shop` has the type `Shop!`: select the subfields you need, `shop { … }` (line 1, column 3)" + ); + assert_eq!( + refusal("{ shop { name { length } } }"), + "Field `name` has the type `String!`, which has no subfields (line 1, column 10)" + ); +} + +#[test] +fn refuses_variables_that_do_not_fit() { + assert_eq!( + refusal("query($first: String!) { orders(first: $first) { nodes { id } } }"), + "Variable `$first` of type `String!` cannot be used for argument `first` of `QueryRoot.orders`, which expects `Int` (line 1, column 26)" + ); + assert_eq!( + refusal("query($id: ID) { product(id: $id) { id } }"), + "Variable `$id` of type `ID` cannot be used for argument `id` of `QueryRoot.product`, which expects `ID!` (line 1, column 18)" + ); + assert_eq!( + refusal("query($ids: [ID]!) { nodes(ids: $ids) { id } }"), + "Variable `$ids` of type `[ID]!` cannot be used for argument `ids` of `QueryRoot.nodes`, which expects `[ID!]!` (line 1, column 22)" + ); + assert_eq!( + refusal("{ orders(first: $first) { nodes { id } } }"), + "Variable `$first` is not declared (line 1, column 3)" + ); + assert_eq!( + refusal("query($first: Int!, $frist: Int) { orders(first: $firs) { nodes { id } } }"), + "Variable `$firs` is not declared (did you mean `first`?) (line 1, column 36)" + ); + assert_eq!( + refusal("query($first: Int!, $after: String) { orders(first: $first) { nodes { id } } }"), + "Variable `$after` is declared but never used" + ); + assert_eq!( + refusal("query($first: Int!, $first: Int!) { orders(first: $first) { nodes { id } } }"), + "Variable `$first` is declared twice (line 1, column 21)" + ); + assert_eq!( + refusal("query($sort: OrderSortKey) { orders(first: 1, sortKey: $sort) { nodes { id } } }"), + "Variable `$sort` has the unknown type `OrderSortKey` (did you mean `OrderSortKeys`?) (line 1, column 7)" + ); + assert_eq!( + refusal("query($order: Order) { shop { name } }"), + "Variable `$order` cannot have the type `Order`: `Order` is an object, not an input type (line 1, column 7)" + ); + assert_eq!( + refusal("query($flag: String!) { shop { name @include(if: $flag) } }"), + "Variable `$flag` of type `String!` cannot be used for argument `if` of `@include`, which expects `Boolean!` (line 1, column 37)" + ); +} + +#[test] +fn refuses_literals_that_do_not_fit() { + assert_eq!( + refusal("{ orders(first: \"1\") { nodes { id } } }"), + "a string is given for argument `first` of `QueryRoot.orders`, of type `Int` (line 1, column 3)" + ); + assert_eq!( + refusal("{ orders(first: 1, reverse: 1) { nodes { id } } }"), + "an integer is given for argument `reverse` of `QueryRoot.orders`, of type `Boolean` (line 1, column 3)" + ); + assert_eq!( + refusal("{ orders(first: 1, sortKey: CREATED) { nodes { id } } }"), + "`CREATED` is not a value of the enum `OrderSortKeys` (did you mean `CREATED_AT`?) (in argument `sortKey` of `QueryRoot.orders`) (line 1, column 3)" + ); + assert_eq!( + refusal("{ orders(first: 1, sortKey: \"CREATED_AT\") { nodes { id } } }"), + "a string is given for argument `sortKey` of `QueryRoot.orders`, of type `OrderSortKeys` (line 1, column 3)" + ); + assert_eq!( + refusal("{ orders(first: FIVE) { nodes { id } } }"), + "The enum value `FIVE` is given for argument `first` of `QueryRoot.orders`, of type `Int` (line 1, column 3)" + ); + assert_eq!( + refusal("{ product(id: null) { id } }"), + "`null` is not allowed for argument `id` of `QueryRoot.product`, of type `ID!` (line 1, column 3)" + ); + assert_eq!( + refusal("{ product(id: [\"a\"]) { id } }"), + "A list is given for argument `id` of `QueryRoot.product`, of type `ID!` (line 1, column 3)" + ); + assert_eq!( + refusal("{ product(id: { value: 1 }) { id } }"), + "An object is given for argument `id` of `QueryRoot.product`, of type `ID!` (line 1, column 3)" + ); +} + +#[test] +fn int_literals_are_32_bit_integers() { + check("{ orders(first: 2147483647) { nodes { id } } }"); + check("query($first: Int = -2147483648) { orders(first: $first) { nodes { id } } }"); + assert_eq!( + refusal("{ orders(first: 2147483648) { nodes { id } } }"), + "The integer is outside the range of `Int`, a 32-bit integer, given for argument `first` of `QueryRoot.orders` (line 1, column 3)" + ); + assert_eq!( + refusal("{ orders(first: -2147483649) { nodes { id } } }"), + "The integer is outside the range of `Int`, a 32-bit integer, given for argument `first` of `QueryRoot.orders` (line 1, column 3)" + ); + // A float, an ID or a custom scalar is not bounded by `Int`. + check("{ orders(first: 1) { nodes { id } } product(id: 99999999999) { id } }"); +} + +#[test] +fn default_values_fit_the_type_of_their_variable() { + check( + "query($first: Int! = 10, $sort: OrderSortKeys = CREATED_AT, $ids: [ID!] = [\"1\"]) { orders(first: $first, sortKey: $sort) { nodes { id } } nodes(ids: $ids) { id } }", + ); + assert_eq!( + refusal("query($first: Int = \"ten\") { orders(first: $first) { nodes { id } } }"), + "a string is given for the default value of `$first`, of type `Int` (line 1, column 7)" + ); + assert_eq!( + refusal("query($first: Int! = null) { orders(first: $first) { nodes { id } } }"), + "`null` is not allowed for the default value of `$first`, of type `Int!` (line 1, column 7)" + ); + assert_eq!( + refusal( + "query($sort: OrderSortKeys = CREATED) { orders(first: 1, sortKey: $sort) { nodes { id } } }" + ), + "`CREATED` is not a value of the enum `OrderSortKeys` (did you mean `CREATED_AT`?) (in the default value of `$sort`) (line 1, column 7)" + ); + assert_eq!( + refusal("query($first: Int = 3000000000) { orders(first: $first) { nodes { id } } }"), + "The integer is outside the range of `Int`, a 32-bit integer, given for the default value of `$first` (line 1, column 7)" + ); +} + +#[test] +fn json_and_custom_scalars_accept_any_literal() { + // `JSON` takes an object, a list or a scalar, in a default value and in an argument. + let operation = check( + "mutation($payload: JSON = {Amount: \"30\", customer_id: 12345, tags: [\"a\", {nested: true}]}) { + flowTriggerReceive(handle: \"h\", payload: $payload) { userErrors { message } } + }", + ); + assert_eq!(operation.variables.len(), 1); + check( + "mutation($items: JSON = [1, \"two\", null]) { flowTriggerReceive(handle: \"h\", payload: $items) { userErrors { message } } }", + ); + check( + "mutation { flowTriggerReceive(handle: \"h\", payload: {Amount: \"30\", list: [1, 2], none: null}) { userErrors { message } } }", + ); + check( + "mutation($id: String) { flowTriggerReceive(handle: \"h\", payload: {customer: $id}) { userErrors { message } } }", + ); + check( + "mutation { flowTriggerReceive(handle: \"h\", payload: [1, 2]) { userErrors { message } } }", + ); + // A variable inside the literal is declared like any other. + assert_eq!( + refusal( + "mutation { flowTriggerReceive(handle: \"h\", payload: {customer: $id}) { userErrors { message } } }" + ), + "Variable `$id` is not declared (line 1, column 12)" + ); + // An object stays refused for a built-in scalar. + assert_eq!( + refusal( + "mutation { flowTriggerReceive(handle: {a: 1}, payload: {}) { userErrors { message } } }" + ), + "An object is given for argument `handle` of `Mutation.flowTriggerReceive`, of type `String` (line 1, column 12)" + ); +} + +#[test] +fn checks_input_object_literals() { + assert_eq!( + refusal( + "mutation { metafieldsSet(metafields: [{ ownerId: \"x\", key: \"k\", valeu: \"v\" }]) { userErrors { message } } }" + ), + "Input type `MetafieldsSetInput` has no field `valeu` (did you mean `value`?) (in argument `metafields` of `Mutation.metafieldsSet`) (line 1, column 12)" + ); + assert_eq!( + refusal( + "mutation { metafieldsSet(metafields: [{ ownerId: \"x\", key: \"k\" }]) { userErrors { message } } }" + ), + "Input type `MetafieldsSetInput` requires the field `value: String!` (in argument `metafields` of `Mutation.metafieldsSet`) (line 1, column 12)" + ); + assert_eq!( + refusal( + "mutation { metafieldsSet(metafields: [{ ownerId: \"x\", key: 1, value: \"v\" }]) { userErrors { message } } }" + ), + "an integer is given for field `key` of `MetafieldsSetInput`, of type `String!` (line 1, column 12)" + ); +} + +#[test] +fn refuses_fragments_that_cannot_apply() { + assert_eq!( + refusal("{ shop { ... on Order { id } } }"), + "A fragment on `Order` never applies to a `Shop` (line 1, column 14)" + ); + assert_eq!( + refusal("{ node(id: 1) { ... on Prodct { title } } }"), + "A fragment is on the unknown type `Prodct` (did you mean `Product`?) (line 1, column 21)" + ); + assert_eq!( + refusal("{ shop { ... on ID { length } } }"), + "A fragment cannot be on `ID`, which is a scalar (line 1, column 14)" + ); + assert_eq!( + refusal("{ shop { ...Missing } }"), + "Fragment `Missing` is not defined; a `graphql!` document contains the fragments it uses (line 1, column 13)" + ); + assert_eq!( + refusal("{ shop { name } } fragment Unused on Shop { id }"), + "Fragment `Unused` is defined but never used (line 1, column 19)" + ); + assert_eq!( + refusal("{ shop { ...A } } fragment A on Shop { name ...B } fragment B on Shop { ...A }"), + "Fragment `A` includes itself (line 1, column 76)" + ); + assert_eq!( + refusal("{ shop { ...A } } fragment A on Shop { id } fragment A on Shop { name }"), + "Fragment `A` is defined twice (line 1, column 45)" + ); +} + +#[test] +fn refuses_ambiguous_keys_and_unions_without_fragments() { + assert_eq!( + refusal("{ shop { name name: email } }"), + "`name` is selected twice with different fields or types (`name: String!` and `email: String!`); give one of them an alias (line 1, column 15)" + ); + assert_eq!( + refusal( + "{ nodes(ids: []) { ... on Product { value: title } ... on Order { value: subtotalLineItemsQuantity } } }" + ), + "`value` is selected twice with different fields or types (`title: String!` and `subtotalLineItemsQuantity: Int!`); give one of them an alias (line 1, column 67)" + ); + let message = refusal("{ order(id: 1) { metafield(key: \"k\") { reference { id } } } }"); + assert!( + message.starts_with( + "`MetafieldReference` is a union: select `id` inside a fragment such as `... on " + ), + "{message}" + ); +} + +#[test] +fn refuses_documents_that_are_not_one_operation() { + assert_eq!( + refusal("{ shop { name } } query Other { shop { id } }"), + "The document contains several operations; `graphql!` takes one (line 1, column 19)" + ); + assert_eq!( + refusal("fragment A on Shop { id }"), + "The document contains no query or mutation" + ); + assert_eq!( + refusal("subscription { shop { name } }"), + "Subscriptions are not supported (line 1, column 1)" + ); + let message = refusal("{ shop { name }"); + assert!(message.starts_with("Invalid GraphQL: "), "{message}"); +} + +// ─── Deprecations ──────────────────────────────────────────────────── + +/// `coordinate @ line:column` of each deprecation. +fn deprecations(source: &str) -> Vec { + check(source) + .deprecations + .iter() + .map(|deprecation| { + let (line, column) = deprecation.position; + format!("{} @ {line}:{column}", deprecation.coordinate) + }) + .collect() +} + +#[test] +fn reports_the_deprecated_fields_arguments_and_values_used() { + assert!(deprecations("{ shop { name } }").is_empty()); + + let operation = check("{ product(id: 1) { bodyHtml descriptionHtml } }"); + assert_eq!(operation.deprecations.len(), 1); + let deprecation = &operation.deprecations[0]; + assert_eq!(deprecation.coordinate, "Product.bodyHtml"); + assert_eq!(deprecation.reason, "Use `descriptionHtml` instead."); + assert_eq!(deprecation.position, (1, 20)); + + // An argument, an enum value, an input field, and fields inside fragments. + assert_eq!( + deprecations( + "query { + collection(id: 1) { image(maxWidth: 10) { url } } + shop { currencyCode ...Legacy } + } + fragment Legacy on Shop { analyticsToken }" + ), + [ + "Collection.image(maxWidth:) @ 2:36", + "Shop.analyticsToken @ 5:40", + ] + ); + assert_eq!( + deprecations( + "mutation { productVariantsBulkCreate(productId: 1, variants: [{ price: 1 }], strategy: DEFAULT) { userErrors { message } } }" + ), + Vec::::new() + ); + let operation = check( + "mutation($id: ID!) { + collectionUpdate(input: { id: $id, publications: [] }) { userErrors { message } } + }", + ); + assert_eq!( + operation + .deprecations + .iter() + .map(|deprecation| deprecation.coordinate.as_str()) + .collect::>(), + // `input` itself is deprecated in 2026-10, for `collection`. + [ + "CollectionInput.publications", + "Mutation.collectionUpdate(input:)" + ] + ); +} + +#[test] +fn reports_deprecated_enum_values_written_in_the_operation() { + let operation = + check("{ shop { name } discountNodes(first: 1, query: \"x\") { nodes { id } } }"); + assert!(operation.deprecations.is_empty()); + let deprecated = admin() + .types + .iter() + .find_map(|(name, definition)| match definition { + shopify_api_graphql::TypeDef::Enum { deprecated, .. } if name == "CurrencyCode" => { + deprecated.keys().next().cloned() + } + _ => None, + }) + .expect("a deprecated currency code"); + let source = format!( + "mutation {{ shopLocaleUpdate(locale: \"fr\", shopLocale: {{ published: true }}) {{ userErrors {{ message }} }} \ + priceListCreate(input: {{ name: \"x\", currency: {deprecated}, parent: {{ adjustment: {{ type: PERCENTAGE_DECREASE, value: 1 }} }} }}) {{ userErrors {{ message }} }} }}" + ); + let operation = check(&source); + assert_eq!( + operation + .deprecations + .iter() + .map(|deprecation| deprecation.coordinate.clone()) + .collect::>(), + [format!("CurrencyCode.{deprecated}")] + ); +} + +// ─── Merging, arguments and directives ─────────────────────────────── + +#[test] +fn a_subfield_of_a_conditional_place_stays_conditional() { + // `name` is only there when `$withName` is true. + let operation = + check("query($withName: Boolean!) { shop { id } shop @include(if: $withName) { name } }"); + assert_eq!( + fields(child(&operation.data, "shop")), + ["id: ID!", "name?: String!"] + ); + + // Two fragments that may each be the one that applies: a subfield is + // certain only when both select it. + let operation = check( + "query($id: ID!) { node(id: $id) { + ... on HasMetafields { metafields(first: 1) { nodes { id } } } + ... on Product { metafields(first: 1) { nodes { id key } } } + } }", + ); + let metafields = child(child(&operation.data, "node"), "metafields"); + assert_eq!(fields(metafields), ["nodes: [Metafield!]!"]); + assert_eq!( + fields(child(metafields, "nodes")), + ["id: ID!", "key?: String!"] + ); + + // A field selected alone under a condition keeps its subfields certain. + let operation = check("query($b: Boolean!) { shop @include(if: $b) { name } }"); + assert_eq!(fields(&operation.data), ["shop?: Shop!"]); + assert_eq!(fields(child(&operation.data, "shop")), ["name: String!"]); +} + +#[test] +fn the_same_key_with_other_arguments_needs_an_alias() { + assert_eq!( + refusal("{ a: product(id: \"1\") { title } a: product(id: \"2\") { handle } }"), + "`a` is selected twice with different arguments (`(id: \"1\")` and `(id: \"2\")`); give one of them an alias (line 1, column 33)" + ); + // The same arguments, in another order, merge. + check( + "{ orders(first: 1, reverse: true) { nodes { id } } orders(reverse: true, first: 1) { nodes { name } } }", + ); + assert_eq!( + refusal("{ product(id: \"1\", id: \"2\") { title } }"), + "Field `QueryRoot.product` is given the argument `id` twice (line 1, column 3)" + ); +} + +/// Arguments compare as Shopify (GraphQL Ruby) compares them: by kind and +/// value, input fields in the order of the text. +#[test] +fn arguments_compare_by_kind_value_and_order() { + let twice = |left: &str, right: &str| { + format!( + "mutation {{ x: flowTriggerReceive(handle: \"h\", payload: {left}) {{ userErrors {{ message }} }} x: flowTriggerReceive(handle: \"h\", payload: {right}) {{ userErrors {{ field }} }} }}" + ) + }; + for (left, right) in [ + ("1", "1.0"), + ("1.0", "-0.0"), + ("0.0", "-0.0"), + ("\"A\"", "A"), + ("\"1\"", "1"), + ("true", "\"true\""), + ("null", "\"null\""), + ("[1]", "1"), + ("[1, 2]", "[2, 1]"), + ("{a: 1}", "{a: 1.0}"), + ("{a: 1}", "{a: 1, b: 2}"), + ("{a: [1]}", "{a: 1}"), + ("{a: \"x\"}", "{a: x}"), + ] { + let refused = refusal(&twice(left, right)); + assert!( + refused.contains("`x` is selected twice with different arguments"), + "{left} / {right}: {refused}" + ); + } + // Written alike: the same value. + for (left, right) in [ + ("1.0", "1.00"), + ("1.0", "10e-1"), + ("\"abc\"", "\"\"\"abc\"\"\""), + ("\"\\u0041\"", "\"A\""), + ("{a: 1, b: [{c: 2, d: 3}]}", "{a: 1, b: [{c: 2, d: 3}]}"), + ] { + check(&twice(left, right)); + } + // The fields of an input object in another order: Shopify refuses it. + for (left, right) in [ + ("{a: 1, b: 2}", "{b: 2, a: 1}"), + ("{n: {a: 1, b: 2}}", "{n: {b: 2, a: 1}}"), + ("[{a: 1, b: 2}]", "[{b: 2, a: 1}]"), + ] { + let refused = refusal(&twice(left, right)); + assert!( + refused.contains( + "`x` is selected twice with the fields of an input object in another order" + ), + "{left} / {right}: {refused}" + ); + } + // An argument given or left out, as `null`. + assert!( + refusal( + "mutation { x: flowTriggerReceive(handle: \"h\", payload: null) { userErrors { message } } x: flowTriggerReceive(handle: \"h\") { userErrors { field } } }" + ) + .contains("different arguments (`(handle: \"h\", payload: null)` and `(handle: \"h\")`)") + ); + // The messages write each value with its kind. + assert!( + refusal(&twice("{a: 1}", "{a: 1.0}")).contains( + "(`(handle: \"h\", payload: {a: 1})` and `(handle: \"h\", payload: {a: 1.0})`)" + ) + ); +} + +/// The order of input fields is read on the text at the position the parser +/// gives: tabs, `\r\n`, comments, block strings and other characters before +/// the fields do not throw it off. +#[test] +fn the_order_of_input_fields_is_found_after_any_text() { + let field = |payload: &str| { + format!( + "x: flowTriggerReceive(handle: \"h\", payload: {payload}) {{ userErrors {{ message }} }}" + ) + }; + let same = field("{a: 1, b: \"é\"}"); + let other = field("{b: \"é\", a: 1}"); + for before in [ + "\t\t", + "\r\n\t# a comment ending in CRLF\r\n ", + "# é\n\u{feff}", + "y: flowTriggerReceive(handle: \"\"\"line\nanother é\r\n\"\"\", payload: \"é\\\"\") { userErrors { message } }\n\t", + "z: flowTriggerReceive(handle: \"ü\", payload: [\"\\u00e9\", {c: 1}]) { userErrors { message } } ", + ] { + check(&format!( + "mutation {{ {before}{same}\r\n\t{before}{same} }}" + )); + let refused = refusal(&format!("mutation {{ {before}{same}\n\t{before}{other} }}")); + assert!( + refused.contains("in another order"), + "{before:?}: {refused}" + ); + } + // Through an alias and a fragment. + check(&format!( + "mutation {{ ...F {same} }} fragment F on Mutation {{\t{same} }}" + )); +} + +/// An alias spelled like its field is still an alias: the arguments after it +/// are read for the order of their input fields (GraphQL Ruby refuses this +/// operation with `fieldConflict`). +#[test] +fn an_alias_spelled_like_its_field_keeps_the_order_of_input_fields() { + let refused = refusal( + "mutation { draftOrderCreate:draftOrderCreate(input:{note:\"x\" tags:[\"y\"]}){draftOrder{id}} draftOrderCreate:draftOrderCreate(input:{tags:[\"y\"] note:\"x\"}){draftOrder{id}} }", + ); + assert!( + refused.contains( + "`draftOrderCreate` is selected twice with the fields of an input object in another order" + ), + "{refused}" + ); + // In the same order, with spaces around the colon or none: one field. + check( + "mutation { draftOrderCreate : draftOrderCreate(input:{note:\"x\" tags:[\"y\"]}){draftOrder{id}} draftOrderCreate:draftOrderCreate(input:{note:\"x\" tags:[\"y\"]}){draftOrder{id}} }", + ); + // The alias of one, the bare name of the other. + let refused = refusal( + "mutation { draftOrderCreate(input:{note:\"x\" tags:[\"y\"]}){draftOrder{id}} draftOrderCreate:draftOrderCreate(input:{tags:[\"y\"] note:\"x\"}){draftOrder{id}} }", + ); + assert!(refused.contains("in another order"), "{refused}"); +} + +#[test] +fn directives_come_from_the_schema() { + // Shopify's `@idempotent`, on a mutation field. + check( + "mutation($key: String!) { + inventorySetQuantities(input: { name: \"available\", reason: \"correction\", quantities: [] }) @idempotent(key: $key) { + userErrors { message } + } + }", + ); + assert_eq!( + refusal("{ shop @inclde(if: true) { name } }"), + "The schema has no directive `@inclde` (did you mean `@include`?) (line 1, column 8)" + ); + assert_eq!( + refusal("query Q @include(if: true) { shop { name } }"), + "`@include` cannot be written on a query (line 1, column 9)" + ); + assert_eq!( + refusal("{ shop @include(if: true, unless: false) { name } }"), + "`@include` has no argument `unless` (line 1, column 8)" + ); + assert_eq!( + refusal("{ shop @include(if: true) @include(if: false) { name } }"), + "`@include` is written twice at the same place (line 1, column 27)" + ); + assert_eq!( + refusal("{ shop @skip { name } }"), + "`@skip` requires the argument `if: Boolean!` (line 1, column 8)" + ); + assert_eq!( + refusal("query($flag: String!) { shop { name @include(if: $flag) } }"), + "Variable `$flag` of type `String!` cannot be used for argument `if` of `@include`, which expects `Boolean!` (line 1, column 37)" + ); +} + +/// FieldsInSetCanMerge: on two different object types, one key may name +/// different fields, or the same field with other arguments, as long as the +/// shapes of the answers agree. On the same type, or an interface, it may not. +#[test] +fn one_key_may_name_different_fields_on_different_object_types() { + let operation = check( + "query($id: ID!) { node(id: $id) { ... on Product { label: title } ... on Order { label: name } } }", + ); + assert_eq!(fields(child(&operation.data, "node")), ["label?: String!"]); + + // Same type of object below: their subfields merge. + let operation = check( + "query($id: ID!) { node(id: $id) { ...P ...O } } + fragment P on ProductVariant { owner: image { url } } + fragment O on Collection { owner: image { url } }", + ); + assert_eq!(fields(child(&operation.data, "node")), ["owner?: Image"]); + + let operation = check( + "query($id: ID!) { node(id: $id) { ... on Product { m: metafield(key: \"a\") { value } } ... on Order { m: metafield(key: \"b\") { value } } } }", + ); + assert_eq!(fields(child(&operation.data, "node")), ["m?: Metafield"]); + + // The same object type: the fields must be the same. + assert!( + refusal( + "query($id: ID!) { node(id: $id) { ... on Product { label: title } ... on Order { label: name } ... on Product { label: handle } } }" + ) + .contains("`label` is selected twice with different fields or types (`title: String!` and `handle: String!`)") + ); + // Shapes that differ, even on different types. + assert!( + refusal( + "query($id: ID!) { node(id: $id) { ... on Product { label: title } ... on Order { label: email } } }" + ) + .contains("`label` is selected twice with different fields or types") + ); +} + +/// Below two exclusive object types, only the shapes must agree, at every +/// depth: `a` may be `url` on one side and `originalSrc` on the other. +/// Where both sides can be in one answer, the fields must still match. +#[test] +fn keys_below_exclusive_object_types_may_name_different_fields() { + let operation = check( + "query($id: ID!) { node(id: $id) { ... on ProductVariant { x: image { a: url } } ... on Collection { x: image { a: originalSrc } } } }", + ); + let node = child(&operation.data, "node"); + assert_eq!(fields(node), ["x?: Image"]); + assert_eq!(fields(child(node, "x")), ["a: URL!"]); + + // Two levels down, the same. + check( + "query($id: ID!) { node(id: $id) { ... on Product { m: metafield(key: \"a\") { d: definition { n: name } } } ... on Order { m: metafield(key: \"b\") { d: definition { n: namespace } } } } }", + ); + + // The same object type on both sides: the subfields must match. + assert!( + refusal( + "query($id: ID!) { node(id: $id) { ... on ProductVariant { x: image { a: url } } ... on ProductVariant { x: image { a: originalSrc } } } }" + ) + .contains("`a` is selected twice with different fields or types (`url: URL!` and `originalSrc: URL!`)") + ); + // An interface on one side: both may be there. + assert!( + refusal( + "query($id: ID!) { node(id: $id) { ... on Node { x: id } ... on Product { x: handle } } }" + ) + .contains("`x` is selected twice") + ); + // Shapes still must agree below exclusive types. + assert!( + refusal( + "query($id: ID!) { node(id: $id) { ... on ProductVariant { x: image { a: url } } ... on Collection { x: image { a: altText } } } }" + ) + .contains("`a` is selected twice with different fields or types") + ); +} + +/// SameResponseShape: below two exclusive object types, one key may name +/// fields of different object types when what is selected below has the +/// same shape. The subfields of both merge, each conditional unless both +/// select it. +#[test] +fn keys_below_exclusive_object_types_may_name_fields_of_different_types() { + let operation = check( + "{ nodes(ids: []) { + ... on Product { price: priceRangeV2 { value: minVariantPrice { amount currencyCode } } } + ... on Order { price: totalPriceSet { value: shopMoney { amount currencyCode } } } + } }", + ); + let nodes = child(&operation.data, "nodes"); + assert_eq!(fields(nodes), ["price?: ProductPriceRangeV2!"]); + let price = child(nodes, "price"); + assert_eq!(price.types, ["ProductPriceRangeV2", "MoneyBag"]); + assert_eq!(fields(price), ["value: MoneyV2!"]); + assert_eq!( + fields(child(price, "value")), + ["amount: Decimal!", "currencyCode: CurrencyCode!"] + ); + + // A subfield one side selects alone is conditional. + let operation = check( + "{ nodes(ids: []) { + ... on Product { price: priceRangeV2 { value: minVariantPrice { amount } min: minVariantPrice { amount } } } + ... on Order { price: totalPriceSet { value: shopMoney { amount currencyCode } } } + } }", + ); + let price = child(child(&operation.data, "nodes"), "price"); + assert_eq!(fields(price), ["value: MoneyV2!", "min?: MoneyV2!"]); + assert_eq!( + fields(child(price, "value")), + ["amount: Decimal!", "currencyCode?: CurrencyCode!"] + ); + + // Both nullable. + check( + "query($id: ID!) { node(id: $id) { + ... on Product { p: compareAtPriceRange { v: maxVariantCompareAtPrice { amount } } } + ... on Order { p: totalDiscountsSet { v: shopMoney { amount } } } + } }", + ); +} + +/// What does not have the same shape stays refused, at any depth: false +/// accepts are worse than false refusals. +#[test] +fn keys_of_different_types_need_the_same_shape() { + let refused = |source: &str, expected: &str| { + let refused = refusal(source); + assert!(refused.contains(expected), "{source}\n{refused}"); + }; + let node = |product: &str, order: &str| { + format!( + "query($id: ID!) {{ node(id: $id) {{ ... on Product {{ {product} }} ... on Order {{ {order} }} }} }}" + ) + }; + // A leaf of another scalar, or of another enum, below. + refused( + &node( + "p: priceRangeV2 { v: minVariantPrice { amount } }", + "p: totalPriceSet { v: shopMoney { amount: currencyCode } }", + ), + "`amount` is selected twice with different fields or types (`amount: Decimal!` and `currencyCode: CurrencyCode!`)", + ); + // A leaf on one side, subfields on the other. + refused( + &node( + "p: seo { t: title }", + "p: totalPriceSet { t: shopMoney { amount } }", + ), + "`t` is selected twice with different fields or types (`title: String` and `shopMoney: MoneyV2!`)", + ); + refused( + &node("p: title", "p: totalPriceSet { shopMoney { amount } }"), + "`p` is selected twice with different fields or types (`title: String!` and `totalPriceSet: MoneyBag!`)", + ); + // Non-null on one side only. + refused( + &node( + "p: priceRangeV2 { v: minVariantPrice { amount } }", + "p: totalDiscountsSet { v: shopMoney { amount } }", + ), + "`p` is selected twice with different fields or types (`priceRangeV2: ProductPriceRangeV2!` and `totalDiscountsSet: MoneyBag`)", + ); + // A list on one side only. + refused( + &node( + "p: options { name }", + "p: totalPriceSet { name: shopMoney { amount } }", + ), + "`p` is selected twice with different fields or types (`options: [ProductOption!]!` and `totalPriceSet: MoneyBag!`)", + ); + // The same parent type: the same field, whatever the types. + refused( + "query($id: ID!) { node(id: $id) { ... on Product { p: priceRangeV2 { v: maxVariantPrice { amount } } } ... on Product { p: compareAtPriceRange { v: maxVariantCompareAtPrice { amount } } } } }", + "`p` is selected twice with different fields or types", + ); + // An interface on one side: both may be there. + refused( + "query($id: ID!) { node(id: $id) { ... on HasMetafields { p: metafield(key: \"a\") { id } } ... on Product { p: featuredMedia { id } } } }", + "`p` is selected twice with different fields or types", + ); + // The same field named on two places must be selected the same way below. + refused( + &node( + "p: priceRangeV2 { v: minVariantPrice { amount } }", + "p: totalPriceSet { v: shopMoney { amount } v: presentmentMoney { amount } }", + ), + "`v` is selected twice with different fields or types (`shopMoney: MoneyV2!` and `presentmentMoney: MoneyV2!`)", + ); +} + +/// A field of an object type needs subfields at every place it is selected, +/// a leaf at none. +#[test] +fn every_place_of_a_field_selects_subfields_or_none() { + assert_eq!( + refusal("{ shop { name } shop }"), + "Field `shop` has the type `Shop!`: select the subfields you need, `shop { … }` (line 1, column 17)" + ); + assert_eq!( + refusal("{ shop { name name { x } } }"), + "Field `name` has the type `String!`, which has no subfields (line 1, column 15)" + ); + assert_eq!( + refusal( + "query($id: ID!) { node(id: $id) { ... on Product { p: seo { title } } ... on Order { p: totalPriceSet } } }" + ), + "Field `totalPriceSet` has the type `MoneyBag!`: select the subfields you need, `totalPriceSet { … }` (line 1, column 86)" + ); +} diff --git a/crates/shopify_api_graphql/tests/bulk.rs b/crates/shopify_api_graphql/tests/bulk.rs new file mode 100644 index 0000000..cc08df1 --- /dev/null +++ b/crates/shopify_api_graphql/tests/bulk.rs @@ -0,0 +1,338 @@ +//! Bulk operations: the rules checked on top of `analyze`, the text a bulk +//! query sends and where its lines go. + +use std::sync::OnceLock; + +use shopify_api_graphql::bulk::{ + Argument, BulkQuery, Connection, Part, ValuePart, analyze_bulk_query, check_bulk_mutation, + query_items, +}; +use shopify_api_graphql::{FieldBase, Schema, analyze}; + +/// A small schema: connections of `Thing`s, an input object that holds an +/// enum and itself, a `JSON` argument. +const SCHEMA: &str = r#"{"format":2,"apiVersion":"2026-10","query":"QueryRoot","mutation":"Mutation","types":{ +"QueryRoot":{"o":{"f":{ + "things":["ThingConnection!",{"filter":"Filter","tags":"[Color!]","data":"JSON","first":"Int","q":"String","sort":"Color"}], + "thing":["Thing",{"id":"ID!"}] +}}}, +"Mutation":{"o":{"f":{"make":["MakePayload",{"id":"ID!","filter":"Filter"}]}}}, +"MakePayload":{"o":{"f":{"a":"ThingConnection!","b":"ThingConnection!","thing":"Thing"}}}, +"Node":{"n":{"f":{"id":"ID!"},"t":["Thing"]}}, +"Thing":{"o":{"f":{"id":"ID!","name":"String","parts":["ThingConnection!",{"q":"String"}],"tags":"[Color!]"},"t":["Node"]}}, +"ThingConnection":{"o":{"f":{"edges":"[ThingEdge!]!","nodes":"[Thing!]!","pageInfo":"PageInfo!"}}}, +"ThingEdge":{"o":{"f":{"node":"Thing!","cursor":"String!"}}}, +"PageInfo":{"o":{"f":{"hasNextPage":"Boolean!"}}}, +"Filter":{"i":{"color":"Color","nested":"Filter","name":"String","colors":"[Color!]"}}, +"Color":{"e":["RED","BLUE"]}, +"ID":"s","String":"s","Boolean":"s","Int":"s","Float":"s","JSON":"s" +}}"#; + +fn schema() -> &'static Schema { + static SCHEMA_ONCE: OnceLock = OnceLock::new(); + SCHEMA_ONCE.get_or_init(|| Schema::from_json(SCHEMA).unwrap()) +} + +fn bulk(source: &str) -> BulkQuery { + let operation = analyze(schema(), source).unwrap_or_else(|error| panic!("{error}")); + analyze_bulk_query(schema(), source, &operation).unwrap_or_else(|error| panic!("{error}")) +} + +fn refusal(source: &str) -> String { + let operation = analyze(schema(), source).unwrap_or_else(|error| panic!("{error}")); + let refused = match operation.kind { + shopify_api_graphql::OperationKind::Query => { + analyze_bulk_query(schema(), source, &operation).err() + } + shopify_api_graphql::OperationKind::Mutation => { + check_bulk_mutation(schema(), source, &operation).err() + } + }; + refused.expect("refused").to_string() +} + +fn text(parts: &[Part]) -> String { + parts + .iter() + .map(|part| match part { + Part::Text(text) => text.clone(), + _ => "(…)".to_string(), + }) + .collect() +} + +#[test] +fn the_text_keeps_constants_and_sets_variables_apart() { + let query = bulk( + r#"query Things($filter: Filter, $q: String = "x \"y\"", $named: Boolean!) { + things(filter: $filter, q: $q, sort: RED) { edges { node { id name @include(if: $named) } } } + }"#, + ); + assert_eq!( + text(&query.parts), + "query Things { things(…) { edges { node { id name @include(…) } } } }" + ); + let Part::Arguments(arguments) = &query.parts[1] else { + panic!("arguments"); + }; + assert_eq!( + named(arguments), + [ + ("filter", &ValuePart::Variable("filter".into())), + ("q", &ValuePart::Variable("q".into())), + ("sort", &ValuePart::Text("RED".into())), + ] + ); + assert_eq!(query.defaults["q"], r#""x \"y\"""#); +} + +fn named(arguments: &[Argument]) -> Vec<(&str, &ValuePart)> { + arguments + .iter() + .map(|argument| (argument.name.as_str(), &argument.value)) + .collect() +} + +#[test] +fn constants_are_written_back_as_graphql() { + let query = bulk( + r#"{ things(filter: {name: """block "quoted" +text""", colors: [RED, BLUE], nested: null}, q: "$q stays", sort: null) { edges { node { id } } } }"#, + ); + assert_eq!( + text(&query.parts), + r#"{ things(filter: {colors: [RED, BLUE], name: "block \"quoted\"\ntext", nested: null}, q: "$q stays", sort: null) { edges { node { id } } } }"# + ); +} + +#[test] +fn variables_deep_in_values_are_set_apart_with_their_place() { + let query = bulk( + "query($c: Color!, $n: String) { things(filter: {colors: [RED, $c], nested: {name: $n}}) { edges { node { id } } } }", + ); + let Part::Arguments(arguments) = &query.parts[1] else { + panic!("arguments"); + }; + let ValuePart::Object(fields) = &arguments[0].value else { + panic!("an object"); + }; + assert_eq!(fields[0].name, "colors"); + assert_eq!( + fields[0].value, + ValuePart::List(vec![ + ValuePart::Text("RED".into()), + ValuePart::Variable("c".into()) + ]) + ); + assert_eq!(fields[1].name, "nested"); + assert!( + matches!(&fields[1].value, ValuePart::Object(nested) if nested[0].value == ValuePart::Variable("n".into())) + ); +} + +#[test] +fn connections_become_lists_of_their_nodes() { + let query = bulk( + "{ things { edges { node { id name parts(q: \"x\") { edges { node { id parts { edges { node { name } } } } } } } } } }", + ); + assert_eq!(shape(&query.connections), "parts: Thing [parts: Thing []]"); + let parts = query + .item + .fields + .iter() + .find(|field| field.key == "parts") + .unwrap(); + assert!(parts.connection); + assert_eq!(parts.ty.to_string(), "[Thing!]!"); + let FieldBase::Object(nodes) = &parts.base else { + panic!("an object"); + }; + let nested = nodes + .fields + .iter() + .find(|field| field.key == "parts") + .unwrap(); + assert!(nested.connection); + // One connection per parent: no `__typename` is needed. + assert!(!text(&query.parts).contains("__typename")); +} + +/// `key: Types [nested]` of each connection. +fn shape(connections: &[Connection]) -> String { + connections + .iter() + .map(|connection| { + format!( + "{}: {} [{}]", + connection.key, + connection.types.join(" "), + shape(&connection.connections) + ) + }) + .collect::>() + .join(", ") +} + +#[test] +fn strings_the_parser_misreads_are_refused() { + let escape = "This string would not reach Shopify as written: the GraphQL parser this crate uses reads it otherwise, and a bulk query is sent as the text it read. Write `\\u0008` rather than `\\b`"; + let block = "This string would not reach Shopify as written: the GraphQL parser this crate uses reads it otherwise, and a bulk query is sent as the text it read. Write it as a quoted string, with escapes"; + assert_eq!( + refusal(r#"{ things(q: "a\bb") { edges { node { id } } } }"#), + format!("{escape} (line 1, column 13)") + ); + assert_eq!( + refusal("query($q: String = \"\\b\") { things(q: $q) { edges { node { id } } } }"), + format!("{escape} (line 1, column 20)") + ); + assert_eq!( + refusal("{ things(q: \"\"\"a\rb\"\"\") { edges { node { id } } } }"), + format!("{block} (line 1, column 13)") + ); + assert_eq!( + refusal("{ things(q: \"\"\"\n\u{a0}a\n\u{a0}b\"\"\") { edges { node { id } } } }"), + format!("{block} (line 1, column 13)") + ); + // Lines indented with U+00A0 (two bytes) and U+2003 (three bytes) make + // `graphql-parser` panic: refused before it reads them, bulk or not. + let indent = "This block string indents its lines with different Unicode whitespace, which the GraphQL parser this crate uses cannot read. Indent it with spaces or tabs, or write it as a quoted string"; + for source in [ + "{ things(q: \"\"\"\n\u{a0}a\n\u{2003}b\"\"\") { edges { node { id } } } }", + "{ thing(id: \"\"\"\n\u{2003}a\n\u{a0}b\"\"\") { id } }", + ] { + assert_eq!( + analyze(schema(), source).unwrap_err().to_string(), + format!("{indent} (line 1, column 13)"), + "{source}" + ); + } + // In a comment, a `\b` is nothing. + bulk("# \"\\b\"\n{ things(q: \"\\u0008\") { edges { node { id } } } }"); + // `\u{…}` and surrogate pairs do not parse. + for source in [ + r#"{ things(q: "\u{1F600}") { edges { node { id } } } }"#, + r#"{ things(q: "\uD83D\uDE00") { edges { node { id } } } }"#, + ] { + assert!(analyze(schema(), source).is_err(), "{source}"); + } +} + +#[test] +fn another_field_aliased_id_is_refused_beside_a_nested_connection() { + let message = "`id: name` is refused on the nodes of `things`, which have the nested connection `parts`: each nested line is placed under its parent by the `id` of that parent. Give `name` another alias"; + assert_eq!( + refusal("{ things { edges { node { id: name parts { edges { node { id } } } } } } }"), + format!("{message} (line 1, column 27)") + ); + assert_eq!( + refusal( + "{ things { edges { node { ...F parts { edges { node { id } } } } } } } fragment F on Thing { id: name }" + ), + format!("{message} (line 1, column 94)") + ); + // The analysis refuses two fields under one key before the bulk rules. + let error = analyze( + schema(), + "{ things { edges { node { id id: name parts { edges { node { id } } } } } } }", + ) + .unwrap_err(); + assert!(error.message.contains("`id` is selected twice"), "{error}"); + // Without a nested connection, `id` may name any field. + bulk("{ things { edges { node { id: name parts: name } } } }"); +} + +#[test] +fn siblings_that_may_return_one_type_are_refused() { + assert_eq!( + refusal( + "{ things { edges { node { id a: parts { edges { node { id } } } b: parts { edges { node { id } } } } } } }" + ), + "`a` and `b`, connections of each node of `things`, may both return `Thing`: their lines in the results could not be told apart. Query one of them in another bulk query (line 1, column 65)" + ); +} + +#[test] +fn json_variables_are_refused() { + assert_eq!( + refusal("query($d: JSON) { things(data: $d) { edges { node { id } } } }"), + "Variable `$d` may hold a `JSON` value, which a bulk query cannot take: Shopify takes no variables for a bulk query, and this crate writes them into its text as GraphQL literals (line 1, column 7)" + ); +} + +#[test] +fn the_rules_of_shopify_are_refusals() { + for (source, message) in [ + ( + "{ thing(id: \"1\") { id parts { edges { node { id } } } } }", + "The top-level field of a bulk query is a connection: `thing` is `Thing`. Run it as an ordinary query, or select a connection such as `products` (line 1, column 3)", + ), + ( + "{ things { edges { cursor node { id } } } }", + "A connection of a bulk query selects `edges { node { … } }` and nothing else, as Shopify documents it (`things`): `cursor` is refused beside `node` (line 1, column 20)", + ), + ( + "{ things { edges { n: node { id } } } }", + "A connection of a bulk query selects `edges { node { … } }` and nothing else, as Shopify documents it (`things`): write `node`, without alias, arguments or directives (line 1, column 20)", + ), + ( + "{ things { edges { node { id parts @include(if: true) { edges { node { id } } } } } } }", + "A connection of a bulk query cannot have directives such as `@include`: Shopify writes its nodes on lines of their own (line 1, column 36)", + ), + ( + "{ things { edges { node { name parts { edges { node { id } } } } } } }", + "The nodes of `things` have the nested connection `parts`: select their `id`, without an alias or a directive, in this `node { … }`. Shopify refuses the query otherwise, and places each nested line under its parent by that `id` (line 1, column 20)", + ), + ( + "{ things { edges { node { id @include(if: true) parts { edges { node { id } } } } } } }", + "The nodes of `things` have the nested connection `parts`: select their `id`, without an alias or a directive, in this `node { … }`. Shopify refuses the query otherwise, and places each nested line under its parent by that `id` (line 1, column 20)", + ), + ( + "{ things { edges { node { id __typename: name } } } }", + "`__typename` cannot be an alias in a bulk query: the lines of its results hold `__parentId`, and `_shopifyApiTypename` where this crate selects `__typename` to place them (line 1, column 30)", + ), + ( + "{ _shopifyApiTypename: things { edges { node { id } } } }", + "`_shopifyApiTypename` cannot be an alias in a bulk query: the lines of its results hold `__parentId`, and `_shopifyApiTypename` where this crate selects `__typename` to place them (line 1, column 3)", + ), + ( + "{ __things: things { edges { node { id } } } }", + "`__things` cannot be an alias in a bulk query: the lines of its results hold `__parentId`, and `_shopifyApiTypename` where this crate selects `__typename` to place them (line 1, column 3)", + ), + ( + "mutation { make(id: \"1\") { a { edges { node { id } } } b { edges { node { id } } } } }", + "The mutation of a bulk operation selects one connection at most (`a`), Shopify's limit: `b` is a second one (line 1, column 56)", + ), + ( + "mutation { ...M } fragment M on Mutation { make(id: \"1\") { thing { id } } }", + "A bulk mutation selects one top-level field, not a fragment (line 1, column 15)", + ), + ] { + assert_eq!(refusal(source), message, "{source}"); + } + // One connection in a mutation, at any depth. + let source = "mutation { make(id: \"1\") { a { edges { node { id } } } thing { id } } }"; + let operation = analyze(schema(), source).unwrap(); + check_bulk_mutation(schema(), source, &operation).unwrap(); +} + +#[test] +fn the_enums_of_input_objects_are_described_for_the_variables() { + let source = "query($filter: Filter, $tags: [Color!], $q: String) { things(filter: $filter, tags: $tags, q: $q) { edges { node { id } } } }"; + let operation = analyze(schema(), source).unwrap(); + let query = analyze_bulk_query(schema(), source, &operation).unwrap(); + let code = query_items(schema(), &operation, &query, "e::quote!(::shopify_api)).to_string(); + // `Filter` holds an enum, a list of them and itself; `name` holds none. + assert!( + code.contains( + "static __SHOPIFY_API_BULK_INPUT_Filter : [(& str , :: shopify_api :: __private :: bulk :: BulkType) ; 3usize] = [(\"color\" , :: shopify_api :: __private :: bulk :: BulkType :: Enum) , (\"colors\" , :: shopify_api :: __private :: bulk :: BulkType :: List (& :: shopify_api :: __private :: bulk :: BulkType :: Enum)) , (\"nested\" , :: shopify_api :: __private :: bulk :: BulkType :: Input (& __SHOPIFY_API_BULK_INPUT_Filter))]" + ), + "{code}" + ); + assert!(code.contains("name : \"tags\" , ty : :: shopify_api :: __private :: bulk :: BulkType :: List (& :: shopify_api :: __private :: bulk :: BulkType :: Enum)"), "{code}"); + assert!( + code.contains( + "name : \"q\" , ty : :: shopify_api :: __private :: bulk :: BulkType :: Plain" + ), + "{code}" + ); +} diff --git a/crates/shopify_api_graphql/tests/internal_schema.rs b/crates/shopify_api_graphql/tests/internal_schema.rs new file mode 100644 index 0000000..c327b38 --- /dev/null +++ b/crates/shopify_api_graphql/tests/internal_schema.rs @@ -0,0 +1,101 @@ +//! `shopify_api` checks its own operations, `graphql/operations/*.graphql`, +//! against `graphql/internal.schema.json`: the test schema cut down to them. +//! `SHOPIFY_API_BLESS=1` (`mise run schema:internal`) writes it again. + +use std::path::{Path, PathBuf}; + +use shopify_api_graphql::{FieldBase, Schema, analyze}; + +fn runtime_crate() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../shopify_api/graphql") +} + +#[test] +fn the_internal_schema_is_cut_down_to_the_operations_of_shopify_api() { + let dir = runtime_crate(); + let full = Schema::from_json(&std::fs::read_to_string(dir.join("admin.schema.json")).unwrap()) + .unwrap(); + let mut files: Vec = std::fs::read_dir(dir.join("operations")) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| { + path.extension() + .is_some_and(|extension| extension == "graphql") + }) + .collect(); + files.sort(); + let operations: Vec = files + .iter() + .map(|file| std::fs::read_to_string(file).unwrap()) + .collect(); + let operations: Vec<&str> = operations.iter().map(String::as_str).collect(); + assert!(operations.len() >= 10); + + let internal = full.restricted_to(&operations).unwrap(); + for (file, operation) in files.iter().zip(&operations) { + assert_eq!( + analyze(&internal, operation).unwrap(), + analyze(&full, operation).unwrap(), + "{}", + file.display() + ); + } + assert!(internal.types.len() < full.types.len() / 10); + + let path = dir.join("internal.schema.json"); + let json = internal.to_json(); + if std::env::var_os("SHOPIFY_API_BLESS").is_some() { + std::fs::write(&path, &json).unwrap(); + } + let written = std::fs::read_to_string(&path).unwrap_or_default(); + assert!( + written == json, + "{} is not the schema of the operations: run `mise run schema:internal`", + path.display() + ); +} + +#[test] +fn a_restricted_schema_refuses_what_it_left_out() { + let dir = runtime_crate(); + let full = Schema::from_json(&std::fs::read_to_string(dir.join("admin.schema.json")).unwrap()) + .unwrap(); + let internal = full.restricted_to(&["{ shop { name } }"]).unwrap(); + assert!(analyze(&internal, "{ shop { name } }").is_ok()); + let error = analyze(&internal, "{ shop { email } }").unwrap_err(); + assert!( + error.to_string().contains("has no field `email`"), + "{error}" + ); + assert!(full.restricted_to(&["{ shop { nam } }"]).is_err()); +} + +/// Cutting the schema keeps every possible type of an interface or a union: +/// a fragment on one of them stays conditional, and its fields optional. +#[test] +fn a_restricted_schema_keeps_fragments_on_abstract_types_conditional() { + let dir = runtime_crate(); + let full = Schema::from_json(&std::fs::read_to_string(dir.join("admin.schema.json")).unwrap()) + .unwrap(); + for query in [ + "query($id: ID!) { node(id: $id) { id ... on Product { title } } }", + "query($id: ID!) { node(id: $id) { id ...P } } fragment P on Product { title }", + ] { + let cut = full.restricted_to(&[query]).unwrap(); + let shape = analyze(&cut, query).unwrap(); + assert_eq!(shape, analyze(&full, query).unwrap(), "{query}"); + let FieldBase::Object(node) = &shape.data.fields[0].base else { + panic!("node is an object"); + }; + let title = node + .fields + .iter() + .find(|field| field.key == "title") + .unwrap(); + assert!(title.conditional, "{query}: {title:?}"); + + // Through JSON too, as `graphql!` reads it. + let reloaded = Schema::from_json(&cut.to_json()).unwrap(); + assert_eq!(analyze(&reloaded, query).unwrap(), shape, "{query}"); + } +} diff --git a/crates/shopify_api_graphql/tests/literal.rs b/crates/shopify_api_graphql/tests/literal.rs new file mode 100644 index 0000000..514278e --- /dev/null +++ b/crates/shopify_api_graphql/tests/literal.rs @@ -0,0 +1,736 @@ +//! Values written in Rust for input types, checked against the Shopify Admin +//! schema 2026-10: what is refused, with which message, and how what is +//! accepted is sent. + +use std::collections::BTreeMap; +use std::sync::OnceLock; + +use proc_macro2::{Ident, Span}; +use quote::quote; +use shopify_api_graphql::codegen::input_object_id; +use shopify_api_graphql::literal::{ + Expr, Field, For, List, Literals, Object, Value, VariableValue, +}; +use shopify_api_graphql::{Schema, TypeDef, analyze}; + +fn admin() -> &'static Schema { + static ADMIN: OnceLock = OnceLock::new(); + ADMIN.get_or_init(|| { + Schema::from_json(include_str!("../../shopify_api/graphql/admin.schema.json")).unwrap() + }) +} + +fn rust(text: &str) -> Value { + Value::Rust(Expr { + tokens: text.parse().unwrap(), + span: Span::call_site(), + }) +} + +fn ident(name: &str) -> Value { + Value::Ident(Ident::new(name, Span::call_site())) +} + +fn null() -> Value { + Value::Null(Span::call_site()) +} + +fn raw(text: &str) -> Value { + Value::Raw { + keyword: Span::call_site(), + value: Expr { + tokens: text.parse().unwrap(), + span: Span::call_site(), + }, + } +} + +/// An object; a name ending with `?` is `name?: value`. +fn object(fields: Vec<(&str, Value)>) -> Object { + Object { + span: Span::call_site(), + fields: fields + .into_iter() + .map(|(name, value)| Field { + name: name.trim_end_matches('?').to_string(), + name_span: Span::call_site(), + optional: name.ends_with('?').then(Span::call_site), + value, + }) + .collect(), + } +} + +fn list(items: Vec) -> Value { + Value::List(List { + span: Span::call_site(), + items, + rust: None, + }) +} + +/// The code of `input!(name { … })` and, after it, its warnings, or the +/// refusal. +fn input(name: &str, fields: Vec<(&str, Value)>) -> Result<(String, String), String> { + let mut literals = Literals::new(admin(), quote!(::shopify_api)); + let code = literals + .input_object(name, Span::call_site(), &object(fields)) + .map_err(|error| error.message)?; + let all = format!("{code} {}", literals.finish()); + Ok((code.to_string(), all)) +} + +fn refusal(name: &str, fields: Vec<(&str, Value)>) -> String { + match input(name, fields) { + Ok((code, _)) => panic!("accepted: {code}"), + Err(message) => message, + } +} + +#[test] +fn an_object_is_sent_field_by_field_in_its_order() { + let (code, items) = input( + "ProductUpdateInput", + vec![ + ("id", rust("product_id")), + ("title", rust("format!(\"{name} (promo)\")")), + ("status", ident("ACTIVE")), + ("descriptionHtml", null()), + ("vendor?", rust("new_vendor")), + ( + "seo", + Value::Object(object(vec![("title", rust("seo_title"))])), + ), + ( + "metafields", + Value::For(Box::new(For { + span: Span::call_site(), + pattern: quote!(m), + iterable: quote!(&rows), + filter: Some(quote!(!m.value.is_empty())), + item: Value::Object(object(vec![ + ("key", rust("&m.key")), + ("type", rust("\"single_line_text_field\"")), + ])), + })), + ), + ("tags", list(vec![rust("\"a\""), rust("tag")])), + ], + ) + .unwrap(); + let id = input_object_id("ProductUpdateInput"); + assert!( + code.starts_with(&format!( + ":: shopify_api :: __private :: InputObject :: < {id}u64 > :: __new (\"ProductUpdateInput\" , ({{" + )), + "{code}" + ); + // The items of `[for … => …]` are built in the loop, an argument: after + // the fields of the object. + let keys: Vec<&str> = code + .match_indices("literal :: Field (\"") + .chain(code.match_indices("literal :: Optional (\"")) + .map(|(at, matched)| { + let rest = &code[at + matched.len()..]; + &rest[..rest.find('"').unwrap()] + }) + .collect(); + assert_eq!( + keys, + [ + "id", + "title", + "status", + "descriptionHtml", + "seo", + "title", + "metafields", + "tags", + "key", + "type", + "vendor" + ] + ); + // The enum value is a string; `null` is `()`; the list is built in a loop. + assert!(code.contains("Field (\"status\" , \"ACTIVE\")"), "{code}"); + assert!(code.contains("Field (\"descriptionHtml\" , ())"), "{code}"); + assert!( + code.contains("for m in & rows { if ! m . value . is_empty ()"), + "{code}" + ); + // Each Rust expression goes through a trait that names its place. + assert!( + items.contains( + "message = \"`title` of `ProductUpdateInput` expects a `String`, not `{Self}`\"" + ), + "{items}" + ); + assert!( + items.contains("message = \"`vendor?:` takes an `Option` or a `shopify_api::Maybe` of a `String`, not `{Self}`\""), + "{items}" + ); + // The check of a scalar field takes the types of the scalar, not an + // `Option`, and says what to write for one. + assert!( + items.contains("note = \"`vendor?: value` takes an `Option`, `None` leaving the field out; `vendor: null` sends `null`\""), + "{items}" + ); +} + +#[test] +fn fields_are_checked_against_the_input_object() { + assert_eq!( + refusal( + "ProductUpdateInput", + vec![("id", rust("id")), ("titel", rust("title"))] + ), + "Input object `ProductUpdateInput` has no field `titel` (did you mean `title`?)" + ); + assert_eq!( + refusal( + "ProductUpdateInput", + vec![("title", rust("a")), ("title", rust("b"))] + ), + "The field `title` of `ProductUpdateInput` is given twice" + ); + assert_eq!( + refusal( + "MetafieldsSetInput", + vec![("namespace", rust("\"custom\""))] + ), + "Input object `MetafieldsSetInput` requires the fields `key: String!`, `ownerId: ID!` and `value: String!`: add them" + ); + assert_eq!( + refusal( + "MetafieldsSetInput", + vec![("ownerId", rust("id")), ("key", rust("key"))] + ), + "Input object `MetafieldsSetInput` requires the field `value: String!`: add it" + ); + // The fields of a nested object, and of the items of a list. + assert_eq!( + refusal( + "ProductUpdateInput", + vec![( + "metafields", + list(vec![Value::Object(object(vec![("kee", rust("k"))]))]) + )] + ), + "Input object `MetafieldInput` has no field `kee` (did you mean `key`?)" + ); +} + +#[test] +fn null_and_absence_follow_nullability_and_defaults() { + assert_eq!( + refusal( + "MetafieldsSetInput", + vec![ + ("ownerId", null()), + ("key", rust("k")), + ("value", rust("v")) + ] + ), + "`null` is not allowed for `ownerId` of `MetafieldsSetInput`, of type `ID!`" + ); + assert_eq!( + refusal( + "MetafieldsSetInput", + vec![ + ("ownerId?", rust("id")), + ("key", rust("k")), + ("value", rust("v")) + ] + ), + "`ownerId` of `MetafieldsSetInput` is required (`ID!`): it cannot be left out, so `?:` does not apply; write `ownerId: …`" + ); + assert_eq!( + refusal("ProductUpdateInput", vec![("vendor?", null())]), + "`vendor?: null` is `vendor: null`" + ); + assert_eq!( + refusal( + "ProductUpdateInput", + vec![("seo?", Value::Object(object(vec![])))] + ), + "`seo?:` takes a Rust expression, an `Option` or a `shopify_api::Maybe` whose `None` leaves the field out; write `seo: …` for this value" + ); + // Non-null with a default: `?:` takes an `Option`, not a `Maybe`. + let (_, items) = input( + "InventoryTransferCreateInput", + vec![("lineItems?", rust("line_items"))], + ) + .unwrap(); + assert!( + items.contains("`lineItems` of `InventoryTransferCreateInput` is non-null (`[InventoryTransferLineItemInput!]!`): `lineItems?:` takes an `Option`, not a `Maybe`, whose `Null` it refuses"), + "{items}" + ); + assert!( + items.contains("message = \"`lineItems?:` takes an `Option` of a list of `InventoryTransferLineItemInput`, built with `input!(InventoryTransferLineItemInput {{ … }})`, not `{Self}`\""), + "{items}" + ); +} + +#[test] +fn enum_values_are_checked_and_raw_is_only_for_enums() { + assert_eq!( + refusal("ProductUpdateInput", vec![("status", ident("ACTIV"))]), + "`ACTIV` is not a value of the enum `ProductStatus` (did you mean `ACTIVE`?): `status` of `ProductUpdateInput` takes `ACTIVE`, `ARCHIVED`, `DRAFT` or `UNLISTED`" + ); + assert_eq!( + refusal("ProductUpdateInput", vec![("status", ident("status"))]), + "`status` is not a value of the enum `ProductStatus`: `status` of `ProductUpdateInput` takes `ACTIVE`, `ARCHIVED`, `DRAFT` or `UNLISTED`; for a string known at run time, write `raw(status)`" + ); + assert_eq!( + refusal("ProductUpdateInput", vec![("status", rust("\"ACTIVE\""))]), + "`status` of `ProductUpdateInput` expects a value of the enum `ProductStatus`: write it bare, as `ACTIVE`, or `raw(…)` for a string known at run time" + ); + assert_eq!( + refusal("ProductUpdateInput", vec![("status?", rust("status"))]), + "`status` of `ProductUpdateInput` holds a value of the enum `ProductStatus`: for a string known at run time, write `status?: raw(…)`, with an `Option` of it" + ); + assert_eq!( + refusal("ProductUpdateInput", vec![("title", raw("title"))]), + "`raw(…)` is only for a value of an enum: `title` of `ProductUpdateInput` expects a `String`" + ); + assert_eq!( + refusal( + "CollectionSourceInclusionConditionProductStatusInput", + vec![("values", rust("statuses"))] + ), + "`values` of `CollectionSourceInclusionConditionProductStatusInput` expects a list of values of the enum `ProductStatus`: write them bare, `[ACTIVE, …]`, or `[for value in … => raw(value)]` for strings known at run time" + ); + let exemptions = refusal( + "CompanyLocationInput", + vec![ + ("name", rust("name")), + ("taxExemptions", list(vec![ident("NONE")])), + ], + ); + assert!( + exemptions.starts_with("`NONE` is not a value of the enum `TaxExemption`: an item of `taxExemptions` of `CompanyLocationInput` takes `CA_STATUS_CARD_EXEMPTION`, "), + "{exemptions}" + ); + assert!(exemptions.ends_with(" values)"), "{exemptions}"); + + let (code, _) = input( + "ProductUpdateInput", + vec![("status", raw("status")), ("id", rust("id"))], + ) + .unwrap(); + // `raw(…)` is an argument, evaluated where the caller wrote it. + assert!( + code.contains("Field (\"status\" , __shopify_api_value0)"), + "{code}" + ); + assert!( + code.contains(". build (:: shopify_api :: __private :: literal :: raw ((status)) , (id))"), + "{code}" + ); +} + +#[test] +fn a_value_has_the_form_of_its_type() { + assert_eq!( + refusal( + "ProductUpdateInput", + vec![("title", Value::Object(object(vec![("value", rust("v"))])))] + ), + "`title` of `ProductUpdateInput` expects a `String`, not an object" + ); + assert_eq!( + refusal("ProductUpdateInput", vec![("title", list(vec![rust("t")]))]), + "`title` of `ProductUpdateInput` expects a `String`, not a list" + ); + assert_eq!( + refusal( + "ProductUpdateInput", + vec![("metafields", Value::Object(object(vec![])))] + ), + "`metafields` of `ProductUpdateInput` expects a list of `MetafieldInput`, built with `input!(MetafieldInput { … })`, not an object" + ); + assert_eq!( + refusal( + "ProductCreateInput", + vec![("productOptions", list(vec![null()]))] + ), + "`null` is not allowed for an item of `productOptions` of `ProductCreateInput`, of type `OptionCreateInput!`" + ); +} + +#[test] +fn input_takes_an_input_object_of_the_schema() { + assert_eq!( + refusal("MetafieldSetInput", vec![]), + "The schema has no input object `MetafieldSetInput` (did you mean `MetafieldsSetInput`?)" + ); + assert_eq!( + refusal("Product", vec![]), + "`Product` is an object, not an input object: `input!` builds the input objects of the schema" + ); +} + +#[test] +fn deprecated_fields_and_enum_values_warn() { + let (_, items) = input("ProductVariantsBulkInput", vec![("barcode", rust("code"))]).unwrap(); + assert!( + items.contains("deprecated (note = \"`ProductVariantsBulkInput.barcode` is deprecated in the Shopify Admin API 2026-10: Use `barcodes` instead.\")"), + "{items}" + ); + let (_, items) = input( + "DeliveryCarrierCalculatedOptionDefinitionUpdateInput", + vec![("id", rust("id")), ("currency", ident("ANG"))], + ) + .unwrap(); + assert!( + items.contains("deprecated (note = \"`CurrencyCode.ANG` is deprecated in the Shopify Admin API 2026-10: Use `XCG` instead.\")"), + "{items}" + ); +} + +fn variable(source: &str, value: Value) -> Result { + let operation = analyze(admin(), source).unwrap(); + let mut literals = Literals::new(admin(), quote!(::shopify_api)); + literals + .variable(&operation.variables[0], &value) + .map_err(|error| error.message) +} + +#[test] +fn inline_variables_of_scalars_convert_as_before_and_others_are_literals() { + let converted = |value: VariableValue| match value { + VariableValue::Converted { ty, value } => format!("{ty} = {}", value.tokens), + VariableValue::Literal(code) => panic!("a literal: {code}"), + }; + let ids = "query($ids: [ID!]!) { nodes(ids: $ids) { id } }"; + assert_eq!( + converted( + variable( + "query($first: Int!) { products(first: $first) { nodes { id } } }", + rust("{ compute() }") + ) + .unwrap() + ), + ":: core :: primitive :: i64 = { compute () }" + ); + let array = Value::List(List { + span: Span::call_site(), + items: vec![ident("a"), rust("&b")], + rust: Some(Expr { + tokens: quote!([a, &b]), + span: Span::call_site(), + }), + }); + assert_eq!( + converted(variable(ids, array).unwrap()), + ":: std :: vec :: Vec < :: std :: string :: String > = [a , & b]" + ); + let sort = "query($sortKey: ProductSortKeys) { products(first: 1, sortKey: $sortKey) { nodes { id } } }"; + assert_eq!( + converted(variable(sort, raw("key")).unwrap()), + ":: core :: option :: Option < :: std :: string :: String > = key" + ); + assert!(matches!( + variable(sort, ident("TITLE")).unwrap(), + VariableValue::Literal(_) + )); + assert_eq!( + variable(sort, rust("key")).unwrap_err(), + "`$sortKey` expects a value of the enum `ProductSortKeys`: write it bare, as `CREATED_AT`, or `raw(…)` for a string known at run time" + ); + assert_eq!( + variable(ids, raw("id")).unwrap_err(), + "`raw(…)` is only for a value of an enum: `$ids` expects a list of `ID`" + ); + let metafields = "mutation($metafields: [MetafieldsSetInput!]!) { metafieldsSet(metafields: $metafields) { userErrors { message } } }"; + let VariableValue::Literal(code) = variable(metafields, rust("rows")).unwrap() else { + panic!("a literal"); + }; + assert!( + code.to_string().contains("Checks }) . build ((rows))"), + "{code}" + ); + assert_eq!( + variable(metafields, Value::Object(object(vec![]))).unwrap_err(), + "`$metafields` expects a list of `MetafieldsSetInput`, built with `input!(MetafieldsSetInput { … })`, not an object" + ); +} + +#[test] +fn input_object_ids_differ_for_every_input_object_of_the_schema() { + // FNV-1a: the same in every crate and every build. + assert_eq!(input_object_id(""), 0xcbf2_9ce4_8422_2325); + assert_eq!(input_object_id("a"), 0xaf63_dc4c_8601_ec8c); + let mut seen = BTreeMap::new(); + for (name, definition) in &admin().types { + if let TypeDef::Input { .. } = definition + && let Some(other) = seen.insert(input_object_id(name), name) + { + panic!("`{name}` and `{other}` have the same id"); + } + } + assert!(seen.len() > 500); +} + +/// Each Rust expression is checked, when it is built, for the scalar its +/// innermost type is: an `Int`, a `Float`, a non-null `JSON`, with or +/// without `?:`. +#[test] +fn each_expression_is_checked_for_its_scalar() { + let schema = Schema::from_json( + r#"{"format": 2, "apiVersion": "2026-10", "query": "Q", "types": { + "String": "s", "Int": "s", "Float": "s", "Boolean": "s", "JSON": "s", + "T": {"i": {"i": "Int!", "f": "[Float]", "j": "JSON!", "jd": "JSON!=", "jl": "[JSON!]", "jn": "JSON", "s": "String"}}, + "Q": {"o": {"f": {"echo": ["String", {"input": "T!"}]}}} + }}"#, + ) + .unwrap(); + let mut literals = Literals::new(&schema, quote!(::shopify_api)); + let code = literals + .input_object( + "T", + Span::call_site(), + &object(vec![ + ("i", rust("a")), + ("f", rust("b")), + ("j", rust("c")), + ("jd?", rust("d")), + ("jl", rust("e")), + ("jn", rust("f")), + ("s", rust("g")), + ]), + ) + .unwrap() + .to_string(); + let mut kinds: Vec<(usize, &str)> = ["literal :: leaf :: < ", "literal :: optional :: < "] + .iter() + .flat_map(|marker| code.match_indices(marker)) + .map(|(at, marker)| { + let kind = &code[at + marker.len() + "literal :: ".len()..]; + (at, &kind[..kind.find(' ').unwrap()]) + }) + .collect(); + kinds.sort_unstable(); + let kinds: Vec<&str> = kinds.into_iter().map(|(_, kind)| kind).collect(); + assert_eq!( + kinds, + ["Int", "Float", "Json", "Json", "Json", "MaybeJson", "Text"] + ); +} + +/// An integer literal outside of the 32 bits of `Int` is refused where an +/// `Int` is expected: a field, a `?:` value, an item, a variable. +#[test] +fn integer_literals_outside_of_int_are_refused() { + let refused = |fields: Vec<(&str, Value)>| refusal("DraftOrderLineItemInput", fields); + for (text, site) in [ + ( + "2_147_483_648_i64", + "`quantity` of `DraftOrderLineItemInput`", + ), + ( + "2_147_483_648i64", + "`quantity` of `DraftOrderLineItemInput`", + ), + ( + "0x1_0000_0000_i64", + "`quantity` of `DraftOrderLineItemInput`", + ), + ("-2147483649", "`quantity` of `DraftOrderLineItemInput`"), + ("0x8000_0000", "`quantity` of `DraftOrderLineItemInput`"), + ("(3000000000)", "`quantity` of `DraftOrderLineItemInput`"), + ( + "340282366920938463463374607431768211456", + "`quantity` of `DraftOrderLineItemInput`", + ), + ] { + assert_eq!( + refused(vec![("quantity", rust(text))]), + format!( + "The integer is outside the range of `Int`, a 32-bit integer, given for {site}" + ), + "{text}" + ); + } + let message = |site: &str| { + format!("The integer is outside the range of `Int`, a 32-bit integer, given for {site}") + }; + assert_eq!( + refusal( + "DraftOrderInput", + vec![( + "lineItems", + list(vec![Value::Object(object(vec![( + "quantity", + rust("-2_147_483_649") + )]))]) + )] + ), + message("`quantity` of `DraftOrderLineItemInput`") + ); + let first = "query($first: Int!) { products(first: $first) { nodes { id } } }"; + assert_eq!( + variable(first, rust("4_294_967_296_u64")).unwrap_err(), + message("`$first`") + ); + let schema = Schema::from_json( + r#"{"format": 2, "apiVersion": "2026-10", "query": "Q", "types": { + "Int": "s", "String": "s", + "T": {"i": {"l": "[Int!]", "m": "[[Int]]"}}, + "Q": {"o": {"f": {"echo": ["String", {"input": "T!"}]}}} + }}"#, + ) + .unwrap(); + for (field, value) in [ + ("l", rust("[1, 2_147_483_648]")), + ("l", list(vec![rust("1"), rust("2_147_483_648")])), + ("m", rust("[[1], [(-2_147_483_649)]]")), + ] { + let error = Literals::new(&schema, quote!(::shopify_api)) + .input_object("T", Span::call_site(), &object(vec![(field, value)])) + .unwrap_err(); + assert!( + error + .message + .starts_with("The integer is outside the range of `Int`"), + "{}", + error.message + ); + } + // At the bounds, computed, or in a form whose meaning depends on what a + // name resolves to: checked when the value is built. + assert!( + input( + "DraftOrderLineItemInput", + vec![ + ("quantity", rust("-2_147_483_648")), + ("grams?", rust("Some(1 << 40)")) + ] + ) + .is_ok() + ); + assert!( + input( + "DraftOrderLineItemInput", + vec![ + ("quantity", rust("Some(3_000_000_000)")), + ("grams?", rust("Some(3_000_000_000)")) + ] + ) + .is_ok() + ); + for value in ["vec![2_147_483_648]", "[2_147_483_648; 2]"] { + assert!( + Literals::new(&schema, quote!(::shopify_api)) + .input_object("T", Span::call_site(), &object(vec![("l", rust(value))])) + .is_ok(), + "{value}" + ); + } + assert!( + input( + "DraftOrderLineItemInput", + vec![("quantity", rust("0x7fff_ffff_i64"))] + ) + .is_ok() + ); + for text in [ + "0xffff_ffff_i32", + "2_147_483_648_i32", + "-129i8", + "256u8", + "0x1_0000_0000_usize", + ] { + assert!( + input("DraftOrderLineItemInput", vec![("quantity", rust(text))]).is_ok(), + "a literal its suffix's type cannot hold is checked when built: {text}" + ); + } + assert!( + input( + "DraftOrderLineItemInput", + vec![("quantity", rust("-2_147_483_648_i32"))] + ) + .is_ok() + ); +} + +/// A constant of the type of its place is written as it is, with nothing +/// to check; one of another type is checked, and refused by rustc. +#[test] +fn constants_are_written_in_place() { + let (code, _) = input( + "DraftOrderLineItemInput", + vec![ + ("quantity", rust("-12")), + ("title", rust("\"t\"")), + ("requiresShipping", rust("true")), + ( + "weight", + Value::Object(object(vec![ + ("unit", ident("GRAMS")), + ("value", rust("2.5")), + ])), + ), + ], + ) + .unwrap(); + assert!(!code.contains("Checks"), "{code}"); + for (field, value) in [ + ("quantity", "\"12\""), + ("quantity", "12i128"), + ("quantity", "1.5"), + ("title", "12"), + ("title", "b\"t\""), + ("requiresShipping", "1"), + ] { + let mut fields = vec![(field, rust(value))]; + if field != "quantity" { + fields.push(("quantity", rust("1"))); + } + let (code, _) = input("DraftOrderLineItemInput", fields).unwrap(); + assert!(code.contains("Checks"), "{field}: {value}"); + } +} + +#[test] +fn a_one_of_input_takes_exactly_one_field_not_null() { + let rule = "`ProductSetIdentifiers` is a oneOf input: give exactly one of `customId`, `handle` or `id`, not null"; + let (code, _) = input("ProductSetIdentifiers", vec![("handle", rust("handle"))]).unwrap(); + assert!(code.contains("\"handle\""), "{code}"); + input( + "ProductSetIdentifiers", + vec![("id", rust("\"gid://shopify/Product/1\""))], + ) + .unwrap(); + + assert_eq!(refusal("ProductSetIdentifiers", vec![]), rule); + assert_eq!( + refusal( + "ProductSetIdentifiers", + vec![("id", rust("id")), ("handle", rust("handle"))] + ), + format!("{rule}: `id` is given already") + ); + assert_eq!( + refusal("ProductSetIdentifiers", vec![("handle?", rust("handle"))]), + format!("{rule}: write `handle: …`, not `handle?:`") + ); + assert_eq!( + refusal("ProductSetIdentifiers", vec![("handle", null())]), + format!("{rule}: `handle: null` is not one") + ); + // The value of the field is checked as non-null: no `Option` nor `Maybe`. + let (_, items) = input("ProductSetIdentifiers", vec![("handle", rust("handle"))]).unwrap(); + assert!(!items.contains("or an `Option` of it"), "{items}"); + + // Nested, and as the value of a variable. + let source = "mutation($identifier: ProductSetIdentifiers, $input: ProductSetInput!) { productSet(identifier: $identifier, input: $input) { product { id } } }"; + let two = Value::Object(object(vec![("id", rust("id")), ("handle", rust("h"))])); + assert_eq!( + variable(source, two).unwrap_err(), + format!("{rule}: `id` is given already") + ); + let one = Value::Object(object(vec![("id", rust("id"))])); + variable(source, one).unwrap(); +} diff --git a/crates/shopify_api_macros/Cargo.toml b/crates/shopify_api_macros/Cargo.toml new file mode 100644 index 0000000..594ff1d --- /dev/null +++ b/crates/shopify_api_macros/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "shopify_api_macros" +description = "The `graphql!` macro of `shopify_api`: Shopify Admin GraphQL operations checked at compile time, with typed variables and results." +documentation = "https://docs.rs/shopify_api" +keywords = ["shopify", "graphql", "macros"] +categories = ["development-tools::procedural-macro-helpers", "api-bindings"] +readme = "README.md" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +include = ["src/**", "Cargo.toml", "README.md", "LICENSE.txt"] + +[lib] +proc-macro = true + +[dependencies] +shopify_api_graphql = { workspace = true, features = ["download"] } + +proc-macro2.workspace = true +quote.workspace = true +syn.workspace = true + +[lints] +workspace = true diff --git a/crates/shopify_api_macros/LICENSE.txt b/crates/shopify_api_macros/LICENSE.txt new file mode 120000 index 0000000..1ef648f --- /dev/null +++ b/crates/shopify_api_macros/LICENSE.txt @@ -0,0 +1 @@ +../../LICENSE.txt \ No newline at end of file diff --git a/crates/shopify_api_macros/README.md b/crates/shopify_api_macros/README.md new file mode 100644 index 0000000..2b13b08 --- /dev/null +++ b/crates/shopify_api_macros/README.md @@ -0,0 +1,7 @@ +# shopify_api_macros + +The `graphql!` and `input!` procedural macros of [`shopify_api`](https://crates.io/crates/shopify_api). +Use them through `shopify_api::graphql!` and `shopify_api::input!`, which +document them: the generated code refers to `::shopify_api`, or to the path +given with `crate = ::my_framework::shopify_api`, and does not compile +without it. diff --git a/crates/shopify_api_macros/src/lib.rs b/crates/shopify_api_macros/src/lib.rs new file mode 100644 index 0000000..3f34a81 --- /dev/null +++ b/crates/shopify_api_macros/src/lib.rs @@ -0,0 +1,1162 @@ +//! The `graphql!` and `input!` macros of `shopify_api`. Use them through +//! `shopify_api`, which re-exports and documents them. +#![forbid(unsafe_code)] + +mod value; + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::SystemTime; + +use proc_macro2::{Span, TokenStream}; +use quote::{format_ident, quote, quote_spanned}; +use shopify_api_graphql::bulk::{ + BulkQuery, ITEM_TYPE, analyze_bulk_query, check_bulk_mutation, query_items, template_ident, +}; +use shopify_api_graphql::codegen::{ + DATA_TYPE, data_types, deprecation_warning, variables_types, variables_types_for, +}; +use shopify_api_graphql::literal::{self, Literals, Value, VariableValue}; +use shopify_api_graphql::project::{cargo_home, may_download, metadata_snippet, project_schema}; +use shopify_api_graphql::{ + MINIMUM_API_VERSION, Operation, OperationKind, Schema, SchemaSource, TEST_SCHEMA_ENV, Variable, + analyze, is_supported_api_version, latest_api_version, schema_source, test_schema_applies, +}; +use syn::parse::{Parse, ParseStream}; +use syn::spanned::Spanned; +use syn::{Attribute, Ident, LitStr, Token, Visibility}; + +/// The schema of `shopify_api`'s own operations, relative to its `Cargo.toml`: +/// the Admin schema cut down to what they use. A crate that depends on +/// `shopify_api` selects a version for its operations, not for these. +const INTERNAL_SCHEMA_PATH: &str = "graphql/internal.schema.json"; + +/// Where the text of an operation comes from. +enum Source { + /// `"query { … }"`. + Literal(LitStr), + /// `file("graphql/orders.graphql")`, relative to the crate's `Cargo.toml`. + File(LitStr), + /// `bulk("…")` or `bulk(file("…"))`: a bulk query or a bulk mutation. + Bulk(Box), +} + +const SOURCE_FORM: &str = + "expected the GraphQL operation as a string literal, `file(\"path.graphql\")` or `bulk(…)`"; + +impl Source { + fn parse_text(input: ParseStream, bulk: bool) -> syn::Result { + let expected = if bulk { + "`bulk(…)` takes the operation as a string literal or `file(\"path.graphql\")`" + } else { + SOURCE_FORM + }; + if input.peek(Ident) && input.peek2(syn::token::Paren) { + let keyword: Ident = input.parse()?; + let content; + syn::parenthesized!(content in input); + if keyword == "file" { + let path: LitStr = content.parse()?; + if !content.is_empty() { + return Err(content.error("`file(…)` takes one path")); + } + return Ok(Self::File(path)); + } + if keyword == "bulk" && !bulk { + let source = Self::parse_text(&content, true)?; + if !content.is_empty() { + return Err(content.error("`bulk(…)` takes one operation")); + } + return Ok(Self::Bulk(Box::new(source))); + } + return Err(syn::Error::new(keyword.span(), expected)); + } + input + .parse() + .map(Self::Literal) + .map_err(|error| syn::Error::new(error.span(), expected)) + } + + /// The text, and whether it is a bulk operation. + fn text(&self) -> (&Self, bool) { + match self { + Self::Bulk(source) => (source, true), + other => (other, false), + } + } +} + +impl Parse for Source { + fn parse(input: ParseStream) -> syn::Result { + Self::parse_text(input, false) + } +} + +/// `crate = path` before the rest of a macro's input: where the generated +/// code finds `shopify_api`, `::shopify_api` when it is not given. +struct Krate(TokenStream); + +impl Krate { + /// Reads `crate = path` and its separator, `,` or `;`, when the input starts with it. + fn parse(input: ParseStream) -> syn::Result { + if !input.peek(Token![crate]) || !input.peek2(Token![=]) { + return Ok(Self(quote!(::shopify_api))); + } + input.parse::()?; + input.parse::()?; + let path: syn::Path = input.parse().map_err(|error| { + syn::Error::new( + error.span(), + "expected the path of `shopify_api` after `crate =`: `crate = ::my_framework::shopify_api`", + ) + })?; + let first = &path.segments[0].ident; + if path.leading_colon.is_none() && first != "crate" && first != "$crate" { + // The generated code sits in modules of its own, where a relative + // path, or a name brought in by `use`, does not resolve. + return Err(syn::Error::new( + first.span(), + "the path of `crate =` must be absolute: `crate = ::my_framework::shopify_api` or `crate = crate::shopify_api`", + )); + } + if let Some(segment) = path.segments.first() + && segment.ident == "$crate" + { + // serde's derive takes the path as text, where `$crate` means nothing. + return Err(syn::Error::new( + segment.ident.span(), + "`crate = $crate::…` cannot reach serde's derive: write the absolute path, `crate = ::my_framework::shopify_api`", + )); + } + if let Some(arguments) = path + .segments + .iter() + .find(|segment| !segment.arguments.is_none()) + { + return Err(syn::Error::new( + arguments.arguments.span(), + "the path of `crate =` takes no generic arguments", + )); + } + if input.peek(Token![,]) { + input.parse::()?; + } else if input.peek(Token![;]) { + input.parse::()?; + } else { + return Err(input.error("expected `,` or `;` after `crate = path`")); + } + Ok(Self(quote!(#path))) + } +} + +/// `graphql!(SOURCE, name = value, …)`, or modules: +/// `graphql! { pub mod name = SOURCE; mod other = SOURCE }`, after an +/// optional `crate = path`. +struct Invocation { + krate: TokenStream, + input: Input, +} + +impl Parse for Invocation { + fn parse(input: ParseStream) -> syn::Result { + let Krate(krate) = Krate::parse(input)?; + Ok(Self { + krate, + input: input.parse()?, + }) + } +} + +enum Input { + Expression { + source: Source, + variables: Vec<(Ident, Value)>, + }, + Modules(Vec), +} + +struct Module { + attributes: Vec, + visibility: Visibility, + name: Ident, + source: Source, +} + +impl Parse for Input { + fn parse(input: ParseStream) -> syn::Result { + let mut attributes = input.call(Attribute::parse_outer)?; + let mut visibility: Visibility = input.parse()?; + + if input.peek(Token![mod]) { + let mut modules = Vec::new(); + loop { + input.parse::()?; + let name: Ident = input.parse()?; + input.parse::()?; + let source: Source = input.parse()?; + modules.push(Module { + attributes, + visibility, + name, + source, + }); + if input.is_empty() { + break; + } + input.parse::().map_err(|error| { + syn::Error::new(error.span(), "expected `;` after the module") + })?; + if input.is_empty() { + break; + } + attributes = input.call(Attribute::parse_outer)?; + visibility = input.parse()?; + if !input.peek(Token![mod]) { + return Err(input.error( + "expected another module, `mod name = \"…\";`, or the end of `graphql!`", + )); + } + } + return Ok(Self::Modules(modules)); + } + + if let Some(attribute) = attributes.first() { + return Err(syn::Error::new( + attribute.span(), + "attributes need the module form: `mod name = \"…\";`", + )); + } + if !matches!(visibility, Visibility::Inherited) { + return Err(syn::Error::new( + visibility.span(), + "a visibility needs the module form: `pub mod name = \"…\";`", + )); + } + let source: Source = input.parse()?; + let mut variables = Vec::new(); + while !input.is_empty() { + input.parse::()?; + if input.is_empty() { + break; + } + let name: Ident = input.parse().map_err(|error| { + syn::Error::new(error.span(), "expected a variable: `name = value`") + })?; + input.parse::()?; + variables.push((name, value::parse_value(input)?)); + } + Ok(Self::Expression { source, variables }) + } +} + +/// `input!(TypeName { field: value, … })`, after an optional `crate = path`. +struct InputObject { + krate: TokenStream, + name: Ident, + object: Value, +} + +impl Parse for InputObject { + fn parse(input: ParseStream) -> syn::Result { + let Krate(krate) = Krate::parse(input)?; + const FORM: &str = + "expected an input object of the schema: `input!(TypeName { field: value, … })`"; + let name: Ident = input + .parse() + .map_err(|error| syn::Error::new(error.span(), FORM))?; + if !input.peek(syn::token::Brace) { + return Err(input.error(FORM)); + } + let content; + let braces = syn::braced!(content in input); + let object = value::parse_object(&content, braces.span.join())?; + if !input.is_empty() { + return Err(input.error("expected the end of `input!`")); + } + Ok(Self { + krate, + name, + object, + }) + } +} + +/// The text of an operation, where to point at it, and the file it was read from. +struct Text { + query: LitStr, + file: Option, +} + +impl Text { + fn read(source: &Source) -> syn::Result { + match source { + Source::Bulk(source) => Self::read(source), + Source::Literal(query) => Ok(Self { + query: query.clone(), + file: None, + }), + Source::File(path) => { + let file = resolve(manifest_dir().as_deref(), Path::new(&path.value())); + let text = std::fs::read_to_string(&file).map_err(|error| { + syn::Error::new( + path.span(), + format!( + "Cannot read `{}`, relative to the Cargo.toml of the crate: {error}", + path.value() + ), + ) + })?; + Ok(Self { + query: LitStr::new(&text, path.span()), + file: Some(file), + }) + } + } + } + + fn span(&self) -> Span { + self.query.span() + } + + /// Makes the compiler rebuild the crate when the file changes. + fn tracking(&self) -> Option { + let file = self.file.as_ref()?.to_string_lossy().to_string(); + Some(quote!( + const _: &str = ::core::include_str!(#file); + )) + } +} + +fn manifest_dir() -> Option { + std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from) +} + +fn resolve(manifest_dir: Option<&Path>, path: &Path) -> PathBuf { + match manifest_dir { + Some(dir) if path.is_relative() => dir.join(path), + _ => path.to_path_buf(), + } +} + +/// Parsed schema files by path, with the modification time they were read at. +type SchemaCache = HashMap, Arc)>; + +/// The schema operations are checked against, and its file. +struct LoadedSchema { + path: PathBuf, + schema: Arc, +} + +impl LoadedSchema { + /// The schema of the crate being compiled. + fn load() -> Result { + // The file read depends on the package's `Cargo.toml` only, and on + // the internal test variable, which applies to every package: both + // are tracked. Where the package is, and whether cargo was asked to + // build it, are not: they only decide whether a missing or outdated + // file is downloaded or a compile error. + let dir = manifest_dir(); + let test_schema = std::env::var_os(TEST_SCHEMA_ENV); + let package = std::env::var("CARGO_PKG_NAME").ok(); + let (path, schema) = + match schema_source(dir.as_deref(), test_schema.as_deref(), package.as_deref())? { + SchemaSource::File(path) => { + let schema = read_schema(&path).map_err(|error| { + format!("`{}`, named by {TEST_SCHEMA_ENV}: {error}", path.display()) + })?; + (path, schema) + } + SchemaSource::Project { dir, path, pinned } => { + let primary = std::env::var_os("CARGO_PRIMARY_PACKAGE").is_some(); + let may_download = may_download(&dir, cargo_home().as_deref(), primary); + let read = |path: &Path| { + read_schema(path).map_err(|error| format!("`{}`: {error}", path.display())) + }; + // A proc macro has no progress to show. + let schema = project_schema( + &dir, + &path, + pinned.as_deref(), + may_download, + SystemTime::now(), + read, + |_, _| {}, + )?; + (path, schema) + } + }; + if !is_supported_api_version(&schema.api_version) { + return Err(format!( + "`{}` is the schema of `{}`, a version shopify_api does not call (from {MINIMUM_API_VERSION}, or `unstable`): \ + declare another one in Cargo.toml:\n\n{}", + path.display(), + schema.api_version, + metadata_snippet(&latest_api_version(SystemTime::now())) + )); + } + Ok(Self { schema, path }) + } + + /// The schema of `shopify_api`'s own operations. + fn internal() -> Result { + let path = resolve(manifest_dir().as_deref(), Path::new(INTERNAL_SCHEMA_PATH)); + let schema = + read_schema(&path).map_err(|error| format!("`{}`: {error}", path.display()))?; + Ok(Self { schema, path }) + } + + fn schema(&self) -> &Schema { + &self.schema + } + + /// Makes the compiler rebuild the crate when what the expansion depends on changes. + fn tracking(&self) -> TokenStream { + // One operation of the crate is enough to track a file, which may be large. + static TRACKED: Mutex> = Mutex::new(Vec::new()); + let mut tracked = TRACKED + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + // The manifest declares the API version and names the schema file, + // which holds the schema. + let manifest = manifest_dir().map(|dir| dir.join("Cargo.toml")); + let files = [manifest, Some(self.path.clone())] + .into_iter() + .flatten() + .filter(|path| path.is_file()); + let files: Vec = files + .filter(|path| { + let new = !tracked.contains(path); + if new { + tracked.push(path.clone()); + } + new + }) + .map(|path| path.to_string_lossy().to_string()) + .collect(); + // The internal test variable is tracked only where it applies. + let package = std::env::var("CARGO_PKG_NAME").ok(); + let test_schema = test_schema_applies(package.as_deref()).then(|| { + quote!( + const _: ::core::option::Option<&str> = ::core::option_env!(#TEST_SCHEMA_ENV); + ) + }); + quote! { + #test_schema + #(const _: &[u8] = ::core::include_bytes!(#files);)* + } + } + + /// A refusal of a literal value, at its token. + fn literal_error(&self, error: literal::Error) -> syn::Error { + syn::Error::new( + error.span, + format!( + "{}\n(checked against the Shopify Admin API {})", + error.message, + self.schema().api_version + ), + ) + } + + /// Checks an operation, pointing a refusal at its text. + fn check(&self, text: &Text) -> syn::Result { + analyze(self.schema(), &text.query.value()).map_err(|error| self.text_error(text, error)) + } + + /// A refusal of an operation, at its text. + fn text_error(&self, text: &Text, error: impl std::fmt::Display) -> syn::Error { + let file = match &text.file { + Some(file) => { + let relative = manifest_dir() + .and_then(|dir| file.strip_prefix(dir).ok().map(Path::to_path_buf)); + format!(" in {}", relative.as_deref().unwrap_or(file).display()) + } + None => String::new(), + }; + syn::Error::new( + text.span(), + format!( + "{error}{file}\n(checked against the Shopify Admin API {})", + self.schema().api_version + ), + ) + } + + /// Checks a bulk operation: what `check` checks, then Shopify's bulk rules. + fn check_bulk(&self, text: &Text) -> syn::Result<(Operation, Option)> { + let operation = self.check(text)?; + let source = text.query.value(); + let bulk = match operation.kind { + OperationKind::Query => Some( + analyze_bulk_query(self.schema(), &source, &operation) + .map_err(|error| self.text_error(text, error))?, + ), + OperationKind::Mutation => { + check_bulk_mutation(self.schema(), &source, &operation) + .map_err(|error| self.text_error(text, error))?; + None + } + }; + Ok((operation, bulk)) + } +} + +/// Reads a schema file. One compilation expands many operations: each file is +/// parsed once, and again when it changes. The error does not name the file. +fn read_schema(file: &Path) -> Result, String> { + static CACHE: Mutex> = Mutex::new(None); + let modified = std::fs::metadata(file) + .and_then(|metadata| metadata.modified()) + .ok(); + let mut cache = CACHE + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let cache = cache.get_or_insert_with(HashMap::new); + if let Some((cached, schema)) = cache.get(file) + && *cached == modified + { + return Ok(schema.clone()); + } + let json = std::fs::read_to_string(file).map_err(|error| format!("cannot read it: {error}"))?; + let schema = Schema::from_json(&json) + .map(Arc::new) + .map_err(|error| error.to_string())?; + cache.insert(file.to_path_buf(), (modified, schema.clone())); + Ok(schema) +} + +/// One warning per deprecated thing the operation uses: the use of a +/// `#[deprecated]` constant, at the operation, whose note says what and why. +fn deprecation_warnings(schema: &Schema, operation: &Operation, text: &Text) -> TokenStream { + let warnings = operation.deprecations.iter().map(|deprecation| { + let (line, column) = deprecation.position; + let note = format!( + "`{}` is deprecated in the Shopify Admin API {}: {} (line {line}, column {column} of the operation)", + deprecation.coordinate, schema.api_version, deprecation.reason + ); + deprecation_warning(text.span(), ¬e) + }); + quote!(#(#warnings)*) +} + +fn kind(operation: &Operation, krate: &TokenStream) -> TokenStream { + match operation.kind { + OperationKind::Query => quote!(#krate::__private::OperationKind::Query), + OperationKind::Mutation => quote!(#krate::__private::OperationKind::Mutation), + } +} + +/// What `graphql!` builds from a checked operation. +enum Flavor { + /// An `Operation`. + Plain, + /// A `BulkQuery`. + BulkQuery(Box), + /// A `BulkMutation`: the variables of one line. + BulkMutation, +} + +impl Flavor { + fn of(schema: &LoadedSchema, source: &Source, text: &Text) -> syn::Result<(Operation, Self)> { + if !source.text().1 { + return Ok((schema.check(text)?, Self::Plain)); + } + let (operation, bulk) = schema.check_bulk(text)?; + let flavor = match bulk { + Some(bulk) => Self::BulkQuery(Box::new(bulk)), + None => Self::BulkMutation, + }; + Ok((operation, flavor)) + } + + /// The type built. + fn target(&self, krate: &TokenStream) -> TokenStream { + let data = format_ident!("{}", DATA_TYPE); + let item = format_ident!("{}", ITEM_TYPE); + match self { + Self::Plain => quote!(#krate::__private::Operation<#data>), + Self::BulkQuery(_) => quote!(#krate::__private::bulk::BulkQuery<#item>), + Self::BulkMutation => quote!(#krate::__private::bulk::BulkMutation<#data>), + } + } + + /// What runs it, for the documentation. + fn runner(&self) -> &'static str { + match self { + Self::Plain => "`Shopify::execute`", + Self::BulkQuery(_) => "`Shopify::bulk_query`", + Self::BulkMutation => "`Shopify::bulk_mutation`, one per line,", + } + } + + /// The result types, and what a bulk query needs to run. + fn types(&self, schema: &Schema, operation: &Operation, krate: &TokenStream) -> TokenStream { + match self { + Self::BulkQuery(bulk) => query_items(schema, operation, bulk, krate), + Self::Plain | Self::BulkMutation => data_types(operation, krate), + } + } + + /// The checked operation, without its variables. + fn constructor( + &self, + schema: &Schema, + operation: &Operation, + query: &TokenStream, + krate: &TokenStream, + ) -> TokenStream { + let data = format_ident!("{}", DATA_TYPE); + let item = format_ident!("{}", ITEM_TYPE); + let api_version = &schema.api_version; + let name = match &operation.name { + Some(name) => quote!(::core::option::Option::Some(#name)), + None => quote!(::core::option::Option::None), + }; + match self { + Self::Plain => { + let kind = kind(operation, krate); + quote!(#krate::__private::Operation::<#data>::__checked(#query, #kind, #name, #api_version)) + } + Self::BulkQuery(_) => { + let template = template_ident(); + quote!(#krate::__private::bulk::BulkQuery::<#item>::__checked(&#template, #query, #name, #api_version)) + } + Self::BulkMutation => { + quote!(#krate::__private::bulk::BulkMutation::<#data>::__checked(#query, #name, #api_version)) + } + } + } + + /// The method that sets a variable converted by `IntoVariable`. + fn converting_setter(&self) -> Ident { + match self { + Self::Plain => format_ident!("variable"), + Self::BulkQuery(_) | Self::BulkMutation => format_ident!("__converted_variable"), + } + } +} + +/// `graphql!("…", name = value)`: the operation as a value. +/// +/// `krate` is the path of the runtime crate in the generated code, its only +/// one: every item is reached through `#krate::__private`, so that a crate +/// re-exporting `shopify_api` (`extern crate it as shopify_api`, or +/// `crate = …`) needs nothing but that module. +fn expand_expression( + schema: &LoadedSchema, + source: &Source, + variables: &[(Ident, Value)], + krate: &TokenStream, +) -> syn::Result { + let krate = krate.clone(); + let text = Text::read(source)?; + let (operation, flavor) = Flavor::of(schema, source, &text)?; + + // Each value with the variable it is for. + let mut given: Vec<(&Variable, &Value)> = Vec::new(); + for (name, value) in variables { + let Some(declared) = operation + .variables + .iter() + .find(|variable| name == &variable.name) + else { + let declared: Vec = operation + .variables + .iter() + .map(|variable| format!("${}", variable.name)) + .collect(); + let known = if declared.is_empty() { + "it declares no variables".to_string() + } else { + format!("it declares {}", declared.join(", ")) + }; + return Err(syn::Error::new( + name.span(), + format!("The operation has no variable `${name}`: {known}"), + )); + }; + if given + .iter() + .any(|(earlier, _)| earlier.name == declared.name) + { + return Err(syn::Error::new( + name.span(), + format!("Variable `${name}` is given twice"), + )); + } + given.push((declared, value)); + } + if let Some(missing) = operation.variables.iter().find(|variable| { + variable.is_required() + && !given + .iter() + .any(|(declared, _)| declared.name == variable.name) + }) { + return Err(syn::Error::new( + text.span(), + format!( + "Variable `${}: {}` needs a value: add `{} = …` after the operation", + missing.name, missing.ty, missing.name + ), + )); + } + + // The values are arguments of the setters, outside the block that + // declares the types of the operation: they cannot name them. + let mut literals = Literals::new(schema.schema(), krate.clone()); + let mut setters = Vec::new(); + let converting = flavor.converting_setter(); + for (declared, value) in &given { + let key = &declared.name; + match literals + .variable(declared, value) + .map_err(|error| schema.literal_error(error))? + { + VariableValue::Converted { ty, value } => { + let tokens = literal::argument(&value); + let mut method = converting.clone(); + method.set_span(value.span); + setters.push(quote_spanned!(value.span=> .#method::<#ty, _>(#key, #tokens))); + } + VariableValue::Literal(code) => { + setters.push(quote!(.__literal_variable(#key, #code))); + } + } + } + let literal_warnings = literals.finish(); + + let tracking = schema.tracking(); + let file = text.tracking(); + let warnings = deprecation_warnings(schema.schema(), &operation, &text); + let types = flavor.types(schema.schema(), &operation, &krate); + let query = &text.query; + let constructor = flavor.constructor(schema.schema(), &operation, "e!(#query), &krate); + Ok(quote! { + ({ + #tracking + #file + #warnings + #literal_warnings + #types + #constructor + }) + #(#setters)* + }) +} + +/// `graphql! { mod name = "…"; }`: the operation as a module that names its types. +fn expand_module( + schema: &LoadedSchema, + module: &Module, + krate: &TokenStream, +) -> syn::Result { + let Module { + attributes, + visibility, + name, + source, + } = module; + let krate = krate.clone(); + let text = Text::read(source)?; + let (operation, flavor) = Flavor::of(schema, source, &text)?; + let target = flavor.target(&krate); + let constructor = flavor.constructor(schema.schema(), &operation, "e!(QUERY), &krate); + let variables = if operation.variables.is_empty() { + let doc = format!( + " The operation, for {}.", + flavor.runner().trim_end_matches(',') + ); + quote! { + #[doc = #doc] + pub fn operation() -> #target { + #constructor + } + } + } else if matches!(flavor, Flavor::Plain) { + variables_types(schema.schema(), &operation, &krate, &constructor) + } else { + variables_types_for( + schema.schema(), + &operation, + &krate, + &constructor, + &target, + flavor.runner(), + ) + }; + + let tracking = schema.tracking(); + let file = text.tracking(); + let warnings = deprecation_warnings(schema.schema(), &operation, &text); + let types = flavor.types(schema.schema(), &operation, &krate); + let query = &text.query; + let api_version = &schema.schema().api_version; + let operation_name = match &operation.name { + Some(name) => quote!(::core::option::Option::Some(#name)), + None => quote!(::core::option::Option::None), + }; + let kind = kind(&operation, &krate); + Ok(quote! { + #(#attributes)* + #visibility mod #name { + #tracking + #file + #warnings + + /// The text of the operation. + pub const QUERY: &str = #query; + /// The name of the operation, when it has one. + pub const NAME: ::core::option::Option<&str> = #operation_name; + /// A query or a mutation. + pub const KIND: #krate::__private::OperationKind = #kind; + /// The Admin API version the operation was checked against. + pub const API_VERSION: &str = #api_version; + + #types + #variables + } + }) +} + +fn expand( + invocation: Invocation, + schema: Result, +) -> syn::Result { + let schema = schema.map_err(|message| syn::Error::new(Span::call_site(), message))?; + let Invocation { krate, input } = invocation; + match input { + Input::Expression { source, variables } => { + expand_expression(&schema, &source, &variables, &krate) + } + Input::Modules(modules) => { + let mut expanded = TokenStream::new(); + for module in &modules { + expanded.extend(expand_module(&schema, module, &krate)?); + } + Ok(expanded) + } + } +} + +/// `input!(TypeName { … })`: an `InputObject` of that type. +fn expand_input( + input: InputObject, + schema: Result, +) -> syn::Result { + let schema = schema.map_err(|message| syn::Error::new(Span::call_site(), message))?; + let Value::Object(object) = &input.object else { + unreachable!("`input!` reads an object"); + }; + let mut literals = Literals::new(schema.schema(), input.krate.clone()); + let value = literals + .input_object(&input.name.to_string(), input.name.span(), object) + .map_err(|error| schema.literal_error(error))?; + let checks = literals.finish(); + let tracking = schema.tracking(); + Ok(quote! {{ + #tracking + #checks + #value + }}) +} + +/// See `shopify_api::graphql!`. +#[proc_macro] +pub fn graphql(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input = syn::parse_macro_input!(input as Invocation); + expand(input, LoadedSchema::load()) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + +/// See `shopify_api::input!`. +#[proc_macro] +pub fn input(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input = syn::parse_macro_input!(input as InputObject); + expand_input(input, LoadedSchema::load()) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + +/// `graphql!` for the operations of `shopify_api` itself, checked against its +/// `graphql/internal.schema.json`. Not for other crates. +#[doc(hidden)] +#[proc_macro] +pub fn __graphql_internal(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input = syn::parse_macro_input!(input as Invocation); + expand(input, LoadedSchema::internal()) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + +/// `input!` for `shopify_api` itself. Not for other crates. +#[doc(hidden)] +#[proc_macro] +pub fn __input_internal(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input = syn::parse_macro_input!(input as InputObject); + expand_input(input, LoadedSchema::internal()) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + +#[cfg(test)] +mod tests { + use super::*; + + const SCHEMA: &str = r#"{"format":2,"apiVersion":"2026-07","query":"QueryRoot","types":{ +"QueryRoot":{"o":{"f":{"ping":"String"}}}, +"String":"s" +}}"#; + + /// An empty directory removed when the test ends. + struct Project(PathBuf); + + impl Project { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir() + .join(format!("shopify-api-macros-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + + fn write(&self, path: &str, content: &str) -> PathBuf { + let file = self.0.join(path); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, content).unwrap(); + file + } + } + + impl Drop for Project { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn schema_files_are_read_once_and_again_when_they_change() { + let project = Project::new("read"); + let file = project.write("graphql/admin.schema.json", SCHEMA); + + let first = read_schema(&file).unwrap(); + assert_eq!(first.api_version, "2026-07"); + assert!(Arc::ptr_eq(&first, &read_schema(&file).unwrap())); + + // A later modification time, as after `shopify-api schema download`. + std::fs::write(&file, SCHEMA.replace("2026-07", "2026-10")).unwrap(); + let later = SystemTime::now() + std::time::Duration::from_secs(5); + std::fs::File::options() + .write(true) + .open(&file) + .unwrap() + .set_modified(later) + .unwrap(); + assert_eq!(read_schema(&file).unwrap().api_version, "2026-10"); + } + + #[test] + fn a_malformed_schema_file_says_why() { + let project = Project::new("malformed"); + let file = project.write("graphql/admin.schema.json", "{"); + + let error = read_schema(&file).unwrap_err(); + assert!(error.starts_with("Invalid schema file: "), "{error}"); + + let error = read_schema(&project.0.join("absent.json")).unwrap_err(); + assert!(error.starts_with("cannot read it: "), "{error}"); + } + + #[test] + fn parses_the_path_of_the_runtime_crate() { + let krate = |text: &str| { + syn::parse_str::(text) + .unwrap() + .krate + .to_string() + .replace(' ', "") + }; + assert_eq!(krate(r#""{ shop { id } }", first = 1"#), "::shopify_api"); + assert_eq!( + krate(r#"crate = ::openshop::shopify_api, "{ shop { id } }", first = 1"#), + "::openshop::shopify_api" + ); + assert_eq!( + krate(r#"crate = crate::shopify_api; pub mod a = "{ shop { id } }";"#), + "crate::shopify_api" + ); + let Invocation { input, .. } = syn::parse_str( + r#"crate = ::openshop::shopify_api; #[doc = "A."] pub mod a = "{ shop { id } }"; mod b = "{ shop { name } }""#, + ) + .unwrap(); + let Input::Modules(modules) = input else { + panic!("modules"); + }; + assert_eq!(modules.len(), 2); + let Invocation { input, .. } = + syn::parse_str(r#"crate = ::openshop::shopify_api, bulk("{ shop { id } }")"#).unwrap(); + assert!(matches!( + input, + Input::Expression { + source: Source::Bulk(_), + .. + } + )); + + let object: InputObject = + syn::parse_str("crate = ::openshop::shopify_api, MetafieldsSetInput { key: k }") + .unwrap(); + assert_eq!( + object.krate.to_string().replace(' ', ""), + "::openshop::shopify_api" + ); + assert_eq!(object.name, "MetafieldsSetInput"); + let object: InputObject = syn::parse_str("MetafieldsSetInput { key: k }").unwrap(); + assert_eq!(object.krate.to_string().replace(' ', ""), "::shopify_api"); + } + + #[test] + fn parses_both_forms_and_both_sources() { + let expression: Input = + syn::parse_str(r#""{ shop { name } }", first = 1, after = cursor,"#).unwrap(); + let Input::Expression { + source: Source::Literal(query), + variables, + } = expression + else { + panic!("an expression with a literal"); + }; + assert_eq!(query.value(), "{ shop { name } }"); + let names: Vec = variables.iter().map(|(name, _)| name.to_string()).collect(); + assert_eq!(names, ["first", "after"]); + + let expression: Input = syn::parse_str(r#"file("graphql/shop.graphql"), id = id"#).unwrap(); + let Input::Expression { + source: Source::File(path), + variables, + } = expression + else { + panic!("an expression with a file"); + }; + assert_eq!(path.value(), "graphql/shop.graphql"); + assert_eq!(variables.len(), 1); + + let module: Input = + syn::parse_str("#[doc = \"Docs.\"] pub mod shop_name = \"{ shop { name } }\";") + .unwrap(); + let Input::Modules(modules) = module else { + panic!("a module"); + }; + assert_eq!(modules.len(), 1); + assert_eq!(modules[0].name, "shop_name"); + assert_eq!(modules[0].attributes.len(), 1); + + // Several modules, `;` between them and optional after the last. + for text in [ + r#"#[doc = "A."] pub mod a = "{ shop { name } }"; pub(crate) mod b = file("b.graphql"); mod c = "{ shop { id } }""#, + r#"#[doc = "A."] pub mod a = "{ shop { name } }"; pub(crate) mod b = file("b.graphql"); mod c = "{ shop { id } }";"#, + ] { + let Input::Modules(modules) = syn::parse_str::(text).unwrap() else { + panic!("modules"); + }; + let names: Vec = modules + .iter() + .map(|module| module.name.to_string()) + .collect(); + assert_eq!(names, ["a", "b", "c"]); + assert_eq!(modules[0].attributes.len(), 1); + assert!(modules[1].attributes.is_empty()); + assert!(matches!(modules[0].visibility, Visibility::Public(_))); + assert!(matches!(modules[1].visibility, Visibility::Restricted(_))); + assert!(matches!(modules[1].source, Source::File(_))); + assert!(matches!(modules[2].visibility, Visibility::Inherited)); + } + + // `bulk(…)` around either source, in both forms. + let Input::Expression { + source: Source::Bulk(inner), + variables, + } = syn::parse_str::(r#"bulk("{ shop { name } }"), first = 1"#).unwrap() + else { + panic!("a bulk expression"); + }; + assert!(matches!(*inner, Source::Literal(_))); + assert_eq!(variables.len(), 1); + let Input::Modules(modules) = syn::parse_str::( + r#"pub mod a = bulk(file("a.graphql")); mod b = bulk("{ shop { id } }");"#, + ) + .unwrap() else { + panic!("modules"); + }; + assert!( + matches!(&modules[0].source, Source::Bulk(inner) if matches!(**inner, Source::File(_))) + ); + assert!( + matches!(&modules[1].source, Source::Bulk(inner) if matches!(**inner, Source::Literal(_))) + ); + + for (source, message) in [ + ( + "crate = shopify_api, \"{ shop { id } }\"", + "the path of `crate =` must be absolute: `crate = ::my_framework::shopify_api` or `crate = crate::shopify_api`", + ), + ( + "crate = ::a::b, \"{ shop { id } }\"", + "the path of `crate =` takes no generic arguments", + ), + ( + "crate = ::a::b \"{ shop { id } }\"", + "expected `,` or `;` after `crate = path`", + ), + ( + "crate = , \"{ shop { id } }\"", + "expected the path of `shopify_api` after `crate =`: `crate = ::my_framework::shopify_api`", + ), + ] { + let error = syn::parse_str::(source) + .err() + .expect(source) + .to_string(); + assert_eq!(error, message, "{source}"); + } + + for (source, message) in [ + ("first = 1", SOURCE_FORM), + (r#"path("x.graphql")"#, SOURCE_FORM), + (r#"file("a", "b")"#, "`file(…)` takes one path"), + ( + r#"bulk(bulk("{ shop { id } }"))"#, + "`bulk(…)` takes the operation as a string literal or `file(\"path.graphql\")`", + ), + ( + "bulk(1)", + "`bulk(…)` takes the operation as a string literal or `file(\"path.graphql\")`", + ), + (r#"bulk("a", "b")"#, "`bulk(…)` takes one operation"), + (r#"bulk(file("a", "b"))"#, "`file(…)` takes one path"), + ( + r#""{ shop { name } }", 1"#, + "expected a variable: `name = value`", + ), + ( + r#"pub "{ shop { name } }""#, + "a visibility needs the module form: `pub mod name = \"…\";`", + ), + ( + r#"mod shop = "{ shop { name } }"; 1"#, + "expected another module, `mod name = \"…\";`, or the end of `graphql!`", + ), + ( + r#"mod a = "{ shop { name } }" mod b = "{ shop { id } }""#, + "expected `;` after the module", + ), + ] { + let error = syn::parse_str::(source) + .err() + .expect(source) + .to_string(); + assert_eq!(error, message, "{source}"); + } + } +} diff --git a/crates/shopify_api_macros/src/value.rs b/crates/shopify_api_macros/src/value.rs new file mode 100644 index 0000000..ff0bffd --- /dev/null +++ b/crates/shopify_api_macros/src/value.rs @@ -0,0 +1,306 @@ +//! Reads the values of inline variables and of `input!` into +//! [`Value`]s, which `shopify_api_graphql::literal` checks against the +//! schema. +//! +//! The text alone decides what is read; the type expected where the value +//! stands decides what it means: +//! +//! - `{` starts an object when it is empty or starts with `name:` or +//! `name?:`, which no Rust block does; `{ compute() }` stays a block. +//! - `[a, b]` is kept both as a list of values and as the Rust array it +//! also is: a list where a list is expected, the array elsewhere. `[x; 3]` +//! is an array. +//! - `null`, `raw(…)` and a lone identifier are those forms only when they +//! are the whole value: `null.clone()` or `raw(x).len()` are Rust. + +use proc_macro2::{Delimiter, Spacing, Span, TokenTree}; +use quote::ToTokens; +use shopify_api_graphql::literal::{Expr, Field, For, List, Object, Value}; +use syn::buffer::Cursor; +use syn::ext::IdentExt; +use syn::parse::{ParseStream, Parser}; +use syn::spanned::Spanned; +use syn::{Ident, Token}; + +pub(crate) fn parse_value(input: ParseStream) -> syn::Result { + let cursor = input.cursor(); + if let Some((ident, rest)) = cursor.ident() { + if ident == "null" && ends_after(input, 1) { + input.call(Ident::parse_any)?; + return Ok(Value::Null(ident.span())); + } + if ident == "raw" && rest.group(Delimiter::Parenthesis).is_some() && ends_after(input, 2) { + input.call(Ident::parse_any)?; + let content; + syn::parenthesized!(content in input); + let value: syn::Expr = content.parse().map_err(|error| { + syn::Error::new( + error.span(), + "`raw(…)` takes the value of the enum, as a string", + ) + })?; + if !content.is_empty() { + return Err(content.error("`raw(…)` takes one value")); + } + return Ok(Value::Raw { + keyword: ident.span(), + value: expr(&value), + }); + } + if ends_after(input, 1) { + return Ok(Value::Ident(input.call(Ident::parse_any)?)); + } + } + if let Some((inside, _, _)) = cursor.group(Delimiter::Brace) + && ends_after(input, 1) + && is_object(inside) + { + let content; + let braces = syn::braced!(content in input); + return parse_object(&content, braces.span.join()); + } + if cursor.group(Delimiter::Bracket).is_some() && ends_after(input, 1) { + let Some(TokenTree::Group(group)) = input.parse::>()? else { + unreachable!("a bracketed group was seen"); + }; + return parse_brackets(group); + } + let value: syn::Expr = input.parse()?; + Ok(Value::Rust(expr(&value))) +} + +/// `{ name: value, name?: value, … }`, its braces read. +pub(crate) fn parse_object(content: ParseStream, span: Span) -> syn::Result { + let mut fields = Vec::new(); + while !content.is_empty() { + let name = content + .call(Ident::parse_any) + .map_err(|error| syn::Error::new(error.span(), "expected a field: `name: value`"))?; + let optional = content + .parse::>()? + .map(|question| question.span); + if !content.peek(Token![:]) || content.peek(Token![::]) { + return Err(syn::Error::new( + name.span(), + format!("expected `:` after the field: `{name}: value`"), + )); + } + content.parse::()?; + let value = parse_value(content)?; + fields.push(Field { + name: name.unraw().to_string(), + name_span: name.span(), + optional, + value, + }); + if content.is_empty() { + break; + } + content + .parse::() + .map_err(|error| syn::Error::new(error.span(), "expected `,` between two fields"))?; + } + Ok(Value::Object(Object { span, fields })) +} + +fn parse_brackets(group: proc_macro2::Group) -> syn::Result { + let span = group.span(); + let content = group.stream(); + if matches!(content.clone().into_iter().next(), Some(TokenTree::Ident(ident)) if ident == "for") + { + return (|input: ParseStream| parse_for(input, span)).parse2(content); + } + let items = (|input: ParseStream| { + let mut items = Vec::new(); + while !input.is_empty() { + items.push(parse_value(input)?); + if input.is_empty() { + break; + } + input.parse::()?; + } + Ok(items) + }) + .parse2(content); + let rust = syn::parse2::(TokenTree::Group(group).into_token_stream()) + .ok() + .map(|array| expr(&array)); + match (items, rust) { + (Ok(items), rust) => Ok(Value::List(List { span, items, rust })), + (Err(_), Some(rust)) => Ok(Value::Rust(rust)), + (Err(error), None) => Err(error), + } +} + +/// `for pattern in iterable if filter => item`, inside the brackets. +fn parse_for(input: ParseStream, span: Span) -> syn::Result { + input.parse::()?; + let pattern = syn::Pat::parse_multi_with_leading_vert(input)?; + input.parse::()?; + let iterable = syn::Expr::parse_without_eager_brace(input)?; + let filter = match input.parse::>()? { + Some(_) => Some(syn::Expr::parse_without_eager_brace(input)?.into_token_stream()), + None => None, + }; + input.parse::]>().map_err(|error| { + syn::Error::new( + error.span(), + "expected `=>` and the value of each item: `[for x in xs => value]`", + ) + })?; + let item = parse_value(input)?; + if !input.is_empty() { + return Err(input.error("expected `]`: one value follows `=>`")); + } + Ok(Value::For(Box::new(For { + span, + pattern: pattern.into_token_stream(), + iterable: iterable.into_token_stream(), + filter, + item, + }))) +} + +fn expr(value: &syn::Expr) -> Expr { + Expr { + tokens: value.to_token_stream(), + span: value.span(), + } +} + +/// The value ends after `count` token trees: at the end, or at a `,`. +fn ends_after(input: ParseStream, count: usize) -> bool { + let mut cursor = input.cursor(); + for _ in 0..count { + match cursor.token_tree() { + Some((_, next)) => cursor = next, + None => return false, + } + } + cursor.eof() || matches!(cursor.punct(), Some((punct, _)) if punct.as_char() == ',') +} + +/// The inside of braces reads as an object: empty, or `name:` (not +/// `name::`) or `name?:` first. +fn is_object(inside: Cursor) -> bool { + if inside.eof() { + return true; + } + let Some((_, rest)) = inside.ident() else { + return false; + }; + let is = |cursor: Cursor, character: char| matches!(cursor.punct(), Some((punct, _)) if punct.as_char() == character); + match rest.punct() { + Some((colon, after)) if colon.as_char() == ':' => { + !(colon.spacing() == Spacing::Joint && is(after, ':')) + } + Some((question, after)) if question.as_char() == '?' => is(after, ':'), + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(text: &str) -> Value { + parse_value.parse_str(text).unwrap() + } + + fn kind(value: &Value) -> String { + match value { + Value::Null(_) => "null".to_string(), + Value::Raw { value, .. } => format!("raw({})", value.tokens), + Value::Ident(ident) => format!("ident {ident}"), + Value::Object(object) => { + let fields: Vec = object + .fields + .iter() + .map(|field| { + let question = if field.optional.is_some() { "?" } else { "" }; + format!("{}{question}: {}", field.name, kind(&field.value)) + }) + .collect(); + format!("{{{}}}", fields.join(", ")) + } + Value::List(list) => { + let items: Vec = list.items.iter().map(kind).collect(); + let rust = if list.rust.is_some() { + " (also rust)" + } else { + "" + }; + format!("[{}]{rust}", items.join(", ")) + } + Value::For(comprehension) => format!( + "for {} in {}{} => {}", + comprehension.pattern, + comprehension.iterable, + comprehension + .filter + .as_ref() + .map(|filter| format!(" if {filter}")) + .unwrap_or_default(), + kind(&comprehension.item) + ), + Value::Rust(expr) => format!("rust {}", expr.tokens), + } + } + + #[test] + fn reads_each_form_from_the_text_alone() { + for (text, read) in [ + ("null", "null"), + ("null.clone()", "rust null . clone ()"), + ("raw(status)", "raw(status)"), + ("raw(a).len()", "rust raw (a) . len ()"), + ("ACTIVE", "ident ACTIVE"), + ("{}", "{}"), + ("{ compute() }", "rust { compute () }"), + ("{ x }", "rust { x }"), + ("{ a::b() }", "rust { a :: b () }"), + ( + "{ id: id, type: \"t\", vendor?: v, seo: { title: t }, }", + "{id: ident id, type: rust \"t\", vendor?: ident v, seo: {title: ident t}}", + ), + ("[a, b]", "[ident a, ident b] (also rust)"), + ("[x; 3]", "rust [x ; 3]"), + ("[{ a: 1 }, null]", "[{a: rust 1}, null]"), + ("[a, b].to_vec()", "rust [a , b] . to_vec ()"), + ( + "[for m in &rows if !m.value.is_empty() => { key: &m.key }]", + "for m in & rows if ! m . value . is_empty () => {key: rust & m . key}", + ), + ( + "[for (i, m) in rows.iter().enumerate() => i]", + "for (i , m) in rows . iter () . enumerate () => ident i", + ), + ("format!(\"{name}\")", "rust format ! (\"{name}\")"), + ("Some(x)", "rust Some (x)"), + ] { + assert_eq!(kind(&parse(text)), read, "{text}"); + } + } + + #[test] + fn says_what_is_wrong_in_an_object() { + for (text, message) in [ + ("{ a: 1 b: 2 }", "expected `,` between two fields"), + ("{ a: 1, b }", "expected `:` after the field: `b: value`"), + ("{ a: 1, 2: 3 }", "expected a field: `name: value`"), + ("raw()", "`raw(…)` takes the value of the enum, as a string"), + ("raw(a, b)", "`raw(…)` takes one value"), + ( + "[for x in xs x]", + "expected `=>` and the value of each item: `[for x in xs => value]`", + ), + ( + "[for x in xs => x, y]", + "expected `]`: one value follows `=>`", + ), + ] { + let error = parse_value.parse_str(text).expect_err(text); + assert_eq!(error.to_string(), message, "{text}"); + } + } +} diff --git a/deny.toml b/deny.toml new file mode 100644 index 0000000..0cf2e85 --- /dev/null +++ b/deny.toml @@ -0,0 +1,31 @@ +# Policy of `mise run audit`. cargo-deny checks what the workspace depends on; +# `cargo audit` reads the same RustSec database from Cargo.lock alone. + +[graph] +all-features = true + +[advisories] +version = 2 +yanked = "deny" + +[bans] +multiple-versions = "allow" +wildcards = "deny" +allow-wildcard-paths = true + +[sources] +unknown-registry = "deny" +unknown-git = "deny" + +[licenses] +version = 2 +# Permissive licenses only: the crates are MIT. +allow = [ + "MIT", + "Apache-2.0", + "Apache-2.0 WITH LLVM-exception", + "BSD-3-Clause", + "ISC", + "Unicode-3.0", + "CDLA-Permissive-2.0", +] diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..9c47e91 --- /dev/null +++ b/mise.toml @@ -0,0 +1,74 @@ +# Toolchain and tasks. Run `mise install` once, then `mise run ` (`mise tasks` lists them). +[tools] +rust = { version = "1.99.1", profile = "minimal", components = "clippy,rustfmt" } +"cargo:cargo-audit" = "0.22.2" +cargo-deny = "0.20.2" + +[env] +RUST_BACKTRACE = "1" + +[tasks.fmt] +description = "Format the workspace" +run = "cargo fmt --all" + +[tasks."fmt:check"] +description = "Check the formatting of the workspace" +run = "cargo fmt --all -- --check" + +[tasks.lint] +description = "Clippy on every crate, target and feature, warnings are errors" +run = "cargo clippy --workspace --all-targets --all-features --locked -- -D warnings" + +[tasks.test] +description = "Run every test, with every feature. No network: Shopify is mocked." +run = "cargo test --workspace --all-features --locked" + +[tasks."test:min"] +description = "Build and test the client with its default features only" +run = "cargo test -p shopify_api --locked" + +[tasks."check:features"] +description = "Build the client without its default features, then with each feature alone, and run its doctests without them: what feature unification in the workspace hides" +run = [ + "cargo check -p shopify_api --no-default-features --lib --locked", + "cargo check -p shopify_api --no-default-features --features webhooks --lib --locked", + "cargo check -p shopify_api --no-default-features --features oauth --lib --locked", + "cargo check -p shopify_api --no-default-features --features testing --lib --locked", + "cargo test -p shopify_api --no-default-features --doc --locked", +] + +[tasks.doc] +description = "Build the documentation, warnings are errors" +env = { RUSTDOCFLAGS = "-D warnings" } +run = "cargo doc --workspace --all-features --no-deps --locked" + +[tasks.check] +description = "What CI runs: fmt check, clippy, tests, docs, features alone" +depends = ["fmt:check", "lint", "test", "test:min", "check:features", "doc"] + +[tasks.msrv] +description = "Build the workspace with the minimum supported Rust version (1.88)" +run = "cargo +1.88 check --workspace --all-features --locked" + +[tasks."ui:bless"] +description = "Rewrite the expected compiler errors of the `graphql!` compile-fail tests" +env = { TRYBUILD = "overwrite" } +run = "cargo test -p shopify_api --all-features --locked --test compile_fail" + +[tasks."schema:test"] +description = "Download the Admin schema the tests use again, for the version in crates/shopify_api/Cargo.toml" +dir = "crates/shopify_api" +run = "cargo run -p shopify_api --features cli --locked -- schema download" + +[tasks."schema:internal"] +description = "Cut the test schema down to the operations of shopify_api, into crates/shopify_api/graphql/internal.schema.json" +env = { SHOPIFY_API_BLESS = "1" } +run = "cargo test -p shopify_api_graphql --locked --test internal_schema" + +[tasks."test:live"] +description = "Run the tests against a real development store (needs SHOPIFY_TEST_SHOP and a token, see tests/live.rs)" +run = "cargo test -p shopify_api --all-features --locked --test live -- --ignored --test-threads=1" + +[tasks.audit] +description = "Known vulnerabilities, licenses and sources of the dependencies (needs the network)" +run = ["cargo audit", "cargo deny check"] diff --git a/schema_dl.graphql b/schema_dl.graphql deleted file mode 100644 index 73ad976..0000000 --- a/schema_dl.graphql +++ /dev/null @@ -1,107 +0,0 @@ -query IntrospectionQuery { - __schema { - queryType { - name - } - mutationType { - name - } - subscriptionType { - name - } - types { - ...FullType - } - directives { - name - description - locations - args { - ...InputValue - } - } - } -} - -fragment FullType on __Type { - kind - name - description - fields(includeDeprecated: true) { - name - description - args { - ...InputValue - } - type { - ...TypeRef - } - isDeprecated - deprecationReason - } - inputFields { - ...InputValue - } - interfaces { - ...TypeRef - } - enumValues(includeDeprecated: true) { - name - description - isDeprecated - deprecationReason - } - possibleTypes { - ...TypeRef - } -} - -fragment InputValue on __InputValue { - name - description - type { - ...TypeRef - } - defaultValue -} - -fragment TypeRef on __Type { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - ofType { - kind - name - } - } - } - } - } - } - } - } - } -} diff --git a/src/auth.rs b/src/auth.rs deleted file mode 100644 index 283e607..0000000 --- a/src/auth.rs +++ /dev/null @@ -1,293 +0,0 @@ -use std::{future::Future, pin::Pin}; - -use chrono::{DateTime, Utc}; -use serde::{Deserialize, Serialize}; - -use crate::{Shopify, ShopifyAPIError}; - -pub type TokenStoreFuture<'a> = - Pin> + Send + 'a>>; - -pub trait TokenStore: Send + Sync { - fn save_token<'a>(&'a self, shop: &'a str, token: TokenData) -> TokenStoreFuture<'a>; -} - -#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)] -pub struct TokenData { - pub access_token: String, - pub scope: Option, - pub expires_at: Option>, - pub refresh_token: Option, - pub refresh_token_expires_at: Option>, -} - -impl std::fmt::Debug for TokenData { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("TokenData") - .field("access_token", &"") - .field("scope", &self.scope) - .field("expires_at", &self.expires_at) - .field( - "refresh_token", - &self.refresh_token.as_ref().map(|_| ""), - ) - .field("refresh_token_expires_at", &self.refresh_token_expires_at) - .finish() - } -} - -impl TokenData { - pub fn never_expiring(access_token: impl Into) -> Self { - Self { - access_token: access_token.into(), - scope: None, - expires_at: None, - refresh_token: None, - refresh_token_expires_at: None, - } - } - - pub fn expires_within(&self, leeway: chrono::Duration) -> bool { - self.expires_at - .map(|expires_at| expires_at <= Utc::now() + leeway) - .unwrap_or(false) - } -} - -#[derive(Clone, Eq, PartialEq)] -pub enum ShopifyAuth { - AccessToken(String), - ClientCredentials { - client_id: String, - client_secret: String, - current_token: Option, - }, - ExpiringOfflineToken { - client_id: String, - client_secret: String, - token: TokenData, - }, -} - -impl std::fmt::Debug for ShopifyAuth { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - ShopifyAuth::AccessToken(_) => { - f.debug_tuple("AccessToken").field(&"").finish() - } - ShopifyAuth::ClientCredentials { current_token, .. } => f - .debug_struct("ClientCredentials") - .field("client_id", &"") - .field("client_secret", &"") - .field("current_token", current_token) - .finish(), - ShopifyAuth::ExpiringOfflineToken { token, .. } => f - .debug_struct("ExpiringOfflineToken") - .field("client_id", &"") - .field("client_secret", &"") - .field("token", token) - .finish(), - } - } -} - -impl ShopifyAuth { - pub fn client_credentials( - client_id: impl Into, - client_secret: impl Into, - ) -> Self { - Self::ClientCredentials { - client_id: client_id.into(), - client_secret: client_secret.into(), - current_token: None, - } - } - - pub fn expiring_offline_token( - client_id: impl Into, - client_secret: impl Into, - token: TokenData, - ) -> Self { - Self::ExpiringOfflineToken { - client_id: client_id.into(), - client_secret: client_secret.into(), - token, - } - } -} - -#[derive(Debug, Deserialize)] -struct TokenResponse { - access_token: String, - scope: Option, - expires_in: Option, - refresh_token: Option, - refresh_token_expires_in: Option, -} - -impl TokenResponse { - fn into_token_data(self) -> TokenData { - TokenData { - access_token: self.access_token, - scope: self.scope, - expires_at: self - .expires_in - .map(|seconds| Utc::now() + chrono::Duration::seconds(seconds)), - refresh_token: self.refresh_token, - refresh_token_expires_at: self - .refresh_token_expires_in - .map(|seconds| Utc::now() + chrono::Duration::seconds(seconds)), - } - } -} - -impl Shopify { - pub async fn access_token(&self) -> Result { - let auth = self - .auth - .lock() - .map_err(|_| ShopifyAPIError::Authentication("auth lock poisoned".to_string()))? - .clone(); - - match auth { - ShopifyAuth::AccessToken(token) => Ok(token), - ShopifyAuth::ClientCredentials { - client_id, - client_secret, - current_token, - } => { - if let Some(token) = current_token { - if !token.expires_within(self.token_refresh_leeway) { - return Ok(token.access_token); - } - } - - let token = self - .request_client_credentials_token(&client_id, &client_secret) - .await?; - self.persist_and_replace_auth( - ShopifyAuth::ClientCredentials { - client_id, - client_secret, - current_token: Some(token.clone()), - }, - token.clone(), - ) - .await?; - Ok(token.access_token) - } - ShopifyAuth::ExpiringOfflineToken { - client_id, - client_secret, - token, - } => { - if !token.expires_within(self.token_refresh_leeway) { - return Ok(token.access_token); - } - - let refresh_token = token.refresh_token.as_deref().ok_or_else(|| { - ShopifyAPIError::Authentication( - "expiring offline token is missing refresh_token".to_string(), - ) - })?; - let refreshed = self - .refresh_token_with_credentials(&client_id, &client_secret, refresh_token) - .await?; - self.persist_and_replace_auth( - ShopifyAuth::ExpiringOfflineToken { - client_id, - client_secret, - token: refreshed.clone(), - }, - refreshed.clone(), - ) - .await?; - Ok(refreshed.access_token) - } - } - } - - async fn persist_and_replace_auth( - &self, - auth: ShopifyAuth, - token: TokenData, - ) -> Result<(), ShopifyAPIError> { - self.replace_auth(auth)?; - if let Some(store) = &self.token_store { - store.save_token(self.shop_domain(), token).await?; - } - Ok(()) - } - - pub async fn request_client_credentials_token( - &self, - client_id: &str, - client_secret: &str, - ) -> Result { - let response = self - .client() - .post(self.token_url()) - .form(&[ - ("grant_type", "client_credentials"), - ("client_id", client_id), - ("client_secret", client_secret), - ]) - .send() - .await? - .error_for_status()? - .json::() - .await?; - - Ok(response.into_token_data()) - } - - pub async fn refresh_token_with_credentials( - &self, - client_id: &str, - client_secret: &str, - refresh_token: &str, - ) -> Result { - let response = self - .client() - .post(self.token_url()) - .form(&[ - ("grant_type", "refresh_token"), - ("client_id", client_id), - ("client_secret", client_secret), - ("refresh_token", refresh_token), - ]) - .send() - .await? - .error_for_status()? - .json::() - .await?; - - Ok(response.into_token_data()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn token_expiration_uses_leeway() { - let token = TokenData { - access_token: "token".to_string(), - scope: None, - expires_at: Some(Utc::now() + chrono::Duration::minutes(1)), - refresh_token: None, - refresh_token_expires_at: None, - }; - - assert!(token.expires_within(chrono::Duration::minutes(5))); - assert!(!token.expires_within(chrono::Duration::seconds(1))); - } - - #[test] - fn static_token_never_expires() { - let token = TokenData::never_expiring("token"); - - assert!(!token.expires_within(chrono::Duration::days(365))); - } -} diff --git a/src/bin/shopify-api.rs b/src/bin/shopify-api.rs deleted file mode 100644 index f885f92..0000000 --- a/src/bin/shopify-api.rs +++ /dev/null @@ -1,97 +0,0 @@ -use std::{fs::File, path::PathBuf}; - -use clap::{Parser, Subcommand}; -use shopify_api::{ - download_public_admin_schema, ApiVersion, Shopify, ShopifyAPIError, ShopifyAuth, ShopifyConfig, -}; - -#[derive(Debug, Parser)] -#[command(name = "shopify-api")] -#[command(about = "Shopify API helper commands")] -struct Cli { - #[command(subcommand)] - command: Commands, -} - -#[derive(Debug, Subcommand)] -enum Commands { - Schema { - #[command(subcommand)] - command: SchemaCommands, - }, -} - -#[derive(Debug, Subcommand)] -enum SchemaCommands { - Download { - #[arg(long)] - shop: Option, - #[arg(long)] - access_token: Option, - #[arg(long)] - client_id: Option, - #[arg(long)] - client_secret: Option, - #[arg(long, default_value = shopify_api::DEFAULT_API_VERSION)] - api_version: String, - #[arg(long)] - public: bool, - #[arg(long)] - out: PathBuf, - }, -} - -#[tokio::main] -async fn main() -> Result<(), ShopifyAPIError> { - let cli = Cli::parse(); - - match cli.command { - Commands::Schema { - command: - SchemaCommands::Download { - shop, - access_token, - client_id, - client_secret, - api_version, - public, - out, - }, - } => { - let api_version = ApiVersion::new(api_version)?; - let schema = if public { - download_public_admin_schema(api_version.as_str()).await? - } else { - let shop = shop.ok_or_else(|| { - ShopifyAPIError::Authentication( - "provide --shop unless using --public".to_string(), - ) - })?; - - let auth = match (access_token, client_id, client_secret) { - (Some(token), None, None) => ShopifyAuth::AccessToken(token), - (None, Some(client_id), Some(client_secret)) => { - ShopifyAuth::client_credentials(client_id, client_secret) - } - _ => { - return Err(ShopifyAPIError::Authentication( - "provide either --access-token or both --client-id and --client-secret" - .to_string(), - )); - } - }; - - let config = ShopifyConfig { - api_version, - ..ShopifyConfig::default() - }; - let shopify = Shopify::new(shop, auth, config)?; - shopify.download_admin_schema().await? - }; - let file = File::create(out).map_err(|err| ShopifyAPIError::Other(err.to_string()))?; - serde_json::to_writer_pretty(file, &schema)?; - } - } - - Ok(()) -} diff --git a/src/graphql/bulk_query.rs b/src/graphql/bulk_query.rs deleted file mode 100644 index 8f4075c..0000000 --- a/src/graphql/bulk_query.rs +++ /dev/null @@ -1,562 +0,0 @@ -use std::time::{Duration, Instant}; - -use serde::{Deserialize, Serialize}; -use serde_json::json; - -use crate::{Shopify, ShopifyAPIError}; - -#[derive(Debug, Serialize, Deserialize, Clone)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum StagedUploadResource { - BulkMutationVariables, - CollectionImage, - File, - Image, - Model3D, - ProductImage, - ReturnLabel, - UrlRedirectImport, - Video, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct StagedUploadParameter { - pub name: String, - pub value: String, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct StagedMediaUploadTarget { - pub parameters: Vec, - #[serde(rename = "resourceUrl")] - pub resource_url: String, - pub url: String, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct StagedUploadsCreateInput { - pub filename: String, - pub mime_type: String, - pub resource: StagedUploadResource, - pub http_method: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub file_size: Option, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct ShopifyUserError { - pub field: Option>, - pub message: String, -} - -#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum ShopifyBulkErrorCode { - AccessDenied, - InternalServerError, - Timeout, -} - -#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum ShopifyBulkStatus { - Canceled, - Canceling, - Completed, - Created, - Expired, - Failed, - Running, -} - -impl ShopifyBulkStatus { - pub fn is_terminal(&self) -> bool { - matches!( - self, - ShopifyBulkStatus::Canceled - | ShopifyBulkStatus::Completed - | ShopifyBulkStatus::Expired - | ShopifyBulkStatus::Failed - ) - } -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct ShopifyBulkOperation { - pub id: String, - pub url: Option, - #[serde(rename = "partialDataUrl")] - pub partial_data_url: Option, - pub status: ShopifyBulkStatus, - #[serde(rename = "errorCode")] - pub error_code: Option, - #[serde(rename = "createdAt")] - pub created_at: Option, - #[serde(rename = "completedAt")] - pub completed_at: Option, - #[serde(rename = "objectCount")] - pub object_count: Option, - #[serde(rename = "fileSize")] - pub file_size: Option, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct BulkOperationPayload { - #[serde(rename = "bulkOperation")] - pub bulk_operation: Option, - #[serde(rename = "userErrors")] - pub user_errors: Vec, -} - -#[derive(Debug, Clone)] -pub struct BulkWaitOptions { - pub poll_interval: Duration, - pub timeout: Option, -} - -impl Default for BulkWaitOptions { - fn default() -> Self { - Self { - poll_interval: Duration::from_secs(10), - timeout: None, - } - } -} - -#[derive(Debug, Clone, Default)] -pub struct BulkOperationsFilter { - pub first: u32, - pub query: Option, - pub after: Option, -} - -#[derive(Debug, Clone)] -pub struct BulkConcurrencyOptions { - pub max_concurrent: usize, -} - -impl Default for BulkConcurrencyOptions { - fn default() -> Self { - Self { max_concurrent: 5 } - } -} - -#[derive(Debug, Deserialize)] -struct RunBulkQueryData { - #[serde(rename = "bulkOperationRunQuery")] - payload: BulkOperationPayload, -} - -#[derive(Debug, Deserialize)] -struct RunBulkMutationData { - #[serde(rename = "bulkOperationRunMutation")] - payload: BulkOperationPayload, -} - -#[derive(Debug, Deserialize)] -struct BulkOperationData { - #[serde(rename = "bulkOperation")] - bulk_operation: Option, -} - -#[derive(Debug, Deserialize)] -struct BulkOperationsData { - #[serde(rename = "bulkOperations")] - bulk_operations: BulkOperationConnection, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct BulkOperationConnection { - pub edges: Vec, - #[serde(rename = "pageInfo")] - pub page_info: PageInfo, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct BulkOperationEdge { - pub cursor: String, - pub node: ShopifyBulkOperation, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct PageInfo { - #[serde(rename = "hasNextPage")] - pub has_next_page: bool, - #[serde(rename = "endCursor")] - pub end_cursor: Option, -} - -#[derive(Debug, Deserialize)] -struct StagedUploadsData { - #[serde(rename = "stagedUploadsCreate")] - staged_uploads_create: StagedUploadsCreatePayload, -} - -#[derive(Debug, Deserialize)] -struct StagedUploadsCreatePayload { - #[serde(rename = "stagedTargets")] - staged_targets: Vec, - #[serde(rename = "userErrors")] - user_errors: Vec, -} - -impl Shopify { - pub async fn run_bulk_queries( - &self, - queries: I, - options: BulkConcurrencyOptions, - ) -> Result, ShopifyAPIError> - where - I: IntoIterator, - S: AsRef, - { - let queries = queries.into_iter().collect::>(); - if queries.len() > options.max_concurrent { - return Err(ShopifyAPIError::Other(format!( - "received {} bulk queries but max_concurrent is {}", - queries.len(), - options.max_concurrent - ))); - } - - let mut operations = Vec::with_capacity(queries.len()); - for query in queries { - operations.push(self.run_bulk_query(query.as_ref()).await?); - } - - Ok(operations) - } - - pub async fn run_bulk_mutations( - &self, - mutations: I, - options: BulkConcurrencyOptions, - ) -> Result, ShopifyAPIError> - where - I: IntoIterator, - M: AsRef, - P: AsRef, - { - let mutations = mutations.into_iter().collect::>(); - if mutations.len() > options.max_concurrent { - return Err(ShopifyAPIError::Other(format!( - "received {} bulk mutations but max_concurrent is {}", - mutations.len(), - options.max_concurrent - ))); - } - - let mut operations = Vec::with_capacity(mutations.len()); - for (mutation, staged_upload_path) in mutations { - operations.push( - self.run_bulk_mutation(mutation.as_ref(), staged_upload_path.as_ref()) - .await?, - ); - } - - Ok(operations) - } - - pub async fn run_bulk_query( - &self, - query: &str, - ) -> Result { - self.run_bulk_query_with_grouping(query, false).await - } - - pub async fn run_bulk_query_with_grouping( - &self, - query: &str, - group_objects: bool, - ) -> Result { - let data: RunBulkQueryData = self - .graphql( - r#" - mutation bulkOperationRunQuery($query: String!, $groupObjects: Boolean!) { - bulkOperationRunQuery(query: $query, groupObjects: $groupObjects) { - bulkOperation { - id - status - url - partialDataUrl - } - userErrors { - field - message - } - } - } - "#, - &json!({ - "query": query, - "groupObjects": group_objects, - }), - ) - .await?; - - Ok(data.payload) - } - - pub async fn run_bulk_mutation( - &self, - mutation: &str, - staged_upload_path: &str, - ) -> Result { - let data: RunBulkMutationData = self - .graphql( - r#" - mutation bulkOperationRunMutation($mutation: String!, $stagedUploadPath: String!) { - bulkOperationRunMutation( - mutation: $mutation, - stagedUploadPath: $stagedUploadPath - ) { - bulkOperation { - id - status - url - partialDataUrl - } - userErrors { - field - message - } - } - } - "#, - &json!({ - "mutation": mutation, - "stagedUploadPath": staged_upload_path, - }), - ) - .await?; - - Ok(data.payload) - } - - pub async fn get_bulk_operation( - &self, - id: &str, - ) -> Result, ShopifyAPIError> { - let data: BulkOperationData = self - .graphql( - r#" - query bulkOperation($id: ID!) { - bulkOperation(id: $id) { - id - status - errorCode - createdAt - completedAt - objectCount - fileSize - url - partialDataUrl - } - } - "#, - &json!({ "id": id }), - ) - .await?; - - Ok(data.bulk_operation) - } - - pub async fn list_bulk_operations( - &self, - filter: BulkOperationsFilter, - ) -> Result { - let first = if filter.first == 0 { 10 } else { filter.first }; - let data: BulkOperationsData = self - .graphql( - r#" - query bulkOperations($first: Int!, $query: String, $after: String) { - bulkOperations(first: $first, query: $query, after: $after) { - edges { - cursor - node { - id - status - errorCode - createdAt - completedAt - objectCount - fileSize - url - partialDataUrl - } - } - pageInfo { - hasNextPage - endCursor - } - } - } - "#, - &json!({ - "first": first, - "query": filter.query, - "after": filter.after, - }), - ) - .await?; - - Ok(data.bulk_operations) - } - - pub async fn wait_for_bulk( - &self, - id: &str, - options: BulkWaitOptions, - ) -> Result { - let started_at = Instant::now(); - - loop { - let operation = self.get_bulk_operation(id).await?.ok_or_else(|| { - ShopifyAPIError::Other(format!("bulk operation `{id}` was not found")) - })?; - - if operation.status.is_terminal() { - return Ok(operation); - } - - if let Some(timeout) = options.timeout { - if started_at.elapsed() >= timeout { - return Err(ShopifyAPIError::Timeout(format!( - "bulk operation `{id}` did not finish within {timeout:?}" - ))); - } - } - - tokio::time::sleep(options.poll_interval).await; - } - } - - pub async fn stage_upload_jsonl(&self, data: &[T]) -> Result - where - T: Serialize, - { - let jsonl_data = data - .iter() - .map(serde_json::to_string) - .collect::, _>>()? - .join("\n"); - - let target = self - .create_staged_upload("bulk_op_vars", "text/jsonl") - .await?; - - let mut staged_upload_path = String::new(); - let mut form = reqwest::multipart::Form::new(); - - for parameter in target.parameters { - if parameter.name == "key" { - staged_upload_path = parameter.value.clone(); - } - form = form.text(parameter.name, parameter.value); - } - - let file_part = reqwest::multipart::Part::bytes(jsonl_data.into_bytes()) - .file_name("bulk_op_vars") - .mime_str("text/jsonl") - .map_err(|err| ShopifyAPIError::Other(err.to_string()))?; - - form = form.part("file", file_part); - self.client() - .post(&target.url) - .multipart(form) - .send() - .await? - .error_for_status()?; - - if staged_upload_path.is_empty() { - return Err(ShopifyAPIError::Other( - "staged upload did not return a key parameter".to_string(), - )); - } - - Ok(staged_upload_path) - } - - pub async fn download_bulk_jsonl(url: &str) -> Result, ShopifyAPIError> - where - T: serde::de::DeserializeOwned, - { - let body = reqwest::get(url).await?.error_for_status()?.text().await?; - parse_jsonl(&body) - } - - async fn create_staged_upload( - &self, - filename: &str, - mime_type: &str, - ) -> Result { - let input = StagedUploadsCreateInput { - filename: filename.to_string(), - mime_type: mime_type.to_string(), - resource: StagedUploadResource::BulkMutationVariables, - http_method: "POST".to_string(), - file_size: None, - }; - - let data: StagedUploadsData = self - .graphql( - r#" - mutation stagedUploadsCreate($input: [StagedUploadInput!]!) { - stagedUploadsCreate(input: $input) { - stagedTargets { - url - resourceUrl - parameters { - name - value - } - } - userErrors { - field - message - } - } - } - "#, - &json!({ "input": [input] }), - ) - .await?; - - if !data.staged_uploads_create.user_errors.is_empty() { - return Err(ShopifyAPIError::Other(format!( - "stagedUploadsCreate returned errors: {:?}", - data.staged_uploads_create.user_errors - ))); - } - - data.staged_uploads_create - .staged_targets - .into_iter() - .next() - .ok_or_else(|| ShopifyAPIError::Other("no staged upload target returned".to_string())) - } -} - -pub fn parse_jsonl(body: &str) -> Result, ShopifyAPIError> -where - T: serde::de::DeserializeOwned, -{ - body.lines() - .filter(|line| !line.trim().is_empty()) - .map(|line| serde_json::from_str(line).map_err(ShopifyAPIError::JsonParseError)) - .collect() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parses_jsonl_bulk_results() { - let parsed: Vec = parse_jsonl("{\"id\":1}\n{\"id\":2}\n\n").unwrap(); - - assert_eq!(parsed.len(), 2); - assert_eq!(parsed[0]["id"], 1); - } -} diff --git a/src/graphql/mod.rs b/src/graphql/mod.rs deleted file mode 100644 index da7338a..0000000 --- a/src/graphql/mod.rs +++ /dev/null @@ -1,146 +0,0 @@ -mod bulk_query; -pub mod types; - -use serde::{Deserialize, Serialize}; - -use crate::{utils::ReadJsonTreeSteps, Shopify, ShopifyAPIError}; - -pub use bulk_query::*; - -#[cfg(feature = "graphql-client")] -use graphql_client::{GraphQLQuery, Response as GraphQLClientResponse}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct GraphqlResponse { - pub data: Option, - pub errors: Option>, - pub extensions: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct GraphqlError { - pub message: String, - pub locations: Option, - pub path: Option, - pub extensions: Option, -} - -#[derive(Debug, Serialize)] -struct GraphqlRequest<'a, Variables> { - query: &'a str, - variables: &'a Variables, -} - -impl Shopify { - pub async fn graphql_raw( - &self, - query: &str, - variables: &Variables, - ) -> Result, ShopifyAPIError> - where - Variables: serde::Serialize, - { - let token = self.access_token().await?; - let response = self - .client() - .post(self.get_query_url()) - .header("Content-Type", "application/json") - .header("X-Shopify-Access-Token", token) - .json(&GraphqlRequest { query, variables }) - .send() - .await? - .error_for_status()?; - - let status = response.status(); - let body = response.text().await?; - log::debug!("shopify graphql response status: {status}"); - serde_json::from_str(&body).map_err(ShopifyAPIError::JsonParseError) - } - - pub async fn graphql( - &self, - query: &str, - variables: &Variables, - ) -> Result - where - ReturnType: serde::de::DeserializeOwned, - Variables: serde::Serialize, - { - let response = self.graphql_raw(query, variables).await?; - if let Some(errors) = response.errors { - if errors.iter().any(|error| { - error - .extensions - .as_ref() - .and_then(|v| v.get("code")) - .and_then(|v| v.as_str()) - == Some("THROTTLED") - }) { - return Err(ShopifyAPIError::Throttled); - } - return Err(ShopifyAPIError::GraphqlErrors(errors)); - } - - let data = response.data.ok_or(ShopifyAPIError::MissingGraphqlData)?; - serde_json::from_value(data).map_err(ShopifyAPIError::JsonParseError) - } - - pub async fn graphql_at_path( - &self, - query: &str, - variables: &Variables, - json_finder: &[ReadJsonTreeSteps<'_>], - ) -> Result - where - ReturnType: serde::de::DeserializeOwned, - Variables: serde::Serialize, - { - let data = self - .graphql::(query, variables) - .await?; - let value = crate::utils::read_json_tree(&data, json_finder) - .map_err(|_| ShopifyAPIError::NotWantedJsonFormat(data.to_string()))?; - serde_json::from_value(value.to_owned()).map_err(ShopifyAPIError::JsonParseError) - } - - #[cfg(feature = "graphql-client")] - pub async fn post_graphql( - &self, - variables: Q::Variables, - ) -> Result, ShopifyAPIError> { - let token = self.access_token().await?; - let body = Q::build_query(variables); - let response = self - .client() - .post(self.get_query_url()) - .header("Content-Type", "application/json") - .header("X-Shopify-Access-Token", token) - .json(&body) - .send() - .await? - .error_for_status()?; - - response - .json::>() - .await - .map_err(ShopifyAPIError::ConnectionFailed) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn graphql_response_parses_errors_and_extensions() { - let raw = r#"{ - "errors": [{"message": "boom", "extensions": {"code": "THROTTLED"}}], - "extensions": {"cost": {"actualQueryCost": 1}} - }"#; - - let parsed: GraphqlResponse = serde_json::from_str(raw).unwrap(); - - assert_eq!(parsed.errors.unwrap()[0].message, "boom"); - assert!(parsed.extensions.unwrap().get("cost").is_some()); - } -} diff --git a/src/graphql/types.rs b/src/graphql/types.rs deleted file mode 100644 index 58afde7..0000000 --- a/src/graphql/types.rs +++ /dev/null @@ -1,12 +0,0 @@ -// Missing types from the GraphQL schema -#[allow(clippy::upper_case_acronyms)] -pub type Decimal = String; - -#[allow(clippy::upper_case_acronyms)] -pub type JSON = String; - -#[allow(clippy::upper_case_acronyms)] -pub type UnsignedInt64 = String; - -#[allow(clippy::upper_case_acronyms)] -pub type DateTime = String; diff --git a/src/lib.rs b/src/lib.rs deleted file mode 100644 index fae6c0d..0000000 --- a/src/lib.rs +++ /dev/null @@ -1,284 +0,0 @@ -use std::sync::{Arc, Mutex}; - -use thiserror::Error; - -pub mod auth; -pub mod graphql; -pub mod schema; -pub mod utils; -#[cfg(feature = "webhooks")] -pub mod webhooks; - -pub use auth::{ShopifyAuth, TokenData, TokenStore}; -pub use graphql::{ - BulkConcurrencyOptions, BulkOperationPayload, BulkOperationsFilter, BulkWaitOptions, - GraphqlError, GraphqlResponse, ShopifyBulkOperation, ShopifyBulkStatus, -}; -pub use schema::{download_public_admin_schema, SHOPIFY_DEV_ADMIN_SCHEMA_PROXY}; - -pub const DEFAULT_API_VERSION: &str = "2026-04"; -pub const MIN_API_VERSION: &str = "2026-04"; -pub static VERSION: &str = "shopify_api/0.10"; - -#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] -pub struct ApiVersion(String); - -impl ApiVersion { - pub fn new(version: impl Into) -> Result { - let version = version.into(); - validate_api_version(&version)?; - Ok(Self(version)) - } - - pub fn as_str(&self) -> &str { - &self.0 - } -} - -impl Default for ApiVersion { - fn default() -> Self { - Self(DEFAULT_API_VERSION.to_string()) - } -} - -impl std::fmt::Display for ApiVersion { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.0.fmt(f) - } -} - -impl TryFrom<&str> for ApiVersion { - type Error = ShopifyAPIError; - - fn try_from(value: &str) -> Result { - Self::new(value) - } -} - -impl TryFrom for ApiVersion { - type Error = ShopifyAPIError; - - fn try_from(value: String) -> Result { - Self::new(value) - } -} - -#[derive(Clone)] -pub struct ShopifyConfig { - pub api_version: ApiVersion, - #[cfg(feature = "webhooks")] - pub shared_secret: Option, - pub token_store: Option>, - pub token_refresh_leeway: chrono::Duration, - pub user_agent: String, -} - -impl Default for ShopifyConfig { - fn default() -> Self { - Self { - api_version: ApiVersion::default(), - #[cfg(feature = "webhooks")] - shared_secret: None, - token_store: None, - token_refresh_leeway: chrono::Duration::minutes(5), - user_agent: VERSION.to_string(), - } - } -} - -#[derive(Clone)] -pub struct Shopify { - pub api_version: ApiVersion, - #[cfg(feature = "webhooks")] - pub(crate) shared_secret: Option, - auth: Arc>, - client: reqwest::Client, - query_url: String, - token_url: String, - shop: String, - shop_domain: String, - token_store: Option>, - token_refresh_leeway: chrono::Duration, -} - -impl std::fmt::Debug for Shopify { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Shopify") - .field("api_version", &self.api_version) - .field("query_url", &self.query_url) - .field("token_url", &self.token_url) - .field("shop", &self.shop) - .field("shop_domain", &self.shop_domain) - .finish_non_exhaustive() - } -} - -#[derive(Debug, Error)] -pub enum ShopifyAPIError { - #[error("connection failed")] - ConnectionFailed(#[from] reqwest::Error), - - #[error("response body is broken")] - ResponseBroken, - - #[error("not a JSON response: {0}")] - NotJson(String), - - #[error("not wanted JSON format: {0}")] - NotWantedJsonFormat(String), - - #[error("request throttled")] - Throttled, - - #[error("JSON parsing error: {0}")] - JsonParseError(#[from] serde_json::Error), - - #[error("invalid API version `{version}`: minimum supported version is {minimum}")] - InvalidApiVersion { version: String, minimum: String }, - - #[error("authentication error: {0}")] - Authentication(String), - - #[error("GraphQL returned errors: {0:?}")] - GraphqlErrors(Vec), - - #[error("missing GraphQL data")] - MissingGraphqlData, - - #[error("invalid header value: {0}")] - InvalidHeaderValue(#[from] reqwest::header::InvalidHeaderValue), - - #[error("operation timed out: {0}")] - Timeout(String), - - #[error("other error: {0}")] - Other(String), -} - -impl Shopify { - pub fn new( - shop: impl AsRef, - auth: ShopifyAuth, - config: ShopifyConfig, - ) -> Result { - let shop = shop.as_ref().to_string(); - let shop_domain = normalize_shop_domain(&shop); - let query_url = format!( - "https://{}/admin/api/{}/graphql.json", - shop_domain, config.api_version - ); - let token_url = format!("https://{}/admin/oauth/access_token", shop_domain); - let mut headers = reqwest::header::HeaderMap::new(); - headers.insert( - reqwest::header::USER_AGENT, - reqwest::header::HeaderValue::from_str(&config.user_agent)?, - ); - let client = reqwest::Client::builder() - .default_headers(headers) - .build()?; - - Ok(Self { - api_version: config.api_version, - #[cfg(feature = "webhooks")] - shared_secret: config.shared_secret, - auth: Arc::new(Mutex::new(auth)), - client, - query_url, - token_url, - shop, - shop_domain, - token_store: config.token_store, - token_refresh_leeway: config.token_refresh_leeway, - }) - } - - pub fn get_shop(&self) -> &str { - &self.shop - } - - pub fn shop_domain(&self) -> &str { - &self.shop_domain - } - - pub fn get_query_url(&self) -> &str { - &self.query_url - } - - pub fn token_url(&self) -> &str { - &self.token_url - } - - pub(crate) fn client(&self) -> &reqwest::Client { - &self.client - } - - pub fn replace_auth(&self, auth: ShopifyAuth) -> Result<(), ShopifyAPIError> { - let mut current = self - .auth - .lock() - .map_err(|_| ShopifyAPIError::Authentication("auth lock poisoned".to_string()))?; - *current = auth; - Ok(()) - } -} - -fn normalize_shop_domain(shop: &str) -> String { - let shop = shop.trim().trim_start_matches("https://"); - let shop = shop.trim_start_matches("http://").trim_end_matches('/'); - if shop.ends_with(".myshopify.com") { - shop.to_string() - } else { - format!("{shop}.myshopify.com") - } -} - -fn validate_api_version(version: &str) -> Result<(), ShopifyAPIError> { - let parsed = parse_api_version(version); - let minimum = parse_api_version(MIN_API_VERSION); - - match (parsed, minimum) { - (Some(parsed), Some(minimum)) if parsed >= minimum => Ok(()), - _ => Err(ShopifyAPIError::InvalidApiVersion { - version: version.to_string(), - minimum: MIN_API_VERSION.to_string(), - }), - } -} - -fn parse_api_version(version: &str) -> Option<(u16, u8)> { - let (year, month) = version.split_once('-')?; - Some((year.parse().ok()?, month.parse().ok()?)) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn api_version_rejects_versions_before_2026_04() { - assert!(ApiVersion::new("2025-10").is_err()); - assert!(ApiVersion::new("2026-01").is_err()); - assert_eq!(ApiVersion::new("2026-04").unwrap().as_str(), "2026-04"); - assert_eq!(ApiVersion::new("2026-07").unwrap().as_str(), "2026-07"); - } - - #[test] - fn endpoints_are_built_from_normalized_shop_and_version() { - let shopify = Shopify::new( - "example", - ShopifyAuth::AccessToken("token".to_string()), - ShopifyConfig::default(), - ) - .unwrap(); - - assert_eq!(shopify.shop_domain(), "example.myshopify.com"); - assert_eq!( - shopify.get_query_url(), - "https://example.myshopify.com/admin/api/2026-04/graphql.json" - ); - assert_eq!( - shopify.token_url(), - "https://example.myshopify.com/admin/oauth/access_token" - ); - } -} diff --git a/src/schema.rs b/src/schema.rs deleted file mode 100644 index 898b64c..0000000 --- a/src/schema.rs +++ /dev/null @@ -1,42 +0,0 @@ -use serde_json::json; - -use crate::{ApiVersion, Shopify, ShopifyAPIError}; - -pub const ADMIN_SCHEMA_INTROSPECTION_QUERY: &str = include_str!("../schema_dl.graphql"); -pub const SHOPIFY_DEV_ADMIN_SCHEMA_PROXY: &str = "https://shopify.dev/admin-graphql-direct-proxy"; - -pub async fn download_public_admin_schema( - api_version: impl AsRef, -) -> Result { - let api_version = ApiVersion::new(api_version.as_ref())?; - let url = format!("{SHOPIFY_DEV_ADMIN_SCHEMA_PROXY}/{api_version}"); - let response = reqwest::Client::new() - .post(url) - .json(&json!({ - "query": ADMIN_SCHEMA_INTROSPECTION_QUERY, - "variables": {}, - })) - .send() - .await? - .error_for_status()?; - - response - .json() - .await - .map_err(ShopifyAPIError::ConnectionFailed) -} - -impl Shopify { - /// Downloads the Admin GraphQL schema through the authenticated shop endpoint. - pub async fn download_admin_schema(&self) -> Result { - let response = self - .graphql_raw(ADMIN_SCHEMA_INTROSPECTION_QUERY, &json!({})) - .await?; - - if let Some(errors) = response.errors { - return Err(ShopifyAPIError::GraphqlErrors(errors)); - } - - serde_json::to_value(response).map_err(ShopifyAPIError::JsonParseError) - } -} diff --git a/src/utils.rs b/src/utils.rs deleted file mode 100644 index b6a5e00..0000000 --- a/src/utils.rs +++ /dev/null @@ -1,228 +0,0 @@ -use std::future::Future; - -/// Retry function for async functions -/// # Example -/// ``` -/// use shopify_api::utils::retry_async; -/// use std::io::{Error, ErrorKind}; -/// -/// async fn my_async_function(args: &(String, u8)) -> Result<(), Error> { -/// Err(Error::new(ErrorKind::Other, "Error")) -/// } -/// -/// #[tokio::main] -/// async fn main() { -/// let result = retry_async(3, my_async_function, &(String::from("test"), 1)).await; -/// assert!(result.is_err()); -/// } -/// ``` -/// # Errors -/// This function returns an error if the async function returns an error -/// # Panics -/// This function panics if the number of retries is 0 -pub async fn retry_async<'a, Fut, F, Args, Out, ErrOut>( - max_retries: u64, - func: Fut, - args: &'a Args, -) -> Result -where - Fut: Fn(&'a Args) -> F, - F: Future>, - ErrOut: std::fmt::Debug, -{ - if max_retries == 0 { - panic!("Max retries cannot be 0"); - } - - let mut count: u64 = 0; - let mut result: Result = func(args).await; - - while count < max_retries - 1 && result.is_err() { - let executed_func = func(args); - - result = executed_func.await; - if result.is_ok() { - return result; - } - - count += 1; - } - - result -} - -/// Retry function for sync functions -/// # Example -/// ``` -/// use shopify_api::utils::retry_sync; -/// use std::io::{Error, ErrorKind}; -/// -/// fn my_sync_function(args: &(String, u8)) -> Result<(), Error> { -/// Err(Error::new(ErrorKind::Other, "Error")) -/// } -/// -/// fn main() { -/// let result = retry_sync(3, my_sync_function, &(String::from("test"), 1)); -/// assert!(result.is_err()); -/// } -/// ``` -/// # Errors -/// This function returns an error if the sync function returns an error -/// # Panics -/// This function panics if the number of retries is 0 -pub fn retry_sync<'a, F, Args, Out, ErrOut>( - max_retries: u64, - func: F, - args: &'a Args, -) -> Result -where - F: Fn(&'a Args) -> Result, - ErrOut: std::fmt::Debug, -{ - if max_retries == 0 { - panic!("Max retries cannot be 0"); - } - - let mut count: u64 = 0; - let mut result: Result = func(args); - - while count < max_retries - 1 && result.is_err() { - let executed_func = func(args); - - result = executed_func; - if result.is_ok() { - return result; - } - - count += 1; - } - - result -} - -#[derive(Clone, Debug)] -pub enum ReadJsonTreeError { - JsonNotFound, -} - -#[derive(Clone, Debug)] -pub enum ReadJsonTreeSteps<'a> { - Key(&'a str), - Index(usize), -} - -/// Read json tree with a path -/// # Example -/// ``` -/// use shopify_api::utils::read_json_tree; -/// use serde_json::json; -/// -/// let json: serde_json::Value = json!({ -/// "a": { -/// "b": { -/// "c": "d" -/// } -/// } -/// }); -/// -/// -/// let success_read = read_json_tree( -/// &json, -/// &vec![ -/// shopify_api::utils::ReadJsonTreeSteps::Key("a"), -/// shopify_api::utils::ReadJsonTreeSteps::Key("b"), -/// shopify_api::utils::ReadJsonTreeSteps::Key("c") -/// ] -/// ); -/// -/// let error_read = read_json_tree( -/// &json, -/// &vec![ -/// shopify_api::utils::ReadJsonTreeSteps::Key("a"), -/// shopify_api::utils::ReadJsonTreeSteps::Key("b"), -/// shopify_api::utils::ReadJsonTreeSteps::Key("d") -/// ] -/// ); -/// -/// println!("{:?}", success_read); -/// assert_eq!(success_read.unwrap(), &json!("d")); -/// assert!(error_read.is_err()); -/// ``` -/// # Errors -/// This function returns an error if the json tree is not found -pub fn read_json_tree<'a>( - json_value: &'a serde_json::Value, - path: &[ReadJsonTreeSteps], -) -> Result<&'a serde_json::Value, ReadJsonTreeError> { - let mut actual_value: &serde_json::Value = json_value; - - for step in path { - match step { - ReadJsonTreeSteps::Key(key) => { - actual_value = actual_value - .get(key) - .ok_or(ReadJsonTreeError::JsonNotFound)?; - } - ReadJsonTreeSteps::Index(index) => { - actual_value = actual_value - .get(*index) - .ok_or(ReadJsonTreeError::JsonNotFound)?; - } - } - } - - Ok(actual_value) -} - -#[cfg(feature = "debug")] -pub fn deserialize_from_value(value: serde_json::Value) -> Result -where - T: serde::de::DeserializeOwned, -{ - let json_string = serde_json::to_string(&value) - .map_err(|err| format!("Error serializing JSON value: {err}"))?; - let jd = &mut serde_json::Deserializer::from_str(&json_string); - - let result: Result = serde_path_to_error::deserialize(jd); - match result { - Ok(customer) => Ok(customer), - Err(err) => Err(format!( - "Error parsing JSON at {}: {}", - err.path(), - err.inner() - )), - } -} - -#[cfg(not(feature = "debug"))] -pub fn deserialize_from_value(value: serde_json::Value) -> Result -where - T: serde::de::DeserializeOwned, -{ - let result: Result = serde_json::from_value(value); - match result { - Ok(customer) => Ok(customer), - Err(err) => Err(format!("Error parsing JSON: {}", err)), - } -} - -#[cfg(feature = "debug")] -pub fn deserialize_from_str(json_string: &str) -> Result -where - T: serde::de::DeserializeOwned, -{ - let value: serde_json::Value = - serde_json::from_str(json_string).map_err(|err| format!("Error parsing JSON: {err}"))?; - deserialize_from_value(value) -} - -#[cfg(not(feature = "debug"))] -pub fn deserialize_from_str(json_string: &str) -> Result -where - T: serde::de::DeserializeOwned, -{ - match serde_json::from_str(json_string) { - Ok(customer) => Ok(customer), - Err(err) => Err(format!("Error parsing JSON: {}", err)), - } -} diff --git a/src/webhooks/frameworks/mod.rs b/src/webhooks/frameworks/mod.rs deleted file mode 100644 index 690add4..0000000 --- a/src/webhooks/frameworks/mod.rs +++ /dev/null @@ -1,325 +0,0 @@ -#![cfg(feature = "warp-wrapper")] -pub mod warp; - -// Webhook payload structs used by the optional warp receiver. - -use serde::{Deserialize, Serialize}; -use serde_json::Value; - -#[derive(Debug)] -pub enum ShopifyWebhook { - InventoryItemCreate(InventoryItem), - InventoryItemUpdate(InventoryItem), - InventoryItemDelete(InventoryItem), - InventoryLevelConnect(InventoryLevel), - InventoryLevelDisconnect(InventoryLevel), - InventoryLevelUpdate(InventoryLevel), - CustomersCreate(Customer), - CustomersUpdate(Customer), - OrdersCreate(Order), - OrdersUpdated(Order), - Other((String, Value)), -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct InventoryLevel { - pub inventory_item_id: u64, - pub location_id: u64, - pub available: Option, - pub updated_at: Option, - pub admin_graphql_api_id: Option, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct InventoryItem { - pub id: u64, - pub sku: String, - pub created_at: String, - pub updated_at: String, - pub requires_shipping: bool, - pub cost: Option, - pub country_code_of_origin: Option, - pub province_code_of_origin: Option, - pub harmonized_system_code: Option, - pub tracked: bool, - pub country_harmonized_system_codes: Vec, - pub admin_graphql_api_id: Option, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct Address { - pub id: u64, - pub customer_id: u64, - pub first_name: Option, - pub last_name: Option, - pub company: Option, - pub address1: Option, - pub address2: Option, - pub city: Option, - pub province: Option, - pub country: Option, - pub zip: Option, - pub phone: Option, - pub province_code: Option, - pub country_code: Option, - pub country_name: Option, - pub default: bool, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct Customer { - pub id: u64, - pub email: String, - pub created_at: String, - pub updated_at: String, - pub first_name: Option, - pub last_name: Option, - pub orders_count: Option, - pub state: String, - pub total_spent: Option, - pub last_order_id: Option, - pub note: Option, - pub verified_email: bool, - pub multipass_identifier: Option, - pub tax_exempt: bool, - pub tags: Option, - pub last_order_name: Option, - pub phone: Option, - pub addresses: Vec
, - pub admin_graphql_api_id: String, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct CountryHarmonizedSystemCode { - pub harmonized_system_code: String, - pub country_code: String, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct Order { - pub id: u64, - pub admin_graphql_api_id: String, - pub app_id: Option, - pub browser_ip: Option, - pub buyer_accepts_marketing: bool, - pub cancel_reason: Option, - pub cancelled_at: Option, - pub cart_token: Option, - pub checkout_id: Option, - pub checkout_token: Option, - pub client_details: Option, - pub closed_at: Option, - pub confirmation_number: Option, - pub confirmed: bool, - pub contact_email: String, - pub created_at: String, - pub currency: String, - pub current_subtotal_price: String, - pub current_subtotal_price_set: OrderPriceSet, - pub current_total_additional_fees_set: Option, - pub current_total_discounts: String, - pub current_total_discounts_set: OrderPriceSet, - pub current_total_duties_set: Option, - pub current_total_price: String, - pub current_total_price_set: OrderPriceSet, - pub current_total_tax: String, - pub current_total_tax_set: OrderPriceSet, - pub customer_locale: Option, - pub device_id: Option, - pub discount_codes: Vec, - pub email: String, - pub estimated_taxes: bool, - pub financial_status: String, - pub fulfillment_status: Option, - pub landing_site: Option, - pub landing_site_ref: Option, - pub location_id: Option, - pub merchant_of_record_app_id: Option, - pub name: String, - pub note: Option, - pub note_attributes: Vec, - pub number: u64, - pub order_number: u64, - pub order_status_url: String, - pub original_total_additional_fees_set: Option, - pub original_total_duties_set: Option, - pub payment_gateway_names: Vec, - pub phone: Option, - pub po_number: Option, - pub presentment_currency: String, - pub processed_at: Option, - pub reference: Option, - pub referring_site: Option, - pub source_identifier: Option, - pub source_name: String, - pub source_url: Option, - pub subtotal_price: String, - pub subtotal_price_set: OrderPriceSet, - pub tags: String, - pub tax_exempt: bool, - pub tax_lines: Vec, - pub taxes_included: bool, - pub test: bool, - pub token: String, - pub total_discounts: String, - pub total_discounts_set: OrderPriceSet, - pub total_line_items_price: String, - pub total_line_items_price_set: OrderPriceSet, - pub total_outstanding: String, - pub total_price: String, - pub total_price_set: OrderPriceSet, - pub total_shipping_price_set: OrderPriceSet, - pub total_tax: String, - pub total_tax_set: OrderPriceSet, - pub total_tip_received: String, - pub total_weight: u64, - pub updated_at: String, - pub user_id: Option, - pub billing_address: Option, - pub customer: OrderCustomer, - pub discount_applications: Vec, - pub fulfillments: Vec, - pub line_items: Vec, - pub payment_terms: Option, - pub refunds: Vec, - pub shipping_address: Option, - pub shipping_lines: Vec, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderClientDetails {} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderPriceSet { - pub shop_money: OrderMoney, - pub presentment_money: OrderMoney, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderMoney { - pub amount: String, - pub currency_code: String, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderAdditionalFeesSet {} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderDutiesSet {} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderDiscountCode { - pub code: Option, - pub amount: Option, - #[serde(rename = "type")] - pub _type: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderNoteAttribute { - pub name: Option, - pub value: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderTaxLine { - pub title: Option, - pub price: Option, - pub rate: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderAddress { - pub first_name: Option, - pub address1: Option, - pub phone: Option, - pub city: Option, - pub zip: Option, - pub province: Option, - pub country: Option, - pub last_name: Option, - pub address2: Option, - pub company: Option, - pub latitude: Option, - pub longitude: Option, - pub name: Option, - pub country_code: Option, - pub province_code: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderCustomer { - pub id: u64, - pub email: Option, - pub created_at: Option, - pub updated_at: Option, - pub first_name: Option, - pub last_name: Option, - pub state: Option, - pub note: Option, - pub verified_email: bool, - pub multipass_identifier: Option, - pub tax_exempt: bool, - pub phone: Option, - pub email_marketing_consent: Option, - pub sms_marketing_consent: Option, - pub tags: Option, - pub currency: String, - pub tax_exemptions: Vec, - pub admin_graphql_api_id: String, - pub default_address: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderConsent { - pub state: Option, - pub opt_in_level: Option, - pub consent_updated_at: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderDiscountApplication {} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderFulfillment {} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderLineItem { - pub id: u64, - pub admin_graphql_api_id: Option, - pub variant_id: Option, - pub quantity: i32, - pub price: String, - pub grams: i32, - pub name: String, - pub title: String, - pub variant_title: Option, - pub sku: Option, - pub variant_inventory_management: Option, - pub product_id: Option, - pub fulfillment_service: String, - pub product_exists: bool, - pub taxable: bool, - pub total_discount: String, - pub fulfillment_status: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderPaymentTerms {} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderRefund {} - -#[derive(Debug, Serialize, Deserialize)] -pub struct OrderShippingLine { - pub id: u64, - pub title: String, - pub price: String, - pub code: Option, - pub source: String, - pub phone: Option, - pub requested_fulfillment_service_id: Option, - pub delivery_category: Option, - pub carrier_identifier: Option, - pub discounted_price: String, -} diff --git a/src/webhooks/frameworks/warp.rs b/src/webhooks/frameworks/warp.rs deleted file mode 100644 index 6979f53..0000000 --- a/src/webhooks/frameworks/warp.rs +++ /dev/null @@ -1,129 +0,0 @@ -use super::{Customer, InventoryItem, InventoryLevel, ShopifyWebhook}; -use crate::Shopify; -use serde_json; -use std::future::Future; -use std::sync::Arc; -use tokio::sync::Mutex; -use warp::http::StatusCode; -use warp::{Filter, Rejection}; - -impl Shopify { - #[cfg(feature = "warp-wrapper")] - pub fn warp_wrapper( - path: &str, - shopify_filter: Arc>, - extra_data: T, - callback: F, - ) -> warp::filters::BoxedFilter<(impl warp::Reply,)> - where - T: Clone + Send + Sync + 'static, - F: Fn(ShopifyWebhook, Arc>, T) -> Fut + Clone + Send + Sync + 'static, - Fut: Future> + Send, - { - let path_clone = path.to_string(); - - warp::path(path_clone) - .and(warp::post()) - .and(warp::any().map(move || shopify_filter.clone())) - .and(warp::any().map(move || extra_data.clone())) - .and(warp::header::("x-shopify-hmac-sha256")) - .and(warp::header::("X-Shopify-Topic")) - .and(warp::body::bytes()) - .and_then( - move |shopify: Arc>, - extra: T, - header: String, - topic: String, - body: bytes::Bytes| { - let callback_clone = callback.clone(); - async move { - let is_valid = shopify.lock().await.verify_hmac(&body, &header); - - if !is_valid { - return Ok::<_, Rejection>(warp::reply::with_status( - warp::reply::html("Invalid HMAC"), - StatusCode::BAD_REQUEST, - )); - } - - let str_body = match std::str::from_utf8(&body) { - Ok(body) => body, - Err(_) => { - return Ok::<_, Rejection>(warp::reply::with_status( - warp::reply::html("Invalid UTF-8 payload"), - StatusCode::BAD_REQUEST, - )); - } - }; - - log::debug!("Received webhook topic: {}", topic); - - let webhook_data = match topic.as_str() { - "inventory_items/create" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::InventoryItemCreate) - } - "inventory_items/update" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::InventoryItemUpdate) - } - "inventory_items/delete" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::InventoryItemDelete) - } - "inventory_levels/connect" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::InventoryLevelConnect) - } - "inventory_levels/disconnect" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::InventoryLevelDisconnect) - } - "inventory_levels/update" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::InventoryLevelUpdate) - } - "customers/create" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::CustomersCreate) - } - "customers/update" => { - crate::utils::deserialize_from_str::(str_body) - .map(ShopifyWebhook::CustomersUpdate) - } - "orders/create" => crate::utils::deserialize_from_str(str_body) - .map(ShopifyWebhook::OrdersCreate), - "orders/updated" => crate::utils::deserialize_from_str(str_body) - .map(ShopifyWebhook::OrdersUpdated), - _ => serde_json::from_str(str_body) - .map(|value| ShopifyWebhook::Other((topic.clone(), value))) - .map_err(|err| format!("Error parsing JSON: {err}")), - }; - - let webhook_data = match webhook_data { - Ok(webhook_data) => webhook_data, - Err(err) => { - log::info!("Failed to parse webhook payload: {}", err); - return Ok::<_, Rejection>(warp::reply::with_status( - warp::reply::html("Invalid JSON payload"), - StatusCode::BAD_REQUEST, - )); - } - }; - - match callback_clone(webhook_data, shopify.clone(), extra.clone()).await { - Ok(_) => Ok(warp::reply::with_status( - warp::reply::html("Success"), - StatusCode::OK, - )), - Err(_e) => { - let custom_error = warp::reject::reject(); - Err(custom_error) - } - } - } - }, - ) - .boxed() - } -} diff --git a/src/webhooks/mod.rs b/src/webhooks/mod.rs deleted file mode 100644 index 2938721..0000000 --- a/src/webhooks/mod.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub mod frameworks; -pub mod verify; -pub mod webhook; - -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Deserialize, Serialize, Clone, Eq, PartialEq)] -pub struct WebhookSubscription { - pub id: String, - pub topic: String, - pub format: String, - pub uri: String, -} diff --git a/src/webhooks/verify.rs b/src/webhooks/verify.rs deleted file mode 100644 index 3845984..0000000 --- a/src/webhooks/verify.rs +++ /dev/null @@ -1,27 +0,0 @@ -use crate::Shopify; -use base64::prelude::*; -use hmac::{Hmac, KeyInit, Mac}; -use sha2::Sha256; - -impl Shopify { - pub fn verify_hmac(&self, data: &[u8], hmac_header: &str) -> bool { - if let Some(secret) = &self.shared_secret { - let Ok(mut mac) = Hmac::::new_from_slice(secret.as_bytes()) else { - log::info!("Failed to create webhook HMAC"); - return false; - }; - - let Ok(expected_hmac) = BASE64_STANDARD.decode(hmac_header) else { - log::info!("Invalid webhook HMAC header encoding"); - return false; - }; - - mac.update(data); - return mac.verify_slice(&expected_hmac).is_ok(); - } - - log::info!("No shared secret found"); - - false - } -} diff --git a/src/webhooks/webhook.rs b/src/webhooks/webhook.rs deleted file mode 100644 index 6167da5..0000000 --- a/src/webhooks/webhook.rs +++ /dev/null @@ -1,217 +0,0 @@ -use super::WebhookSubscription; -use crate::{Shopify, ShopifyAPIError}; -use serde::Deserialize; -use serde_json::json; - -#[derive(Debug, Deserialize)] -struct WebhookSubscriptionsData { - #[serde(rename = "webhookSubscriptions")] - webhook_subscriptions: WebhookSubscriptionConnection, -} - -#[derive(Debug, Deserialize)] -struct WebhookSubscriptionConnection { - edges: Vec, -} - -#[derive(Debug, Deserialize)] -struct WebhookSubscriptionEdge { - node: WebhookSubscriptionNode, -} - -#[derive(Debug, Deserialize)] -struct WebhookSubscriptionNode { - id: String, - topic: String, - format: String, - uri: String, -} - -#[derive(Debug, Deserialize)] -struct WebhookCreateData { - #[serde(rename = "webhookSubscriptionCreate")] - webhook_subscription_create: WebhookMutationPayload, -} - -#[derive(Debug, Deserialize)] -struct WebhookDeleteData { - #[serde(rename = "webhookSubscriptionDelete")] - webhook_subscription_delete: WebhookDeletePayload, -} - -#[derive(Debug, Deserialize)] -struct WebhookMutationPayload { - #[serde(rename = "webhookSubscription")] - webhook_subscription: Option, - #[serde(rename = "userErrors")] - user_errors: Vec, -} - -#[derive(Debug, Deserialize)] -struct WebhookDeletePayload { - #[serde(rename = "deletedWebhookSubscriptionId")] - deleted_webhook_subscription_id: Option, - #[serde(rename = "userErrors")] - user_errors: Vec, -} - -#[allow(dead_code)] -#[derive(Debug, Deserialize)] -struct WebhookUserError { - field: Option>, - message: String, -} - -impl From for WebhookSubscription { - fn from(node: WebhookSubscriptionNode) -> Self { - Self { - id: node.id, - topic: node.topic, - format: node.format, - uri: node.uri, - } - } -} - -impl Shopify { - pub async fn list_webhooks(&self) -> Result, ShopifyAPIError> { - let data: WebhookSubscriptionsData = self - .graphql( - r#" - query webhookSubscriptions { - webhookSubscriptions(first: 250) { - edges { - node { - id - topic - format - uri - } - } - } - } - "#, - &json!({}), - ) - .await?; - - Ok(data - .webhook_subscriptions - .edges - .into_iter() - .map(|edge| edge.node.into()) - .collect()) - } - - pub async fn add_webhook( - &self, - address: &str, - topic: &str, - format: &str, - ) -> Result { - let data: WebhookCreateData = self - .graphql( - r#" - mutation webhookSubscriptionCreate( - $topic: WebhookSubscriptionTopic!, - $uri: String!, - $format: WebhookSubscriptionFormat! - ) { - webhookSubscriptionCreate( - topic: $topic, - webhookSubscription: { - uri: $uri, - format: $format - } - ) { - webhookSubscription { - id - topic - format - uri - } - userErrors { - field - message - } - } - } - "#, - &json!({ - "topic": topic, - "uri": address, - "format": format, - }), - ) - .await?; - - if !data.webhook_subscription_create.user_errors.is_empty() { - return Err(ShopifyAPIError::Other(format!( - "webhookSubscriptionCreate returned errors: {:?}", - data.webhook_subscription_create.user_errors - ))); - } - - data.webhook_subscription_create - .webhook_subscription - .map(Into::into) - .ok_or_else(|| ShopifyAPIError::Other("no webhook subscription returned".to_string())) - } - - pub async fn delete_webhook(&self, webhook_id: &str) -> Result<(), ShopifyAPIError> { - let data: WebhookDeleteData = self - .graphql( - r#" - mutation webhookSubscriptionDelete($id: ID!) { - webhookSubscriptionDelete(id: $id) { - deletedWebhookSubscriptionId - userErrors { - field - message - } - } - } - "#, - &json!({ "id": webhook_id }), - ) - .await?; - - if !data.webhook_subscription_delete.user_errors.is_empty() { - return Err(ShopifyAPIError::Other(format!( - "webhookSubscriptionDelete returned errors: {:?}", - data.webhook_subscription_delete.user_errors - ))); - } - - data.webhook_subscription_delete - .deleted_webhook_subscription_id - .map(|_| ()) - .ok_or_else(|| ShopifyAPIError::Other("webhook was not deleted".to_string())) - } - - pub async fn webhook_auto_config( - &self, - desired_webhooks: Vec<(&str, &str, &str)>, - ) -> Result<(), ShopifyAPIError> { - let existing_webhooks = self.list_webhooks().await?; - let mut desired = desired_webhooks; - - for webhook in &existing_webhooks { - let matches_desired = desired.iter().position(|(address, topic, format)| { - webhook.uri == *address && webhook.topic == *topic && webhook.format == *format - }); - - if let Some(index) = matches_desired { - desired.remove(index); - } else { - self.delete_webhook(&webhook.id).await?; - } - } - - for (address, topic, format) in desired { - self.add_webhook(address, topic, format).await?; - } - - Ok(()) - } -} diff --git a/tests/live.rs b/tests/live.rs deleted file mode 100644 index dc88553..0000000 --- a/tests/live.rs +++ /dev/null @@ -1,213 +0,0 @@ -use serde::Deserialize; -use std::time::Duration; - -use shopify_api::{ - BulkConcurrencyOptions, BulkOperationsFilter, BulkWaitOptions, Shopify, ShopifyAPIError, - ShopifyAuth, ShopifyBulkStatus, ShopifyConfig, -}; - -fn live_client() -> Option { - let shop = std::env::var("SHOPIFY_TEST_SHOP").ok()?; - let token = std::env::var("SHOPIFY_TEST_ACCESS_TOKEN").ok()?; - Shopify::new( - shop, - ShopifyAuth::AccessToken(token), - ShopifyConfig::default(), - ) - .ok() -} - -fn live_client_credentials_client() -> Option { - let shop = std::env::var("SHOPIFY_TEST_SHOP").ok()?; - let client_id = std::env::var("SHOPIFY_TEST_CLIENT_ID").ok()?; - let client_secret = std::env::var("SHOPIFY_TEST_CLIENT_SECRET").ok()?; - Shopify::new( - shop, - ShopifyAuth::client_credentials(client_id, client_secret), - ShopifyConfig::default(), - ) - .ok() -} - -#[derive(Debug, Deserialize)] -struct ShopQuery { - shop: Shop, -} - -#[derive(Debug, Deserialize)] -struct Shop { - name: String, -} - -#[tokio::test] -async fn live_graphql_shop_query_when_env_is_present() -> Result<(), ShopifyAPIError> { - let Some(shopify) = live_client() else { - return Ok(()); - }; - - let data: ShopQuery = shopify - .graphql("query { shop { name } }", &serde_json::json!({})) - .await?; - - assert!(!data.shop.name.is_empty()); - Ok(()) -} - -#[tokio::test] -async fn live_schema_download_when_env_is_present() -> Result<(), ShopifyAPIError> { - let Some(shopify) = live_client() else { - return Ok(()); - }; - - let schema = shopify.download_admin_schema().await?; - - assert!(schema.pointer("/data/__schema").is_some()); - Ok(()) -} - -#[tokio::test] -async fn live_client_credentials_when_env_is_present() -> Result<(), ShopifyAPIError> { - let Some(shopify) = live_client_credentials_client() else { - return Ok(()); - }; - let token = shopify.access_token().await?; - - assert!(!token.is_empty()); - Ok(()) -} - -#[tokio::test] -async fn live_bulk_query_wait_list_and_download_when_env_is_present() -> Result<(), ShopifyAPIError> -{ - let Some(shopify) = live_client_credentials_client() else { - return Ok(()); - }; - - let payload = shopify - .run_bulk_query( - r#"{ - products { - edges { - node { - id - title - } - } - } - }"#, - ) - .await?; - - assert!( - payload.user_errors.is_empty(), - "bulk query returned user errors: {:?}", - payload.user_errors - ); - - let operation = payload - .bulk_operation - .expect("bulkOperationRunQuery should return a bulk operation"); - - let listed = shopify - .list_bulk_operations(BulkOperationsFilter { - first: 5, - ..BulkOperationsFilter::default() - }) - .await?; - assert!(listed.edges.iter().any(|edge| edge.node.id == operation.id)); - - let operation = shopify - .wait_for_bulk( - &operation.id, - BulkWaitOptions { - poll_interval: Duration::from_secs(5), - timeout: Some(Duration::from_secs(180)), - }, - ) - .await?; - - assert_eq!(operation.status, ShopifyBulkStatus::Completed); - - if let Some(url) = operation.url { - let rows: Vec = Shopify::download_bulk_jsonl(&url).await?; - for row in rows { - assert!(row.get("id").is_some()); - } - } - - Ok(()) -} - -#[tokio::test] -async fn live_five_concurrent_bulk_queries_when_enabled() -> Result<(), ShopifyAPIError> { - if std::env::var("SHOPIFY_TEST_BULK_CONCURRENCY") - .ok() - .as_deref() - != Some("1") - { - return Ok(()); - } - - let Some(shopify) = live_client_credentials_client() else { - return Ok(()); - }; - - let query = r#"{ - products(first: 1) { - edges { - node { - id - title - } - } - } - }"#; - let payloads = shopify - .run_bulk_queries(vec![query; 5], BulkConcurrencyOptions::default()) - .await?; - let operations = payloads - .into_iter() - .map(|payload| { - assert!( - payload.user_errors.is_empty(), - "bulk query returned user errors: {:?}", - payload.user_errors - ); - payload - .bulk_operation - .expect("bulkOperationRunQuery should return a bulk operation") - }) - .collect::>(); - - assert_eq!(operations.len(), 5); - - let running_or_recent = shopify - .list_bulk_operations(BulkOperationsFilter { - first: 10, - query: Some("type:QUERY".to_string()), - ..BulkOperationsFilter::default() - }) - .await?; - for operation in &operations { - assert!(running_or_recent - .edges - .iter() - .any(|edge| edge.node.id == operation.id)); - } - - for operation in operations { - let operation = shopify - .wait_for_bulk( - &operation.id, - BulkWaitOptions { - poll_interval: Duration::from_secs(5), - timeout: Some(Duration::from_secs(180)), - }, - ) - .await?; - - assert_eq!(operation.status, ShopifyBulkStatus::Completed); - } - - Ok(()) -}