@apollion-dsi/relay 0.27.2 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +146 -0
  2. package/lib/chunks/chunk-54QV6DFY.esm.js +1 -0
  3. package/lib/chunks/chunk-FYOI5Q5V.esm.js +0 -0
  4. package/lib/chunks/chunk-GZONWSRB.esm.js +1 -0
  5. package/lib/chunks/chunk-KIA6YWO5.esm.js +1 -0
  6. package/lib/chunks/chunk-RMYDTZUF.esm.js +1 -0
  7. package/lib/chunks/chunk-XJA2SRQY.esm.js +1 -0
  8. package/lib/commitMutation/commitMutation.d.ts +15 -15
  9. package/lib/commitMutation/index.d.ts +4 -4
  10. package/lib/commitMutation/index.esm.js +1 -0
  11. package/lib/index.d.ts +10 -10
  12. package/lib/index.esm.js +1 -1
  13. package/lib/index.js +1 -1
  14. package/lib/mutationUtils/index.d.ts +5 -5
  15. package/lib/mutationUtils/index.esm.js +1 -0
  16. package/lib/mutationUtils/mutationUtils.d.ts +60 -60
  17. package/lib/relayArgsInterface/index.d.ts +3 -3
  18. package/lib/relayArgsInterface/index.esm.js +1 -0
  19. package/lib/relayArgsInterface/relayArgsInterface.d.ts +106 -79
  20. package/lib/setupRelayEnvironment/executeEnvironment.d.ts +13 -13
  21. package/lib/setupRelayEnvironment/fetchQuery.d.ts +19 -19
  22. package/lib/setupRelayEnvironment/fetchWithRetries.d.ts +20 -20
  23. package/lib/setupRelayEnvironment/index.d.ts +11 -0
  24. package/lib/setupRelayEnvironment/index.esm.js +1 -0
  25. package/lib/setupRelayEnvironment/setupRelayEnvironment.d.ts +74 -57
  26. package/lib/setupRelayEnvironment/setupRelayEnvironment.helpers.d.ts +64 -56
  27. package/lib/setupRelayEnvironment/storage.d.ts +17 -17
  28. package/lib/setupRelayEnvironment/subscriptionHandler.d.ts +26 -20
  29. package/lib/useEnvironment/index.d.ts +5 -5
  30. package/lib/useEnvironment/index.esm.js +1 -0
  31. package/lib/useEnvironment/useEnvironment.d.ts +16 -16
  32. package/package.json +33 -6
  33. package/README.MD +0 -119
@@ -4,22 +4,22 @@ declare const kMountEnvironment: unique symbol;
4
4
  declare const kFeetchHandler: unique symbol;
5
5
  declare const kSubscriptionHandler: unique symbol;
