@apollion-dsi/relay 0.28.0 → 0.29.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.
package/README.md CHANGED
@@ -38,20 +38,23 @@ yarn add @apollion-dsi/relay react
38
38
 
39
39
  ## Quick start
40
40
 
41
- Create the Environment and provide it to your tree:
41
+ Create the Environment and provide it to your tree with `EnvironmentProvider`
42
+ — the single Relay provider, backing both the DS `useEnvironment()` hook and
43
+ every `react-relay` store hook (`useLazyLoadQuery`, `usePreloadedQuery`,
44
+ `useFragment`, `useSubscription`). Do not also mount `react-relay`'s
45
+ `RelayEnvironmentProvider` yourself — `EnvironmentProvider` already does:
42
46
 
43
47
  ```tsx
44
- import { CreateRelayEnvironment } from '@apollion-dsi/relay';
45
- import { RelayEnvironmentProvider } from 'react-relay';
48
+ import { CreateRelayEnvironment, EnvironmentProvider } from '@apollion-dsi/relay';
46
49
  import { App } from './app';
47
50
 
48
51
  const { Environment } = new CreateRelayEnvironment({
49
52
  url: 'https://api.example.com/graphql',
50
53
  });
51
54
 
52
- <RelayEnvironmentProvider environment={Environment}>
55
+ <EnvironmentProvider environment={Environment}>
53
56
  <App />
54
- </RelayEnvironmentProvider>;
57
+ </EnvironmentProvider>;
55
58
  ```
56
59
 
57
60
  ## Authentication: Bearer vs. httpOnly cookie
