@clicktap/ui 0.34.1 → 0.35.2

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.
@@ -1 +1 @@
1
- "use client";import{jsxs as y,jsx as m}from"react/jsx-runtime";import{useState as L,useRef as P,useEffect as $,useCallback as g}from"react";import{Group as R,Label as T}from"react-aria-components";import{cn as d}from"../../utils/cn.js";function Z({autoFocus:A=!1,description:k,errorMessage:b,isDisabled:j=!1,isInvalid:w=!1,isMasked:I=!1,isRequired:N=!0,label:V,length:n=6,name:_,onChange:c,value:v="",type:h="numeric",validationBehavior:S,className:z,classNames:p,...B}){const[r,D]=L(()=>Array(n).fill("")),l=P([]);$(()=>{l.current=l.current.slice(0,n)},[n]),$(()=>{A&&l.current[0]?.focus()},[A]);const J=g(t=>{const e=t.target.value,u=Number(t.target.getAttribute("data-pin-input-index"));e!==""&&u<n-1&&l.current?.[u+1]?.focus();const o=r.map((s,f)=>f===u?e:s);D(o);const a=o.join("");c?.(a)},[r,n,c]),K=g(t=>{const e=Number(t.currentTarget.getAttribute("data-pin-input-index"));if(t.ctrlKey||t.metaKey)return;const u=["Backspace","Delete","ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Control","Alt","Meta","Shift","Tab","Enter","Escape"],o={alpha:/^[a-z]$/i,alphanumeric:/^[a-z0-9]$/i,numeric:/^[0-9]$/i};if(!t.key.match(o[h])&&!u.includes(t.key)&&t.preventDefault(),r[e]===""&&e>0&&t.key==="Backspace"){const a=r.map((f,x)=>x===e-1?"":f);D(a),l.current?.[e-1]?.focus(),t.preventDefault();const s=a.join("");c?.(s)}if(r[e]===""&&e<r.length-1&&t.key==="Delete"){const a=r.map((f,x)=>x===e+1?"":f);D(a),l.current?.[e+1]?.focus(),t.preventDefault();const s=a.join("");c?.(s)}},[r,h,c]),E=g(t=>{const e=Number(t.currentTarget.getAttribute("data-pin-input-index"));t.preventDefault();const u=t.clipboardData?.getData("text");if(!u)return;const o=u.split("").filter(i=>{switch(h){case"alpha":return/^[a-zA-Z]$/.test(i);case"alphanumeric":return/^[a-z0-9]$/i.test(i);default:return/^[0-9]$/.test(i)}});if(o.length===0)return;const a=[...r];let s=e;for(let i=0;i<o.length&&e+i<n;i++)a[e+i]=o[i],s=e+i;D(a);const f=a.join("");c?.(f);const x=s+1<n?s+1:n-1;l.current[x]?.focus()},[r,h,n,c]);return y(R,{className:d("flex flex-wrap gap-2",z),"aria-label":V,...B,children:[V&&m(T,{className:d("flex text-slate-500 text-sm grow shrink-0 basis-full",p?.label),children:V}),r.map((t,e)=>m("div",{className:d("flex flex-col w-full flex-1 text-slate-900",p?.inputWrap),children:m("input",{className:d("border-solid border border-slate-300 rounded-md","text-sm text-slate-900 placeholder-slate-400 text-center","h-10 px-2 py-0 m-0 w-full","bg-white","transition-all duration-200 ease-in-out","hover:border-slate-400","focus:outline-2 focus:outline focus:outline-slate-200 focus:border-slate-400","disabled:border-slate-200 disabled:bg-slate-100",w&&"border-red-500 bg-red-100 text-red-600",w&&"hover:border-red-600 focus:border-red-600 focus:outline-red-200",p?.input),onChange:J,onKeyDown:K,onPaste:E,type:I?"password":"text",autoComplete:"one-time-code",ref:u=>{l.current[e]=u},value:t,maxLength:1,"data-pin-input-index":e,disabled:j,required:N,"aria-label":`Pin Input Digit ${e+1}`})},`pin-input-${e}`)),(k||w&&b)&&y("div",{className:d("flex flex-row flex-wrap grow shrink-0 basis-full",p?.textWrap),children:[k&&m("p",{className:d("flex text-slate-500 text-sm grow shrink-0 basis-full",p?.description),children:k}),w&&b&&typeof b=="string"&&m("p",{className:d("flex text-red-500 text-sm grow shrink-0 basis-full",p?.error),children:b})]})]})}export{Z as PinInput,Z as default};
1
+ "use client";import{jsxs as y,jsx as m}from"react/jsx-runtime";import{useState as E,useRef as L,useEffect as $,useCallback as g}from"react";import{Group as P,Label as R}from"react-aria-components";import{cn as f}from"../../utils/cn.js";function Z({autoFocus:A=!1,description:k,errorMessage:b,isDisabled:j=!1,isInvalid:w=!1,isMasked:I=!1,isRequired:N=!0,label:V,length:n=6,name:T,onChange:c,value:_="",type:h="numeric",validationBehavior:S,className:z,classNames:p,...B}){const[r,D]=E(()=>Array(n).fill("")),l=L([]);$(()=>{l.current=l.current.slice(0,n)},[n]),$(()=>{A&&l.current[0]?.focus()},[A]);const J=g(t=>{const e=t.target.value,u=Number(t.target.getAttribute("data-pin-input-index"));e!==""&&u<n-1&&l.current?.[u+1]?.focus();const o=r.map((s,d)=>d===u?e:s);D(o);const a=o.join("");c?.(a)},[r,n,c]),K=g(t=>{const e=Number(t.currentTarget.getAttribute("data-pin-input-index"));if(t.ctrlKey||t.metaKey)return;const u=["Backspace","Delete","ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Control","Alt","Meta","Shift","Tab","Enter","Escape"],o={alpha:/^[a-z]$/i,alphanumeric:/^[a-z0-9]$/i,numeric:/^[0-9]$/i};if(!t.key.match(o[h])&&!u.includes(t.key)&&t.preventDefault(),r[e]===""&&e>0&&t.key==="Backspace"){const a=r.map((d,x)=>x===e-1?"":d);D(a),l.current?.[e-1]?.focus(),t.preventDefault();const s=a.join("");c?.(s)}if(r[e]===""&&e<r.length-1&&t.key==="Delete"){const a=r.map((d,x)=>x===e+1?"":d);D(a),l.current?.[e+1]?.focus(),t.preventDefault();const s=a.join("");c?.(s)}},[r,h,c]),v=g(t=>{const e=Number(t.currentTarget.getAttribute("data-pin-input-index"));t.preventDefault();const u=t.clipboardData?.getData("text");if(!u)return;const o=u.split("").filter(i=>{switch(h){case"alpha":return/^[a-zA-Z]$/.test(i);case"alphanumeric":return/^[a-z0-9]$/i.test(i);default:return/^[0-9]$/.test(i)}});if(o.length===0)return;const a=[...r];let s=e;for(let i=0;i<o.length&&e+i<n;i++)a[e+i]=o[i],s=e+i;D(a);const d=a.join("");c?.(d);const x=s+1<n?s+1:n-1;l.current[x]?.focus()},[r,h,n,c]);return y(P,{className:f("flex flex-wrap gap-2",z),"aria-label":V,...B,children:[V&&m(R,{className:f("flex text-slate-500 text-sm grow shrink-0 basis-full",p?.label),children:V}),r.map((t,e)=>m("div",{className:f("flex flex-col w-full flex-1 text-slate-900",p?.inputWrap),children:m("input",{className:f("border-solid border border-slate-300 rounded-md","text-sm text-slate-900 placeholder-slate-400 text-center","h-10 px-2 py-0 m-0 w-full","bg-white","[&::-ms-reveal]:hidden [&::-ms-clear]:hidden","transition-all duration-200 ease-in-out","hover:border-slate-400","focus:outline-2 focus:outline focus:outline-slate-200 focus:border-slate-400","disabled:border-slate-200 disabled:bg-slate-100",w&&"border-red-500 bg-red-100 text-red-600",w&&"hover:border-red-600 focus:border-red-600 focus:outline-red-200",p?.input),onChange:J,onKeyDown:K,onPaste:v,type:I?"password":"text",autoComplete:"one-time-code",ref:u=>{l.current[e]=u},value:t,maxLength:1,"data-pin-input-index":e,disabled:j,required:N,"aria-label":`Pin Input Digit ${e+1}`})},`pin-input-${e}`)),(k||w&&b)&&y("div",{className:f("flex flex-row flex-wrap grow shrink-0 basis-full",p?.textWrap),children:[k&&m("p",{className:f("flex text-slate-500 text-sm grow shrink-0 basis-full",p?.description),children:k}),w&&b&&typeof b=="string"&&m("p",{className:f("flex text-red-500 text-sm grow shrink-0 basis-full",p?.error),children:b})]})]})}export{Z as PinInput,Z as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clicktap/ui",
3
- "version": "0.34.1",
3
+ "version": "0.35.2",
4
4
  "private": false,
5
5
  "author": "Clicktap",
6
6
  "description": "A library of React UI components and low-level hooks.",
@@ -1,6 +1,7 @@
1
1
  import { ClientError, RequestDocument, Variables } from 'graphql-request';
2
2
  import { GraphQLClientRequestHeaders } from 'graphql-request/build/esm/types';
3
3
  import { TypedDocumentNode } from '@graphql-typed-document-node/core';
4
+ export { ClientError, GraphQLClient } from 'graphql-request';
4
5
  export type AuthAwareEventName = 'unauthenticated' | 'permissionDenied' | 'serverError';
5
6
  export interface AuthAwareEventDetail {
6
7
  status: number;
@@ -46,4 +47,3 @@ export declare function createAuthAwareGraphqlClient(): AuthAwareGraphqlClient;
46
47
  * toast actors.
47
48
  */
48
49
  export declare function createAuthAwareFetch(): typeof fetch;
49
- export {};
@@ -53,4 +53,4 @@ spurious results.`)}}return!1};class Be{constructor(t,n="GraphQL request",r={lin
53
53
  }`)}function E(e,t,n=""){return t!=null&&t!==""?e+t+n:""}function K(e){return E(" ",e.replace(/\n/g,`
54
54
  `))}function oe(e){var t;return(t=e?.some(n=>n.includes(`
55
55
  `)))!==null&&t!==void 0?t:!1}const Ie=e=>{let t;const n=e.definitions.filter(r=>r.kind==="OperationDefinition");return n.length===1&&(t=n[0]?.name?.value),t},ae=e=>{if(typeof e=="string"){let n;try{const r=gt(e);n=Ie(r)}catch{}return{query:e,operationName:n}}const t=Ie(e);return{query:Ft(e),operationName:t}};class B extends Error{constructor(t,n){const r=`${B.extractMessage(t)}: ${JSON.stringify({response:t,request:n})}`;super(r),Object.setPrototypeOf(this,B.prototype),this.response=t,this.request=n,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,B)}static extractMessage(t){return t.errors?.[0]?.message??`GraphQL Error (Code: ${t.status})`}}var X=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Mt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var W={exports:{}},Oe;function Ut(){return Oe||(Oe=1,(function(e,t){var n=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof X<"u"&&X,r=(function(){function s(){this.fetch=!1,this.DOMException=n.DOMException}return s.prototype=n,new s})();(function(s){(function(c){var u=typeof s<"u"&&s||typeof self<"u"&&self||typeof X<"u"&&X||{},h={searchParams:"URLSearchParams"in u,iterable:"Symbol"in u&&"iterator"in Symbol,blob:"FileReader"in u&&"Blob"in u&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in u,arrayBuffer:"ArrayBuffer"in u};function d(o){return o&&DataView.prototype.isPrototypeOf(o)}if(h.arrayBuffer)var y=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],v=ArrayBuffer.isView||function(o){return o&&y.indexOf(Object.prototype.toString.call(o))>-1};function m(o){if(typeof o!="string"&&(o=String(o)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(o)||o==="")throw new TypeError('Invalid character in header field name: "'+o+'"');return o.toLowerCase()}function O(o){return typeof o!="string"&&(o=String(o)),o}function x(o){var l={next:function(){var N=o.shift();return{done:N===void 0,value:N}}};return h.iterable&&(l[Symbol.iterator]=function(){return l}),l}function T(o){this.map={},o instanceof T?o.forEach(function(l,N){this.append(N,l)},this):Array.isArray(o)?o.forEach(function(l){if(l.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+l.length);this.append(l[0],l[1])},this):o&&Object.getOwnPropertyNames(o).forEach(function(l){this.append(l,o[l])},this)}T.prototype.append=function(o,l){o=m(o),l=O(l);var N=this.map[o];this.map[o]=N?N+", "+l:l},T.prototype.delete=function(o){delete this.map[m(o)]},T.prototype.get=function(o){return o=m(o),this.has(o)?this.map[o]:null},T.prototype.has=function(o){return this.map.hasOwnProperty(m(o))},T.prototype.set=function(o,l){this.map[m(o)]=O(l)},T.prototype.forEach=function(o,l){for(var N in this.map)this.map.hasOwnProperty(N)&&o.call(l,this.map[N],N,this)},T.prototype.keys=function(){var o=[];return this.forEach(function(l,N){o.push(N)}),x(o)},T.prototype.values=function(){var o=[];return this.forEach(function(l){o.push(l)}),x(o)},T.prototype.entries=function(){var o=[];return this.forEach(function(l,N){o.push([N,l])}),x(o)},h.iterable&&(T.prototype[Symbol.iterator]=T.prototype.entries);function C(o){if(!o._noBody){if(o.bodyUsed)return Promise.reject(new TypeError("Already read"));o.bodyUsed=!0}}function w(o){return new Promise(function(l,N){o.onload=function(){l(o.result)},o.onerror=function(){N(o.error)}})}function Y(o){var l=new FileReader,N=w(l);return l.readAsArrayBuffer(o),N}function k(o){var l=new FileReader,N=w(l),I=/charset=([A-Za-z0-9_-]+)/.exec(o.type),_=I?I[1]:"utf-8";return l.readAsText(o,_),N}function L(o){for(var l=new Uint8Array(o),N=new Array(l.length),I=0;I<l.length;I++)N[I]=String.fromCharCode(l[I]);return N.join("")}function U(o){if(o.slice)return o.slice(0);var l=new Uint8Array(o.byteLength);return l.set(new Uint8Array(o)),l.buffer}function $(){return this.bodyUsed=!1,this._initBody=function(o){this.bodyUsed=this.bodyUsed,this._bodyInit=o,o?typeof o=="string"?this._bodyText=o:h.blob&&Blob.prototype.isPrototypeOf(o)?this._bodyBlob=o:h.formData&&FormData.prototype.isPrototypeOf(o)?this._bodyFormData=o:h.searchParams&&URLSearchParams.prototype.isPrototypeOf(o)?this._bodyText=o.toString():h.arrayBuffer&&h.blob&&d(o)?(this._bodyArrayBuffer=U(o.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):h.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(o)||v(o))?this._bodyArrayBuffer=U(o):this._bodyText=o=Object.prototype.toString.call(o):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof o=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):h.searchParams&&URLSearchParams.prototype.isPrototypeOf(o)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},h.blob&&(this.blob=function(){var o=C(this);if(o)return o;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var o=C(this);return o||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(h.blob)return this.blob().then(Y);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var o=C(this);if(o)return o;if(this._bodyBlob)return k(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(L(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},h.formData&&(this.formData=function(){return this.text().then(qe)}),this.json=function(){return this.text().then(JSON.parse)},this}var z=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function Ve(o){var l=o.toUpperCase();return z.indexOf(l)>-1?l:o}function F(o,l){if(!(this instanceof F))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');l=l||{};var N=l.body;if(o instanceof F){if(o.bodyUsed)throw new TypeError("Already read");this.url=o.url,this.credentials=o.credentials,l.headers||(this.headers=new T(o.headers)),this.method=o.method,this.mode=o.mode,this.signal=o.signal,!N&&o._bodyInit!=null&&(N=o._bodyInit,o.bodyUsed=!0)}else this.url=String(o);if(this.credentials=l.credentials||this.credentials||"same-origin",(l.headers||!this.headers)&&(this.headers=new T(l.headers)),this.method=Ve(l.method||this.method||"GET"),this.mode=l.mode||this.mode||null,this.signal=l.signal||this.signal||(function(){if("AbortController"in u){var A=new AbortController;return A.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&N)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(N),(this.method==="GET"||this.method==="HEAD")&&(l.cache==="no-store"||l.cache==="no-cache")){var I=/([?&])_=[^&]*/;if(I.test(this.url))this.url=this.url.replace(I,"$1_="+new Date().getTime());else{var _=/\?/;this.url+=(_.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}F.prototype.clone=function(){return new F(this,{body:this._bodyInit})};function qe(o){var l=new FormData;return o.trim().split("&").forEach(function(N){if(N){var I=N.split("="),_=I.shift().replace(/\+/g," "),A=I.join("=").replace(/\+/g," ");l.append(decodeURIComponent(_),decodeURIComponent(A))}}),l}function je(o){var l=new T,N=o.replace(/\r?\n[\t ]+/g," ");return N.split("\r").map(function(I){return I.indexOf(`
56
- `)===0?I.substr(1,I.length):I}).forEach(function(I){var _=I.split(":"),A=_.shift().trim();if(A){var J=_.join(":").trim();try{l.append(A,J)}catch(re){console.warn("Response "+re.message)}}}),l}$.call(F.prototype);function S(o,l){if(!(this instanceof S))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(l||(l={}),this.type="default",this.status=l.status===void 0?200:l.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=l.statusText===void 0?"":""+l.statusText,this.headers=new T(l.headers),this.url=l.url||"",this._initBody(o)}$.call(S.prototype),S.prototype.clone=function(){return new S(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new T(this.headers),url:this.url})},S.error=function(){var o=new S(null,{status:200,statusText:""});return o.ok=!1,o.status=0,o.type="error",o};var $e=[301,302,303,307,308];S.redirect=function(o,l){if($e.indexOf(l)===-1)throw new RangeError("Invalid status code");return new S(null,{status:l,headers:{location:o}})},c.DOMException=u.DOMException;try{new c.DOMException}catch{c.DOMException=function(l,N){this.message=l,this.name=N;var I=Error(l);this.stack=I.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function ie(o,l){return new Promise(function(N,I){var _=new F(o,l);if(_.signal&&_.signal.aborted)return I(new c.DOMException("Aborted","AbortError"));var A=new XMLHttpRequest;function J(){A.abort()}A.onload=function(){var D={statusText:A.statusText,headers:je(A.getAllResponseHeaders()||"")};_.url.indexOf("file://")===0&&(A.status<200||A.status>599)?D.status=200:D.status=A.status,D.url="responseURL"in A?A.responseURL:D.headers.get("X-Request-URL");var P="response"in A?A.response:A.responseText;setTimeout(function(){N(new S(P,D))},0)},A.onerror=function(){setTimeout(function(){I(new TypeError("Network request failed"))},0)},A.ontimeout=function(){setTimeout(function(){I(new TypeError("Network request timed out"))},0)},A.onabort=function(){setTimeout(function(){I(new c.DOMException("Aborted","AbortError"))},0)};function re(D){try{return D===""&&u.location.href?u.location.href:D}catch{return D}}if(A.open(_.method,re(_.url),!0),_.credentials==="include"?A.withCredentials=!0:_.credentials==="omit"&&(A.withCredentials=!1),"responseType"in A&&(h.blob?A.responseType="blob":h.arrayBuffer&&(A.responseType="arraybuffer")),l&&typeof l.headers=="object"&&!(l.headers instanceof T||u.Headers&&l.headers instanceof u.Headers)){var Te=[];Object.getOwnPropertyNames(l.headers).forEach(function(D){Te.push(m(D)),A.setRequestHeader(D,O(l.headers[D]))}),_.headers.forEach(function(D,P){Te.indexOf(P)===-1&&A.setRequestHeader(P,D)})}else _.headers.forEach(function(D,P){A.setRequestHeader(P,D)});_.signal&&(_.signal.addEventListener("abort",J),A.onreadystatechange=function(){A.readyState===4&&_.signal.removeEventListener("abort",J)}),A.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return ie.polyfill=!0,u.fetch||(u.fetch=ie,u.Headers=T,u.Request=F,u.Response=S),c.Headers=T,c.Request=F,c.Response=S,c.fetch=ie,Object.defineProperty(c,"__esModule",{value:!0}),c})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=n.fetch?n:r;t=i.fetch,t.default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t})(W,W.exports)),W.exports}var de=Ut();const ee=Mt(de),Vt=Object.freeze(Object.defineProperty({__proto__:null,default:ee},Symbol.toStringTag,{value:"Module"})),V=e=>{let t={};return e&&(typeof Headers<"u"&&e instanceof Headers||Vt&&de.Headers&&e instanceof de.Headers?t=He(e):Array.isArray(e)?e.forEach(([n,r])=>{n&&r!==void 0&&(t[n]=r)}):t=e),t},_e=e=>e.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),qt=e=>{if(!Array.isArray(e.query)){const r=e,i=[`query=${encodeURIComponent(_e(r.query))}`];return e.variables&&i.push(`variables=${encodeURIComponent(r.jsonSerializer.stringify(r.variables))}`),r.operationName&&i.push(`operationName=${encodeURIComponent(r.operationName)}`),i.join("&")}if(typeof e.variables<"u"&&!Array.isArray(e.variables))throw new Error("Cannot create query with given variable type, array expected");const t=e,n=e.query.reduce((r,i,s)=>(r.push({query:_e(i),variables:t.variables?t.jsonSerializer.stringify(t.variables[s]):void 0}),r),[]);return`query=${encodeURIComponent(t.jsonSerializer.stringify(n))}`},jt=e=>async t=>{const{url:n,query:r,variables:i,operationName:s,fetch:c,fetchOptions:u,middleware:h}=t,d={...t.headers};let y="",v;e==="POST"?(v=$t(r,i,s,u.jsonSerializer),typeof v=="string"&&(d["Content-Type"]="application/json")):y=qt({query:r,variables:i,operationName:s,jsonSerializer:u.jsonSerializer??ye});const m={method:e,headers:d,body:v,...u};let O=n,x=m;if(h){const T=await Promise.resolve(h({...m,url:n,operationName:s,variables:i})),{url:C,...w}=T;O=C,x=w}return y&&(O=`${O}?${y}`),await c(O,x)};class ge{constructor(t,n={}){this.url=t,this.requestConfig=n,this.rawRequest=async(...r)=>{const[i,s,c]=r,u=ze(i,s,c),{headers:h,fetch:d=ee,method:y="POST",requestMiddleware:v,responseMiddleware:m,...O}=this.requestConfig,{url:x}=this;u.signal!==void 0&&(O.signal=u.signal);const{operationName:T}=ae(u.query);return ce({url:x,query:u.query,variables:u.variables,headers:{...V(ue(h)),...V(u.requestHeaders)},operationName:T,fetch:d,method:y,fetchOptions:O,middleware:v}).then(C=>(m&&m(C),C)).catch(C=>{throw m&&m(C),C})}}async request(t,...n){const[r,i]=n,s=Ye(t,r,i),{headers:c,fetch:u=ee,method:h="POST",requestMiddleware:d,responseMiddleware:y,...v}=this.requestConfig,{url:m}=this;s.signal!==void 0&&(v.signal=s.signal);const{query:O,operationName:x}=ae(s.document);return ce({url:m,query:O,variables:s.variables,headers:{...V(ue(c)),...V(s.requestHeaders)},operationName:x,fetch:u,method:h,fetchOptions:v,middleware:d}).then(T=>(y&&y(T),T.data)).catch(T=>{throw y&&y(T),T})}batchRequests(t,n){const r=Je(t,n),{headers:i,...s}=this.requestConfig;r.signal!==void 0&&(s.signal=r.signal);const c=r.documents.map(({document:h})=>ae(h).query),u=r.documents.map(({variables:h})=>h);return ce({url:this.url,query:c,variables:u,headers:{...V(ue(i)),...V(r.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??ee,method:this.requestConfig.method||"POST",fetchOptions:s,middleware:this.requestConfig.requestMiddleware}).then(h=>(this.requestConfig.responseMiddleware&&this.requestConfig.responseMiddleware(h),h.data)).catch(h=>{throw this.requestConfig.responseMiddleware&&this.requestConfig.responseMiddleware(h),h})}setHeaders(t){return this.requestConfig.headers=t,this}setHeader(t,n){const{headers:r}=this.requestConfig;return r?r[t]=n:this.requestConfig.headers={[t]:n},this}setEndpoint(t){return this.url=t,this}}const ce=async e=>{const{query:t,variables:n,fetchOptions:r}=e,i=jt(Ge(e.method??"post")),s=Array.isArray(e.query),c=await i(e),u=await Gt(c,r.jsonSerializer??ye),h=Array.isArray(u)?!u.some(({data:y})=>!y):!!u.data,d=Array.isArray(u)||!u.errors||Array.isArray(u.errors)&&!u.errors.length||r.errorPolicy==="all"||r.errorPolicy==="ignore";if(c.ok&&d&&h){const{errors:y,...v}=(Array.isArray(u),u),m=r.errorPolicy==="ignore"?v:u;return{...s?{data:m}:m,headers:c.headers,status:c.status}}else{const y=typeof u=="string"?{error:u}:u;throw new B({...y,status:c.status,headers:c.headers},{query:t,variables:n})}},$t=(e,t,n,r)=>{const i=r??ye;if(!Array.isArray(e))return i.stringify({query:e,variables:t,operationName:n});if(typeof t<"u"&&!Array.isArray(t))throw new Error("Cannot create request body with given variable type, array expected");const s=e.reduce((c,u,h)=>(c.push({query:u,variables:t?t[h]:void 0}),c),[]);return i.stringify(s)},Gt=async(e,t)=>{let n;return e.headers.forEach((r,i)=>{i.toLowerCase()==="content-type"&&(n=r)}),n&&(n.toLowerCase().startsWith("application/json")||n.toLowerCase().startsWith("application/graphql+json")||n.toLowerCase().startsWith("application/graphql-response+json"))?t.parse(await e.text()):e.text()},ue=e=>typeof e=="function"?e():e;class Ht{constructor(){this.listeners=new Map}subscribe(t,n){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n),()=>{this.listeners.get(t)?.delete(n)}}dispatch(t,n){this.listeners.get(t)?.forEach(r=>r(n))}}const le=new Ht;function Ue(e,t){e===401?le.dispatch("unauthenticated",t):e===403?le.dispatch("permissionDenied",t):e>=500&&le.dispatch("serverError",t)}function be(e){if(!(e instanceof B))return;const t=e.response?.status;typeof t=="number"&&Ue(t,{status:t,error:e})}function De(e){if(e instanceof B&&e.response?.data){const{data:t,errors:n}=e.response;if(t){if(process.env.NODE_ENV==="development"&&n?.length){const{query:r,variables:i}=e.request??{},s=r?.match(/^\s*(?:query|mutation|subscription)\s+([A-Za-z_][A-Za-z0-9_]*)/)?.[1];for(const c of n)console.error(`[GraphQL] ${s??"operation"} — field error at ${c.path?.join(".")??"unknown"}: ${c.message}`,{error:c,request:{operationName:s,variables:i,query:r}})}return t}}throw e}function Yt(){const e=async(r,i,s,c)=>{const u=new ge(r,{headers:c});try{return await u.request({document:i,variables:s})}catch(h){return be(h),De(h)}},t=async r=>{const i=new ge(r.url,{headers:r.requestHeaders,signal:r.signal});try{return await i.request({document:r.document,variables:r.variables})}catch(s){return be(s),De(s)}},n=e;return n.withOptions=t,n}function zt(){return async function(t,n){const r=await fetch(t,n);return(r.status===401||r.status===403||r.status>=500)&&Ue(r.status,{status:r.status,response:r.clone()}),r}}export{le as authAwareEvents,zt as createAuthAwareFetch,Yt as createAuthAwareGraphqlClient};
56
+ `)===0?I.substr(1,I.length):I}).forEach(function(I){var _=I.split(":"),A=_.shift().trim();if(A){var J=_.join(":").trim();try{l.append(A,J)}catch(re){console.warn("Response "+re.message)}}}),l}$.call(F.prototype);function S(o,l){if(!(this instanceof S))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(l||(l={}),this.type="default",this.status=l.status===void 0?200:l.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=l.statusText===void 0?"":""+l.statusText,this.headers=new T(l.headers),this.url=l.url||"",this._initBody(o)}$.call(S.prototype),S.prototype.clone=function(){return new S(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new T(this.headers),url:this.url})},S.error=function(){var o=new S(null,{status:200,statusText:""});return o.ok=!1,o.status=0,o.type="error",o};var $e=[301,302,303,307,308];S.redirect=function(o,l){if($e.indexOf(l)===-1)throw new RangeError("Invalid status code");return new S(null,{status:l,headers:{location:o}})},c.DOMException=u.DOMException;try{new c.DOMException}catch{c.DOMException=function(l,N){this.message=l,this.name=N;var I=Error(l);this.stack=I.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function ie(o,l){return new Promise(function(N,I){var _=new F(o,l);if(_.signal&&_.signal.aborted)return I(new c.DOMException("Aborted","AbortError"));var A=new XMLHttpRequest;function J(){A.abort()}A.onload=function(){var D={statusText:A.statusText,headers:je(A.getAllResponseHeaders()||"")};_.url.indexOf("file://")===0&&(A.status<200||A.status>599)?D.status=200:D.status=A.status,D.url="responseURL"in A?A.responseURL:D.headers.get("X-Request-URL");var P="response"in A?A.response:A.responseText;setTimeout(function(){N(new S(P,D))},0)},A.onerror=function(){setTimeout(function(){I(new TypeError("Network request failed"))},0)},A.ontimeout=function(){setTimeout(function(){I(new TypeError("Network request timed out"))},0)},A.onabort=function(){setTimeout(function(){I(new c.DOMException("Aborted","AbortError"))},0)};function re(D){try{return D===""&&u.location.href?u.location.href:D}catch{return D}}if(A.open(_.method,re(_.url),!0),_.credentials==="include"?A.withCredentials=!0:_.credentials==="omit"&&(A.withCredentials=!1),"responseType"in A&&(h.blob?A.responseType="blob":h.arrayBuffer&&(A.responseType="arraybuffer")),l&&typeof l.headers=="object"&&!(l.headers instanceof T||u.Headers&&l.headers instanceof u.Headers)){var Te=[];Object.getOwnPropertyNames(l.headers).forEach(function(D){Te.push(m(D)),A.setRequestHeader(D,O(l.headers[D]))}),_.headers.forEach(function(D,P){Te.indexOf(P)===-1&&A.setRequestHeader(P,D)})}else _.headers.forEach(function(D,P){A.setRequestHeader(P,D)});_.signal&&(_.signal.addEventListener("abort",J),A.onreadystatechange=function(){A.readyState===4&&_.signal.removeEventListener("abort",J)}),A.send(typeof _._bodyInit>"u"?null:_._bodyInit)})}return ie.polyfill=!0,u.fetch||(u.fetch=ie,u.Headers=T,u.Request=F,u.Response=S),c.Headers=T,c.Request=F,c.Response=S,c.fetch=ie,Object.defineProperty(c,"__esModule",{value:!0}),c})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=n.fetch?n:r;t=i.fetch,t.default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t})(W,W.exports)),W.exports}var de=Ut();const ee=Mt(de),Vt=Object.freeze(Object.defineProperty({__proto__:null,default:ee},Symbol.toStringTag,{value:"Module"})),V=e=>{let t={};return e&&(typeof Headers<"u"&&e instanceof Headers||Vt&&de.Headers&&e instanceof de.Headers?t=He(e):Array.isArray(e)?e.forEach(([n,r])=>{n&&r!==void 0&&(t[n]=r)}):t=e),t},_e=e=>e.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),qt=e=>{if(!Array.isArray(e.query)){const r=e,i=[`query=${encodeURIComponent(_e(r.query))}`];return e.variables&&i.push(`variables=${encodeURIComponent(r.jsonSerializer.stringify(r.variables))}`),r.operationName&&i.push(`operationName=${encodeURIComponent(r.operationName)}`),i.join("&")}if(typeof e.variables<"u"&&!Array.isArray(e.variables))throw new Error("Cannot create query with given variable type, array expected");const t=e,n=e.query.reduce((r,i,s)=>(r.push({query:_e(i),variables:t.variables?t.jsonSerializer.stringify(t.variables[s]):void 0}),r),[]);return`query=${encodeURIComponent(t.jsonSerializer.stringify(n))}`},jt=e=>async t=>{const{url:n,query:r,variables:i,operationName:s,fetch:c,fetchOptions:u,middleware:h}=t,d={...t.headers};let y="",v;e==="POST"?(v=$t(r,i,s,u.jsonSerializer),typeof v=="string"&&(d["Content-Type"]="application/json")):y=qt({query:r,variables:i,operationName:s,jsonSerializer:u.jsonSerializer??ye});const m={method:e,headers:d,body:v,...u};let O=n,x=m;if(h){const T=await Promise.resolve(h({...m,url:n,operationName:s,variables:i})),{url:C,...w}=T;O=C,x=w}return y&&(O=`${O}?${y}`),await c(O,x)};class ge{constructor(t,n={}){this.url=t,this.requestConfig=n,this.rawRequest=async(...r)=>{const[i,s,c]=r,u=ze(i,s,c),{headers:h,fetch:d=ee,method:y="POST",requestMiddleware:v,responseMiddleware:m,...O}=this.requestConfig,{url:x}=this;u.signal!==void 0&&(O.signal=u.signal);const{operationName:T}=ae(u.query);return ce({url:x,query:u.query,variables:u.variables,headers:{...V(ue(h)),...V(u.requestHeaders)},operationName:T,fetch:d,method:y,fetchOptions:O,middleware:v}).then(C=>(m&&m(C),C)).catch(C=>{throw m&&m(C),C})}}async request(t,...n){const[r,i]=n,s=Ye(t,r,i),{headers:c,fetch:u=ee,method:h="POST",requestMiddleware:d,responseMiddleware:y,...v}=this.requestConfig,{url:m}=this;s.signal!==void 0&&(v.signal=s.signal);const{query:O,operationName:x}=ae(s.document);return ce({url:m,query:O,variables:s.variables,headers:{...V(ue(c)),...V(s.requestHeaders)},operationName:x,fetch:u,method:h,fetchOptions:v,middleware:d}).then(T=>(y&&y(T),T.data)).catch(T=>{throw y&&y(T),T})}batchRequests(t,n){const r=Je(t,n),{headers:i,...s}=this.requestConfig;r.signal!==void 0&&(s.signal=r.signal);const c=r.documents.map(({document:h})=>ae(h).query),u=r.documents.map(({variables:h})=>h);return ce({url:this.url,query:c,variables:u,headers:{...V(ue(i)),...V(r.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??ee,method:this.requestConfig.method||"POST",fetchOptions:s,middleware:this.requestConfig.requestMiddleware}).then(h=>(this.requestConfig.responseMiddleware&&this.requestConfig.responseMiddleware(h),h.data)).catch(h=>{throw this.requestConfig.responseMiddleware&&this.requestConfig.responseMiddleware(h),h})}setHeaders(t){return this.requestConfig.headers=t,this}setHeader(t,n){const{headers:r}=this.requestConfig;return r?r[t]=n:this.requestConfig.headers={[t]:n},this}setEndpoint(t){return this.url=t,this}}const ce=async e=>{const{query:t,variables:n,fetchOptions:r}=e,i=jt(Ge(e.method??"post")),s=Array.isArray(e.query),c=await i(e),u=await Gt(c,r.jsonSerializer??ye),h=Array.isArray(u)?!u.some(({data:y})=>!y):!!u.data,d=Array.isArray(u)||!u.errors||Array.isArray(u.errors)&&!u.errors.length||r.errorPolicy==="all"||r.errorPolicy==="ignore";if(c.ok&&d&&h){const{errors:y,...v}=(Array.isArray(u),u),m=r.errorPolicy==="ignore"?v:u;return{...s?{data:m}:m,headers:c.headers,status:c.status}}else{const y=typeof u=="string"?{error:u}:u;throw new B({...y,status:c.status,headers:c.headers},{query:t,variables:n})}},$t=(e,t,n,r)=>{const i=r??ye;if(!Array.isArray(e))return i.stringify({query:e,variables:t,operationName:n});if(typeof t<"u"&&!Array.isArray(t))throw new Error("Cannot create request body with given variable type, array expected");const s=e.reduce((c,u,h)=>(c.push({query:u,variables:t?t[h]:void 0}),c),[]);return i.stringify(s)},Gt=async(e,t)=>{let n;return e.headers.forEach((r,i)=>{i.toLowerCase()==="content-type"&&(n=r)}),n&&(n.toLowerCase().startsWith("application/json")||n.toLowerCase().startsWith("application/graphql+json")||n.toLowerCase().startsWith("application/graphql-response+json"))?t.parse(await e.text()):e.text()},ue=e=>typeof e=="function"?e():e;class Ht{constructor(){this.listeners=new Map}subscribe(t,n){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n),()=>{this.listeners.get(t)?.delete(n)}}dispatch(t,n){this.listeners.get(t)?.forEach(r=>r(n))}}const le=new Ht;function Ue(e,t){e===401?le.dispatch("unauthenticated",t):e===403?le.dispatch("permissionDenied",t):e>=500&&le.dispatch("serverError",t)}function be(e){if(!(e instanceof B))return;const t=e.response?.status;typeof t=="number"&&Ue(t,{status:t,error:e})}function De(e){if(e instanceof B&&e.response?.data){const{data:t,errors:n}=e.response;if(t){if(process.env.NODE_ENV==="development"&&n?.length){const{query:r,variables:i}=e.request??{},s=r?.match(/^\s*(?:query|mutation|subscription)\s+([A-Za-z_][A-Za-z0-9_]*)/)?.[1];for(const c of n)console.error(`[GraphQL] ${s??"operation"} — field error at ${c.path?.join(".")??"unknown"}: ${c.message}`,{error:c,request:{operationName:s,variables:i,query:r}})}return t}}throw e}function Yt(){const e=async(r,i,s,c)=>{const u=new ge(r,{headers:c});try{return await u.request({document:i,variables:s})}catch(h){return be(h),De(h)}},t=async r=>{const i=new ge(r.url,{headers:r.requestHeaders,signal:r.signal});try{return await i.request({document:r.document,variables:r.variables})}catch(s){return be(s),De(s)}},n=e;return n.withOptions=t,n}function zt(){return async function(t,n){const r=await fetch(t,n);return(r.status===401||r.status===403||r.status>=500)&&Ue(r.status,{status:r.status,response:r.clone()}),r}}export{B as ClientError,ge as GraphQLClient,le as authAwareEvents,zt as createAuthAwareFetch,Yt as createAuthAwareGraphqlClient};
package/utils/error.d.ts CHANGED
@@ -1,3 +1,18 @@
1
+ /**
2
+ * Structurally extract the HTTP status from a `graphql-request` `ClientError`
3
+ * (or any error carrying `response.status`) — without an `instanceof` check.
4
+ *
5
+ * `graphql-request` is bundled per consuming package, so an
6
+ * `error instanceof ClientError` using a consumer's *own* copy of the class
7
+ * fails for an error thrown by `@clicktap/ui`'s bundled copy (the dual-package
8
+ * hazard) — the redirect / logout path then silently never fires. Duck-typing
9
+ * `response.status` is identity-agnostic and works regardless of which copy
10
+ * threw, so prefer this at cross-package boundaries (SSR route/data fetches,
11
+ * actor error handlers) over `instanceof`.
12
+ *
13
+ * Returns `undefined` when no numeric status is present.
14
+ */
15
+ export declare function getRequestErrorStatus(error: unknown): number | undefined;
1
16
  /**
2
17
  * Returns a safe, user-facing error message.
3
18
  *
package/utils/error.js CHANGED
@@ -1 +1 @@
1
- import{isDevelopment as o}from"./env.js";const n="Something went wrong. Please try again later.";function i(e,s=n){if(o){const t=e!=null&&typeof e=="object"&&"response"in e&&typeof e.response=="object"?e.response?.status:void 0;console.error("[Request Error]",...t?[t]:[],e)}return s}export{i as default,i as getSafeErrorMessage};
1
+ import{isDevelopment as n}from"./env.js";const o="Something went wrong. Please try again later.";function r(t){if(t==null||typeof t!="object"||!("response"in t))return;const e=t.response;if(e==null||typeof e!="object"||!("status"in e))return;const s=e.status;return typeof s=="number"?s:void 0}function i(t,e=o){if(n){const s=r(t);console.error("[Request Error]",...s?[s]:[],t)}return e}export{i as default,r as getRequestErrorStatus,i as getSafeErrorMessage};
@@ -1,13 +0,0 @@
1
- import { ReactNode } from 'react';
2
- import { Meta, StoryObj } from '@storybook/react';
3
- import { Avatar } from './Avatar';
4
- import { AvatarGroup } from './AvatarGroup/AvatarGroup';
5
- declare function Layout({ children }: {
6
- children: ReactNode;
7
- }): ReactNode;
8
- type Story = StoryObj<typeof Avatar>;
9
- type StoryGroup = StoryObj<typeof AvatarGroup>;
10
- declare const meta: Meta<typeof Layout>;
11
- export default meta;
12
- export declare const AvatarComponent: Story;
13
- export declare const AvatarGroupComponent: StoryGroup;
@@ -1,8 +0,0 @@
1
- import { Meta, StoryObj } from '@storybook/react';
2
- import { Badge } from './Badge';
3
- import { BadgeProps } from './Badge.types';
4
- type Story = StoryObj<typeof Badge>;
5
- declare function Component(props: BadgeProps): import("react/jsx-runtime").JSX.Element;
6
- declare const meta: Meta<typeof Component>;
7
- export default meta;
8
- export declare const Example: Story;
@@ -1,6 +0,0 @@
1
- import { Meta, StoryObj } from '@storybook/react';
2
- import { Divider } from './Divider';
3
- type Story = StoryObj<typeof Divider>;
4
- declare const meta: Meta<typeof Divider>;
5
- export default meta;
6
- export declare const Example: Story;
@@ -1,6 +0,0 @@
1
- import { Meta, StoryObj } from '@storybook/react';
2
- import { Link } from './Link';
3
- type Story = StoryObj<typeof Link>;
4
- declare const meta: Meta<typeof Link>;
5
- export default meta;
6
- export declare const Example: Story;
@@ -1,6 +0,0 @@
1
- import { Meta, StoryObj } from '@storybook/react';
2
- import { Meter } from './Meter';
3
- type Story = StoryObj<typeof Meter>;
4
- declare const meta: Meta<typeof Meter>;
5
- export default meta;
6
- export declare const Base: Story;
@@ -1,20 +0,0 @@
1
- import { Meta, StoryObj } from '@storybook/react';
2
- import { Time } from './Time';
3
- type Story = StoryObj<typeof Time>;
4
- /**
5
- * `<Time>` reads the configured ("server") timezone and the viewer's ("local")
6
- * timezone from `TimezoneProvider`. In the app the provider is fed by the
7
- * server-resolved `displayTimezone` (server) and the viewer's cookie (local).
8
- */
9
- declare const meta: Meta<typeof Time>;
10
- export default meta;
11
- /** Interactive playground — toggle `local`/`showZone` and the Intl format options. */
12
- export declare const Example: Story;
13
- /** Default: renders in the configured ("server") timezone — the hydration- & index-safe baseline. */
14
- export declare const ServerTime: Story;
15
- /** Opt-in: renders in the viewer's ("client") timezone via the `local` prop. */
16
- export declare const LocalTime: Story;
17
- /** Same instant, both modes side by side — the configured zone vs. the viewer's zone. */
18
- export declare const ServerVsLocal: Story;
19
- /** Invalid/empty input renders the `fallback` (default `-`). */
20
- export declare const Fallback: Story;
@@ -1,6 +0,0 @@
1
- import { Meta, StoryObj } from '@storybook/react';
2
- import { TimeInput } from './TimeInput';
3
- type Story = StoryObj<typeof TimeInput>;
4
- declare const meta: Meta<typeof TimeInput>;
5
- export default meta;
6
- export declare const Base: Story;
@@ -1,6 +0,0 @@
1
- import { Meta, StoryObj } from '@storybook/react';
2
- import { ToggleButton } from './ToggleButton';
3
- type Story = StoryObj<typeof ToggleButton>;
4
- declare const meta: Meta<typeof ToggleButton>;
5
- export default meta;
6
- export declare const Example: Story;