6
6
  /**
7
- * Fábrica de `Environment` Relay com bateria inclusa: autenticação JWT,
8
- * retries com backoff, suporte a subscriptions via WebSocket, cache de
9
- * respostas e estratégia plugável de storage (localStorage ou cookie).
7
+ * Batteries-included Relay `Environment` factory: JWT authentication,
8
+ * retries with backoff, subscription support via WebSocket, response
9
+ * caching and a pluggable storage strategy (localStorage or cookie).
10
10
  *
11
- * Esta classe encapsula a configuração que normalmente precisaria ser
12
- * escrita à mão para cada projeto que usa Relay: criar `Network`,
13
- * `RecordSource`, `Store`, configurar `fetch` com retries/timeout,
14
- * adicionar headers de autenticação, lidar com redirecionamento em caso
15
- * de sessão expirada e opcionalmente registrar um handler de
16
- * subscriptions GraphQL.
11
+ * This class encapsulates the configuration that would normally have to be
12
+ * written by hand for every project using Relay: creating `Network`,
13
+ * `RecordSource`, `Store`, configuring `fetch` with retries/timeout,
14
+ * adding authentication headers, handling redirection when the
15
+ * session expires and optionally registering a GraphQL
16
+ * subscriptions handler.
17
17
  *
18
- * A instância exposta possui a propriedade pública `Environment`, que é
19
- * o objeto que deve ser passado para `react-relay` (via `RelayEnvironmentProvider`
20
- * ou `QueryRenderer`).
18
+ * The exposed instance has the public `Environment` property, which is
19
+ * the object that must be passed to `react-relay` (via `RelayEnvironmentProvider`
20
+ * or `QueryRenderer`).
21
21
  *
22
- * @example Setup mínimo
22
+ * @example Minimal setup
23
23
  * ```ts
24
24
  * import { CreateRelayEnvironment } from '@apollion-dsi/relay';
25
25
  *
@@ -28,7 +28,7 @@ declare const kSubscriptionHandler: unique symbol;
28
28
  * });
29
29
  * ```
30
30
  *
31
- * @example Com auth JWT (Bearer) e retries
31
+ * @example With JWT (Bearer) auth and retries
32
32
  * ```ts
33
33
  * const { Environment } = new CreateRelayEnvironment({
34
34
  * url: 'https://api.example.com/graphql/',
@@ -39,12 +39,12 @@ declare const kSubscriptionHandler: unique symbol;
39
39
  * });
40
40
  * ```
41
41
  *
42
- * @example Com sessão por cookie httpOnly (modelo seguro p/ SPA)
42
+ * @example With httpOnly cookie session (secure model for SPAs)
43
43
  * ```ts
44
- * // O token de sessão fica num cookie httpOnly + SameSite (invisível ao
45
- * // JS, imune a XSS). Nada é lido do storage e nenhum Bearer é injetado;
46
- * // `credentials:'include'` faz o browser anexar o cookie sozinho. Em
47
- * // erro de auth (401) o refresh é disparado contra `authUrl`.
44
+ * // The session token lives in an httpOnly + SameSite cookie (invisible to
45
+ * // JS, immune to XSS). Nothing is read from storage and no Bearer is injected;
46
+ * // `credentials:'include'` makes the browser attach the cookie on its own. On
47
+ * // an auth error (401) the refresh is dispatched against `authUrl`.
48
48
  * const { Environment } = new CreateRelayEnvironment({
49
49
  * url: 'https://api.example.com/graphql/',
50
50
  * authUrl: 'https://api.example.com/auth/refresh/',
@@ -54,7 +54,7 @@ declare const kSubscriptionHandler: unique symbol;
54
54
  * });
55
55
  * ```
56
56
  *
57
- * @example Com subscriptions
57
+ * @example With subscriptions
58
58
  * ```ts
59
59
  * const { Environment } = new CreateRelayEnvironment({
60
60
  * url: 'https://api.example.com/graphql/',
@@ -63,86 +63,103 @@ declare const kSubscriptionHandler: unique symbol;
63
63
  * });
64
64
  * ```
65
65
  *
66
- * @see {@link RelayArgsInterface} para a lista completa de opções de configuração.
66
+ * @example With persisted queries (server-aligned hash allowlist)
67
+ * ```ts
68
+ * // Requires `persistConfig` in the consumer's relay.config.json, e.g.
69
+ * // { "persistConfig": { "file": "./persisted/queryMap.json", "algorithm": "MD5" } }.
70
+ * // The request body becomes `{ name, doc_id, variables }` — the GraphQL
71
+ * // text never leaves the build; the server resolves the hash against the
72
+ * // query map and refuses anything else.
73
+ * const { Environment } = new CreateRelayEnvironment({
74
+ * url: 'https://api.example.com/graphql/',
75
+ * usePersistedQueries: true,
76
+ * });
77
+ * ```
78
+ *
79
+ * @see {@link RelayArgsInterface} for the complete list of configuration options.
67
80
  */