@@ -1 +1 @@
1
- import{a as s}from"./chunk-GZONWSRB.esm.js";import{Environment as ae,Network as ue,RecordSource as le,Store as ce}from"relay-runtime";import{Observable as te,QueryResponseCache as re}from"relay-runtime";var E=!!(typeof window!="undefined"&&window.document&&window.document.createElement),f={canUseDOM:E,canUseWorkers:typeof Worker!="undefined",canUseEventListeners:E&&!!(window.addEventListener||window.attachEvent),canUseViewport:E&&!!window.screen,isInWorker:!E};function $(e){return async t=>{let r=e.timeout,o=e.retries,a=0,i=0;return new Promise((u,l)=>{let c={};c.sendTimedRequest=()=>{a++,i=Date.now();let n=!0,p=new AbortController,m=setTimeout(()=>{if(n=!1,p.abort(),c.shouldRetry(a))e.useDebug&&console.log("fetchWithRetries: HTTP timeout, retrying."),c.retryRequest();else{let h=new Error(`fetchWithRetries(): Failed to get response from server, tried ${a} times.`);h.name="TimeOutError",l(h)}},r);fetch(e.url,{...t,signal:p.signal}).then(async h=>{if(clearTimeout(m),n)if(h.status>=200&&h.status<300)u(h);else if(c.shouldRetry(a)&&e.retryWhen.includes(h.status))e.useDebug&&console.log("fetchWithRetries: HTTP error, retrying..."),c.retryRequest();else{let d=new Error(`fetchWithRetries(): Still no successful response after ${a} retries, giving up.`);d.response=h,l(d)}}).catch(h=>{clearTimeout(m),h.name!=="AbortError"&&l(h)})},c.retryRequest=()=>{let n=o[a-1],p=i+n;setTimeout(c.sendTimedRequest,p-Date.now())},c.shouldRetry=n=>f.canUseDOM&&e.useRetries&&n<=o.length,c.sendTimedRequest()})}}s($,"fetchWithRetries");import{PatchResolver as X}from"fetch-multipart-graphql";var x=s(e=>e.operationKind==="mutation","isMutation"),O=s(e=>e.operationKind==="query","isQuery"),V=s(e=>!!(e&&e.force),"forceFetch"),Y=s(()=>f.canUseDOM?window.location.search.startsWith("?")?"&":"?":"","getParamsDelimiter"),C=s(()=>f.canUseDOM?window.location.pathname:"","getBrowserLocation"),R=s((e,t,r)=>{let o=e;(e!==t||r.loginRoute!==t)&&(o=`${t}${Y()}redirect=${e}`),window.location.href=o},"redirectUser");function L(e){if(!e.id)throw new Error(`[usePersistedQueries] Operation "${e.name}" has no persisted id \u2014 run relay-compiler with "persistConfig" set in relay.config.json.`);return e.id}s(L,"getPersistedOperationId");function Z(e,t,r,o){let a=new FormData,i=o!=null&&o.usePersistedQueries?{[o.persistedOperationField||"doc_id"]:L(e),variables:t,operationName:e.name}:{query:e.text,variables:t,operationName:e.name};a.append("operations",JSON.stringify(i));let u={};for(let l=0;l<r.files.length;l++)a.append(`${l}`,r.files[l]),u[`${l}`]=[r.path(l)];return a.append("map",JSON.stringify(u)),a}s(Z,"getRequestBodyWithUploadables");function ee(e,t,r){return r!=null&&r.usePersistedQueries?JSON.stringify({name:e.name,[r.persistedOperationField||"doc_id"]:L(e),variables:t}):JSON.stringify({name:e.name,query:e.text,variables:t})}s(ee,"getRequestBodyWithoutUplodables");function B(e,t,r,o){return r?Z(e,t,r,o):ee(e,t,o)}s(B,"getRequestBody");var U=s(e=>{if(e.credentials)return e.credentials;if(e.authMode==="cookie")return"include"},"resolveCredentials"),_=s((e,t)=>{let r=new Headers;if(t?r.append("Accept","*/*"):(r.append("Accept","application/json"),r.append("Content-type","application/json")),e.useAuthorization&&e.authMode!=="cookie"){let{sessionToken:o}=e.StorageHandler.getTokens();o&&C()!==e.loginRoute&&r.append("Authorization",`Bearer ${o}`)}return e.partner&&r.append("X-Partner",e.partner),r},"getHeaders"),j=s((e,t,r)=>{if(e.status<300&&e.headers&&e.headers.get("Content-Type")&&e.headers.get("Content-Type").indexOf("multipart/mixed")>=0){let o=e.body.getReader(),a=new TextDecoder,i=new X({onResponse:s(u=>t.next(u),"onResponse")});o.read().then(s(function u({value:l,done:c}){if(c)t.complete();else{let n;try{n=a.decode(l),i.handleChunk(n)}catch(p){let m=p;m.response=e,m.statusCode=e.status,m.bodyText=n,t.error(m)}o.read().then(u)}},"sendNext"))}else e.headers&&e.headers.get("Content-Type")&&e.headers.get("Content-Type").indexOf("application/json")>=0?e.json().then(r):e.text().then(o=>{t.next([o]),t.complete()})},"handleData"),b=1e3,v=b*60;var J=s(e=>{let t=new re({ttl:e.cacheTime,size:e.cacheSize}),r=$(e);async function o(){if(e.sessionCheckUrl===!1)return!1;let i=U(e);try{if(e.authMode==="cookie"){let n=e.sessionCheckUrl||e.authUrl;return(await fetch(n,{method:"POST",credentials:i||"include"})).status===200}let{sessionToken:u}=e.StorageHandler.getTokens(),l=e.sessionCheckUrl||`${e.authUrl}user/me`;return(await fetch(l,{headers:{"Content-Type":"application/json",Authorization:u},...i?{credentials:i}:{}})).status===200}catch(u){return console.warn(`[Auth] ${u.message}`),!1}}s(o,"checkSession");async function a(i,u,l,c,n){try{let p=i.id||("cacheID"in i?i.cacheID:null)||String(i.text);if(e.useCache&&O(i)&&!V(l)){let d=t.get(p,u);if(d){n.next(d),n.complete();return}}e.useCache&&x(i)&&t.clear();let m=U(e),h=await r({method:"POST",headers:_(e,c),body:B(i,u,c,e),...m?{credentials:m}:{}});j(h,n,async d=>{if(e.useCache&&O(i)&&t.set(p,u,d),!n.closed){if(x(i)&&d.errors&&n.error(d.errors),d.errors){if(await o()||(e.StorageHandler.clear(),R("/",e.loginRoute,e)),e.redirectOnError){let z=[];Array.isArray(d.errors)&&(z=d.errors.map(({status_code:P})=>P));let Q=C();z.some(P=>e.authenticationErrors.includes(P))&&Q!==e.loginRoute&&(e.StorageHandler.clear(),R(Q,e.loginRoute,e))}n.error(d.errors)}else d.data?n.next(d):n.error(d);n.complete()}})}catch(p){if(f.canUseDOM&&!["AbortError","TimeOutError"].includes(p.name)&&e.StorageHandler.clear(),e.redirectOnError){let h=C();h!==e.loginRoute&&R(h,e.loginRoute,e)}await o()||(e.StorageHandler.clear(),R("/",e.loginRoute,e)),n.error(p)}}return s(a,"fetchFn"),(i,u,l,c)=>te.create(n=>{a(i,u,l,c,n)})},"createFetchFunction");import se from"js-cookie";var A=class A{get(t){throw new Error('Must implement a "GET" method')}set(t,r){throw new Error('Must implement a "SET" method')}delete(t){throw new Error('Must implement a "DELETE" method')}};s(A,"DefaultStrategy");var k=A,I=class I extends k{constructor(){super(),this.strategy=localStorage}get(t){return this.strategy.getItem(t)}set(t,r){this.strategy.setItem(t,r)}delete(t){this.strategy.removeItem(t)}};s(I,"LocalStorageStrategy");var D=I,F=class F extends k{constructor(){super(),this.strategy=se}get(t){return this.strategy.get(t)}set(t,r){this.strategy.set(t,r)}delete(t){this.strategy.remove(t)}};s(F,"CookieStrategy");var M=F,y=Symbol("storage-handler"),g=Symbol("prop-session"),w=Symbol("prop-refresh"),H=class H{constructor(t){this[g]=t.sessionStorageProp,this[w]=t.refreshStorageProp,t.storageType==="cookie"?this[y]=new M:this[y]=new D}getTokens(){return{refreshToken:this[y].get(this[w]),sessionToken:this[y].get(this[g])}}setTokens(t){this[y].set(this[w],t.refreshToken),this[y].set(this[g],t.sessionToken)}clear(){this[y].delete(this[w]),this[y].delete(this[g])}hasChangedSession({sessionToken:t}){let{sessionToken:r}=this.getTokens();return t!==r}};s(H,"StorageClass");var S=H;import{createClient as oe}from"graphql-ws";import{Observable as ie}from"relay-runtime";function ne(e,t,r){if(e.usePersistedQueries){if(!t.id)throw new Error(`[usePersistedQueries] Operation "${t.name}" has no persisted id \u2014 run relay-compiler with "persistConfig" set in relay.config.json.`);return{operationName:t.name,query:"",variables:r,extensions:{[e.persistedOperationField||"doc_id"]:t.id}}}return{operationName:t.name,query:t.text||"",variables:r}}s(ne,"getSubscribePayload");function K(e){return()=>{let t;return(r,o)=>ie.create(a=>(t||(t=oe({url:e.socket})),t.subscribe(ne(e,r,o),{next:s(i=>a.next(i),"next"),error:s(i=>a.error(i),"error"),complete:s(()=>a.complete(),"complete")})))}}s(K,"setupSubscription");var G=Symbol("mount-environment"),N=Symbol("handler-fetch"),q=Symbol("handler-subscription"),W=class W{constructor(t){if(this.url=t.url,this.authUrl=t.authUrl,this.socket=t.socket,this.storageType=t.storageType||"localStorage",this.cacheSize=t.cacheSize||250,this.cacheTime=t.cacheTime||v*8,this.timeout=t.timeout||v*15,this.sessionStorageProp=t.sessionStorageProp||"USER_SESSION_TOKEN",this.refreshStorageProp=t.refreshStorageProp||"USER_REFRESH_TOKEN",this.loginRoute=t.loginRoute||"/",this.useCache=t.useCache||!1,this.useDebug=t.useDebug||!1,this.useAuthorization=t.useAuthorization||!1,this.authMode=t.authMode||"bearer",this.credentials=t.credentials,this.sessionCheckUrl=t.sessionCheckUrl,this.useRetries=t.useRetries||!1,this.useSubscription=t.useSubscription||!1,this.redirectOnError=t.redirectOnError||!1,this.retryWhen=t.retryWhen||[503,504,521,522,524],this.authenticationErrors=t.authenticationErrors||[401,403],this.retries=t.retries||[b,b*2,b*3,b*5,b*8,b*13,b*21,b*34],this.partner=t.partner||void 0,this.usePersistedQueries=t.usePersistedQueries||!1,this.persistedOperationField=t.persistedOperationField||"doc_id",!this.url)throw new Error("[HTTPFetchEndpoint] You must at least set url parameter.");if(this.useAuthorization&&!this.authUrl)throw new Error('[useAuthorization] Authorization is set but no "authUrl" was provided.');if(this.authMode==="cookie"&&this.sessionCheckUrl!==!1&&!this.authUrl)throw new Error('[authMode:cookie] Cookie auth refreshes against "authUrl" \u2014 provide it or set "sessionCheckUrl: false" to disable the probe.');if(this.StorageHandler=new S(this),this.useSubscription){if(!this.socket)throw new Error("[useSubscription] If you choose to use WebSocket you must set a socket endpoint.");this[q]=K(this)()}this[N]=J(this),this[G]()}[(N,q,G)](){let t=ue.create(this[N],this[q]||null),r=new le,o=new ce(r);this.Environment=new ae({network:t,store:o})}};s(W,"RelayEnvironment");var T=W;export{T as a};
1
+ import{a as s}from"./chunk-GZONWSRB.esm.js";import{Environment as ae,Network as ue,RecordSource as le,Store as ce}from"relay-runtime";import{Observable as te,QueryResponseCache as re}from"relay-runtime";var E=!!(typeof window!="undefined"&&window.document&&window.document.createElement),f={canUseDOM:E,canUseWorkers:typeof Worker!="undefined",canUseEventListeners:E&&!!(window.addEventListener||window.attachEvent),canUseViewport:E&&!!window.screen,isInWorker:!E};function $(e){return async t=>{let r=e.timeout,i=e.retries,a=0,o=0;return new Promise((u,l)=>{let c={};c.sendTimedRequest=()=>{a++,o=Date.now();let n=!0,p=new AbortController,m=setTimeout(()=>{if(n=!1,p.abort(),c.shouldRetry(a))e.useDebug&&console.log("fetchWithRetries: HTTP timeout, retrying."),c.retryRequest();else{let h=new Error(`fetchWithRetries(): Failed to get response from server, tried ${a} times.`);h.name="TimeOutError",l(h)}},r);fetch(e.url,{...t,signal:p.signal}).then(async h=>{if(clearTimeout(m),n)if(h.status>=200&&h.status<300)u(h);else if(c.shouldRetry(a)&&e.retryWhen.includes(h.status))e.useDebug&&console.log("fetchWithRetries: HTTP error, retrying..."),c.retryRequest();else{let d=new Error(`fetchWithRetries(): Still no successful response after ${a} retries, giving up.`);d.response=h,l(d)}}).catch(h=>{clearTimeout(m),h.name!=="AbortError"&&l(h)})},c.retryRequest=()=>{let n=i[a-1],p=o+n;setTimeout(c.sendTimedRequest,p-Date.now())},c.shouldRetry=n=>f.canUseDOM&&e.useRetries&&n<=i.length,c.sendTimedRequest()})}}s($,"fetchWithRetries");import{PatchResolver as X}from"fetch-multipart-graphql";var x=s(e=>e.operationKind==="mutation","isMutation"),O=s(e=>e.operationKind==="query","isQuery"),V=s(e=>!!(e&&e.force),"forceFetch"),Y=s(()=>f.canUseDOM?window.location.search.startsWith("?")?"&":"?":"","getParamsDelimiter"),C=s(()=>f.canUseDOM?window.location.pathname:"","getBrowserLocation"),R=s((e,t,r)=>{let i=e;(e!==t||r.loginRoute!==t)&&(i=`${t}${Y()}redirect=${e}`),window.location.href=i},"redirectUser");function L(e){if(!e.id)throw new Error(`[usePersistedQueries] Operation "${e.name}" has no persisted id \u2014 run relay-compiler with "persistConfig" set in relay.config.json.`);return e.id}s(L,"getPersistedOperationId");function Z(e,t,r,i){let a=new FormData,o=i!=null&&i.usePersistedQueries?{[i.persistedOperationField||"doc_id"]:L(e),variables:t,operationName:e.name}:{query:e.text,variables:t,operationName:e.name};a.append("operations",JSON.stringify(o));let u={};for(let l=0;l<r.files.length;l++)a.append(`${l}`,r.files[l]),u[`${l}`]=[r.path(l)];return a.append("map",JSON.stringify(u)),a}s(Z,"getRequestBodyWithUploadables");function ee(e,t,r){return r!=null&&r.usePersistedQueries?JSON.stringify({name:e.name,[r.persistedOperationField||"doc_id"]:L(e),variables:t}):JSON.stringify({name:e.name,query:e.text,variables:t})}s(ee,"getRequestBodyWithoutUplodables");function B(e,t,r,i){return r?Z(e,t,r,i):ee(e,t,i)}s(B,"getRequestBody");var U=s(e=>{if(e.credentials)return e.credentials;if(e.authMode==="cookie")return"include"},"resolveCredentials"),_=s((e,t)=>{let r=new Headers;if(t?r.append("Accept","*/*"):(r.append("Accept","application/json"),r.append("Content-type","application/json")),e.useAuthorization&&e.authMode!=="cookie"){let{sessionToken:i}=e.StorageHandler.getTokens();i&&C()!==e.loginRoute&&r.append("Authorization",`Bearer ${i}`)}return e.partner&&r.append("X-Partner",e.partner),r},"getHeaders"),j=s((e,t,r)=>{if(e.status<300&&e.headers&&e.headers.get("Content-Type")&&e.headers.get("Content-Type").indexOf("multipart/mixed")>=0){let i=e.body.getReader(),a=new TextDecoder,o=new X({onResponse:s(u=>t.next(u),"onResponse")});i.read().then(s(function u({value:l,done:c}){if(c)t.complete();else{let n;try{n=a.decode(l),o.handleChunk(n)}catch(p){let m=p;m.response=e,m.statusCode=e.status,m.bodyText=n,t.error(m)}i.read().then(u)}},"sendNext"))}else e.headers&&e.headers.get("Content-Type")&&e.headers.get("Content-Type").indexOf("application/json")>=0?e.json().then(r):e.text().then(i=>{t.next([i]),t.complete()})},"handleData"),b=1e3,v=b*60;var J=s(e=>{let t=new re({ttl:e.cacheTime,size:e.cacheSize}),r=$(e);async function i(){if(e.sessionCheckUrl===!1)return!1;let o=U(e);try{if(e.authMode==="cookie"){let n=e.sessionCheckUrl||e.authUrl;return(await fetch(n,{method:"POST",credentials:o||"include"})).status===200}let{sessionToken:u}=e.StorageHandler.getTokens(),l=e.sessionCheckUrl||`${e.authUrl}user/me`;return(await fetch(l,{headers:{"Content-Type":"application/json",Authorization:u},...o?{credentials:o}:{}})).status===200}catch(u){return console.warn(`[Auth] ${u.message}`),!1}}s(i,"checkSession");async function a(o,u,l,c,n){try{let p=o.id||("cacheID"in o?o.cacheID:null)||String(o.text);if(e.useCache&&O(o)&&!V(l)){let d=t.get(p,u);if(d){n.next(d),n.complete();return}}e.useCache&&x(o)&&t.clear();let m=U(e),h=await r({method:"POST",headers:_(e,c),body:B(o,u,c,e),...m?{credentials:m}:{}});j(h,n,async d=>{if(e.useCache&&O(o)&&t.set(p,u,d),!n.closed){if(x(o)&&d.errors&&n.error(d.errors),d.errors){if(await i()||(e.StorageHandler.clear(),R("/",e.loginRoute,e)),e.redirectOnError){let z=[];Array.isArray(d.errors)&&(z=d.errors.map(({status_code:P})=>P));let Q=C();z.some(P=>e.authenticationErrors.includes(P))&&Q!==e.loginRoute&&(e.StorageHandler.clear(),R(Q,e.loginRoute,e))}n.error(d.errors)}else d.data?n.next(d):n.error(d);n.complete()}})}catch(p){if(f.canUseDOM&&!["AbortError","TimeOutError"].includes(p.name)&&e.StorageHandler.clear(),e.redirectOnError){let h=C();h!==e.loginRoute&&R(h,e.loginRoute,e)}await i()||(e.StorageHandler.clear(),R("/",e.loginRoute,e)),n.error(p)}}return s(a,"fetchFn"),(o,u,l,c)=>te.create(n=>{a(o,u,l,c,n)})},"createFetchFunction");import se from"js-cookie";var M=class M{get(t){throw new Error('Must implement a "GET" method')}set(t,r){throw new Error('Must implement a "SET" method')}delete(t){throw new Error('Must implement a "DELETE" method')}};s(M,"DefaultStrategy");var k=M,A=class A extends k{constructor(){super(),this.strategy=localStorage}get(t){return this.strategy.getItem(t)}set(t,r){this.strategy.setItem(t,r)}delete(t){this.strategy.removeItem(t)}};s(A,"LocalStorageStrategy");var D=A,F=class F extends k{constructor(){super(),this.strategy=se}get(t){return this.strategy.get(t)}set(t,r){this.strategy.set(t,r)}delete(t){this.strategy.remove(t)}};s(F,"CookieStrategy");var I=F,y=Symbol("storage-handler"),g=Symbol("prop-session"),w=Symbol("prop-refresh"),H=class H{constructor(t){this[g]=t.sessionStorageProp,this[w]=t.refreshStorageProp,t.storageType==="cookie"?this[y]=new I:this[y]=new D}getTokens(){return{refreshToken:this[y].get(this[w]),sessionToken:this[y].get(this[g])}}setTokens(t){this[y].set(this[w],t.refreshToken),this[y].set(this[g],t.sessionToken)}clear(){this[y].delete(this[w]),this[y].delete(this[g])}hasChangedSession({sessionToken:t}){let{sessionToken:r}=this.getTokens();return t!==r}};s(H,"StorageClass");var S=H;import{createClient as ie}from"graphql-ws";import{Observable as oe}from"relay-runtime";function ne(e,t,r){if(e.usePersistedQueries){if(!t.id)throw new Error(`[usePersistedQueries] Operation "${t.name}" has no persisted id \u2014 run relay-compiler with "persistConfig" set in relay.config.json.`);return{operationName:t.name,query:"",variables:r,extensions:{[e.persistedOperationField||"doc_id"]:t.id}}}return{operationName:t.name,query:t.text||"",variables:r}}s(ne,"getSubscribePayload");function K(e){return()=>{let t;return(r,i)=>oe.create(a=>(t||(t=ie({url:e.socket})),t.subscribe(ne(e,r,i),{next:s(o=>a.next(o),"next"),error:s(o=>a.error(o),"error"),complete:s(()=>a.complete(),"complete")})))}}s(K,"setupSubscription");var G=Symbol("mount-environment"),N=Symbol("handler-fetch"),q=Symbol("handler-subscription"),W=class W{constructor(t){if(this.url=t.url,this.authUrl=t.authUrl,this.socket=t.socket,this.storageType=t.storageType||"localStorage",this.cacheSize=t.cacheSize||250,this.cacheTime=t.cacheTime||v*8,this.timeout=t.timeout||v*15,this.sessionStorageProp=t.sessionStorageProp||"USER_SESSION_TOKEN",this.refreshStorageProp=t.refreshStorageProp||"USER_REFRESH_TOKEN",this.loginRoute=t.loginRoute||"/",this.useCache=t.useCache||!1,this.useDebug=t.useDebug||!1,this.useAuthorization=t.useAuthorization||!1,this.authMode=t.authMode||"bearer",this.credentials=t.credentials,this.sessionCheckUrl=t.sessionCheckUrl,this.useRetries=t.useRetries||!1,this.useSubscription=t.useSubscription||!1,this.redirectOnError=t.redirectOnError||!1,this.retryWhen=t.retryWhen||[503,504,521,522,524],this.authenticationErrors=t.authenticationErrors||[401,403],this.retries=t.retries||[b,b*2,b*3,b*5,b*8,b*13,b*21,b*34],this.partner=t.partner||void 0,this.usePersistedQueries=t.usePersistedQueries||!1,this.persistedOperationField=t.persistedOperationField||"doc_id",this.initialRecords=t.initialRecords,!this.url)throw new Error("[HTTPFetchEndpoint] You must at least set url parameter.");if(this.useAuthorization&&!this.authUrl)throw new Error('[useAuthorization] Authorization is set but no "authUrl" was provided.');if(this.authMode==="cookie"&&this.sessionCheckUrl!==!1&&!this.authUrl)throw new Error('[authMode:cookie] Cookie auth refreshes against "authUrl" \u2014 provide it or set "sessionCheckUrl: false" to disable the probe.');if(this.StorageHandler=new S(this),this.useSubscription){if(!this.socket)throw new Error("[useSubscription] If you choose to use WebSocket you must set a socket endpoint.");this[q]=K(this)()}this[N]=J(this),this[G]()}[(N,q,G)](){let t=ue.create(this[N],this[q]||null),r=new le(this.initialRecords),i=new ce(r);this.Environment=new ae({network:t,store:i})}};s(W,"RelayEnvironment");var T=W;export{T as a};
@@ -0,0 +1 @@
1
+ import{a as r}from"./chunk-GZONWSRB.esm.js";import e from"react";import{RelayEnvironmentProvider as i}from"react-relay";var t=e.createContext(void 0);function d({children:n,environment:o}){return e.createElement(t.Provider,{value:{environment:o}},e.createElement(i,{environment:o},n))}r(d,"EnvironmentProvider");function E(){let n=e.useContext(t);if(n===void 0)throw new Error("useEnvironment must be used within a EnvironmentProvider");if(n.environment===null||n.environment===void 0)throw new Error("You should provide a Relay Environment to EnvironmentProvider component");return n}r(E,"useEnvironment");export{d as a,E as b};
package/lib/index.esm.js CHANGED
@@ -1 +1 @@
1
- import{a as o}from"./chunks/chunk-RMYDTZUF.esm.js";import{a as m,b as f,c as p,d as x,e as n,f as a,g as i,h as l}from"./chunks/chunk-XJA2SRQY.esm.js";import"./chunks/chunk-FYOI5Q5V.esm.js";import{a as r}from"./chunks/chunk-KIA6YWO5.esm.js";import{a as e,b as t}from"./chunks/chunk-54QV6DFY.esm.js";import"./chunks/chunk-GZONWSRB.esm.js";export{f as ClientMutationID,r as CreateRelayEnvironment,e as EnvironmentProvider,o as commitMutation,i as connectionDeleteEdgeUpdater,n as connectionUpdater,l as copyObjScalarsToProxy,m as isObject,x as listRecordAddUpdater,p as listRecordRemoveUpdater,a as optimisticConnectionUpdater,t as useEnvironment};
1
+ import{a as o}from"./chunks/chunk-RMYDTZUF.esm.js";import{a as m,b as f,c as p,d as x,e as n,f as a,g as i,h as l}from"./chunks/chunk-XJA2SRQY.esm.js";import"./chunks/chunk-FYOI5Q5V.esm.js";import{a as r}from"./chunks/chunk-CHTVEJCU.esm.js";import{a as e,b as t}from"./chunks/chunk-EATF764J.esm.js";import"./chunks/chunk-GZONWSRB.esm.js";export{f as ClientMutationID,r as CreateRelayEnvironment,e as EnvironmentProvider,o as commitMutation,i as connectionDeleteEdgeUpdater,n as connectionUpdater,l as copyObjScalarsToProxy,m as isObject,x as listRecordAddUpdater,p as listRecordRemoveUpdater,a as optimisticConnectionUpdater,t as useEnvironment};
package/lib/index.js CHANGED
@@ -1 +1 @@
1
- var ge=Object.create;var S=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var xe=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var o=(e,t)=>S(e,"name",{value:t,configurable:!0});var we=(e,t)=>{for(var r in t)S(e,r,{get:t[r],enumerable:!0})},Y=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Re(t))!Ee.call(e,i)&&i!==r&&S(e,i,{get:()=>t[i],enumerable:!(n=be(t,i))||n.enumerable});return e};var G=(e,t,r)=>(r=e!=null?ge(xe(e)):{},Y(t||!e||!e.__esModule?S(r,"default",{value:e,enumerable:!0}):r,e)),Se=e=>Y(S({},"__esModule",{value:!0}),e);var We={};we(We,{ClientMutationID:()=>Ie,CreateRelayEnvironment:()=>x,EnvironmentProvider:()=>Oe,commitMutation:()=>Le,connectionDeleteEdgeUpdater:()=>Fe,connectionUpdater:()=>fe,copyObjScalarsToProxy:()=>He,isObject:()=>me,listRecordAddUpdater:()=>De,listRecordRemoveUpdater:()=>Ae,optimisticConnectionUpdater:()=>Ne,useEnvironment:()=>ke});module.exports=Se(We);var g=require("relay-runtime");var U=require("relay-runtime");var O=!!(typeof window!="undefined"&&window.document&&window.document.createElement),R={canUseDOM:O,canUseWorkers:typeof Worker!="undefined",canUseEventListeners:O&&!!(window.addEventListener||window.attachEvent),canUseViewport:O&&!!window.screen,isInWorker:!O};function X(e){return async t=>{let r=e.timeout,n=e.retries,i=0,s=0;return new Promise((a,u)=>{let l={};l.sendTimedRequest=()=>{i++,s=Date.now();let c=!0,h=new AbortController,m=setTimeout(()=>{if(c=!1,h.abort(),l.shouldRetry(i))e.useDebug&&console.log("fetchWithRetries: HTTP timeout, retrying."),l.retryRequest();else{let d=new Error(`fetchWithRetries(): Failed to get response from server, tried ${i} times.`);d.name="TimeOutError",u(d)}},r);fetch(e.url,{...t,signal:h.signal}).then(async d=>{if(clearTimeout(m),c)if(d.status>=200&&d.status<300)a(d);else if(l.shouldRetry(i)&&e.retryWhen.includes(d.status))e.useDebug&&console.log("fetchWithRetries: HTTP error, retrying..."),l.retryRequest();else{let p=new Error(`fetchWithRetries(): Still no successful response after ${i} retries, giving up.`);p.response=d,u(p)}}).catch(d=>{clearTimeout(m),d.name!=="AbortError"&&u(d)})},l.retryRequest=()=>{let c=n[i-1],h=s+c;setTimeout(l.sendTimedRequest,h-Date.now())},l.shouldRetry=c=>R.canUseDOM&&e.useRetries&&c<=n.length,l.sendTimedRequest()})}}o(X,"fetchWithRetries");var Z=require("fetch-multipart-graphql");var D=o(e=>e.operationKind==="mutation","isMutation"),N=o(e=>e.operationKind==="query","isQuery"),ee=o(e=>!!(e&&e.force),"forceFetch"),Pe=o(()=>R.canUseDOM?window.location.search.startsWith("?")?"&":"?":"","getParamsDelimiter"),k=o(()=>R.canUseDOM?window.location.pathname:"","getBrowserLocation"),P=o((e,t,r)=>{let n=e;(e!==t||r.loginRoute!==t)&&(n=`${t}${Pe()}redirect=${e}`),window.location.href=n},"redirectUser");function te(e){if(!e.id)throw new Error(`[usePersistedQueries] Operation "${e.name}" has no persisted id \u2014 run relay-compiler with "persistConfig" set in relay.config.json.`);return e.id}o(te,"getPersistedOperationId");function Ce(e,t,r,n){let i=new FormData,s=n!=null&&n.usePersistedQueries?{[n.persistedOperationField||"doc_id"]:te(e),variables:t,operationName:e.name}:{query:e.text,variables:t,operationName:e.name};i.append("operations",JSON.stringify(s));let a={};for(let u=0;u<r.files.length;u++)i.append(`${u}`,r.files[u]),a[`${u}`]=[r.path(u)];return i.append("map",JSON.stringify(a)),i}o(Ce,"getRequestBodyWithUploadables");function ve(e,t,r){return r!=null&&r.usePersistedQueries?JSON.stringify({name:e.name,[r.persistedOperationField||"doc_id"]:te(e),variables:t}):JSON.stringify({name:e.name,query:e.text,variables:t})}o(ve,"getRequestBodyWithoutUplodables");function re(e,t,r,n){return r?Ce(e,t,r,n):ve(e,t,n)}o(re,"getRequestBody");var F=o(e=>{if(e.credentials)return e.credentials;if(e.authMode==="cookie")return"include"},"resolveCredentials"),oe=o((e,t)=>{let r=new Headers;if(t?r.append("Accept","*/*"):(r.append("Accept","application/json"),r.append("Content-type","application/json")),e.useAuthorization&&e.authMode!=="cookie"){let{sessionToken:n}=e.StorageHandler.getTokens();n&&k()!==e.loginRoute&&r.append("Authorization",`Bearer ${n}`)}return e.partner&&r.append("X-Partner",e.partner),r},"getHeaders"),ne=o((e,t,r)=>{if(e.status<300&&e.headers&&e.headers.get("Content-Type")&&e.headers.get("Content-Type").indexOf("multipart/mixed")>=0){let n=e.body.getReader(),i=new TextDecoder,s=new Z.PatchResolver({onResponse:o(a=>t.next(a),"onResponse")});n.read().then(o(function a({value:u,done:l}){if(l)t.complete();else{let c;try{c=i.decode(u),s.handleChunk(c)}catch(h){let m=h;m.response=e,m.statusCode=e.status,m.bodyText=c,t.error(m)}n.read().then(a)}},"sendNext"))}else e.headers&&e.headers.get("Content-Type")&&e.headers.get("Content-Type").indexOf("application/json")>=0?e.json().then(r):e.text().then(n=>{t.next([n]),t.complete()})},"handleData"),f=1e3,H=f*60;var se=o(e=>{let t=new U.QueryResponseCache({ttl:e.cacheTime,size:e.cacheSize}),r=X(e);async function n(){if(e.sessionCheckUrl===!1)return!1;let s=F(e);try{if(e.authMode==="cookie"){let c=e.sessionCheckUrl||e.authUrl;return(await fetch(c,{method:"POST",credentials:s||"include"})).status===200}let{sessionToken:a}=e.StorageHandler.getTokens(),u=e.sessionCheckUrl||`${e.authUrl}user/me`;return(await fetch(u,{headers:{"Content-Type":"application/json",Authorization:a},...s?{credentials:s}:{}})).status===200}catch(a){return console.warn(`[Auth] ${a.message}`),!1}}o(n,"checkSession");async function i(s,a,u,l,c){try{let h=s.id||("cacheID"in s?s.cacheID:null)||String(s.text);if(e.useCache&&N(s)&&!ee(u)){let p=t.get(h,a);if(p){c.next(p),c.complete();return}}e.useCache&&D(s)&&t.clear();let m=F(e),d=await r({method:"POST",headers:oe(e,l),body:re(s,a,l,e),...m?{credentials:m}:{}});ne(d,c,async p=>{if(e.useCache&&N(s)&&t.set(h,a,p),!c.closed){if(D(s)&&p.errors&&c.error(p.errors),p.errors){if(await n()||(e.StorageHandler.clear(),P("/",e.loginRoute,e)),e.redirectOnError){let J=[];Array.isArray(p.errors)&&(J=p.errors.map(({status_code:A})=>A));let K=k();J.some(A=>e.authenticationErrors.includes(A))&&K!==e.loginRoute&&(e.StorageHandler.clear(),P(K,e.loginRoute,e))}c.error(p.errors)}else p.data?c.next(p):c.error(p);c.complete()}})}catch(h){if(R.canUseDOM&&!["AbortError","TimeOutError"].includes(h.name)&&e.StorageHandler.clear(),e.redirectOnError){let d=k();d!==e.loginRoute&&P(d,e.loginRoute,e)}await n()||(e.StorageHandler.clear(),P("/",e.loginRoute,e)),c.error(h)}}return o(i,"fetchFn"),(s,a,u,l)=>U.Observable.create(c=>{i(s,a,u,l,c)})},"createFetchFunction");var ie=G(require("js-cookie"));var q=class q{get(t){throw new Error('Must implement a "GET" method')}set(t,r){throw new Error('Must implement a "SET" method')}delete(t){throw new Error('Must implement a "DELETE" method')}};o(q,"DefaultStrategy");var M=q,V=class V extends M{constructor(){super(),this.strategy=localStorage}get(t){return this.strategy.getItem(t)}set(t,r){this.strategy.setItem(t,r)}delete(t){this.strategy.removeItem(t)}};o(V,"LocalStorageStrategy");var L=V,$=class $ extends M{constructor(){super(),this.strategy=ie.default}get(t){return this.strategy.get(t)}set(t,r){this.strategy.set(t,r)}delete(t){this.strategy.remove(t)}};o($,"CookieStrategy");var W=$,y=Symbol("storage-handler"),C=Symbol("prop-session"),v=Symbol("prop-refresh"),Q=class Q{constructor(t){this[C]=t.sessionStorageProp,this[v]=t.refreshStorageProp,t.storageType==="cookie"?this[y]=new W:this[y]=new L}getTokens(){return{refreshToken:this[y].get(this[v]),sessionToken:this[y].get(this[C])}}setTokens(t){this[y].set(this[v],t.refreshToken),this[y].set(this[C],t.sessionToken)}clear(){this[y].delete(this[v]),this[y].delete(this[C])}hasChangedSession({sessionToken:t}){let{sessionToken:r}=this.getTokens();return t!==r}};o(Q,"StorageClass");var T=Q;var ae=require("graphql-ws"),ce=require("relay-runtime");function Te(e,t,r){if(e.usePersistedQueries){if(!t.id)throw new Error(`[usePersistedQueries] Operation "${t.name}" has no persisted id \u2014 run relay-compiler with "persistConfig" set in relay.config.json.`);return{operationName:t.name,query:"",variables:r,extensions:{[e.persistedOperationField||"doc_id"]:t.id}}}return{operationName:t.name,query:t.text||"",variables:r}}o(Te,"getSubscribePayload");function ue(e){return()=>{let t;return(r,n)=>ce.Observable.create(i=>(t||(t=(0,ae.createClient)({url:e.socket})),t.subscribe(Te(e,r,n),{next:o(s=>i.next(s),"next"),error:o(s=>i.error(s),"error"),complete:o(()=>i.complete(),"complete")})))}}o(ue,"setupSubscription");var le=Symbol("mount-environment"),j=Symbol("handler-fetch"),B=Symbol("handler-subscription"),_=class _{constructor(t){if(this.url=t.url,this.authUrl=t.authUrl,this.socket=t.socket,this.storageType=t.storageType||"localStorage",this.cacheSize=t.cacheSize||250,this.cacheTime=t.cacheTime||H*8,this.timeout=t.timeout||H*15,this.sessionStorageProp=t.sessionStorageProp||"USER_SESSION_TOKEN",this.refreshStorageProp=t.refreshStorageProp||"USER_REFRESH_TOKEN",this.loginRoute=t.loginRoute||"/",this.useCache=t.useCache||!1,this.useDebug=t.useDebug||!1,this.useAuthorization=t.useAuthorization||!1,this.authMode=t.authMode||"bearer",this.credentials=t.credentials,this.sessionCheckUrl=t.sessionCheckUrl,this.useRetries=t.useRetries||!1,this.useSubscription=t.useSubscription||!1,this.redirectOnError=t.redirectOnError||!1,this.retryWhen=t.retryWhen||[503,504,521,522,524],this.authenticationErrors=t.authenticationErrors||[401,403],this.retries=t.retries||[f,f*2,f*3,f*5,f*8,f*13,f*21,f*34],this.partner=t.partner||void 0,this.usePersistedQueries=t.usePersistedQueries||!1,this.persistedOperationField=t.persistedOperationField||"doc_id",!this.url)throw new Error("[HTTPFetchEndpoint] You must at least set url parameter.");if(this.useAuthorization&&!this.authUrl)throw new Error('[useAuthorization] Authorization is set but no "authUrl" was provided.');if(this.authMode==="cookie"&&this.sessionCheckUrl!==!1&&!this.authUrl)throw new Error('[authMode:cookie] Cookie auth refreshes against "authUrl" \u2014 provide it or set "sessionCheckUrl: false" to disable the probe.');if(this.StorageHandler=new T(this),this.useSubscription){if(!this.socket)throw new Error("[useSubscription] If you choose to use WebSocket you must set a socket endpoint.");this[B]=ue(this)()}this[j]=se(this),this[le]()}[(j,B,le)](){let t=g.Network.create(this[j],this[B]||null),r=new g.RecordSource,n=new g.Store(r);this.Environment=new g.Environment({network:t,store:n})}};o(_,"RelayEnvironment");var x=_;var I=G(require("react"));var de=I.default.createContext(void 0);function Oe({children:e,environment:t}){return I.default.createElement(de.Provider,{value:{environment:t}},e)}o(Oe,"EnvironmentProvider");function ke(){let e=I.default.useContext(de);if(e===void 0)throw new Error("useEnvironment must be used within a EnvironmentProvider");if(e.environment===null||e.environment===void 0)throw new Error("You should provide a Relay Environment to EnvironmentProvider component");return e}o(ke,"useEnvironment");var z=require("node:crypto");var pe="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ue=128,b,E;function Me(e){if(e<0)throw new RangeError("Wrong ID size");try{!b||b.length<e?(b=Buffer.allocUnsafe(e*Ue),z.webcrypto.getRandomValues(b),E=0):E+e>b.length&&(z.webcrypto.getRandomValues(b),E=0)}catch(t){throw b=void 0,t}E+=e}o(Me,"fillPool");function he(e=21){Me(e|=0);let t="";for(let r=E-e;r<E;r++)t+=pe[b[r]&63];return t}o(he,"nanoid");var w=require("relay-runtime");function me(e){return e!==null&&typeof e=="object"}o(me,"isObject");var Ie=he();function Ae({parentId:e,itemId:t,parentFieldName:r,store:n}){let i=n.get(e),s=i.getLinkedRecords(r);i.setLinkedRecords(s.filter(a=>a.dataID!==t),r)}o(Ae,"listRecordRemoveUpdater");function De({parentId:e,item:t,type:r,parentFieldName:n,store:i}){let s=i.create(t.id,r);Object.keys(t).forEach(l=>{s.setValue(t[l],l)});let a=i.get(e),u=a.getLinkedRecords(n);a.setLinkedRecords([...u,s],n)}o(De,"listRecordAddUpdater");function fe(e,t,r,n,i=!1){if(n){let s=e.get(t),a=w.ConnectionHandler.getConnection(s,r);if(!a)return;i?w.ConnectionHandler.insertEdgeBefore(a,n):w.ConnectionHandler.insertEdgeAfter(a,n)}}o(fe,"connectionUpdater");function Ne({parentId:e,store:t,connectionName:r,item:n,customNode:i,itemType:s}){let a=i||t.create(n.id,s);!i&&Object.keys(n).forEach(l=>{a.setValue(n[l],l)});let u=t.create(`client:newEdge:${String(a.getDataID).match(/[^:]+$/)[0]}`,`${s}Edge`);u.setLinkedRecord(a,"node"),fe(t,e,r,u)}o(Ne,"optimisticConnectionUpdater");function Fe({parentId:e,connectionName:t,nodeId:r,store:n}){let i=n.get(e),s=w.ConnectionHandler.getConnection(i,t);if(!s){console.warn(`Connection ${t} not found on ${e}`);return}w.ConnectionHandler.deleteNode(s,r)}o(Fe,"connectionDeleteEdgeUpdater");function He({object:e,proxy:t}){Object.keys(e).forEach(r=>{me(e[r])||Array.isArray(e[r])||t.setValue(e[r],r)})}o(He,"copyObjScalarsToProxy");var ye=require("relay-runtime");var Le=o((e,t)=>new Promise((r,n)=>{(0,ye.commitMutation)(e,{...t,onError:n,onCompleted:r})}),"commitMutation");0&&(module.exports={ClientMutationID,CreateRelayEnvironment,EnvironmentProvider,commitMutation,connectionDeleteEdgeUpdater,connectionUpdater,copyObjScalarsToProxy,isObject,listRecordAddUpdater,listRecordRemoveUpdater,optimisticConnectionUpdater,useEnvironment});
1
+ var ge=Object.create;var S=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var Ee=Object.getOwnPropertyNames;var xe=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty;var o=(e,t)=>S(e,"name",{value:t,configurable:!0});var Se=(e,t)=>{for(var r in t)S(e,r,{get:t[r],enumerable:!0})},Y=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ee(t))!we.call(e,i)&&i!==r&&S(e,i,{get:()=>t[i],enumerable:!(n=be(t,i))||n.enumerable});return e};var G=(e,t,r)=>(r=e!=null?ge(xe(e)):{},Y(t||!e||!e.__esModule?S(r,"default",{value:e,enumerable:!0}):r,e)),Pe=e=>Y(S({},"__esModule",{value:!0}),e);var qe={};Se(qe,{ClientMutationID:()=>Ae,CreateRelayEnvironment:()=>E,EnvironmentProvider:()=>ke,commitMutation:()=>We,connectionDeleteEdgeUpdater:()=>He,connectionUpdater:()=>ye,copyObjScalarsToProxy:()=>Le,isObject:()=>fe,listRecordAddUpdater:()=>Ne,listRecordRemoveUpdater:()=>De,optimisticConnectionUpdater:()=>Fe,useEnvironment:()=>Ue});module.exports=Pe(qe);var R=require("relay-runtime");var I=require("relay-runtime");var k=!!(typeof window!="undefined"&&window.document&&window.document.createElement),b={canUseDOM:k,canUseWorkers:typeof Worker!="undefined",canUseEventListeners:k&&!!(window.addEventListener||window.attachEvent),canUseViewport:k&&!!window.screen,isInWorker:!k};function X(e){return async t=>{let r=e.timeout,n=e.retries,i=0,s=0;return new Promise((a,u)=>{let l={};l.sendTimedRequest=()=>{i++,s=Date.now();let c=!0,h=new AbortController,m=setTimeout(()=>{if(c=!1,h.abort(),l.shouldRetry(i))e.useDebug&&console.log("fetchWithRetries: HTTP timeout, retrying."),l.retryRequest();else{let d=new Error(`fetchWithRetries(): Failed to get response from server, tried ${i} times.`);d.name="TimeOutError",u(d)}},r);fetch(e.url,{...t,signal:h.signal}).then(async d=>{if(clearTimeout(m),c)if(d.status>=200&&d.status<300)a(d);else if(l.shouldRetry(i)&&e.retryWhen.includes(d.status))e.useDebug&&console.log("fetchWithRetries: HTTP error, retrying..."),l.retryRequest();else{let p=new Error(`fetchWithRetries(): Still no successful response after ${i} retries, giving up.`);p.response=d,u(p)}}).catch(d=>{clearTimeout(m),d.name!=="AbortError"&&u(d)})},l.retryRequest=()=>{let c=n[i-1],h=s+c;setTimeout(l.sendTimedRequest,h-Date.now())},l.shouldRetry=c=>b.canUseDOM&&e.useRetries&&c<=n.length,l.sendTimedRequest()})}}o(X,"fetchWithRetries");var Z=require("fetch-multipart-graphql");var D=o(e=>e.operationKind==="mutation","isMutation"),N=o(e=>e.operationKind==="query","isQuery"),ee=o(e=>!!(e&&e.force),"forceFetch"),ve=o(()=>b.canUseDOM?window.location.search.startsWith("?")?"&":"?":"","getParamsDelimiter"),U=o(()=>b.canUseDOM?window.location.pathname:"","getBrowserLocation"),P=o((e,t,r)=>{let n=e;(e!==t||r.loginRoute!==t)&&(n=`${t}${ve()}redirect=${e}`),window.location.href=n},"redirectUser");function te(e){if(!e.id)throw new Error(`[usePersistedQueries] Operation "${e.name}" has no persisted id \u2014 run relay-compiler with "persistConfig" set in relay.config.json.`);return e.id}o(te,"getPersistedOperationId");function Ce(e,t,r,n){let i=new FormData,s=n!=null&&n.usePersistedQueries?{[n.persistedOperationField||"doc_id"]:te(e),variables:t,operationName:e.name}:{query:e.text,variables:t,operationName:e.name};i.append("operations",JSON.stringify(s));let a={};for(let u=0;u<r.files.length;u++)i.append(`${u}`,r.files[u]),a[`${u}`]=[r.path(u)];return i.append("map",JSON.stringify(a)),i}o(Ce,"getRequestBodyWithUploadables");function Te(e,t,r){return r!=null&&r.usePersistedQueries?JSON.stringify({name:e.name,[r.persistedOperationField||"doc_id"]:te(e),variables:t}):JSON.stringify({name:e.name,query:e.text,variables:t})}o(Te,"getRequestBodyWithoutUplodables");function re(e,t,r,n){return r?Ce(e,t,r,n):Te(e,t,n)}o(re,"getRequestBody");var F=o(e=>{if(e.credentials)return e.credentials;if(e.authMode==="cookie")return"include"},"resolveCredentials"),oe=o((e,t)=>{let r=new Headers;if(t?r.append("Accept","*/*"):(r.append("Accept","application/json"),r.append("Content-type","application/json")),e.useAuthorization&&e.authMode!=="cookie"){let{sessionToken:n}=e.StorageHandler.getTokens();n&&U()!==e.loginRoute&&r.append("Authorization",`Bearer ${n}`)}return e.partner&&r.append("X-Partner",e.partner),r},"getHeaders"),ne=o((e,t,r)=>{if(e.status<300&&e.headers&&e.headers.get("Content-Type")&&e.headers.get("Content-Type").indexOf("multipart/mixed")>=0){let n=e.body.getReader(),i=new TextDecoder,s=new Z.PatchResolver({onResponse:o(a=>t.next(a),"onResponse")});n.read().then(o(function a({value:u,done:l}){if(l)t.complete();else{let c;try{c=i.decode(u),s.handleChunk(c)}catch(h){let m=h;m.response=e,m.statusCode=e.status,m.bodyText=c,t.error(m)}n.read().then(a)}},"sendNext"))}else e.headers&&e.headers.get("Content-Type")&&e.headers.get("Content-Type").indexOf("application/json")>=0?e.json().then(r):e.text().then(n=>{t.next([n]),t.complete()})},"handleData"),f=1e3,H=f*60;var se=o(e=>{let t=new I.QueryResponseCache({ttl:e.cacheTime,size:e.cacheSize}),r=X(e);async function n(){if(e.sessionCheckUrl===!1)return!1;let s=F(e);try{if(e.authMode==="cookie"){let c=e.sessionCheckUrl||e.authUrl;return(await fetch(c,{method:"POST",credentials:s||"include"})).status===200}let{sessionToken:a}=e.StorageHandler.getTokens(),u=e.sessionCheckUrl||`${e.authUrl}user/me`;return(await fetch(u,{headers:{"Content-Type":"application/json",Authorization:a},...s?{credentials:s}:{}})).status===200}catch(a){return console.warn(`[Auth] ${a.message}`),!1}}o(n,"checkSession");async function i(s,a,u,l,c){try{let h=s.id||("cacheID"in s?s.cacheID:null)||String(s.text);if(e.useCache&&N(s)&&!ee(u)){let p=t.get(h,a);if(p){c.next(p),c.complete();return}}e.useCache&&D(s)&&t.clear();let m=F(e),d=await r({method:"POST",headers:oe(e,l),body:re(s,a,l,e),...m?{credentials:m}:{}});ne(d,c,async p=>{if(e.useCache&&N(s)&&t.set(h,a,p),!c.closed){if(D(s)&&p.errors&&c.error(p.errors),p.errors){if(await n()||(e.StorageHandler.clear(),P("/",e.loginRoute,e)),e.redirectOnError){let J=[];Array.isArray(p.errors)&&(J=p.errors.map(({status_code:A})=>A));let K=U();J.some(A=>e.authenticationErrors.includes(A))&&K!==e.loginRoute&&(e.StorageHandler.clear(),P(K,e.loginRoute,e))}c.error(p.errors)}else p.data?c.next(p):c.error(p);c.complete()}})}catch(h){if(b.canUseDOM&&!["AbortError","TimeOutError"].includes(h.name)&&e.StorageHandler.clear(),e.redirectOnError){let d=U();d!==e.loginRoute&&P(d,e.loginRoute,e)}await n()||(e.StorageHandler.clear(),P("/",e.loginRoute,e)),c.error(h)}}return o(i,"fetchFn"),(s,a,u,l)=>I.Observable.create(c=>{i(s,a,u,l,c)})},"createFetchFunction");var ie=G(require("js-cookie"));var q=class q{get(t){throw new Error('Must implement a "GET" method')}set(t,r){throw new Error('Must implement a "SET" method')}delete(t){throw new Error('Must implement a "DELETE" method')}};o(q,"DefaultStrategy");var M=q,V=class V extends M{constructor(){super(),this.strategy=localStorage}get(t){return this.strategy.getItem(t)}set(t,r){this.strategy.setItem(t,r)}delete(t){this.strategy.removeItem(t)}};o(V,"LocalStorageStrategy");var L=V,$=class $ extends M{constructor(){super(),this.strategy=ie.default}get(t){return this.strategy.get(t)}set(t,r){this.strategy.set(t,r)}delete(t){this.strategy.remove(t)}};o($,"CookieStrategy");var W=$,y=Symbol("storage-handler"),v=Symbol("prop-session"),C=Symbol("prop-refresh"),Q=class Q{constructor(t){this[v]=t.sessionStorageProp,this[C]=t.refreshStorageProp,t.storageType==="cookie"?this[y]=new W:this[y]=new L}getTokens(){return{refreshToken:this[y].get(this[C]),sessionToken:this[y].get(this[v])}}setTokens(t){this[y].set(this[C],t.refreshToken),this[y].set(this[v],t.sessionToken)}clear(){this[y].delete(this[C]),this[y].delete(this[v])}hasChangedSession({sessionToken:t}){let{sessionToken:r}=this.getTokens();return t!==r}};o(Q,"StorageClass");var T=Q;var ae=require("graphql-ws"),ce=require("relay-runtime");function Oe(e,t,r){if(e.usePersistedQueries){if(!t.id)throw new Error(`[usePersistedQueries] Operation "${t.name}" has no persisted id \u2014 run relay-compiler with "persistConfig" set in relay.config.json.`);return{operationName:t.name,query:"",variables:r,extensions:{[e.persistedOperationField||"doc_id"]:t.id}}}return{operationName:t.name,query:t.text||"",variables:r}}o(Oe,"getSubscribePayload");function ue(e){return()=>{let t;return(r,n)=>ce.Observable.create(i=>(t||(t=(0,ae.createClient)({url:e.socket})),t.subscribe(Oe(e,r,n),{next:o(s=>i.next(s),"next"),error:o(s=>i.error(s),"error"),complete:o(()=>i.complete(),"complete")})))}}o(ue,"setupSubscription");var le=Symbol("mount-environment"),j=Symbol("handler-fetch"),B=Symbol("handler-subscription"),_=class _{constructor(t){if(this.url=t.url,this.authUrl=t.authUrl,this.socket=t.socket,this.storageType=t.storageType||"localStorage",this.cacheSize=t.cacheSize||250,this.cacheTime=t.cacheTime||H*8,this.timeout=t.timeout||H*15,this.sessionStorageProp=t.sessionStorageProp||"USER_SESSION_TOKEN",this.refreshStorageProp=t.refreshStorageProp||"USER_REFRESH_TOKEN",this.loginRoute=t.loginRoute||"/",this.useCache=t.useCache||!1,this.useDebug=t.useDebug||!1,this.useAuthorization=t.useAuthorization||!1,this.authMode=t.authMode||"bearer",this.credentials=t.credentials,this.sessionCheckUrl=t.sessionCheckUrl,this.useRetries=t.useRetries||!1,this.useSubscription=t.useSubscription||!1,this.redirectOnError=t.redirectOnError||!1,this.retryWhen=t.retryWhen||[503,504,521,522,524],this.authenticationErrors=t.authenticationErrors||[401,403],this.retries=t.retries||[f,f*2,f*3,f*5,f*8,f*13,f*21,f*34],this.partner=t.partner||void 0,this.usePersistedQueries=t.usePersistedQueries||!1,this.persistedOperationField=t.persistedOperationField||"doc_id",this.initialRecords=t.initialRecords,!this.url)throw new Error("[HTTPFetchEndpoint] You must at least set url parameter.");if(this.useAuthorization&&!this.authUrl)throw new Error('[useAuthorization] Authorization is set but no "authUrl" was provided.');if(this.authMode==="cookie"&&this.sessionCheckUrl!==!1&&!this.authUrl)throw new Error('[authMode:cookie] Cookie auth refreshes against "authUrl" \u2014 provide it or set "sessionCheckUrl: false" to disable the probe.');if(this.StorageHandler=new T(this),this.useSubscription){if(!this.socket)throw new Error("[useSubscription] If you choose to use WebSocket you must set a socket endpoint.");this[B]=ue(this)()}this[j]=se(this),this[le]()}[(j,B,le)](){let t=R.Network.create(this[j],this[B]||null),r=new R.RecordSource(this.initialRecords),n=new R.Store(r);this.Environment=new R.Environment({network:t,store:n})}};o(_,"RelayEnvironment");var E=_;var O=G(require("react")),de=require("react-relay");var pe=O.default.createContext(void 0);function ke({children:e,environment:t}){return O.default.createElement(pe.Provider,{value:{environment:t}},O.default.createElement(de.RelayEnvironmentProvider,{environment:t},e))}o(ke,"EnvironmentProvider");function Ue(){let e=O.default.useContext(pe);if(e===void 0)throw new Error("useEnvironment must be used within a EnvironmentProvider");if(e.environment===null||e.environment===void 0)throw new Error("You should provide a Relay Environment to EnvironmentProvider component");return e}o(Ue,"useEnvironment");var z=require("node:crypto");var he="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Ie=128,g,x;function Me(e){if(e<0)throw new RangeError("Wrong ID size");try{!g||g.length<e?(g=Buffer.allocUnsafe(e*Ie),z.webcrypto.getRandomValues(g),x=0):x+e>g.length&&(z.webcrypto.getRandomValues(g),x=0)}catch(t){throw g=void 0,t}x+=e}o(Me,"fillPool");function me(e=21){Me(e|=0);let t="";for(let r=x-e;r<x;r++)t+=he[g[r]&63];return t}o(me,"nanoid");var w=require("relay-runtime");function fe(e){return e!==null&&typeof e=="object"}o(fe,"isObject");var Ae=me();function De({parentId:e,itemId:t,parentFieldName:r,store:n}){let i=n.get(e),s=i.getLinkedRecords(r);i.setLinkedRecords(s.filter(a=>a.dataID!==t),r)}o(De,"listRecordRemoveUpdater");function Ne({parentId:e,item:t,type:r,parentFieldName:n,store:i}){let s=i.create(t.id,r);Object.keys(t).forEach(l=>{s.setValue(t[l],l)});let a=i.get(e),u=a.getLinkedRecords(n);a.setLinkedRecords([...u,s],n)}o(Ne,"listRecordAddUpdater");function ye(e,t,r,n,i=!1){if(n){let s=e.get(t),a=w.ConnectionHandler.getConnection(s,r);if(!a)return;i?w.ConnectionHandler.insertEdgeBefore(a,n):w.ConnectionHandler.insertEdgeAfter(a,n)}}o(ye,"connectionUpdater");function Fe({parentId:e,store:t,connectionName:r,item:n,customNode:i,itemType:s}){let a=i||t.create(n.id,s);!i&&Object.keys(n).forEach(l=>{a.setValue(n[l],l)});let u=t.create(`client:newEdge:${String(a.getDataID).match(/[^:]+$/)[0]}`,`${s}Edge`);u.setLinkedRecord(a,"node"),ye(t,e,r,u)}o(Fe,"optimisticConnectionUpdater");function He({parentId:e,connectionName:t,nodeId:r,store:n}){let i=n.get(e),s=w.ConnectionHandler.getConnection(i,t);if(!s){console.warn(`Connection ${t} not found on ${e}`);return}w.ConnectionHandler.deleteNode(s,r)}o(He,"connectionDeleteEdgeUpdater");function Le({object:e,proxy:t}){Object.keys(e).forEach(r=>{fe(e[r])||Array.isArray(e[r])||t.setValue(e[r],r)})}o(Le,"copyObjScalarsToProxy");var Re=require("relay-runtime");var We=o((e,t)=>new Promise((r,n)=>{(0,Re.commitMutation)(e,{...t,onError:n,onCompleted:r})}),"commitMutation");0&&(module.exports={ClientMutationID,CreateRelayEnvironment,EnvironmentProvider,commitMutation,connectionDeleteEdgeUpdater,connectionUpdater,copyObjScalarsToProxy,isObject,listRecordAddUpdater,listRecordRemoveUpdater,optimisticConnectionUpdater,useEnvironment});
@@ -6,6 +6,16 @@
6
6
  * `CreateRelayEnvironment` — any change here is part of the package's