68
81
  export default class RelayEnvironment implements RelayArgsInterface {
69
- /** Endpoint HTTP do servidor GraphQL. Obrigatório. */
82
+ /** HTTP endpoint of the GraphQL server. Required. */
70
83
  url: string;
71
- /** Endpoint do servidor de autenticação. Obrigatório quando `useAuthorization` é `true`. */
84
+ /** Authentication server endpoint. Required when `useAuthorization` is `true`. */
72
85
  authUrl?: string;
73
- /** Endpoint WebSocket para subscriptions. Obrigatório quando `useSubscription` é `true`. */
86
+ /** WebSocket endpoint for subscriptions. Required when `useSubscription` is `true`. */
74
87
  socket?: string;
75
- /** Lista de delays (ms) entre tentativas, quando `useRetries` é `true`. */
88
+ /** List of delays (ms) between attempts, when `useRetries` is `true`. */
76
89
  retries?: number[];
77
- /** Timeout (ms) por requisição. */
90
+ /** Per-request timeout (ms). */
78
91
  timeout?: number;
79
- /** Habilita subscriptions GraphQL via WebSocket. */
92
+ /** Enables GraphQL subscriptions over WebSocket. */
80
93
  useSubscription?: boolean;
81
- /** Habilita injeção do header `Authorization: Bearer <token>` em cada request. */
94
+ /** Enables injecting the `Authorization: Bearer <token>` header on every request. */
82
95
  useAuthorization?: boolean;
83
- /** Modelo de auth: `'bearer'` (token JS + header) ou `'cookie'` (httpOnly). */
96
+ /** Auth model: `'bearer'` (JS token + header) or `'cookie'` (httpOnly). */
84
97
  authMode: 'bearer' | 'cookie';
85
- /** Valor de `credentials` repassado aos fetches GraphQL/refresh. */
98
+ /** `credentials` value forwarded to the GraphQL/refresh fetches. */
86
99
  credentials?: RequestCredentials;
87
- /** URL de verificação/refresh de sessão; `false` desliga o probe. */
100
+ /** Session verification/refresh URL; `false` disables the probe. */
88
101
  sessionCheckUrl?: string | false;
89
- /** Habilita cache de respostas (via `QueryResponseCache` do Relay). */
102
+ /** Enables response caching (via Relay's `QueryResponseCache`). */
90
103
  useCache?: boolean;
91
- /** TTL (ms) das entradas do cache. */
104
+ /** TTL (ms) of the cache entries. */
92
105
  cacheTime?: number;
93
- /** Tamanho máximo do cache (número de queries). */
106
+ /** Maximum cache size (number of queries). */
94
107
  cacheSize?: number;
95
- /** Nome da chave em storage usada para guardar o token de sessão. */
108
+ /** Storage key name used to hold the session token. */
96
109
  sessionStorageProp?: string;
97
- /** Nome da chave em storage usada para guardar o refresh token. */
110
+ /** Storage key name used to hold the refresh token. */
98
111
  refreshStorageProp?: string;
99
- /** Rota usada para redirecionar o usuário em caso de sessão expirada. */
112
+ /** Route used to redirect the user when the session expires. */
100
113
  loginRoute?: string;
101
- /** Liga logs de debug (útil em desenvolvimento). */
114
+ /** Turns on debug logs (useful in development). */
102
115
  useDebug?: boolean;
103
- /** Habilita o mecanismo de retries em caso de erro/timeout. */
116
+ /** Enables the retry mechanism on error/timeout. */
104
117
  useRetries?: boolean;
105
- /** Redireciona automaticamente para `loginRoute` em caso de erro de auth. */
118
+ /** Automatically redirects to `loginRoute` on an auth error. */
106
119
  redirectOnError?: boolean;
107
- /** Lista de status HTTP que disparam retry (quando `useRetries` é `true`). */
120
+ /** List of HTTP statuses that trigger a retry (when `useRetries` is `true`). */
108
121
  retryWhen?: number[];
109
- /** Status HTTP considerados como erros de autenticação (default: 401, 403). */
122
+ /** HTTP statuses treated as authentication errors (default: 401, 403). */
110
123
  authenticationErrors?: number[];
111
- /** Estratégia de storage no browser. */
124
+ /** Browser storage strategy. */
112
125
  storageType: 'cookie' | 'localStorage';
113
- /** Identificador opcional do parceiro, enviado no header `X-Partner`. */
126
+ /** Optional partner identifier, sent in the `X-Partner` header. */
114
127
  partner?: string;
128
+ /** Sends only the build-time operation hash instead of the GraphQL text. */
129
+ usePersistedQueries?: boolean;
130
+ /** Request field carrying the persisted-operation hash. */
131
+ persistedOperationField?: string;
115
132
  /**
116
- * Função de fetch montada para uso pelo `Network` do Relay. Interno.
133
+ * Fetch function assembled for use by Relay's `Network`. Internal.
117
134
  */
118
135
  private [kFeetchHandler]?;
119
136
  /**
120
- * Função de subscription montada para uso pelo `Network` do Relay. Interno.
137
+ * Subscription function assembled for use by Relay's `Network`. Internal.
121
138
  */
122
139
  private [kSubscriptionHandler]?;
123
140
  /**
124
- * Handler de storage. Expõe métodos `getTokens`, `setTokens`, `clear`,
125
- * `hasChangedSession`. Use diretamente quando precisar manipular tokens
126
- * fora do fluxo padrão (ex: tela de login).
141
+ * Storage handler. Exposes the `getTokens`, `setTokens`, `clear`,
142
+ * `hasChangedSession` methods. Use it directly when you need to manipulate
143
+ * tokens outside the standard flow (e.g. a login screen).
127
144
  */
128
145
  StorageHandler: any;
129
146
  /**
130
- * Instância de `Environment` do `relay-runtime` pronta para uso com
147
+ * `relay-runtime` `Environment` instance ready for use with
131
148
  * `RelayEnvironmentProvider` (`react-relay`).
132
149
  */
133
150
  Environment: Environment;
134
151
  /**
135
- * @param config - Configuração da instância. Veja {@link RelayArgsInterface}.
136
- * Apenas `url` é obrigatório; demais opções têm defaults sensatos.
152
+ * @param config - Instance configuration. See {@link RelayArgsInterface}.
153
+ * Only `url` is required; the other options have sensible defaults.
137
154
  *
138
- * @throws {Error} Se `url` não for informado.
139
- * @throws {Error} Se `useAuthorization` for `true` e `authUrl` não for informado.
140
- * @throws {Error} Se `useSubscription` for `true` e `socket` não for informado.
155
+ * @throws {Error} If `url` is not provided.
156
+ * @throws {Error} If `useAuthorization` is `true` and `authUrl` is not provided.
157
+ * @throws {Error} If `useSubscription` is `true` and `socket` is not provided.
141
158
  */
142
159
  constructor(config: RelayArgsInterface);
143
160
  /**
144
- * Monta o `Environment` Relay a partir da fetch function e subscription
145
- * handler configurados. Chamado uma única vez pelo construtor.
161
+ * Assembles the Relay `Environment` from the configured fetch function and
162
+ * subscription handler. Called exactly once by the constructor.
146
163
  */
147
164
  private [kMountEnvironment];
148
165
  }
@@ -1,98 +1,106 @@
1
1
  /**
2
- * @fileoverview Helpers internos usados por `setupRelayEnvironment` para
3
- * montar a Network do Relay: detecção do tipo de operação, construção do
4
- * body/headers da requisição, parse de respostas (incluindo
5
- * `multipart/mixed` para `@defer`/`@stream`), redirecionamento em erro
6
- * de auth e constantes de tempo.
2
+ * @fileoverview Internal helpers used by `setupRelayEnvironment` to
3
+ * assemble the Relay Network: operation-kind detection, request
4
+ * body/header construction, response parsing (including
5
+ * `multipart/mixed` for `@defer`/`@stream`), redirection on auth
6
+ * error and time constants.
7
7
  *
8
- * Não exposto pelo barrel raiz faz parte da implementação interna de
8
+ * Not exposed by the root barrel — part of the internal implementation of
9
9
  * `CreateRelayEnvironment`.
10
10
  */
11
11
  import { CacheConfig, RequestParameters, UploadableMap, Variables } from 'relay-runtime';
12
12
  import { RelayArgsInterface, Sink } from '../relayArgsInterface';
13
- /** Verdadeiro se a operação Relay é uma mutation. */
13
+ /** True if the Relay operation is a mutation. */
14
14
  export declare const isMutation: (request: RequestParameters) => boolean;
15
- /** Verdadeiro se a operação Relay é uma query. */
15
+ /** True if the Relay operation is a query. */
16
16
  export declare const isQuery: (request: RequestParameters) => boolean;
17
- /** Verdadeiro quando o consumidor pediu `force: true` no `CacheConfig` (bypass do cache). */
17
+ /** True when the consumer requested `force: true` in the `CacheConfig` (cache bypass). */
18
18
  export declare const forceFetch: (cacheConfig: CacheConfig) => boolean;
19
19
  /**
20
- * Retorna o delimitador (`?` ou `&`) apropriado para anexar query params
21
- * à URL atual do browser. Retorna string vazia em ambientes sem DOM (SSR).
20
+ * Returns the appropriate delimiter (`?` or `&`) for appending query params
21
+ * to the browser's current URL. Returns an empty string in DOM-less environments (SSR).
22
22
  */
23
23
  export declare const getParamsDelimiter: () => string;
24
24
  /**
25
- * Retorna o `pathname` atual do browser, ou string vazia em ambientes
26
- * sem DOM (SSR).
25
+ * Returns the browser's current `pathname`, or an empty string in
26
+ * DOM-less environments (SSR).
27
27
  */
28
28
  export declare const getBrowserLocation: () => string;