7
7
  * public API.
8
8
  */
9
+ import type { RecordSource } from 'relay-runtime';
10
+ /**
11
+ * Seed records for the Relay store, keyed by `DataID` — the exact shape a
12
+ * `RecordSource` is constructed from (also what `RecordSource.toJSON()`
13
+ * produces). Kept in lockstep with `relay-runtime` via
14
+ * `ConstructorParameters` so it never drifts from the runtime it seeds.
15
+ *
16
+ * @see {@link RelayArgsInterface.initialRecords}
17
+ */
18
+ export type RelayInitialRecords = NonNullable<ConstructorParameters<typeof RecordSource>[0]>;
9
19
  /**
10
20
  * Relay `Observable` sink. Implemented by the Relay runtime and
11
21
  * passed to the `Observable.create` callback. The fetch/subscription
@@ -231,4 +241,39 @@ export interface RelayArgsInterface {
231
241
  * @defaultValue `'doc_id'`
232
242
  */
233
243
  persistedOperationField?: string;
244
+ /**
245
+ * Records used to **seed the Relay store** at environment creation.
246
+ *
247
+ * This is the injection seam for app-owned state (app config, limits,
248
+ * route/session context, DS-prop drivers): write your own records here and
249
+ * read them back through the same fragment/hook machinery as server data —
250
+ * `useLazyLoadQuery` / `useFragment` over a **client schema extension**
251
+ * (client-only fields the consumer declares in their `relay.config.json`),
252
+ * or via a Relay Resolver reading the seeded record.
253
+ *
254
+ * The value is the exact shape `RecordSource` is constructed from (the same
255
+ * shape `RecordSource.toJSON()` emits), so a snapshot can be persisted and
256
+ * rehydrated. When omitted, the store starts empty — fully backward
257
+ * compatible.
258
+ *
259
+ * @example Seed a client-only field on Query (`ROOT_ID`)
260
+ * ```ts
261
+ * import { ROOT_ID, ROOT_TYPE } from 'relay-runtime';
262
+ *
263
+ * const { Environment } = new CreateRelayEnvironment({
264
+ * url: '...',
265
+ * initialRecords: {
266
+ * [ROOT_ID]: {
267
+ * __id: ROOT_ID,
268
+ * __typename: ROOT_TYPE,
269
+ * // read via a client schema extension: `extend type Query { appLocale: String }`
270
+ * appLocale: 'en-US',
271
+ * },
272
+ * },
273
+ * });
274
+ * ```
275
+ *
276
+ * @defaultValue undefined (empty store)
277
+ */
278
+ initialRecords?: RelayInitialRecords;
234
279
  }
@@ -1 +1 @@
1
- import{a}from"../chunks/chunk-KIA6YWO5.esm.js";import"../chunks/chunk-GZONWSRB.esm.js";export{a as CreateRelayEnvironment,a as default};
1
+ import{a}from"../chunks/chunk-CHTVEJCU.esm.js";import"../chunks/chunk-GZONWSRB.esm.js";export{a as CreateRelayEnvironment,a as default};
@@ -1,5 +1,5 @@
1
1
  import { Environment } from 'relay-runtime';
2
- import { RelayArgsInterface } from '../relayArgsInterface';
2
+ import { RelayArgsInterface, RelayInitialRecords } from '../relayArgsInterface';
3
3
  declare const kMountEnvironment: unique symbol;
4
4
  declare const kFeetchHandler: unique symbol;
5
5
  declare const kSubscriptionHandler: unique symbol;
@@ -129,6 +129,8 @@ export default class RelayEnvironment implements RelayArgsInterface {
129
129
  usePersistedQueries?: boolean;
130
130
  /** Request field carrying the persisted-operation hash. */
131
131
  persistedOperationField?: string;
132
+ /** Records used to seed the Relay store at creation (app-owned state). */
133
+ initialRecords?: RelayInitialRecords;
132
134
  /**
133
135
  * Fetch function assembled for use by Relay's `Network`. Internal.
134
136
  */
@@ -1 +1 @@
1
- import{a,b}from"../chunks/chunk-54QV6DFY.esm.js";import"../chunks/chunk-GZONWSRB.esm.js";export{a as EnvironmentProvider,b as useEnvironment};
1
+ import{a,b}from"../chunks/chunk-EATF764J.esm.js";import"../chunks/chunk-GZONWSRB.esm.js";export{a as EnvironmentProvider,b as useEnvironment};
@@ -15,12 +15,26 @@ type EnvironmentProviderInterface = {
15
15
  children: React.ReactNode;
16
16
  } & StateType;
17
17
  /**
18
- * Provider that injects the Relay `Environment` into the React tree via Context.
18
+ * Provider that injects the Relay `Environment` into the React tree.
19
+ *
20
+ * A single mount backs **both** hook systems over the same `Environment`:
21
+ * the DS `useEnvironment()` (imperative `fetchQuery` / `requestSubscription` /
22
+ * `commitMutation`) via `EnvironmentContext`, and every `react-relay` store
23
+ * hook (`useLazyLoadQuery` / `usePreloadedQuery` / `useFragment` /
24
+ * `useSubscription`) via the internally mounted `RelayEnvironmentProvider`.
25
+ * Consumers must never mount `react-relay`'s `RelayEnvironmentProvider`
26
+ * themselves — that wiring is a package detail owned by the DS, which is the
27
+ * seam where DS themes and Relay meet.
19
28
  *
20
29
  * In production, pass the `Environment` property exposed by
21
30
  * `CreateRelayEnvironment`. In tests, pass a `MockEnvironment` from
22
31
  * `relay-test-utils` to make swapping out the backend easier.
23
32
  *
33
+ * Mounting `RelayEnvironmentProvider` twice over the same `Environment`
34
+ * (e.g. a legacy consumer that still wraps its own) is idempotent — the
35
+ * nearest provider wins and it is the same instance — so this change is
36
+ * backward-compatible.
37
+ *
24
38
  * @example
25
39
  * ```tsx
26
40
  * import { CreateRelayEnvironment, EnvironmentProvider } from '@apollion-dsi/relay';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apollion-dsi/relay",
3
- "version": "0.28.0",
3
+ "version": "0.29.0",
4
4
  "description": "Frontend services regarding Relay Environment",
5
5
  "main": "lib/index.js",
6
6
  "module": "lib/index.esm.js",
@@ -1 +0,0 @@
1
- import{a as e}from"./chunk-GZONWSRB.esm.js";import r from"react";var t=r.createContext(void 0);function m({children:n,environment:o}){return r.createElement(t.Provider,{value:{environment:o}},n)}e(m,"EnvironmentProvider");function v(){let n=r.useContext(t);if(n===void 0)throw new Error("useEnvironment must be used within a EnvironmentProvider");if(n.environment===null||n.environment===void 0)throw new Error("You should provide a Relay Environment to EnvironmentProvider component");return n}e(v,"useEnvironment");export{m as a,v as b};