29
29
  /**
30
- * Redireciona o usuário para `redirectTo`, preservando a URL atual em
31
- * `?redirect=` (para o fluxo de login redirecionar de volta).
30
+ * Redirects the user to `redirectTo`, preserving the current URL in
31
+ * `?redirect=` (so the login flow can redirect back).
32
32
  *
33
- * Não adiciona o parâmetro `redirect` quando a URL atual é igual ao
34
- * destino ou quando o destino é a própria `loginRoute`.
33
+ * Does not add the `redirect` parameter when the current URL already equals
34
+ * the destination or when the destination is `loginRoute` itself.
35
35
  *
36
- * @param url - URL atual (origem do redirect).
37
- * @param redirectTo - Destino do redirect.
38
- * @param config - Configuração do environment (usada para checar `loginRoute`).
36
+ * @param url - Current URL (redirect origin).
37
+ * @param redirectTo - Redirect destination.
38
+ * @param config - Environment configuration (used to check `loginRoute`).
39
39
  */
40
40
  export declare const redirectUser: (url: string, redirectTo: string, config?: RelayArgsInterface) => void;
41
+ /** Subset of the Environment configuration the body builders read. */
42
+ interface PersistedConfig {
43
+ usePersistedQueries?: boolean;
44
+ persistedOperationField?: string;
45
+ }
41
46
  /**
42
- * Constrói o body da requisição GraphQL — multipart se uploadables,
43
- * JSON caso contrário.
47
+ * Builds the GraphQL request body — multipart if there are uploadables,
48
+ * JSON otherwise.
44
49
  *
45
- * @param request - Parâmetros da requisição Relay.
46
- * @param variables - Variáveis da operação.
47
- * @param uploadables - Arquivos para upload (opcional).
50
+ * @param request - Relay request parameters.
51
+ * @param variables - Operation variables.
52
+ * @param uploadables - Files to upload (optional).
53
+ * @param config - Environment configuration subset for persisted queries
54
+ * (optional; absent behaves as `usePersistedQueries: false`).
48
55
  */
49
- export declare function getRequestBody(request: RequestParameters, variables: Variables, uploadables?: UploadableMap): string | FormData;
56
+ export declare function getRequestBody(request: RequestParameters, variables: Variables, uploadables?: UploadableMap, config?: PersistedConfig): string | FormData;
50
57
  /**
51
- * Resolve o valor efetivo de `credentials` para os fetches (GraphQL e
52
- * verificação/refresh de sessão).
58
+ * Resolves the effective `credentials` value for the fetches (GraphQL and
59
+ * session verification/refresh).
53
60
  *
54
- * - Se `config.credentials` foi definido explicitamente, ele vence.
55
- * - Caso contrário, no modo `authMode:'cookie'` o default é `'include'`
56
- * (para o browser anexar cookies httpOnly de sessão).
57
- * - No modo `'bearer'` (default) retorna `undefined` — o fetch usa o
58
- * default do browser, preservando a retrocompat.
61
+ * - If `config.credentials` was set explicitly, it wins.
62
+ * - Otherwise, in `authMode:'cookie'` mode the default is `'include'`
63
+ * (so the browser attaches httpOnly session cookies).
64
+ * - In `'bearer'` mode (default) it returns `undefined` — the fetch uses the
65
+ * browser default, preserving backwards compatibility.
59
66
  *
60
- * @param config - Configuração do environment.
61
- * @returns O `RequestCredentials` a usar, ou `undefined` para omitir.
67
+ * @param config - Environment configuration.
68
+ * @returns The `RequestCredentials` to use, or `undefined` to omit.
62
69
  */
63
70
  export declare const resolveCredentials: (config: any) => RequestCredentials | undefined;
64
71
  /**
65
- * Monta os headers HTTP da requisição. Para uploads, usa `Accept: *\/*`
66
- * e deixa o browser definir o `Content-Type` com boundary. Para JSON,
67
- * usa `application/json` em ambos.
72
+ * Assembles the request's HTTP headers. For uploads, uses `Accept: *\/*`
73
+ * and lets the browser set the `Content-Type` with the boundary. For JSON,
74
+ * uses `application/json` for both.
68
75
  *
69
- * Modo `bearer` (default): quando `useAuthorization` está ligado e existe
70
- * um `sessionToken` em storage, anexa `Authorization: Bearer <token>` —
71
- * exceto quando o usuário está na própria rota de login (para evitar
76
+ * `bearer` mode (default): when `useAuthorization` is on and a
77
+ * `sessionToken` exists in storage, attaches `Authorization: Bearer <token>` —
78
+ * except when the user is on the login route itself (to avoid
72
79
  * loops).
73
80
  *
74
- * Modo `cookie` (httpOnly): **nunca** o token em JS nem injeta
75
- * `Authorization` — o cookie de sessão viaja sozinho via `credentials`.
76
- * Isso evita o header `Authorization: Bearer ` vazio que o modo bearer
77
- * produziria quando o token é httpOnly e portanto invisível ao JS.
81
+ * `cookie` mode (httpOnly): **never** reads the token in JS nor injects
82
+ * `Authorization` — the session cookie travels on its own via `credentials`.
83
+ * This avoids the empty `Authorization: Bearer ` header that bearer mode
84
+ * would produce when the token is httpOnly and therefore invisible to JS.
78
85
  *
79
- * Se um `partner` está configurado, adiciona o header `X-Partner`.
86
+ * If a `partner` is configured, adds the `X-Partner` header.
80
87
  */
81
88
  export declare const getHeaders: (args: any, uploadables?: UploadableMap) => HeadersInit;
82
89
  /**
83
- * o `Response` do fetch e empurra os dados para o `Sink` do Relay.
90
+ * Reads the fetch `Response` and pushes the data into the Relay `Sink`.
84
91
  *
85
- * Suporta três modos:
86
- * - `multipart/mixed` (usado por `@defer` e `@stream`): o stream
87
- * chunk a chunk e usa `PatchResolver` para repassar cada patch.
88
- * - `application/json`: parseia o JSON inteiro e chama `callback`.
89
- * - Outros: como texto e empurra como array de strings.
92
+ * Supports three modes:
93
+ * - `multipart/mixed` (used by `@defer` and `@stream`): reads the stream
94
+ * chunk by chunk and uses `PatchResolver` to forward each patch.
95
+ * - `application/json`: parses the whole JSON and calls `callback`.
96
+ * - Others: reads as text and pushes it as an array of strings.
90
97
  *
91
- * Copiado da biblioteca `fetch-multipart-graphql` com adaptações para o
92
- * `Sink` Relay.
98
+ * Copied from the `fetch-multipart-graphql` library with adaptations for the
99
+ * Relay `Sink`.
93
100
  */
94
101
  export declare const handleData: (response: Response, sink: Sink, callback: (data: any) => void) => void;
95
- /** Constante de tempo: 1 segundo em milissegundos. */
102
+ /** Time constant: 1 second in milliseconds. */
96
103
  export declare const ONE_SECOND = 1000;
97
- /** Constante de tempo: 1 minuto em milissegundos. */
104
+ /** Time constant: 1 minute in milliseconds. */
98
105
  export declare const ONE_MINUTE: number;
106
+ export {};
@@ -1,5 +1,5 @@
1
1
  import { RelayArgsInterface } from '../relayArgsInterface';
2
- /** Par de tokens armazenado. */
2
+ /** Stored token pair. */
3
3
  type TokenTypes = {
4
4
  sessionToken?: string;
5
5
  refreshToken?: string;
@@ -8,9 +8,9 @@ declare const kStorageHandler: unique symbol;
8
8
  declare const kPropSession: unique symbol;
9
9
  declare const kPropRefresh: unique symbol;
10
10
  /**
11
- * Handler de storage usado por `CreateRelayEnvironment`. Encapsula a
12
- * estratégia escolhida (`storageType`) e padroniza a manipulação de
13
- * `sessionToken` e `refreshToken` por trás de uma API estável.
11
+ * Storage handler used by `CreateRelayEnvironment`. Encapsulates the
12
+ * chosen strategy (`storageType`) and standardizes the handling of
13
+ * `sessionToken` and `refreshToken` behind a stable API.
14
14
  *
15
15
  * @example
16
16
  * ```ts
@@ -25,34 +25,34 @@ export default class StorageClass {
25
25
  private [kPropSession];
26
26
  private [kPropRefresh];
27
27
  /**
28
- * @param strategy - Instância de `CreateRelayEnvironment` (que
29
- * implementa `RelayArgsInterface`). Os campos lidos são
28
+ * @param strategy - `CreateRelayEnvironment` instance (which
29
+ * implements `RelayArgsInterface`). The fields read are
30
30
  * `storageType`, `sessionStorageProp`, `refreshStorageProp`.
31
31
  */
32
32
  constructor(strategy: RelayArgsInterface);
33
33
  /**
34
- * os tokens atualmente armazenados.
34
+ * Reads the currently stored tokens.
35
35
  *
36
- * @returns Objeto com `sessionToken` e `refreshToken` (podem ser
37
- * `undefined` quando ausentes).
36
+ * @returns Object with `sessionToken` and `refreshToken` (may be
37
+ * `undefined` when absent).
38
38
  */
39
39
  getTokens(): TokenTypes;
40
40
  /**
41
- * Grava ambos os tokens em storage. Use após receber resposta de
42
- * login/refresh.
41
+ * Writes both tokens to storage. Use after receiving a
42
+ * login/refresh response.
43
43
  */
44
44
  setTokens(tokens: TokenTypes): void;
45
45
  /**
46
- * Remove ambos os tokens do storage. Usado em logout ou ao detectar
47
- * sessão expirada.
46
+ * Removes both tokens from storage. Used on logout or when an
47
+ * expired session is detected.
48
48
  */
49
49
  clear(): void;
50
50
  /**
51
- * Compara um novo `sessionToken` com o atualmente armazenado.
51
+ * Compares a new `sessionToken` against the currently stored one.
52
52
  *
53
- * @param tokens - Objeto contendo o novo `sessionToken` (vindo, por
54
- * exemplo, de um header de resposta).
55
- * @returns `true` se o token mudou.
53
+ * @param tokens - Object containing the new `sessionToken` (coming, for
54
+ * example, from a response header).
55
+ * @returns `true` if the token changed.
56
56
  */
57
57
  hasChangedSession({ sessionToken: newSessionToken }: TokenTypes): boolean;
58
58
  }
@@ -1,29 +1,35 @@
1
1
  /**
2
- * @fileoverview Fábrica do subscription handler GraphQL via WebSocket,
3
- * usada por `setupRelayEnvironment` quando `useSubscription` está
4
- * habilitado.
2
+ * @fileoverview Factory for the GraphQL subscription handler over WebSocket,
3
+ * used by `setupRelayEnvironment` when `useSubscription` is
4
+ * enabled.
5
5
  *
6
- * Baseado em `graphql-ws` (protocolo `graphql-transport-ws`).
6
+ * Based on `graphql-ws` (`graphql-transport-ws` protocol).
7
7
  *
8
- * Não exposto pelo barrel raiz implementação interna de
8
+ * Not exposed by the root barrel — internal implementation of
9
9
  * `CreateRelayEnvironment`.
10
10
  */
11
+ /** Subset of the Environment configuration the subscription handler reads. */
12
+ interface SubscriptionSettings {
13
+ socket?: string;
14
+ usePersistedQueries?: boolean;
15
+ persistedOperationField?: string;
16
+ }
11
17
  /**
12
- * Monta a subscription function para o `Network.create` do Relay.
18
+ * Builds the subscription function for Relay's `Network.create`.
13
19
  *
14
- * Retorna uma função (a ser chamada uma vez, no setup do Environment)
15
- * que por sua vez retorna a subscribe function que o Relay vai invocar
16
- * para cada subscription operation. A adaptação de callbacks
17
- * `next/error/complete` do `graphql-ws` para o `Sink` do Observable
18
- * Relay é feita aqui.
20
+ * Returns a factory (invoked once, during Environment setup) which yields the
21
+ * subscribe function Relay calls for each subscription operation. The
22
+ * `graphql-ws` client is created lazily on the first subscription — no socket
23
+ * is opened for environments that never subscribe. The adaptation of
24
+ * `graphql-ws` `next/error/complete` callbacks to the Relay Observable `Sink`
25
+ * happens here.
19
26
  *
20
- * @param settings - Objeto com a URL do endpoint WebSocket (`socket`).
21
- * Quando `useSubscription` é `true` mas `socket` não foi configurado,
22
- * o construtor de `CreateRelayEnvironment` lança erro antes desta
23
- * função ser chamada.
24
- * @returns Função que, quando invocada, retorna a subscribe function
25
- * compatível com `Network.create(fetchFn, subscribeFn)`.
27
+ * @param settings - Environment configuration subset: the WebSocket endpoint
28
+ * (`socket`) plus the persisted-queries flags. When `useSubscription` is
29
+ * `true` but `socket` was not configured, the `CreateRelayEnvironment`
30
+ * constructor throws before this function is called.
31
+ * @returns Factory that, when invoked, returns the subscribe function
32
+ * compatible with `Network.create(fetchFn, subscribeFn)`.
26
33
  */
27
- export declare function setupSubscription(settings: {
28
- socket?: string;
29
- }): () => any;
34
+ export declare function setupSubscription(settings: SubscriptionSettings): () => any;
35
+ export {};
@@ -1,9 +1,9 @@
1
1
  /**
2
- * Barrel público do módulo `useEnvironment`.
2
+ * Public barrel for the `useEnvironment` module.
3
3
  *
4
- * Reexporta o hook `useEnvironment` e o componente `EnvironmentProvider`,
5
- * para que consumidores possam importar via
6
- * `@apollion-dsi/relay/useEnvironment` (granular) ou via
7
- * `@apollion-dsi/relay` (barrel raiz).
4
+ * Re-exports the `useEnvironment` hook and the `EnvironmentProvider`
5
+ * component, so consumers can import via
6
+ * `@apollion-dsi/relay/useEnvironment` (granular) or via
7
+ * `@apollion-dsi/relay` (root barrel).
8
8
  */
9
9
  export * from './useEnvironment';
@@ -0,0 +1 @@
1
+ import{a,b}from"../chunks/chunk-54QV6DFY.esm.js";import"../chunks/chunk-GZONWSRB.esm.js";export{a as EnvironmentProvider,b as useEnvironment};
@@ -2,24 +2,24 @@ import React from 'react';
2
2
  import { Environment } from 'relay-runtime';
3
3
  import { MockEnvironment } from 'relay-test-utils';
4
4
  /**
5
- * Estado interno do Context: contém apenas o `Environment` Relay
6
- * (real ou mockado em testes).
5
+ * Internal Context state: contains only the Relay `Environment`
6
+ * (real, or mocked in tests).
7
7
  */
8
8
  type StateType = {
9
9
  environment: Environment | MockEnvironment;
10
10
  };
11
11
  /**
12
- * Props do `EnvironmentProvider`.
12
+ * Props for `EnvironmentProvider`.
13
13
  */
14
14
  type EnvironmentProviderInterface = {
15
15
  children: React.ReactNode;
16
16
  } & StateType;
17
17
  /**
18
- * Provider que injeta o `Environment` Relay na árvore React via Context.
18
+ * Provider that injects the Relay `Environment` into the React tree via Context.
19
19
  *
20
- * Em produção, passe a propriedade `Environment` exposta por
21
- * `CreateRelayEnvironment`. Em testes, passe um `MockEnvironment` de
22
- * `relay-test-utils` para facilitar a substituição do backend.
20
+ * In production, pass the `Environment` property exposed by
21
+ * `CreateRelayEnvironment`. In tests, pass a `MockEnvironment` from
22
+ * `relay-test-utils` to make swapping out the backend easier.
23
23
  *
24
24
  * @example
25
25
  * ```tsx
@@ -36,7 +36,7 @@ type EnvironmentProviderInterface = {
36
36
  * }
37
37
  * ```
38
38
  *
39
- * @example Em testes
39
+ * @example In tests
40
40
  * ```tsx
41
41
  * import { createMockEnvironment } from 'relay-test-utils';
42
42
  *
@@ -50,16 +50,16 @@ type EnvironmentProviderInterface = {
50
50
  */
51
51
  declare function EnvironmentProvider({ children, environment }: EnvironmentProviderInterface): React.JSX.Element;
52
52
  /**
53
- * Hook para acessar o `Environment` Relay corrente.
53
+ * Hook to access the current Relay `Environment`.
54
54
  *
55
- * Deve ser usado dentro de um `EnvironmentProvider`. Lança erro
56
- * descritivo caso seja chamado fora dele ou se nenhum environment
57
- * tenha sido fornecido falhas silenciosas aqui geralmente viram
58
- * "loading infinito" no Relay, então preferimos falhar cedo.
55
+ * Must be used inside an `EnvironmentProvider`. Throws a descriptive
56
+ * error if called outside of it or if no environment was
57
+ * provided silent failures here usually turn into
58
+ * "infinite loading" in Relay, so we prefer to fail early.
59
59
  *
60
- * @returns Objeto com a propriedade `environment`.
61
- * @throws {Error} Quando usado fora de `EnvironmentProvider` ou quando
62
- * o environment fornecido é `null`/`undefined`.
60
+ * @returns Object with the `environment` property.
61
+ * @throws {Error} When used outside `EnvironmentProvider` or when
62
+ * the provided environment is `null`/`undefined`.
63
63
  *
64
64
  * @example
65
65
  * ```tsx