tempest-react-sdk 0.51.0 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/auth/refresh-queue.cjs +1 -1
  2. package/dist/auth/refresh-queue.cjs.map +1 -1
  3. package/dist/auth/refresh-queue.js +6 -6
  4. package/dist/auth/refresh-queue.js.map +1 -1
  5. package/dist/components/Scheduler/Scheduler.cjs +1 -1
  6. package/dist/components/Scheduler/Scheduler.cjs.map +1 -1
  7. package/dist/components/Scheduler/Scheduler.js +1 -1
  8. package/dist/components/Scheduler/Scheduler.js.map +1 -1
  9. package/dist/components/Scheduler/Scheduler.module.cjs.map +1 -1
  10. package/dist/components/Scheduler/Scheduler.module.js.map +1 -1
  11. package/dist/http/describe-api-error.cjs +1 -1
  12. package/dist/http/describe-api-error.cjs.map +1 -1
  13. package/dist/http/describe-api-error.js +4 -2
  14. package/dist/http/describe-api-error.js.map +1 -1
  15. package/dist/http/use-describe-api-error.cjs +1 -1
  16. package/dist/http/use-describe-api-error.cjs.map +1 -1
  17. package/dist/http/use-describe-api-error.js +3 -2
  18. package/dist/http/use-describe-api-error.js.map +1 -1
  19. package/dist/offline/create-offline-database.cjs +2 -0
  20. package/dist/offline/create-offline-database.cjs.map +1 -0
  21. package/dist/offline/create-offline-database.js +29 -0
  22. package/dist/offline/create-offline-database.js.map +1 -0
  23. package/dist/offline/create-offline-store.cjs +1 -1
  24. package/dist/offline/create-offline-store.cjs.map +1 -1
  25. package/dist/offline/create-offline-store.js +29 -25
  26. package/dist/offline/create-offline-store.js.map +1 -1
  27. package/dist/tempest-react-sdk.cjs +1 -1
  28. package/dist/tempest-react-sdk.d.ts +218 -7
  29. package/dist/tempest-react-sdk.js +43 -42
  30. package/dist/utils/format.cjs +1 -1
  31. package/dist/utils/format.cjs.map +1 -1
  32. package/dist/utils/format.js +8 -3
  33. package/dist/utils/format.js.map +1 -1
  34. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- function e(e){let t=null;return()=>t||(t=(async()=>{try{await e()}finally{t=null}})(),t)}exports.createRefreshQueue=e;
1
+ function e(e,t={}){let{getToken:n}=t,r=null,i=null;return()=>r||(n&&i!==null&&n()===i?Promise.resolve():(r=(async()=>{try{await e(),n&&(i=n()??null)}finally{r=null}})(),r))}exports.createRefreshQueue=e;
2
2
  //# sourceMappingURL=refresh-queue.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"refresh-queue.cjs","names":[],"sources":["../../src/auth/refresh-queue.ts"],"sourcesContent":["/**\n * Deduplicate concurrent refresh calls. When multiple 401 responses arrive\n * at once, all of them share the same in-flight `refresh()` promise instead\n * of triggering N parallel refreshes.\n *\n * @example\n * const refresh = createRefreshQueue(() => AuthService.refresh());\n *\n * // In every request that hits 401:\n * await refresh();\n * // ...retry the original request\n */\nexport function createRefreshQueue(refresh: () => Promise<void>): () => Promise<void> {\n let current: Promise<void> | null = null;\n\n return () => {\n if (current) return current;\n current = (async () => {\n try {\n await refresh();\n } finally {\n current = null;\n }\n })();\n return current;\n };\n}\n"],"mappings":"AAYA,SAAgB,EAAmB,EAAmD,CAClF,IAAI,EAAgC,KAEpC,UACQ,IACJ,GAAW,SAAY,CACnB,GAAI,CACA,MAAM,EAAQ,CAClB,QAAU,CACN,EAAU,IACd,CACJ,EAAA,CAAG,EACI,EAEf"}
1
+ {"version":3,"file":"refresh-queue.cjs","names":[],"sources":["../../src/auth/refresh-queue.ts"],"sourcesContent":["export interface CreateRefreshQueueOptions {\n /**\n * Reads the credential the refresh installs — typically the access token.\n *\n * Supplying it makes the queue skip a refresh whose work another caller has\n * already done. Without it, only calls that literally overlap in time are\n * collapsed.\n */\n getToken?: () => string | null | undefined;\n}\n\n/**\n * Deduplicate concurrent refresh calls. When multiple 401 responses arrive\n * at once, all of them share the same in-flight `refresh()` promise instead\n * of triggering N parallel refreshes.\n *\n * **In-flight sharing alone does not collapse a burst.** A page that fires\n * several requests at once gets several 401s back, but they do not land inside\n * one window: the stragglers arrive after the first refresh already resolved,\n * find no promise to join, and each starts another one — rotating a token that\n * is already fresh. Measured against a mock backend, five concurrent expired\n * requests took two refreshes, not one.\n *\n * Pass `getToken` to close that gap. The queue remembers the token its last\n * refresh produced, and a call that finds that same token still in place returns\n * immediately, because the refresh it was about to perform has already happened.\n * The same five requests then take exactly one refresh, and so do twenty.\n *\n * @param refresh - Performs the refresh and installs the new credentials.\n * @param options - Optional token reader that enables already-refreshed\n * detection.\n * @returns A function that refreshes at most once per rotation.\n *\n * @example\n * const refresh = createRefreshQueue(() => AuthService.refresh(), {\n * getToken: () => useAuthStore.getState().token,\n * });\n *\n * // In every request that hits 401:\n * await refresh();\n * // ...retry the original request\n */\nexport function createRefreshQueue(\n refresh: () => Promise<void>,\n options: CreateRefreshQueueOptions = {},\n): () => Promise<void> {\n const { getToken } = options;\n let current: Promise<void> | null = null;\n let lastIssued: string | null = null;\n\n return () => {\n if (current) return current;\n\n if (getToken && lastIssued !== null && getToken() === lastIssued) {\n return Promise.resolve();\n }\n\n current = (async () => {\n try {\n await refresh();\n if (getToken) lastIssued = getToken() ?? null;\n } finally {\n current = null;\n }\n })();\n return current;\n };\n}\n"],"mappings":"AA0CA,SAAgB,EACZ,EACA,EAAqC,CAAC,EACnB,CACnB,GAAM,CAAE,YAAa,EACjB,EAAgC,KAChC,EAA4B,KAEhC,UACQ,IAEA,GAAY,IAAe,MAAQ,EAAS,IAAM,EAC3C,QAAQ,QAAQ,GAG3B,GAAW,SAAY,CACnB,GAAI,CACA,MAAM,EAAQ,EACV,IAAU,EAAa,EAAS,GAAK,KAC7C,QAAU,CACN,EAAU,IACd,CACJ,EAAA,CAAG,EACI,GAEf"}
@@ -1,13 +1,13 @@
1
1
  //#region src/auth/refresh-queue.ts
2
- function e(e) {
3
- let t = null;
4
- return () => t || (t = (async () => {
2
+ function e(e, t = {}) {
3
+ let { getToken: n } = t, r = null, i = null;
4
+ return () => r || (n && i !== null && n() === i ? Promise.resolve() : (r = (async () => {
5
5
  try {
6
- await e();
6
+ await e(), n && (i = n() ?? null);
7
7
  } finally {
8
- t = null;
8
+ r = null;
9
9
  }
10
- })(), t);
10
+ })(), r));
11
11
  }
12
12
  //#endregion
13
13
  export { e as createRefreshQueue };
@@ -1 +1 @@
1
- {"version":3,"file":"refresh-queue.js","names":[],"sources":["../../src/auth/refresh-queue.ts"],"sourcesContent":["/**\n * Deduplicate concurrent refresh calls. When multiple 401 responses arrive\n * at once, all of them share the same in-flight `refresh()` promise instead\n * of triggering N parallel refreshes.\n *\n * @example\n * const refresh = createRefreshQueue(() => AuthService.refresh());\n *\n * // In every request that hits 401:\n * await refresh();\n * // ...retry the original request\n */\nexport function createRefreshQueue(refresh: () => Promise<void>): () => Promise<void> {\n let current: Promise<void> | null = null;\n\n return () => {\n if (current) return current;\n current = (async () => {\n try {\n await refresh();\n } finally {\n current = null;\n }\n })();\n return current;\n };\n}\n"],"mappings":";AAYA,SAAgB,EAAmB,GAAmD;CAClF,IAAI,IAAgC;CAEpC,aACQ,MACJ,KAAW,YAAY;EACnB,IAAI;GACA,MAAM,EAAQ;EAClB,UAAU;GACN,IAAU;EACd;CACJ,EAAA,CAAG,GACI;AAEf"}
1
+ {"version":3,"file":"refresh-queue.js","names":[],"sources":["../../src/auth/refresh-queue.ts"],"sourcesContent":["export interface CreateRefreshQueueOptions {\n /**\n * Reads the credential the refresh installs — typically the access token.\n *\n * Supplying it makes the queue skip a refresh whose work another caller has\n * already done. Without it, only calls that literally overlap in time are\n * collapsed.\n */\n getToken?: () => string | null | undefined;\n}\n\n/**\n * Deduplicate concurrent refresh calls. When multiple 401 responses arrive\n * at once, all of them share the same in-flight `refresh()` promise instead\n * of triggering N parallel refreshes.\n *\n * **In-flight sharing alone does not collapse a burst.** A page that fires\n * several requests at once gets several 401s back, but they do not land inside\n * one window: the stragglers arrive after the first refresh already resolved,\n * find no promise to join, and each starts another one — rotating a token that\n * is already fresh. Measured against a mock backend, five concurrent expired\n * requests took two refreshes, not one.\n *\n * Pass `getToken` to close that gap. The queue remembers the token its last\n * refresh produced, and a call that finds that same token still in place returns\n * immediately, because the refresh it was about to perform has already happened.\n * The same five requests then take exactly one refresh, and so do twenty.\n *\n * @param refresh - Performs the refresh and installs the new credentials.\n * @param options - Optional token reader that enables already-refreshed\n * detection.\n * @returns A function that refreshes at most once per rotation.\n *\n * @example\n * const refresh = createRefreshQueue(() => AuthService.refresh(), {\n * getToken: () => useAuthStore.getState().token,\n * });\n *\n * // In every request that hits 401:\n * await refresh();\n * // ...retry the original request\n */\nexport function createRefreshQueue(\n refresh: () => Promise<void>,\n options: CreateRefreshQueueOptions = {},\n): () => Promise<void> {\n const { getToken } = options;\n let current: Promise<void> | null = null;\n let lastIssued: string | null = null;\n\n return () => {\n if (current) return current;\n\n if (getToken && lastIssued !== null && getToken() === lastIssued) {\n return Promise.resolve();\n }\n\n current = (async () => {\n try {\n await refresh();\n if (getToken) lastIssued = getToken() ?? null;\n } finally {\n current = null;\n }\n })();\n return current;\n };\n}\n"],"mappings":";AA0CA,SAAgB,EACZ,GACA,IAAqC,CAAC,GACnB;CACnB,IAAM,EAAE,gBAAa,GACjB,IAAgC,MAChC,IAA4B;CAEhC,aACQ,MAEA,KAAY,MAAe,QAAQ,EAAS,MAAM,IAC3C,QAAQ,QAAQ,KAG3B,KAAW,YAAY;EACnB,IAAI;GAEA,AADA,MAAM,EAAQ,GACV,MAAU,IAAa,EAAS,KAAK;EAC7C,UAAU;GACN,IAAU;EACd;CACJ,EAAA,CAAG,GACI;AAEf"}
@@ -1,2 +1,2 @@
1
- const e=require("../../utils/cn.cjs"),t=require("./scheduler-layout.cjs"),n=require("./Scheduler.module.cjs");let r=require("react"),i=require("react/jsx-runtime");var a=6e4;function o({events:o,anchor:s,days:c=7,startHour:l=8,endHour:u=20,snapMinutes:d=30,onEventClick:f,onSlotClick:p,renderEvent:m,locale:h=`pt-BR`,showCurrentTime:g=!0,now:_,className:v,...y}){let[b,x]=(0,r.useState)(()=>_??new Date);(0,r.useEffect)(()=>{if(_||!g)return;let e=setInterval(()=>x(new Date),a);return()=>clearInterval(e)},[_,g]);let S=_??b,C=(0,r.useMemo)(()=>({startMinute:l*60,endMinute:u*60}),[l,u]),w=(s??S).toDateString(),T=(0,r.useMemo)(()=>t.dayRange(new Date(w),c),[w,c]),E=(0,r.useMemo)(()=>t.layoutEvents({events:o,days:T,window:C}),[o,T,C]),D=(0,r.useMemo)(()=>t.layoutAllDay({events:o,days:T}),[o,T]),O=(0,r.useMemo)(()=>t.hourMarks(C),[C]),k=new Intl.DateTimeFormat(h,{weekday:`short`,day:`numeric`}),A=new Intl.DateTimeFormat(h,{hour:`2-digit`,minute:`2-digit`}),j=(e,t)=>{let n=t.currentTarget.getBoundingClientRect(),r=n.height>0?(t.clientY-n.top)/n.height:0,i=C.startMinute+r*(C.endMinute-C.startMinute),a=Math.round(i/d)*d,o=Math.max(C.startMinute,Math.min(C.endMinute,a)),s=new Date(e);return s.setHours(0,o,0,0),s},M=g?t.fractionOfWindow(S,C):null,N=T.findIndex(e=>t.isSameDay(e,S));return(0,i.jsxs)(`div`,{className:e.cn(n.default.wrapper,v),...y,children:[(0,i.jsxs)(`div`,{className:n.default.head,style:{"--tempest-scheduler-days":c},children:[(0,i.jsx)(`span`,{className:n.default.gutterHead}),T.map((t,r)=>(0,i.jsx)(`span`,{className:e.cn(n.default.dayHead,r===N&&n.default.today),children:k.format(t)},t.toISOString()))]}),D.length>0&&(0,i.jsxs)(`div`,{className:n.default.allDayLane,style:{"--tempest-scheduler-days":c},children:[(0,i.jsx)(`span`,{className:n.default.gutterHead,children:`Dia inteiro`}),(0,i.jsx)(`div`,{className:n.default.allDayTrack,children:D.map(({event:e,dayIndex:t,span:r})=>(0,i.jsx)(`button`,{type:`button`,className:n.default.allDayEvent,style:{gridColumn:`${t+1} / span ${r}`},onClick:()=>f?.(e),disabled:!f,children:e.title},e.id))})]}),(0,i.jsxs)(`div`,{className:n.default.body,style:{"--tempest-scheduler-days":c},tabIndex:0,role:`group`,"aria-label":`Grade de horários`,children:[(0,i.jsx)(`div`,{className:n.default.gutter,children:O.map(e=>(0,i.jsx)(`span`,{className:n.default.hourLabel,style:{top:`${(e-C.startMinute)/(C.endMinute-C.startMinute)*100}%`},children:A.format(new Date(2026,0,1,Math.floor(e/60),e%60))},e))}),(0,i.jsxs)(`div`,{className:n.default.grid,"aria-label":`Agenda`,children:[T.map((t,r)=>(0,i.jsx)(`div`,{className:e.cn(n.default.dayColumn,r===N&&n.default.todayColumn),role:`group`,"aria-label":k.format(t),onClick:p?e=>{e.target===e.currentTarget&&p(j(t,e))}:void 0,children:O.map(e=>(0,i.jsx)(`span`,{className:n.default.hourLine,style:{top:`${(e-C.startMinute)/(C.endMinute-C.startMinute)*100}%`}},e))},t.toISOString())),E.map(e=>(0,i.jsx)(`button`,{type:`button`,className:n.default.event,style:{gridColumn:e.dayIndex+1,top:`${e.top*100}%`,height:`${e.height*100}%`,left:`${e.column/e.columns*100}%`,width:`${1/e.columns*100}%`},onClick:()=>f?.(e.event),disabled:!f,title:`${e.event.title} — ${A.format(e.event.start)}`,children:m?m(e.event):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(`span`,{className:n.default.eventTime,children:A.format(e.event.start)}),(0,i.jsx)(`span`,{className:n.default.eventTitle,children:e.event.title})]})},`${e.event.id}-${e.dayIndex}`)),M!==null&&N>=0&&(0,i.jsx)(`span`,{className:n.default.nowLine,style:{top:`${M*100}%`},"aria-hidden":!0,"data-testid":`scheduler-now`})]})]})]})}exports.Scheduler=o;
1
+ const e=require("../../utils/cn.cjs"),t=require("./scheduler-layout.cjs"),n=require("./Scheduler.module.cjs");let r=require("react"),i=require("react/jsx-runtime");var a=6e4;function o({events:o,anchor:s,days:c=7,startHour:l=8,endHour:u=20,snapMinutes:d=30,onEventClick:f,onSlotClick:p,renderEvent:m,locale:h=`pt-BR`,showCurrentTime:g=!0,now:_,className:v,...y}){let[b,x]=(0,r.useState)(()=>_??new Date);(0,r.useEffect)(()=>{if(_||!g)return;let e=setInterval(()=>x(new Date),a);return()=>clearInterval(e)},[_,g]);let S=_??b,C=(0,r.useMemo)(()=>({startMinute:l*60,endMinute:u*60}),[l,u]),w=(s??S).toDateString(),T=(0,r.useMemo)(()=>t.dayRange(new Date(w),c),[w,c]),E=(0,r.useMemo)(()=>t.layoutEvents({events:o,days:T,window:C}),[o,T,C]),D=(0,r.useMemo)(()=>t.layoutAllDay({events:o,days:T}),[o,T]),O=(0,r.useMemo)(()=>t.hourMarks(C),[C]),k=new Intl.DateTimeFormat(h,{weekday:`short`,day:`numeric`}),A=new Intl.DateTimeFormat(h,{hour:`2-digit`,minute:`2-digit`}),j=(e,t)=>{let n=t.currentTarget.getBoundingClientRect(),r=n.height>0?(t.clientY-n.top)/n.height:0,i=C.startMinute+r*(C.endMinute-C.startMinute),a=Math.round(i/d)*d,o=Math.max(C.startMinute,Math.min(C.endMinute,a)),s=new Date(e);return s.setHours(0,o,0,0),s},M=g?t.fractionOfWindow(S,C):null,N=T.findIndex(e=>t.isSameDay(e,S));return(0,i.jsxs)(`div`,{className:e.cn(n.default.wrapper,v),...y,children:[(0,i.jsxs)(`div`,{className:n.default.head,style:{"--tempest-scheduler-days":c},children:[(0,i.jsx)(`span`,{className:n.default.gutterHead}),T.map((t,r)=>(0,i.jsx)(`span`,{className:e.cn(n.default.dayHead,r===N&&n.default.today),children:k.format(t)},t.toISOString()))]}),D.length>0&&(0,i.jsxs)(`div`,{className:n.default.allDayLane,style:{"--tempest-scheduler-days":c},children:[(0,i.jsx)(`span`,{className:n.default.gutterHead,children:`Dia inteiro`}),(0,i.jsx)(`div`,{className:n.default.allDayTrack,children:D.map(({event:e,dayIndex:t,span:r})=>(0,i.jsx)(`button`,{type:`button`,className:n.default.allDayEvent,style:{gridColumn:`${t+1} / span ${r}`},onClick:()=>f?.(e),disabled:!f,children:e.title},e.id))})]}),(0,i.jsxs)(`div`,{className:n.default.body,style:{"--tempest-scheduler-days":c},tabIndex:0,role:`group`,"aria-label":`Grade de horários`,children:[(0,i.jsx)(`div`,{className:n.default.gutter,children:O.map(e=>(0,i.jsx)(`span`,{className:n.default.hourLabel,style:{top:`${(e-C.startMinute)/(C.endMinute-C.startMinute)*100}%`},children:A.format(new Date(2026,0,1,Math.floor(e/60),e%60))},e))}),(0,i.jsxs)(`div`,{className:n.default.grid,"aria-label":`Agenda`,children:[T.map((t,r)=>(0,i.jsx)(`div`,{className:e.cn(n.default.dayColumn,r===N&&n.default.todayColumn),role:`group`,"aria-label":k.format(t),onClick:p?e=>{e.target===e.currentTarget&&p(j(t,e))}:void 0,children:O.map(e=>(0,i.jsx)(`span`,{className:n.default.hourLine,style:{top:`${(e-C.startMinute)/(C.endMinute-C.startMinute)*100}%`}},e))},t.toISOString())),E.map(e=>(0,i.jsx)(`button`,{type:`button`,className:n.default.event,style:{gridColumn:`${e.dayIndex+1} / span 1`,top:`${e.top*100}%`,height:`${e.height*100}%`,left:`${e.column/e.columns*100}%`,width:`${1/e.columns*100}%`},onClick:()=>f?.(e.event),disabled:!f,title:`${e.event.title} — ${A.format(e.event.start)}`,children:m?m(e.event):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(`span`,{className:n.default.eventTime,children:A.format(e.event.start)}),(0,i.jsx)(`span`,{className:n.default.eventTitle,children:e.event.title})]})},`${e.event.id}-${e.dayIndex}`)),M!==null&&N>=0&&(0,i.jsx)(`span`,{className:n.default.nowLine,style:{top:`${M*100}%`},"aria-hidden":!0,"data-testid":`scheduler-now`})]})]})]})}exports.Scheduler=o;
2
2
  //# sourceMappingURL=Scheduler.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"Scheduler.cjs","names":[],"sources":["../../../src/components/Scheduler/Scheduler.tsx"],"sourcesContent":["/**\n * @tempest-limits file-lines, props-count, function-lines — the grid is defined by\n * anchor, days, startHour, endHour and snapMinutes; the content by events,\n * renderEvent, onEventClick and onSlotClick; the reading by locale, showCurrentTime\n * and now. The body lays out overlapping events into columns, which needs the whole\n * day's events at once.\n */\nimport { type HTMLAttributes, type ReactNode, useEffect, useMemo, useState } from \"react\";\n\nimport { cn } from \"@/utils/cn\";\n\nimport {\n dayRange,\n type DayWindow,\n fractionOfWindow,\n hourMarks,\n isSameDay,\n layoutAllDay,\n layoutEvents,\n type SchedulerEvent,\n} from \"./scheduler-layout\";\nimport styles from \"./Scheduler.module.css\";\n\nexport interface SchedulerProps extends Omit<HTMLAttributes<HTMLDivElement>, \"children\"> {\n /** Events to place. Instants are read in the browser's local time. */\n events: readonly SchedulerEvent[];\n /** Any day within the range to show. Default: today. */\n anchor?: Date;\n /** How many consecutive days to render. `1` is a day view, `7` a week. Default `7`. */\n days?: number;\n /** First visible hour, `0`–`23`. Default `8`. */\n startHour?: number;\n /** Last visible hour, `1`–`24`. Default `20`. */\n endHour?: number;\n /** Minutes a click on empty space snaps to. Default `30`. */\n snapMinutes?: number;\n /** Called when an event is activated by click, `Enter` or `Space`. */\n onEventClick?: (event: SchedulerEvent) => void;\n /** Called with the snapped instant when empty space is clicked. */\n onSlotClick?: (start: Date) => void;\n /** Render an event's contents. Defaults to its title and start time. */\n renderEvent?: (event: SchedulerEvent) => ReactNode;\n /** Locale for the day and hour labels. Default `\"pt-BR\"`. */\n locale?: string;\n /** Draw the current-time line. Default `true`. */\n showCurrentTime?: boolean;\n /** Fixed \"now\" for the indicator. Default: the real clock, ticking each minute. */\n now?: Date;\n}\n\n/** Minutes between ticks of the current-time indicator. */\nconst TICK_MS = 60_000;\n\n/**\n * An agenda: events placed on a time grid across consecutive days.\n *\n * `Calendar` is a date *picker* — it answers \"which day?\". This answers \"what is on\n * those days, and when\", which needs a different structure entirely: a vertical time\n * axis, events sized by duration, and overlapping events sitting side by side.\n *\n * That last part is the one worth naming. Overlapping events are grouped into\n * clusters of mutual overlap and every event in a cluster shares one column count,\n * so widths line up; a column is reused the moment it frees, so `9–10`, `9–10`,\n * `10–11` takes two columns and not three. The layout is pure and lives in\n * `scheduler-layout.ts`.\n *\n * Times are local. An event crossing midnight is split into both day columns, and\n * the day range is built by incrementing the calendar day, so a DST boundary does\n * not duplicate or skip a date.\n *\n * @example\n * <Scheduler\n * events={bookings}\n * days={7}\n * startHour={7}\n * endHour={21}\n * onEventClick={(e) => open(e.id)}\n * onSlotClick={(start) => createAt(start)}\n * />\n */\nexport function Scheduler({\n events,\n anchor,\n days: dayCount = 7,\n startHour = 8,\n endHour = 20,\n snapMinutes = 30,\n onEventClick,\n onSlotClick,\n renderEvent,\n locale = \"pt-BR\",\n showCurrentTime = true,\n now,\n className,\n ...rest\n}: SchedulerProps) {\n const [clock, setClock] = useState<Date>(() => now ?? new Date());\n\n /**\n * Keep the current-time line moving.\n *\n * Skipped entirely when `now` is supplied: that is the hook tests and demos use\n * to be deterministic, and a timer would fight it.\n */\n useEffect(() => {\n if (now || !showCurrentTime) return;\n const id = setInterval(() => setClock(new Date()), TICK_MS);\n return () => clearInterval(id);\n }, [now, showCurrentTime]);\n\n const reference = now ?? clock;\n\n const window = useMemo<DayWindow>(\n () => ({ startMinute: startHour * 60, endMinute: endHour * 60 }),\n [startHour, endHour],\n );\n\n /**\n * The calendar day the range starts from, as a stable string.\n *\n * `reference` ticks every minute when the current-time line is live. Depending on\n * the Date itself would re-slice the day range — and therefore relayout every\n * event — once a minute; depending on the day only recomputes at midnight.\n */\n const anchorDay = (anchor ?? reference).toDateString();\n const dayList = useMemo(() => dayRange(new Date(anchorDay), dayCount), [anchorDay, dayCount]);\n\n const placed = useMemo(\n () => layoutEvents({ events, days: dayList, window }),\n [events, dayList, window],\n );\n const allDay = useMemo(() => layoutAllDay({ events, days: dayList }), [events, dayList]);\n const marks = useMemo(() => hourMarks(window), [window]);\n\n const dayLabel = new Intl.DateTimeFormat(locale, { weekday: \"short\", day: \"numeric\" });\n const timeLabel = new Intl.DateTimeFormat(locale, { hour: \"2-digit\", minute: \"2-digit\" });\n\n /** Turn a click's vertical position within a day column into a snapped instant. */\n const slotFromClick = (day: Date, event: React.MouseEvent<HTMLDivElement>): Date => {\n const rect = event.currentTarget.getBoundingClientRect();\n const fraction = rect.height > 0 ? (event.clientY - rect.top) / rect.height : 0;\n const raw = window.startMinute + fraction * (window.endMinute - window.startMinute);\n const snapped = Math.round(raw / snapMinutes) * snapMinutes;\n const clamped = Math.max(window.startMinute, Math.min(window.endMinute, snapped));\n const result = new Date(day);\n result.setHours(0, clamped, 0, 0);\n return result;\n };\n\n const currentFraction = showCurrentTime ? fractionOfWindow(reference, window) : null;\n const todayIndex = dayList.findIndex((day) => isSameDay(day, reference));\n\n return (\n <div className={cn(styles.wrapper, className)} {...rest}>\n <div\n className={styles.head}\n style={{ [\"--tempest-scheduler-days\" as string]: dayCount }}\n >\n <span className={styles.gutterHead} />\n {dayList.map((day, index) => (\n <span\n key={day.toISOString()}\n className={cn(styles.dayHead, index === todayIndex && styles.today)}\n >\n {dayLabel.format(day)}\n </span>\n ))}\n </div>\n\n {allDay.length > 0 && (\n <div\n className={styles.allDayLane}\n style={{ [\"--tempest-scheduler-days\" as string]: dayCount }}\n >\n <span className={styles.gutterHead}>Dia inteiro</span>\n <div className={styles.allDayTrack}>\n {allDay.map(({ event, dayIndex, span }) => (\n <button\n key={event.id}\n type=\"button\"\n className={styles.allDayEvent}\n style={{ gridColumn: `${dayIndex + 1} / span ${span}` }}\n onClick={() => onEventClick?.(event)}\n disabled={!onEventClick}\n >\n {event.title}\n </button>\n ))}\n </div>\n </div>\n )}\n\n {/*\n * Focusable because it scrolls vertically: a scroll region that cannot be\n * focused is unreachable by keyboard, which is what `axe`'s\n * `scrollable-region-focusable` rule is about. It needs a name too, or the\n * new tab stop would announce nothing — but `group`, not `region`: a named\n * `region` is a landmark, and two schedulers on one page would then be two\n * identically-named landmarks (`landmark-unique`).\n */}\n <div\n className={styles.body}\n style={{ [\"--tempest-scheduler-days\" as string]: dayCount }}\n tabIndex={0}\n role=\"group\"\n aria-label=\"Grade de horários\"\n >\n <div className={styles.gutter}>\n {marks.map((minute) => (\n <span\n key={minute}\n className={styles.hourLabel}\n style={{\n top: `${((minute - window.startMinute) / (window.endMinute - window.startMinute)) * 100}%`,\n }}\n >\n {timeLabel.format(\n new Date(2026, 0, 1, Math.floor(minute / 60), minute % 60),\n )}\n </span>\n ))}\n </div>\n\n {/*\n * Not `role=\"grid\"`: that requires `row` children, and the events are\n * siblings of the day columns inside one CSS grid — a `row` wrapper\n * would stop the columns being grid items and collapse the layout.\n * A labelled group per day is the honest structure anyway: a screen\n * reader tabs the event buttons and the group name supplies the day.\n */}\n <div className={styles.grid} aria-label=\"Agenda\">\n {dayList.map((day, index) => (\n <div\n key={day.toISOString()}\n className={cn(\n styles.dayColumn,\n index === todayIndex && styles.todayColumn,\n )}\n role=\"group\"\n aria-label={dayLabel.format(day)}\n onClick={\n onSlotClick\n ? (event) => {\n // Only empty space creates: a click that\n // landed on an event is that event's.\n if (event.target !== event.currentTarget) return;\n onSlotClick(slotFromClick(day, event));\n }\n : undefined\n }\n >\n {marks.map((minute) => (\n <span\n key={minute}\n className={styles.hourLine}\n style={{\n top: `${((minute - window.startMinute) / (window.endMinute - window.startMinute)) * 100}%`,\n }}\n />\n ))}\n </div>\n ))}\n\n {placed.map((item) => (\n <button\n key={`${item.event.id}-${item.dayIndex}`}\n type=\"button\"\n className={styles.event}\n style={{\n gridColumn: item.dayIndex + 1,\n top: `${item.top * 100}%`,\n height: `${item.height * 100}%`,\n left: `${(item.column / item.columns) * 100}%`,\n width: `${(1 / item.columns) * 100}%`,\n }}\n onClick={() => onEventClick?.(item.event)}\n disabled={!onEventClick}\n title={`${item.event.title} — ${timeLabel.format(item.event.start)}`}\n >\n {renderEvent ? (\n renderEvent(item.event)\n ) : (\n <>\n <span className={styles.eventTime}>\n {timeLabel.format(item.event.start)}\n </span>\n <span className={styles.eventTitle}>{item.event.title}</span>\n </>\n )}\n </button>\n ))}\n\n {currentFraction !== null && todayIndex >= 0 && (\n <span\n className={styles.nowLine}\n style={{ top: `${currentFraction * 100}%` }}\n aria-hidden\n data-testid=\"scheduler-now\"\n />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sourcesContent":["/**\n * @tempest-limits file-lines, props-count, function-lines — the grid is defined by\n * anchor, days, startHour, endHour and snapMinutes; the content by events,\n * renderEvent, onEventClick and onSlotClick; the reading by locale, showCurrentTime\n * and now. The body lays out overlapping events into columns, which needs the whole\n * day's events at once.\n */\nimport { type HTMLAttributes, type ReactNode, useEffect, useMemo, useState } from \"react\";\n\nimport { cn } from \"@/utils/cn\";\n\nimport {\n dayRange,\n type DayWindow,\n fractionOfWindow,\n hourMarks,\n isSameDay,\n layoutAllDay,\n layoutEvents,\n type SchedulerEvent,\n} from \"./scheduler-layout\";\nimport styles from \"./Scheduler.module.css\";\n\nexport interface SchedulerProps extends Omit<HTMLAttributes<HTMLDivElement>, \"children\"> {\n /** Events to place. Instants are read in the browser's local time. */\n events: readonly SchedulerEvent[];\n /** Any day within the range to show. Default: today. */\n anchor?: Date;\n /** How many consecutive days to render. `1` is a day view, `7` a week. Default `7`. */\n days?: number;\n /** First visible hour, `0`–`23`. Default `8`. */\n startHour?: number;\n /** Last visible hour, `1`–`24`. Default `20`. */\n endHour?: number;\n /** Minutes a click on empty space snaps to. Default `30`. */\n snapMinutes?: number;\n /** Called when an event is activated by click, `Enter` or `Space`. */\n onEventClick?: (event: SchedulerEvent) => void;\n /** Called with the snapped instant when empty space is clicked. */\n onSlotClick?: (start: Date) => void;\n /** Render an event's contents. Defaults to its title and start time. */\n renderEvent?: (event: SchedulerEvent) => ReactNode;\n /** Locale for the day and hour labels. Default `\"pt-BR\"`. */\n locale?: string;\n /** Draw the current-time line. Default `true`. */\n showCurrentTime?: boolean;\n /** Fixed \"now\" for the indicator. Default: the real clock, ticking each minute. */\n now?: Date;\n}\n\n/** Minutes between ticks of the current-time indicator. */\nconst TICK_MS = 60_000;\n\n/**\n * An agenda: events placed on a time grid across consecutive days.\n *\n * `Calendar` is a date *picker* — it answers \"which day?\". This answers \"what is on\n * those days, and when\", which needs a different structure entirely: a vertical time\n * axis, events sized by duration, and overlapping events sitting side by side.\n *\n * That last part is the one worth naming. Overlapping events are grouped into\n * clusters of mutual overlap and every event in a cluster shares one column count,\n * so widths line up; a column is reused the moment it frees, so `9–10`, `9–10`,\n * `10–11` takes two columns and not three. The layout is pure and lives in\n * `scheduler-layout.ts`.\n *\n * Times are local. An event crossing midnight is split into both day columns, and\n * the day range is built by incrementing the calendar day, so a DST boundary does\n * not duplicate or skip a date.\n *\n * @example\n * <Scheduler\n * events={bookings}\n * days={7}\n * startHour={7}\n * endHour={21}\n * onEventClick={(e) => open(e.id)}\n * onSlotClick={(start) => createAt(start)}\n * />\n */\nexport function Scheduler({\n events,\n anchor,\n days: dayCount = 7,\n startHour = 8,\n endHour = 20,\n snapMinutes = 30,\n onEventClick,\n onSlotClick,\n renderEvent,\n locale = \"pt-BR\",\n showCurrentTime = true,\n now,\n className,\n ...rest\n}: SchedulerProps) {\n const [clock, setClock] = useState<Date>(() => now ?? new Date());\n\n /**\n * Keep the current-time line moving.\n *\n * Skipped entirely when `now` is supplied: that is the hook tests and demos use\n * to be deterministic, and a timer would fight it.\n */\n useEffect(() => {\n if (now || !showCurrentTime) return;\n const id = setInterval(() => setClock(new Date()), TICK_MS);\n return () => clearInterval(id);\n }, [now, showCurrentTime]);\n\n const reference = now ?? clock;\n\n const window = useMemo<DayWindow>(\n () => ({ startMinute: startHour * 60, endMinute: endHour * 60 }),\n [startHour, endHour],\n );\n\n /**\n * The calendar day the range starts from, as a stable string.\n *\n * `reference` ticks every minute when the current-time line is live. Depending on\n * the Date itself would re-slice the day range — and therefore relayout every\n * event — once a minute; depending on the day only recomputes at midnight.\n */\n const anchorDay = (anchor ?? reference).toDateString();\n const dayList = useMemo(() => dayRange(new Date(anchorDay), dayCount), [anchorDay, dayCount]);\n\n const placed = useMemo(\n () => layoutEvents({ events, days: dayList, window }),\n [events, dayList, window],\n );\n const allDay = useMemo(() => layoutAllDay({ events, days: dayList }), [events, dayList]);\n const marks = useMemo(() => hourMarks(window), [window]);\n\n const dayLabel = new Intl.DateTimeFormat(locale, { weekday: \"short\", day: \"numeric\" });\n const timeLabel = new Intl.DateTimeFormat(locale, { hour: \"2-digit\", minute: \"2-digit\" });\n\n /** Turn a click's vertical position within a day column into a snapped instant. */\n const slotFromClick = (day: Date, event: React.MouseEvent<HTMLDivElement>): Date => {\n const rect = event.currentTarget.getBoundingClientRect();\n const fraction = rect.height > 0 ? (event.clientY - rect.top) / rect.height : 0;\n const raw = window.startMinute + fraction * (window.endMinute - window.startMinute);\n const snapped = Math.round(raw / snapMinutes) * snapMinutes;\n const clamped = Math.max(window.startMinute, Math.min(window.endMinute, snapped));\n const result = new Date(day);\n result.setHours(0, clamped, 0, 0);\n return result;\n };\n\n const currentFraction = showCurrentTime ? fractionOfWindow(reference, window) : null;\n const todayIndex = dayList.findIndex((day) => isSameDay(day, reference));\n\n return (\n <div className={cn(styles.wrapper, className)} {...rest}>\n <div\n className={styles.head}\n style={{ [\"--tempest-scheduler-days\" as string]: dayCount }}\n >\n <span className={styles.gutterHead} />\n {dayList.map((day, index) => (\n <span\n key={day.toISOString()}\n className={cn(styles.dayHead, index === todayIndex && styles.today)}\n >\n {dayLabel.format(day)}\n </span>\n ))}\n </div>\n\n {allDay.length > 0 && (\n <div\n className={styles.allDayLane}\n style={{ [\"--tempest-scheduler-days\" as string]: dayCount }}\n >\n <span className={styles.gutterHead}>Dia inteiro</span>\n <div className={styles.allDayTrack}>\n {allDay.map(({ event, dayIndex, span }) => (\n <button\n key={event.id}\n type=\"button\"\n className={styles.allDayEvent}\n style={{ gridColumn: `${dayIndex + 1} / span ${span}` }}\n onClick={() => onEventClick?.(event)}\n disabled={!onEventClick}\n >\n {event.title}\n </button>\n ))}\n </div>\n </div>\n )}\n\n {/*\n * Focusable because it scrolls vertically: a scroll region that cannot be\n * focused is unreachable by keyboard, which is what `axe`'s\n * `scrollable-region-focusable` rule is about. It needs a name too, or the\n * new tab stop would announce nothing — but `group`, not `region`: a named\n * `region` is a landmark, and two schedulers on one page would then be two\n * identically-named landmarks (`landmark-unique`).\n */}\n <div\n className={styles.body}\n style={{ [\"--tempest-scheduler-days\" as string]: dayCount }}\n tabIndex={0}\n role=\"group\"\n aria-label=\"Grade de horários\"\n >\n <div className={styles.gutter}>\n {marks.map((minute) => (\n <span\n key={minute}\n className={styles.hourLabel}\n style={{\n top: `${((minute - window.startMinute) / (window.endMinute - window.startMinute)) * 100}%`,\n }}\n >\n {timeLabel.format(\n new Date(2026, 0, 1, Math.floor(minute / 60), minute % 60),\n )}\n </span>\n ))}\n </div>\n\n {/*\n * Not `role=\"grid\"`: that requires `row` children, and the events are\n * siblings of the day columns inside one CSS grid — a `row` wrapper\n * would stop the columns being grid items and collapse the layout.\n * A labelled group per day is the honest structure anyway: a screen\n * reader tabs the event buttons and the group name supplies the day.\n */}\n <div className={styles.grid} aria-label=\"Agenda\">\n {dayList.map((day, index) => (\n <div\n key={day.toISOString()}\n className={cn(\n styles.dayColumn,\n index === todayIndex && styles.todayColumn,\n )}\n role=\"group\"\n aria-label={dayLabel.format(day)}\n onClick={\n onSlotClick\n ? (event) => {\n // Only empty space creates: a click that\n // landed on an event is that event's.\n if (event.target !== event.currentTarget) return;\n onSlotClick(slotFromClick(day, event));\n }\n : undefined\n }\n >\n {marks.map((minute) => (\n <span\n key={minute}\n className={styles.hourLine}\n style={{\n top: `${((minute - window.startMinute) / (window.endMinute - window.startMinute)) * 100}%`,\n }}\n />\n ))}\n </div>\n ))}\n\n {placed.map((item) => (\n <button\n key={`${item.event.id}-${item.dayIndex}`}\n type=\"button\"\n className={styles.event}\n style={{\n gridColumn: `${item.dayIndex + 1} / span 1`,\n top: `${item.top * 100}%`,\n height: `${item.height * 100}%`,\n left: `${(item.column / item.columns) * 100}%`,\n width: `${(1 / item.columns) * 100}%`,\n }}\n onClick={() => onEventClick?.(item.event)}\n disabled={!onEventClick}\n title={`${item.event.title} — ${timeLabel.format(item.event.start)}`}\n >\n {renderEvent ? (\n renderEvent(item.event)\n ) : (\n <>\n <span className={styles.eventTime}>\n {timeLabel.format(item.event.start)}\n </span>\n <span className={styles.eventTitle}>{item.event.title}</span>\n </>\n )}\n </button>\n ))}\n\n {currentFraction !== null && todayIndex >= 0 && (\n <span\n className={styles.nowLine}\n style={{ top: `${currentFraction * 100}%` }}\n aria-hidden\n data-testid=\"scheduler-now\"\n />\n )}\n </div>\n </div>\n </div>\n );\n}\n\nexport type { SchedulerEvent };\n"],"mappings":"oKAmDA,IAAM,EAAU,IA6BhB,SAAgB,EAAU,CACtB,SACA,SACA,KAAM,EAAW,EACjB,YAAY,EACZ,UAAU,GACV,cAAc,GACd,eACA,cACA,cACA,SAAS,QACT,kBAAkB,GAClB,MACA,YACA,GAAG,GACY,CACf,GAAM,CAAC,EAAO,IAAA,EAAY,EAAA,SAAA,KAAqB,GAAO,IAAI,IAAM,GAQhE,EAAA,EAAA,UAAA,KAAgB,CACZ,GAAI,GAAO,CAAC,EAAiB,OAC7B,IAAM,EAAK,gBAAkB,EAAS,IAAI,IAAM,EAAG,CAAO,EAC1D,UAAa,cAAc,CAAE,CACjC,EAAG,CAAC,EAAK,CAAe,CAAC,EAEzB,IAAM,EAAY,GAAO,EAEnB,GAAA,EAAS,EAAA,QAAA,MACJ,CAAE,YAAa,EAAY,GAAI,UAAW,EAAU,EAAG,GAC9D,CAAC,EAAW,CAAO,CACvB,EASM,GAAa,GAAU,EAAA,CAAW,aAAa,EAC/C,GAAA,EAAU,EAAA,QAAA,KAAc,EAAA,SAAS,IAAI,KAAK,CAAS,EAAG,CAAQ,EAAG,CAAC,EAAW,CAAQ,CAAC,EAEtF,GAAA,EAAS,EAAA,QAAA,KACL,EAAA,aAAa,CAAE,SAAQ,KAAM,EAAS,QAAO,CAAC,EACpD,CAAC,EAAQ,EAAS,CAAM,CAC5B,EACM,GAAA,EAAS,EAAA,QAAA,KAAc,EAAA,aAAa,CAAE,SAAQ,KAAM,CAAQ,CAAC,EAAG,CAAC,EAAQ,CAAO,CAAC,EACjF,GAAA,EAAQ,EAAA,QAAA,KAAc,EAAA,UAAU,CAA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AO,CAAE,IAAK,GAAG,EAAkB,IAAI,EAAG,EAC1C,cAAA,GACA,cAAY,eACf,CAAA,CAEJ,CACJ,CAAA,CAAA,GACJ,GAEb"}
@@ -99,7 +99,7 @@ function h({ events: h, anchor: g, days: _ = 7, startHour: v = 8, endHour: y = 2
99
99
  type: "button",
100
100
  className: s.event,
101
101
  style: {
102
- gridColumn: e.dayIndex + 1,
102
+ gridColumn: `${e.dayIndex + 1} / span 1`,
103
103
  top: `${e.top * 100}%`,
104
104
  height: `${e.height * 100}%`,
105
105
  left: `${e.column / e.columns * 100}%`,
@@ -1 +1 @@
1
- {"version":3,"file":"Scheduler.js","names":[],"sources":["../../../src/components/Scheduler/Scheduler.tsx"],"sourcesContent":["/**\n * @tempest-limits file-lines, props-count, function-lines — the grid is defined by\n * anchor, days, startHour, endHour and snapMinutes; the content by events,\n * renderEvent, onEventClick and onSlotClick; the reading by locale, showCurrentTime\n * and now. The body lays out overlapping events into columns, which needs the whole\n * day's events at once.\n */\nimport { type HTMLAttributes, type ReactNode, useEffect, useMemo, useState } from \"react\";\n\nimport { cn } from \"@/utils/cn\";\n\nimport {\n dayRange,\n type DayWindow,\n fractionOfWindow,\n hourMarks,\n isSameDay,\n layoutAllDay,\n layoutEvents,\n type SchedulerEvent,\n} from \"./scheduler-layout\";\nimport styles from \"./Scheduler.module.css\";\n\nexport interface SchedulerProps extends Omit<HTMLAttributes<HTMLDivElement>, \"children\"> {\n /** Events to place. Instants are read in the browser's local time. */\n events: readonly SchedulerEvent[];\n /** Any day within the range to show. Default: today. */\n anchor?: Date;\n /** How many consecutive days to render. `1` is a day view, `7` a week. Default `7`. */\n days?: number;\n /** First visible hour, `0`–`23`. Default `8`. */\n startHour?: number;\n /** Last visible hour, `1`–`24`. Default `20`. */\n endHour?: number;\n /** Minutes a click on empty space snaps to. Default `30`. */\n snapMinutes?: number;\n /** Called when an event is activated by click, `Enter` or `Space`. */\n onEventClick?: (event: SchedulerEvent) => void;\n /** Called with the snapped instant when empty space is clicked. */\n onSlotClick?: (start: Date) => void;\n /** Render an event's contents. Defaults to its title and start time. */\n renderEvent?: (event: SchedulerEvent) => ReactNode;\n /** Locale for the day and hour labels. Default `\"pt-BR\"`. */\n locale?: string;\n /** Draw the current-time line. Default `true`. */\n showCurrentTime?: boolean;\n /** Fixed \"now\" for the indicator. Default: the real clock, ticking each minute. */\n now?: Date;\n}\n\n/** Minutes between ticks of the current-time indicator. */\nconst TICK_MS = 60_000;\n\n/**\n * An agenda: events placed on a time grid across consecutive days.\n *\n * `Calendar` is a date *picker* — it answers \"which day?\". This answers \"what is on\n * those days, and when\", which needs a different structure entirely: a vertical time\n * axis, events sized by duration, and overlapping events sitting side by side.\n *\n * That last part is the one worth naming. Overlapping events are grouped into\n * clusters of mutual overlap and every event in a cluster shares one column count,\n * so widths line up; a column is reused the moment it frees, so `9–10`, `9–10`,\n * `10–11` takes two columns and not three. The layout is pure and lives in\n * `scheduler-layout.ts`.\n *\n * Times are local. An event crossing midnight is split into both day columns, and\n * the day range is built by incrementing the calendar day, so a DST boundary does\n * not duplicate or skip a date.\n *\n * @example\n * <Scheduler\n * events={bookings}\n * days={7}\n * startHour={7}\n * endHour={21}\n * onEventClick={(e) => open(e.id)}\n * onSlotClick={(start) => createAt(start)}\n * />\n */\nexport function Scheduler({\n events,\n anchor,\n days: dayCount = 7,\n startHour = 8,\n endHour = 20,\n snapMinutes = 30,\n onEventClick,\n onSlotClick,\n renderEvent,\n locale = \"pt-BR\",\n showCurrentTime = true,\n now,\n className,\n ...rest\n}: SchedulerProps) {\n const [clock, setClock] = useState<Date>(() => now ?? new Date());\n\n /**\n * Keep the current-time line moving.\n *\n * Skipped entirely when `now` is supplied: that is the hook tests and demos use\n * to be deterministic, and a timer would fight it.\n */\n useEffect(() => {\n if (now || !showCurrentTime) return;\n const id = setInterval(() => setClock(new Date()), TICK_MS);\n return () => clearInterval(id);\n }, [now, showCurrentTime]);\n\n const reference = now ?? clock;\n\n const window = useMemo<DayWindow>(\n () => ({ startMinute: startHour * 60, endMinute: endHour * 60 }),\n [startHour, endHour],\n );\n\n /**\n * The calendar day the range starts from, as a stable string.\n *\n * `reference` ticks every minute when the current-time line is live. Depending on\n * the Date itself would re-slice the day range — and therefore relayout every\n * event — once a minute; depending on the day only recomputes at midnight.\n */\n const anchorDay = (anchor ?? reference).toDateString();\n const dayList = useMemo(() => dayRange(new Date(anchorDay), dayCount), [anchorDay, dayCount]);\n\n const placed = useMemo(\n () => layoutEvents({ events, days: dayList, window }),\n [events, dayList, window],\n );\n const allDay = useMemo(() => layoutAllDay({ events, days: dayList }), [events, dayList]);\n const marks = useMemo(() => hourMarks(window), [window]);\n\n const dayLabel = new Intl.DateTimeFormat(locale, { weekday: \"short\", day: \"numeric\" });\n const timeLabel = new Intl.DateTimeFormat(locale, { hour: \"2-digit\", minute: \"2-digit\" });\n\n /** Turn a click's vertical position within a day column into a snapped instant. */\n const slotFromClick = (day: Date, event: React.MouseEvent<HTMLDivElement>): Date => {\n const rect = event.currentTarget.getBoundingClientRect();\n const fraction = rect.height > 0 ? (event.clientY - rect.top) / rect.height : 0;\n const raw = window.startMinute + fraction * (window.endMinute - window.startMinute);\n const snapped = Math.round(raw / snapMinutes) * snapMinutes;\n const clamped = Math.max(window.startMinute, Math.min(window.endMinute, snapped));\n const result = new Date(day);\n result.setHours(0, clamped, 0, 0);\n return result;\n };\n\n const currentFraction = showCurrentTime ? fractionOfWindow(reference, window) : null;\n const todayIndex = dayList.findIndex((day) => isSameDay(day, reference));\n\n return (\n <div className={cn(styles.wrapper, className)} {...rest}>\n <div\n className={styles.head}\n style={{ [\"--tempest-scheduler-days\" as string]: dayCount }}\n >\n <span className={styles.gutterHead} />\n {dayList.map((day, index) => (\n <span\n key={day.toISOString()}\n className={cn(styles.dayHead, index === todayIndex && styles.today)}\n >\n {dayLabel.format(day)}\n </span>\n ))}\n </div>\n\n {allDay.length > 0 && (\n <div\n className={styles.allDayLane}\n style={{ [\"--tempest-scheduler-days\" as string]: dayCount }}\n >\n <span className={styles.gutterHead}>Dia inteiro</span>\n <div className={styles.allDayTrack}>\n {allDay.map(({ event, dayIndex, span }) => (\n <button\n key={event.id}\n type=\"button\"\n className={styles.allDayEvent}\n style={{ gridColumn: `${dayIndex + 1} / span ${span}` }}\n onClick={() => onEventClick?.(event)}\n disabled={!onEventClick}\n >\n {event.title}\n </button>\n ))}\n </div>\n </div>\n )}\n\n {/*\n * Focusable because it scrolls vertically: a scroll region that cannot be\n * focused is unreachable by keyboard, which is what `axe`'s\n * `scrollable-region-focusable` rule is about. It needs a name too, or the\n * new tab stop would announce nothing — but `group`, not `region`: a named\n * `region` is a landmark, and two schedulers on one page would then be two\n * identically-named landmarks (`landmark-unique`).\n */}\n <div\n className={styles.body}\n style={{ [\"--tempest-scheduler-days\" as string]: dayCount }}\n tabIndex={0}\n role=\"group\"\n aria-label=\"Grade de horários\"\n >\n <div className={styles.gutter}>\n {marks.map((minute) => (\n <span\n key={minute}\n className={styles.hourLabel}\n style={{\n top: `${((minute - window.startMinute) / (window.endMinute - window.startMinute)) * 100}%`,\n }}\n >\n {timeLabel.format(\n new Date(2026, 0, 1, Math.floor(minute / 60), minute % 60),\n )}\n </span>\n ))}\n </div>\n\n {/*\n * Not `role=\"grid\"`: that requires `row` children, and the events are\n * siblings of the day columns inside one CSS grid — a `row` wrapper\n * would stop the columns being grid items and collapse the layout.\n * A labelled group per day is the honest structure anyway: a screen\n * reader tabs the event buttons and the group name supplies the day.\n */}\n <div className={styles.grid} aria-label=\"Agenda\">\n {dayList.map((day, index) => (\n <div\n key={day.toISOString()}\n className={cn(\n styles.dayColumn,\n index === todayIndex && styles.todayColumn,\n )}\n role=\"group\"\n aria-label={dayLabel.format(day)}\n onClick={\n onSlotClick\n ? (event) => {\n // Only empty space creates: a click that\n // landed on an event is that event's.\n if (event.target !== event.currentTarget) return;\n onSlotClick(slotFromClick(day, event));\n }\n : undefined\n }\n >\n {marks.map((minute) => (\n <span\n key={minute}\n className={styles.hourLine}\n style={{\n top: `${((minute - window.startMinute) / (window.endMinute - window.startMinute)) * 100}%`,\n }}\n />\n ))}\n </div>\n ))}\n\n {placed.map((item) => (\n <button\n key={`${item.event.id}-${item.dayIndex}`}\n type=\"button\"\n className={styles.event}\n style={{\n gridColumn: item.dayIndex + 1,\n top: `${item.top * 100}%`,\n height: `${item.height * 100}%`,\n left: `${(item.column / item.columns) * 100}%`,\n width: `${(1 / item.columns) * 100}%`,\n }}\n onClick={() => onEventClick?.(item.event)}\n disabled={!onEventClick}\n title={`${item.event.title} — ${timeLabel.format(item.event.start)}`}\n >\n {renderEvent ? (\n renderEvent(item.event)\n ) : (\n <>\n <span className={styles.eventTime}>\n {timeLabel.format(item.event.start)}\n </span>\n <span className={styles.eventTitle}>{item.event.title}</span>\n </>\n )}\n </button>\n ))}\n\n {currentFraction !== null && todayIndex >= 0 && (\n <span\n className={styles.nowLine}\n style={{ top: `${currentFraction * 100}%` }}\n aria-hidden\n data-testid=\"scheduler-now\"\n />\n )}\n </div>\n </div>\n </div>\n );\n}\n\nexport type { SchedulerEvent };\n"],"mappings":";;;;;;AAmDA,IAAM,IAAU;AA6BhB,SAAgB,EAAU,EACtB,WACA,WACA,MAAM,IAAW,GACjB,eAAY,GACZ,aAAU,IACV,iBAAc,IACd,iBACA,gBACA,gBACA,YAAS,SACT,qBAAkB,IAClB,QACA,cACA,GAAG,KACY;CACf,IAAM,CAAC,GAAO,KAAY,QAAqB,qBAAO,IAAI,KAAK,CAAC;CAQhE,QAAgB;EACZ,IAAI,KAAO,CAAC,GAAiB;EAC7B,IAAM,IAAK,kBAAkB,kBAAS,IAAI,KAAK,CAAC,GAAG,CAAO;EAC1D,aAAa,cAAc,CAAE;CACjC,GAAG,CAAC,GAAK,CAAe,CAAC;CAEzB,IAAM,IAAY,KAAO,GAEnB,IAAS,SACJ;EAAE,aAAa,IAAY;EAAI,WAAW,IAAU;CAAG,IAC9D,CAAC,GAAW,CAAO,CACvB,GASM,KAAa,KAAU,EAAA,CAAW,aAA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tsx"],"sourcesContent":["/**\n * @tempest-limits file-lines, props-count, function-lines — the grid is defined by\n * anchor, days, startHour, endHour and snapMinutes; the content by events,\n * renderEvent, onEventClick and onSlotClick; the reading by locale, showCurrentTime\n * and now. The body lays out overlapping events into columns, which needs the whole\n * day's events at once.\n */\nimport { type HTMLAttributes, type ReactNode, useEffect, useMemo, useState } from \"react\";\n\nimport { cn } from \"@/utils/cn\";\n\nimport {\n dayRange,\n type DayWindow,\n fractionOfWindow,\n hourMarks,\n isSameDay,\n layoutAllDay,\n layoutEvents,\n type SchedulerEvent,\n} from \"./scheduler-layout\";\nimport styles from \"./Scheduler.module.css\";\n\nexport interface SchedulerProps extends Omit<HTMLAttributes<HTMLDivElement>, \"children\"> {\n /** Events to place. Instants are read in the browser's local time. */\n events: readonly SchedulerEvent[];\n /** Any day within the range to show. Default: today. */\n anchor?: Date;\n /** How many consecutive days to render. `1` is a day view, `7` a week. Default `7`. */\n days?: number;\n /** First visible hour, `0`–`23`. Default `8`. */\n startHour?: number;\n /** Last visible hour, `1`–`24`. Default `20`. */\n endHour?: number;\n /** Minutes a click on empty space snaps to. Default `30`. */\n snapMinutes?: number;\n /** Called when an event is activated by click, `Enter` or `Space`. */\n onEventClick?: (event: SchedulerEvent) => void;\n /** Called with the snapped instant when empty space is clicked. */\n onSlotClick?: (start: Date) => void;\n /** Render an event's contents. Defaults to its title and start time. */\n renderEvent?: (event: SchedulerEvent) => ReactNode;\n /** Locale for the day and hour labels. Default `\"pt-BR\"`. */\n locale?: string;\n /** Draw the current-time line. Default `true`. */\n showCurrentTime?: boolean;\n /** Fixed \"now\" for the indicator. Default: the real clock, ticking each minute. */\n now?: Date;\n}\n\n/** Minutes between ticks of the current-time indicator. */\nconst TICK_MS = 60_000;\n\n/**\n * An agenda: events placed on a time grid across consecutive days.\n *\n * `Calendar` is a date *picker* — it answers \"which day?\". This answers \"what is on\n * those days, and when\", which needs a different structure entirely: a vertical time\n * axis, events sized by duration, and overlapping events sitting side by side.\n *\n * That last part is the one worth naming. Overlapping events are grouped into\n * clusters of mutual overlap and every event in a cluster shares one column count,\n * so widths line up; a column is reused the moment it frees, so `9–10`, `9–10`,\n * `10–11` takes two columns and not three. The layout is pure and lives in\n * `scheduler-layout.ts`.\n *\n * Times are local. An event crossing midnight is split into both day columns, and\n * the day range is built by incrementing the calendar day, so a DST boundary does\n * not duplicate or skip a date.\n *\n * @example\n * <Scheduler\n * events={bookings}\n * days={7}\n * startHour={7}\n * endHour={21}\n * onEventClick={(e) => open(e.id)}\n * onSlotClick={(start) => createAt(start)}\n * />\n */\nexport function Scheduler({\n events,\n anchor,\n days: dayCount = 7,\n startHour = 8,\n endHour = 20,\n snapMinutes = 30,\n onEventClick,\n onSlotClick,\n renderEvent,\n locale = \"pt-BR\",\n showCurrentTime = true,\n now,\n className,\n ...rest\n}: SchedulerProps) {\n const [clock, setClock] = useState<Date>(() => now ?? new Date());\n\n /**\n * Keep the current-time line moving.\n *\n * Skipped entirely when `now` is supplied: that is the hook tests and demos use\n * to be deterministic, and a timer would fight it.\n */\n useEffect(() => {\n if (now || !showCurrentTime) return;\n const id = setInterval(() => setClock(new Date()), TICK_MS);\n return () => clearInterval(id);\n }, [now, showCurrentTime]);\n\n const reference = now ?? clock;\n\n const window = useMemo<DayWindow>(\n () => ({ startMinute: startHour * 60, endMinute: endHour * 60 }),\n [startHour, endHour],\n );\n\n /**\n * The calendar day the range starts from, as a stable string.\n *\n * `reference` ticks every minute when the current-time line is live. Depending on\n * the Date itself would re-slice the day range — and therefore relayout every\n * event — once a minute; depending on the day only recomputes at midnight.\n */\n const anchorDay = (anchor ?? reference).toDateString();\n const dayList = useMemo(() => dayRange(new Date(anchorDay), dayCount), [anchorDay, dayCount]);\n\n const placed = useMemo(\n () => layoutEvents({ events, days: dayList, window }),\n [events, dayList, window],\n );\n const allDay = useMemo(() => layoutAllDay({ events, days: dayList }), [events, dayList]);\n const marks = useMemo(() => hourMarks(window), [window]);\n\n const dayLabel = new Intl.DateTimeFormat(locale, { weekday: \"short\", day: \"numeric\" });\n const timeLabel = new Intl.DateTimeFormat(locale, { hour: \"2-digit\", minute: \"2-digit\" });\n\n /** Turn a click's vertical position within a day column into a snapped instant. */\n const slotFromClick = (day: Date, event: React.MouseEvent<HTMLDivElement>): Date => {\n const rect = event.currentTarget.getBoundingClientRect();\n const fraction = rect.height > 0 ? (event.clientY - rect.top) / rect.height : 0;\n const raw = window.startMinute + fraction * (window.endMinute - window.startMinute);\n const snapped = Math.round(raw / snapMinutes) * snapMinutes;\n const clamped = Math.max(window.startMinute, Math.min(window.endMinute, snapped));\n const result = new Date(day);\n result.setHours(0, clamped, 0, 0);\n return result;\n };\n\n const currentFraction = showCurrentTime ? fractionOfWindow(reference, window) : null;\n const todayIndex = dayList.findIndex((day) => isSameDay(day, reference));\n\n return (\n <div className={cn(styles.wrapper, className)} {...rest}>\n <div\n className={styles.head}\n style={{ [\"--tempest-scheduler-days\" as string]: dayCount }}\n >\n <span className={styles.gutterHead} />\n {dayList.map((day, index) => (\n <span\n key={day.toISOString()}\n className={cn(styles.dayHead, index === todayIndex && styles.today)}\n >\n {dayLabel.format(day)}\n </span>\n ))}\n </div>\n\n {allDay.length > 0 && (\n <div\n className={styles.allDayLane}\n style={{ [\"--tempest-scheduler-days\" as string]: dayCount }}\n >\n <span className={styles.gutterHead}>Dia inteiro</span>\n <div className={styles.allDayTrack}>\n {allDay.map(({ event, dayIndex, span }) => (\n <button\n key={event.id}\n type=\"button\"\n className={styles.allDayEvent}\n style={{ gridColumn: `${dayIndex + 1} / span ${span}` }}\n onClick={() => onEventClick?.(event)}\n disabled={!onEventClick}\n >\n {event.title}\n </button>\n ))}\n </div>\n </div>\n )}\n\n {/*\n * Focusable because it scrolls vertically: a scroll region that cannot be\n * focused is unreachable by keyboard, which is what `axe`'s\n * `scrollable-region-focusable` rule is about. It needs a name too, or the\n * new tab stop would announce nothing — but `group`, not `region`: a named\n * `region` is a landmark, and two schedulers on one page would then be two\n * identically-named landmarks (`landmark-unique`).\n */}\n <div\n className={styles.body}\n style={{ [\"--tempest-scheduler-days\" as string]: dayCount }}\n tabIndex={0}\n role=\"group\"\n aria-label=\"Grade de horários\"\n >\n <div className={styles.gutter}>\n {marks.map((minute) => (\n <span\n key={minute}\n className={styles.hourLabel}\n style={{\n top: `${((minute - window.startMinute) / (window.endMinute - window.startMinute)) * 100}%`,\n }}\n >\n {timeLabel.format(\n new Date(2026, 0, 1, Math.floor(minute / 60), minute % 60),\n )}\n </span>\n ))}\n </div>\n\n {/*\n * Not `role=\"grid\"`: that requires `row` children, and the events are\n * siblings of the day columns inside one CSS grid — a `row` wrapper\n * would stop the columns being grid items and collapse the layout.\n * A labelled group per day is the honest structure anyway: a screen\n * reader tabs the event buttons and the group name supplies the day.\n */}\n <div className={styles.grid} aria-label=\"Agenda\">\n {dayList.map((day, index) => (\n <div\n key={day.toISOString()}\n className={cn(\n styles.dayColumn,\n index === todayIndex && styles.todayColumn,\n )}\n role=\"group\"\n aria-label={dayLabel.format(day)}\n onClick={\n onSlotClick\n ? (event) => {\n // Only empty space creates: a click that\n // landed on an event is that event's.\n if (event.target !== event.currentTarget) return;\n onSlotClick(slotFromClick(day, event));\n }\n : undefined\n }\n >\n {marks.map((minute) => (\n <span\n key={minute}\n className={styles.hourLine}\n style={{\n top: `${((minute - window.startMinute) / (window.endMinute - window.startMinute)) * 100}%`,\n }}\n />\n ))}\n </div>\n ))}\n\n {placed.map((item) => (\n <button\n key={`${item.event.id}-${item.dayIndex}`}\n type=\"button\"\n className={styles.event}\n style={{\n gridColumn: `${item.dayIndex + 1} / span 1`,\n top: `${item.top * 100}%`,\n height: `${item.height * 100}%`,\n left: `${(item.column / item.columns) * 100}%`,\n width: `${(1 / item.columns) * 100}%`,\n }}\n onClick={() => onEventClick?.(item.event)}\n disabled={!onEventClick}\n title={`${item.event.title} — ${timeLabel.format(item.event.start)}`}\n >\n {renderEvent ? (\n renderEvent(item.event)\n ) : (\n <>\n <span className={styles.eventTime}>\n {timeLabel.format(item.event.start)}\n </span>\n <span className={styles.eventTitle}>{item.event.title}</span>\n </>\n )}\n </button>\n ))}\n\n {currentFraction !== null && todayIndex >= 0 && (\n <span\n className={styles.nowLine}\n style={{ top: `${currentFraction * 100}%` }}\n aria-hidden\n data-testid=\"scheduler-now\"\n />\n )}\n </div>\n </div>\n </div>\n );\n}\n\nexport type { SchedulerEvent };\n"],"mappings":";;;;;;AAmDA,IAAM,IAAU;AA6BhB,SAAgB,EAAU,EACtB,WACA,WACA,MAAM,IAAW,GACjB,eAAY,GACZ,aAAU,IACV,iBAAc,IACd,iBACA,gBACA,gBACA,YAAS,SACT,qBAAkB,IAClB,QACA,cACA,GAAG,KACY;CACf,IAAM,CAAC,GAAO,KAAY,QAAqB,qBAAO,IAAI,KAAK,CAAC;CAQhE,QAAgB;EACZ,IAAI,KAAO,CAAC,GAAiB;EAC7B,IAAM,IAAK,kBAAkB,kBAAS,IAAI,KAAK,CAAC,GAAG,CAAO;EAC1D,aAAa,cAAc,CAAE;CACjC,GAAG,CAAC,GAAK,CAAe,CAAC;CAEzB,IAAM,IAAY,KAAO,GAEnB,IAAS,SACJ;EAAE,aAAa,IAAY;EAAI,WAAW,IAAU;CAAG,IAC9D,CAAC,GAAW,CAAO,CACvB,GASM,KAAa,KAAU,EAAA,CAAW,aAAa,GAC/C,IAAU,QAAc,EAAS,IAAI,KAAK,CAAS,GAAG,CAAQ,GAAG,CAAC,GAAW,CAAQ,CAAC,GAEtF,IAAS,QACL,EAAa;EAAE;EAAQ,MAAM;EAAS;CAAO,CAAC,GACpD;EAAC;EAAQ;EAAS;CAAM,CAC5B,GACM,IAAS,QAAc,EAAa;EAAE;EAAQ,MAAM;CAAQ,CAAC,GAAG,CAAC,GAAQ,CAAO,CAAC,GACjF,IAAQ,QAAc,EAAU,CAAM,GAAG,CAAC,CAAM,CAAC,GAEjD,IAAW,IAAI,KAAK,eAAe,GAAQ;EAAE,SAAS;EAAS,KAAK;CAAU,CAAC,GAC/E,IAAY,IAAI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I;QACvB,QAAQ,GAAG,EAAK,SAAS,IAAI;QAC7B,MAAM,GAAI,EAAK,SAAS,EAAK,UAAW,IAAI;QAC5C,OAAO,GAAI,IAAI,EAAK,UAAW,IAAI;OACvC;OACA,eAAe,IAAe,EAAK,KAAK;OACxC,UAAU,CAAC;OACX,OAAO,GAAG,EAAK,MAAM,MAAM,KAAK,EAAU,OAAO,EAAK,MAAM,KAAK;OAEhE,UAAA,IACG,EAAY,EAAK,KAAK,IAEtB,kBAAA,GAAA,EAAA,UAAA,CACI,kBAAC,QAAD;QAAM,WAAW,EAAO;QACnB,UAAA,EAAU,OAAO,EAAK,MAAM,KAAK;OAChC,CAAA,GACN,kBAAC,QAAD;QAAM,WAAW,EAAO;QAAa,UAAA,EAAK,MAAM;OAAY,CAAA,CAC9D,EAAA,CAAA;MAEF,GAxBC,GAAG,EAAK,MAAM,GAAG,GAAG,EAAK,UAwB1B,CACX;MAEA,MAAoB,QAAQ,KAAc,KACvC,kBAAC,QAAD;OACI,WAAW,EAAO;OAClB,OAAO,EAAE,KAAK,GAAG,IAAkB,IAAI,GAAG;OAC1C,eAAA;OACA,eAAY;MACf,CAAA;KAEJ;IACJ,CAAA,CAAA;;EACJ;;AAEb"}
@@ -1 +1 @@
1
- {"version":3,"file":"Scheduler.module.cjs","names":[],"sources":["../../../src/components/Scheduler/Scheduler.module.css"],"sourcesContent":[".wrapper {\n /*\n * Column widths are declared once here and reused by the header, the all-day\n * lane and the grid — three separate grids that have to line up exactly, and\n * would drift the moment any of them computed its own tracks.\n */\n --tempest-scheduler-gutter: 3.5rem;\n --tempest-scheduler-height: 32rem;\n\n display: flex;\n flex-direction: column;\n width: 100%;\n border: 1px solid var(--tempest-border);\n border-radius: var(--tempest-radius-lg);\n background-color: var(--tempest-bg);\n font-family: var(--tempest-font-sans);\n overflow: hidden;\n}\n\n.head,\n.allDayLane {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) repeat(\n var(--tempest-scheduler-days),\n minmax(0, 1fr)\n );\n border-bottom: 1px solid var(--tempest-border);\n background-color: var(--tempest-surface);\n}\n\n.dayHead {\n padding: var(--tempest-space-2);\n text-align: center;\n color: var(--tempest-text-muted);\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-semibold);\n letter-spacing: var(--tempest-tracking-wide);\n text-transform: capitalize;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayHead.today {\n color: var(--tempest-primary);\n}\n\n.gutterHead {\n padding: var(--tempest-space-2);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n text-align: right;\n}\n\n.allDayTrack {\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n grid-column: 2 / -1;\n gap: 2px;\n padding: 2px;\n}\n\n.allDayEvent {\n overflow: hidden;\n padding: 0 var(--tempest-space-2);\n border: none;\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-contrast, #fff);\n font: inherit;\n font-size: var(--tempest-text-xs);\n line-height: 1.5rem;\n text-align: left;\n text-overflow: ellipsis;\n white-space: nowrap;\n cursor: pointer;\n}\n\n.allDayEvent:disabled {\n cursor: default;\n}\n\n.body {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) 1fr;\n height: var(--tempest-scheduler-height);\n overflow-y: auto;\n}\n\n.gutter {\n position: relative;\n border-right: 1px solid var(--tempest-border);\n}\n\n.hourLabel {\n position: absolute;\n right: var(--tempest-space-1);\n /*\n * Nudged up by half a line so the label reads as sitting *on* its hour line\n * rather than hanging below it.\n */\n transform: translateY(-50%);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.grid {\n position: relative;\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n}\n\n.dayColumn {\n position: relative;\n grid-row: 1;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayColumn:first-child {\n border-left: none;\n}\n\n.todayColumn {\n background-color: var(--tempest-surface);\n}\n\n.hourLine {\n position: absolute;\n left: 0;\n right: 0;\n border-top: 1px solid var(--tempest-border);\n pointer-events: none;\n}\n\n/*\n * Events live in the same grid as the day columns, one row deep, positioned inside\n * their column by percentage. Being siblings of the columns rather than children is\n * what lets an event overlay the hour lines without clipping.\n */\n.event {\n position: absolute;\n grid-row: 1;\n display: flex;\n flex-direction: column;\n gap: 1px;\n overflow: hidden;\n padding: 2px var(--tempest-space-1);\n border: 1px solid var(--tempest-bg);\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-contrast, #fff);\n font: inherit;\n text-align: left;\n cursor: pointer;\n}\n\n.event:disabled {\n cursor: default;\n}\n\n.event:focus-visible {\n outline: 2px solid var(--tempest-text);\n outline-offset: -2px;\n}\n\n/*\n * No `opacity` here, deliberately. Dimming the time to signal it as secondary drops\n * it below the AA contrast threshold against the event fill — the browser `axe` sweep\n * caught exactly that (jsdom cannot, since it does not paint). The hierarchy comes\n * from size and weight instead, which cost nothing in contrast.\n */\n.eventTime {\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.eventTitle {\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-medium);\n line-height: var(--tempest-leading-snug);\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.nowLine {\n position: absolute;\n left: 0;\n right: 0;\n grid-row: 1;\n grid-column: 1 / -1;\n height: 0;\n border-top: 2px solid var(--tempest-danger, #dc2626);\n pointer-events: none;\n z-index: 1;\n}\n\n@media (max-width: 640px) {\n .wrapper {\n --tempest-scheduler-gutter: 2.75rem;\n }\n\n .dayHead {\n font-size: 0.625rem;\n padding: var(--tempest-space-1);\n }\n}\n"],"mappings":""}
1
+ {"version":3,"file":"Scheduler.module.cjs","names":[],"sources":["../../../src/components/Scheduler/Scheduler.module.css"],"sourcesContent":[".wrapper {\n /*\n * Column widths are declared once here and reused by the header, the all-day\n * lane and the grid — three separate grids that have to line up exactly, and\n * would drift the moment any of them computed its own tracks.\n */\n --tempest-scheduler-gutter: 3.5rem;\n --tempest-scheduler-height: 32rem;\n\n display: flex;\n flex-direction: column;\n width: 100%;\n border: 1px solid var(--tempest-border);\n border-radius: var(--tempest-radius-lg);\n background-color: var(--tempest-bg);\n font-family: var(--tempest-font-sans);\n overflow: hidden;\n}\n\n.head,\n.allDayLane {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) repeat(\n var(--tempest-scheduler-days),\n minmax(0, 1fr)\n );\n border-bottom: 1px solid var(--tempest-border);\n background-color: var(--tempest-surface);\n}\n\n.dayHead {\n padding: var(--tempest-space-2);\n text-align: center;\n color: var(--tempest-text-muted);\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-semibold);\n letter-spacing: var(--tempest-tracking-wide);\n text-transform: capitalize;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayHead.today {\n color: var(--tempest-primary);\n}\n\n.gutterHead {\n padding: var(--tempest-space-2);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n text-align: right;\n}\n\n.allDayTrack {\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n grid-column: 2 / -1;\n gap: 2px;\n padding: 2px;\n}\n\n.allDayEvent {\n overflow: hidden;\n padding: 0 var(--tempest-space-2);\n border: none;\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-contrast, #fff);\n font: inherit;\n font-size: var(--tempest-text-xs);\n line-height: 1.5rem;\n text-align: left;\n text-overflow: ellipsis;\n white-space: nowrap;\n cursor: pointer;\n}\n\n.allDayEvent:disabled {\n cursor: default;\n}\n\n.body {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) 1fr;\n height: var(--tempest-scheduler-height);\n overflow-y: auto;\n}\n\n.gutter {\n position: relative;\n border-right: 1px solid var(--tempest-border);\n}\n\n.hourLabel {\n position: absolute;\n right: var(--tempest-space-1);\n /*\n * Nudged up by half a line so the label reads as sitting *on* its hour line\n * rather than hanging below it.\n */\n transform: translateY(-50%);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.grid {\n position: relative;\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n}\n\n.dayColumn {\n position: relative;\n grid-row: 1;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayColumn:first-child {\n border-left: none;\n}\n\n.todayColumn {\n background-color: var(--tempest-surface);\n}\n\n.hourLine {\n position: absolute;\n left: 0;\n right: 0;\n border-top: 1px solid var(--tempest-border);\n pointer-events: none;\n}\n\n/*\n * Events live in the same grid as the day columns, one row deep, positioned inside\n * their column by percentage. Being siblings of the columns rather than children is\n * what lets an event overlay the hour lines without clipping.\n */\n/*\n * Absolutely positioned, so the inline `grid-column` it is placed with must name\n * BOTH lines. For an abspos child of a grid container an `auto` side does not\n * mean \"span 1\" — CSS Grid §9.2 resolves it to the container's padding edge, so\n * a bare `grid-column: 3` runs from column 3 to the end of the week and every\n * event covers the whole view. A one-day scheduler hides it: there, \"column 1 to\n * the edge\" happens to be one column. Hence `N / span 1` in Scheduler.tsx.\n */\n.event {\n position: absolute;\n grid-row: 1;\n display: flex;\n flex-direction: column;\n gap: 1px;\n overflow: hidden;\n padding: 2px var(--tempest-space-1);\n border: 1px solid var(--tempest-bg);\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-contrast, #fff);\n font: inherit;\n text-align: left;\n cursor: pointer;\n}\n\n.event:disabled {\n cursor: default;\n}\n\n.event:focus-visible {\n outline: 2px solid var(--tempest-text);\n outline-offset: -2px;\n}\n\n/*\n * No `opacity` here, deliberately. Dimming the time to signal it as secondary drops\n * it below the AA contrast threshold against the event fill — the browser `axe` sweep\n * caught exactly that (jsdom cannot, since it does not paint). The hierarchy comes\n * from size and weight instead, which cost nothing in contrast.\n */\n.eventTime {\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.eventTitle {\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-medium);\n line-height: var(--tempest-leading-snug);\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.nowLine {\n position: absolute;\n left: 0;\n right: 0;\n grid-row: 1;\n grid-column: 1 / -1;\n height: 0;\n border-top: 2px solid var(--tempest-danger, #dc2626);\n pointer-events: none;\n z-index: 1;\n}\n\n@media (max-width: 640px) {\n .wrapper {\n --tempest-scheduler-gutter: 2.75rem;\n }\n\n .dayHead {\n font-size: 0.625rem;\n padding: var(--tempest-space-1);\n }\n}\n"],"mappings":""}
@@ -1 +1 @@
1
- {"version":3,"file":"Scheduler.module.js","names":[],"sources":["../../../src/components/Scheduler/Scheduler.module.css"],"sourcesContent":[".wrapper {\n /*\n * Column widths are declared once here and reused by the header, the all-day\n * lane and the grid — three separate grids that have to line up exactly, and\n * would drift the moment any of them computed its own tracks.\n */\n --tempest-scheduler-gutter: 3.5rem;\n --tempest-scheduler-height: 32rem;\n\n display: flex;\n flex-direction: column;\n width: 100%;\n border: 1px solid var(--tempest-border);\n border-radius: var(--tempest-radius-lg);\n background-color: var(--tempest-bg);\n font-family: var(--tempest-font-sans);\n overflow: hidden;\n}\n\n.head,\n.allDayLane {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) repeat(\n var(--tempest-scheduler-days),\n minmax(0, 1fr)\n );\n border-bottom: 1px solid var(--tempest-border);\n background-color: var(--tempest-surface);\n}\n\n.dayHead {\n padding: var(--tempest-space-2);\n text-align: center;\n color: var(--tempest-text-muted);\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-semibold);\n letter-spacing: var(--tempest-tracking-wide);\n text-transform: capitalize;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayHead.today {\n color: var(--tempest-primary);\n}\n\n.gutterHead {\n padding: var(--tempest-space-2);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n text-align: right;\n}\n\n.allDayTrack {\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n grid-column: 2 / -1;\n gap: 2px;\n padding: 2px;\n}\n\n.allDayEvent {\n overflow: hidden;\n padding: 0 var(--tempest-space-2);\n border: none;\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-contrast, #fff);\n font: inherit;\n font-size: var(--tempest-text-xs);\n line-height: 1.5rem;\n text-align: left;\n text-overflow: ellipsis;\n white-space: nowrap;\n cursor: pointer;\n}\n\n.allDayEvent:disabled {\n cursor: default;\n}\n\n.body {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) 1fr;\n height: var(--tempest-scheduler-height);\n overflow-y: auto;\n}\n\n.gutter {\n position: relative;\n border-right: 1px solid var(--tempest-border);\n}\n\n.hourLabel {\n position: absolute;\n right: var(--tempest-space-1);\n /*\n * Nudged up by half a line so the label reads as sitting *on* its hour line\n * rather than hanging below it.\n */\n transform: translateY(-50%);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.grid {\n position: relative;\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n}\n\n.dayColumn {\n position: relative;\n grid-row: 1;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayColumn:first-child {\n border-left: none;\n}\n\n.todayColumn {\n background-color: var(--tempest-surface);\n}\n\n.hourLine {\n position: absolute;\n left: 0;\n right: 0;\n border-top: 1px solid var(--tempest-border);\n pointer-events: none;\n}\n\n/*\n * Events live in the same grid as the day columns, one row deep, positioned inside\n * their column by percentage. Being siblings of the columns rather than children is\n * what lets an event overlay the hour lines without clipping.\n */\n.event {\n position: absolute;\n grid-row: 1;\n display: flex;\n flex-direction: column;\n gap: 1px;\n overflow: hidden;\n padding: 2px var(--tempest-space-1);\n border: 1px solid var(--tempest-bg);\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-contrast, #fff);\n font: inherit;\n text-align: left;\n cursor: pointer;\n}\n\n.event:disabled {\n cursor: default;\n}\n\n.event:focus-visible {\n outline: 2px solid var(--tempest-text);\n outline-offset: -2px;\n}\n\n/*\n * No `opacity` here, deliberately. Dimming the time to signal it as secondary drops\n * it below the AA contrast threshold against the event fill — the browser `axe` sweep\n * caught exactly that (jsdom cannot, since it does not paint). The hierarchy comes\n * from size and weight instead, which cost nothing in contrast.\n */\n.eventTime {\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.eventTitle {\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-medium);\n line-height: var(--tempest-leading-snug);\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.nowLine {\n position: absolute;\n left: 0;\n right: 0;\n grid-row: 1;\n grid-column: 1 / -1;\n height: 0;\n border-top: 2px solid var(--tempest-danger, #dc2626);\n pointer-events: none;\n z-index: 1;\n}\n\n@media (max-width: 640px) {\n .wrapper {\n --tempest-scheduler-gutter: 2.75rem;\n }\n\n .dayHead {\n font-size: 0.625rem;\n padding: var(--tempest-space-1);\n }\n}\n"],"mappings":""}
1
+ {"version":3,"file":"Scheduler.module.js","names":[],"sources":["../../../src/components/Scheduler/Scheduler.module.css"],"sourcesContent":[".wrapper {\n /*\n * Column widths are declared once here and reused by the header, the all-day\n * lane and the grid — three separate grids that have to line up exactly, and\n * would drift the moment any of them computed its own tracks.\n */\n --tempest-scheduler-gutter: 3.5rem;\n --tempest-scheduler-height: 32rem;\n\n display: flex;\n flex-direction: column;\n width: 100%;\n border: 1px solid var(--tempest-border);\n border-radius: var(--tempest-radius-lg);\n background-color: var(--tempest-bg);\n font-family: var(--tempest-font-sans);\n overflow: hidden;\n}\n\n.head,\n.allDayLane {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) repeat(\n var(--tempest-scheduler-days),\n minmax(0, 1fr)\n );\n border-bottom: 1px solid var(--tempest-border);\n background-color: var(--tempest-surface);\n}\n\n.dayHead {\n padding: var(--tempest-space-2);\n text-align: center;\n color: var(--tempest-text-muted);\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-semibold);\n letter-spacing: var(--tempest-tracking-wide);\n text-transform: capitalize;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayHead.today {\n color: var(--tempest-primary);\n}\n\n.gutterHead {\n padding: var(--tempest-space-2);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n text-align: right;\n}\n\n.allDayTrack {\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n grid-column: 2 / -1;\n gap: 2px;\n padding: 2px;\n}\n\n.allDayEvent {\n overflow: hidden;\n padding: 0 var(--tempest-space-2);\n border: none;\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-contrast, #fff);\n font: inherit;\n font-size: var(--tempest-text-xs);\n line-height: 1.5rem;\n text-align: left;\n text-overflow: ellipsis;\n white-space: nowrap;\n cursor: pointer;\n}\n\n.allDayEvent:disabled {\n cursor: default;\n}\n\n.body {\n display: grid;\n grid-template-columns: var(--tempest-scheduler-gutter) 1fr;\n height: var(--tempest-scheduler-height);\n overflow-y: auto;\n}\n\n.gutter {\n position: relative;\n border-right: 1px solid var(--tempest-border);\n}\n\n.hourLabel {\n position: absolute;\n right: var(--tempest-space-1);\n /*\n * Nudged up by half a line so the label reads as sitting *on* its hour line\n * rather than hanging below it.\n */\n transform: translateY(-50%);\n color: var(--tempest-text-muted);\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.grid {\n position: relative;\n display: grid;\n grid-template-columns: repeat(var(--tempest-scheduler-days), minmax(0, 1fr));\n}\n\n.dayColumn {\n position: relative;\n grid-row: 1;\n border-left: 1px solid var(--tempest-border);\n}\n\n.dayColumn:first-child {\n border-left: none;\n}\n\n.todayColumn {\n background-color: var(--tempest-surface);\n}\n\n.hourLine {\n position: absolute;\n left: 0;\n right: 0;\n border-top: 1px solid var(--tempest-border);\n pointer-events: none;\n}\n\n/*\n * Events live in the same grid as the day columns, one row deep, positioned inside\n * their column by percentage. Being siblings of the columns rather than children is\n * what lets an event overlay the hour lines without clipping.\n */\n/*\n * Absolutely positioned, so the inline `grid-column` it is placed with must name\n * BOTH lines. For an abspos child of a grid container an `auto` side does not\n * mean \"span 1\" — CSS Grid §9.2 resolves it to the container's padding edge, so\n * a bare `grid-column: 3` runs from column 3 to the end of the week and every\n * event covers the whole view. A one-day scheduler hides it: there, \"column 1 to\n * the edge\" happens to be one column. Hence `N / span 1` in Scheduler.tsx.\n */\n.event {\n position: absolute;\n grid-row: 1;\n display: flex;\n flex-direction: column;\n gap: 1px;\n overflow: hidden;\n padding: 2px var(--tempest-space-1);\n border: 1px solid var(--tempest-bg);\n border-radius: var(--tempest-radius-sm);\n background-color: var(--tempest-primary);\n color: var(--tempest-primary-contrast, #fff);\n font: inherit;\n text-align: left;\n cursor: pointer;\n}\n\n.event:disabled {\n cursor: default;\n}\n\n.event:focus-visible {\n outline: 2px solid var(--tempest-text);\n outline-offset: -2px;\n}\n\n/*\n * No `opacity` here, deliberately. Dimming the time to signal it as secondary drops\n * it below the AA contrast threshold against the event fill — the browser `axe` sweep\n * caught exactly that (jsdom cannot, since it does not paint). The hierarchy comes\n * from size and weight instead, which cost nothing in contrast.\n */\n.eventTime {\n font-size: 0.625rem;\n font-variant-numeric: tabular-nums;\n}\n\n.eventTitle {\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-medium);\n line-height: var(--tempest-leading-snug);\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.nowLine {\n position: absolute;\n left: 0;\n right: 0;\n grid-row: 1;\n grid-column: 1 / -1;\n height: 0;\n border-top: 2px solid var(--tempest-danger, #dc2626);\n pointer-events: none;\n z-index: 1;\n}\n\n@media (max-width: 640px) {\n .wrapper {\n --tempest-scheduler-gutter: 2.75rem;\n }\n\n .dayHead {\n font-size: 0.625rem;\n padding: var(--tempest-space-1);\n }\n}\n"],"mappings":""}
@@ -1,2 +1,2 @@
1
- const e=require("./errors.cjs");var t={offline:`Sem conexão com o servidor. Verifique sua internet e tente de novo.`,validation:`Confira os campos destacados e tente de novo.`},n=`tempest.error.offline`,r=`tempest.error.validation`;function i(){return typeof navigator<`u`&&navigator.onLine===!1}function a(n,r,a){let o=a?.offline??t.offline;if(e.isApiError(n)){if(n.status===0)return o;if(n.fields&&Object.keys(n.fields).length>0)return a?.validation??t.validation;let i=n.detail.trim();return i!==``&&i!==e.syntheticDetail(n.status)?i:`${r} (HTTP ${n.status})`}return i()?o:r}exports.API_ERROR_OFFLINE_KEY=n,exports.API_ERROR_VALIDATION_KEY=r,exports.DEFAULT_API_ERROR_STRINGS=t,exports.describeApiError=a;
1
+ const e=require("./errors.cjs");var t={offline:`Sem conexão com o servidor. Verifique sua internet e tente de novo.`,validation:`Confira os campos destacados e tente de novo.`},n=`tempest.error.offline`,r=`tempest.error.validation`;function i(){return typeof navigator<`u`&&navigator.onLine===!1}function a(n,r,a){let o=a?.offline??t.offline;if(e.isApiError(n)){let i=n.code===void 0?void 0:a?.codes?.[n.code];if(i!==void 0)return i;if(n.status===0)return o;if(n.fields&&Object.keys(n.fields).length>0)return a?.validation??t.validation;let s=n.detail.trim();return a?.useDetail!==!1&&s!==``&&s!==e.syntheticDetail(n.status)?s:`${r} (HTTP ${n.status})`}return i()?o:r}exports.API_ERROR_OFFLINE_KEY=n,exports.API_ERROR_VALIDATION_KEY=r,exports.DEFAULT_API_ERROR_STRINGS=t,exports.describeApiError=a;
2
2
  //# sourceMappingURL=describe-api-error.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"describe-api-error.cjs","names":[],"sources":["../../src/http/describe-api-error.ts"],"sourcesContent":["// The last mile of error handling: a typed error is what code reads, a sentence\n// is what a person reads, and every app was writing the funnel between the two.\n// The case everyone forgets is the request that never reached the server, which\n// without special handling renders as the nonsense \"erro 0\".\n\nimport { isApiError, syntheticDetail } from \"./errors\";\n\n/** The fixed sentences {@link describeApiError} may need. */\nexport interface ApiErrorStrings {\n /** Shown when the request never reached the server. */\n offline: string;\n /**\n * Shown when the backend rejected the payload field by field.\n *\n * The per-field messages are on `error.fields`, to be attached to the inputs\n * themselves; this sentence is what the toast says.\n */\n validation: string;\n}\n\n/**\n * PT-BR defaults, used when no strings are supplied and no catalog answers.\n *\n * The SDK's copy is pt-BR everywhere else (`FilterBar`, `DataTable`, `Chat`), so\n * the default here matches rather than introducing an English string that only\n * shows up on a network failure.\n */\nexport const DEFAULT_API_ERROR_STRINGS: ApiErrorStrings = {\n offline: \"Sem conexão com o servidor. Verifique sua internet e tente de novo.\",\n validation: \"Confira os campos destacados e tente de novo.\",\n};\n\n/**\n * Translation key the {@link useDescribeApiError} hook looks up.\n *\n * A catalog that does not define it falls back to\n * {@link DEFAULT_API_ERROR_STRINGS}, because `t` returns the key itself when the\n * lookup misses and printing `tempest.error.offline` at the user would be worse\n * than printing pt-BR at them.\n */\nexport const API_ERROR_OFFLINE_KEY = \"tempest.error.offline\";\n\n/**\n * Translation key for the validation sentence, looked up the same way as\n * {@link API_ERROR_OFFLINE_KEY}.\n */\nexport const API_ERROR_VALIDATION_KEY = \"tempest.error.validation\";\n\n/**\n * Whether the browser currently reports itself as offline.\n *\n * `fetch` rejects a network failure with a plain `TypeError` whose message\n * differs per browser (\"Failed to fetch\", \"NetworkError when attempting to fetch\n * resource.\", \"Load failed\"), so sniffing the message is not portable. The online\n * flag is, and it is the signal that matters for the sentence being chosen.\n *\n * @returns `true` only when the environment positively says it is offline.\n */\nfunction browserIsOffline(): boolean {\n return typeof navigator !== \"undefined\" && navigator.onLine === false;\n}\n\n/**\n * Turn any caught value into a sentence worth showing.\n *\n * The funnel, in order:\n *\n * 1. A request that never reached the server — `status === 0`, or a non-API\n * error thrown while the browser reports itself offline — produces the\n * offline sentence. This is the step apps skip, and skipping it renders\n * \"erro 0\" or a raw `TypeError` at the user.\n * 2. A validation rejection — `error.fields` is set — produces the validation\n * sentence, **not** `detail`. On a `422` the `detail` line is assembled from\n * the backend's field paths and the validator's own wording\n * (`\"items.0.price: Input should be greater than 0\"`), which is right for a\n * log and wrong for a person: it is half English in a pt-BR screen and it\n * names internals. The per-field messages stay on `fields`, where a form can\n * attach them to the inputs that failed.\n * 3. The backend's own `detail`, which is the most specific thing available and\n * is already written for a person.\n * 4. `fallback`, with `(HTTP <status>)` appended when a status is known, so the\n * screenshot in the support ticket carries the one fact a developer needs.\n *\n * Pure on purpose: it works in an interceptor, in a logger and anywhere outside\n * the React tree. {@link useDescribeApiError} is the same funnel with the\n * sentences resolved through `I18nProvider`.\n *\n * @example\n * catch (error) {\n * toast(describeApiError(error, \"Não foi possível salvar o pedido\"));\n * }\n *\n * @param error - The caught value, of any shape.\n * @param fallback - What to say when the error carries nothing better.\n * @param strings - Overrides for the fixed sentences.\n * @returns A sentence to show the user.\n */\nexport function describeApiError(\n error: unknown,\n fallback: string,\n strings?: Partial<ApiErrorStrings>,\n): string {\n const offline = strings?.offline ?? DEFAULT_API_ERROR_STRINGS.offline;\n\n if (isApiError(error)) {\n if (error.status === 0) return offline;\n if (error.fields && Object.keys(error.fields).length > 0) {\n return strings?.validation ?? DEFAULT_API_ERROR_STRINGS.validation;\n }\n const detail = error.detail.trim();\n if (detail !== \"\" && detail !== syntheticDetail(error.status)) return detail;\n return `${fallback} (HTTP ${error.status})`;\n }\n\n if (browserIsOffline()) return offline;\n\n return fallback;\n}\n"],"mappings":"gCA2BA,IAAa,EAA6C,CACtD,QAAS,sEACT,WAAY,+CAChB,EAUa,EAAwB,wBAMxB,EAA2B,2BAYxC,SAAS,GAA4B,CACjC,OAAO,OAAO,UAAc,KAAe,UAAU,SAAW,EACpE,CAqCA,SAAgB,EACZ,EACA,EACA,EACM,CACN,IAAM,EAAU,GAAS,SAAW,EAA0B,QAE9D,GAAI,EAAA,WAAW,CAAK,EAAG,CACnB,GAAI,EAAM,SAAW,EAAG,OAAO,EAC/B,GAAI,EAAM,QAAU,OAAO,KAAK,EAAM,MAAM,CAAC,CAAC,OAAS,EACnD,OAAO,GAAS,YAAc,EAA0B,WAE5D,IAAM,EAAS,EAAM,OAAO,KAAK,EAEjC,OADI,IAAW,IAAM,IAAW,EAAA,gBAAgB,EAAM,MAAM,EAAU,EAC/D,GAAG,EAAS,SAAS,EAAM,OAAO,EAC7C,CAIA,OAFI,EAAiB,EAAU,EAExB,CACX"}
1
+ {"version":3,"file":"describe-api-error.cjs","names":[],"sources":["../../src/http/describe-api-error.ts"],"sourcesContent":["// The last mile of error handling: a typed error is what code reads, a sentence\n// is what a person reads, and every app was writing the funnel between the two.\n// The case everyone forgets is the request that never reached the server, which\n// without special handling renders as the nonsense \"erro 0\".\n\nimport { isApiError, syntheticDetail } from \"./errors\";\n\n/** The fixed sentences {@link describeApiError} may need. */\nexport interface ApiErrorStrings {\n /** Shown when the request never reached the server. */\n offline: string;\n /**\n * Shown when the backend rejected the payload field by field.\n *\n * The per-field messages are on `error.fields`, to be attached to the inputs\n * themselves; this sentence is what the toast says.\n */\n validation: string;\n}\n\n/**\n * PT-BR defaults, used when no strings are supplied and no catalog answers.\n *\n * The SDK's copy is pt-BR everywhere else (`FilterBar`, `DataTable`, `Chat`), so\n * the default here matches rather than introducing an English string that only\n * shows up on a network failure.\n */\nexport const DEFAULT_API_ERROR_STRINGS: ApiErrorStrings = {\n offline: \"Sem conexão com o servidor. Verifique sua internet e tente de novo.\",\n validation: \"Confira os campos destacados e tente de novo.\",\n};\n\n/**\n * Translation key the {@link useDescribeApiError} hook looks up.\n *\n * A catalog that does not define it falls back to\n * {@link DEFAULT_API_ERROR_STRINGS}, because `t` returns the key itself when the\n * lookup misses and printing `tempest.error.offline` at the user would be worse\n * than printing pt-BR at them.\n */\nexport const API_ERROR_OFFLINE_KEY = \"tempest.error.offline\";\n\n/**\n * Translation key for the validation sentence, looked up the same way as\n * {@link API_ERROR_OFFLINE_KEY}.\n */\nexport const API_ERROR_VALIDATION_KEY = \"tempest.error.validation\";\n\n/**\n * Everything {@link describeApiError} accepts beyond the error and the fallback.\n *\n * Extends the fixed sentences rather than sitting beside them, so a caller that\n * already passed `{ offline, validation }` keeps compiling untouched.\n */\nexport interface DescribeApiErrorOptions extends Partial<ApiErrorStrings> {\n /**\n * Maps the backend's programmatic `code` to a sentence in your language.\n *\n * The client already surfaces `code` on `ApiError`, but without this every\n * app writes the same `switch` over it. A hit here wins over every other\n * step: it is the only sentence written for that exact case, by someone who\n * knew both the backend contract and the screen it lands on.\n */\n codes?: Readonly<Record<string, string>>;\n /**\n * Whether the backend's `detail` may be shown when no `code` matched.\n * Default `true`.\n *\n * Set it to `false` when `detail` is written for developers rather than\n * users, or when it could echo internals — the result is then always either\n * a sentence you wrote or the fallback.\n */\n useDetail?: boolean;\n}\n\n/**\n * Whether the browser currently reports itself as offline.\n *\n * `fetch` rejects a network failure with a plain `TypeError` whose message\n * differs per browser (\"Failed to fetch\", \"NetworkError when attempting to fetch\n * resource.\", \"Load failed\"), so sniffing the message is not portable. The online\n * flag is, and it is the signal that matters for the sentence being chosen.\n *\n * @returns `true` only when the environment positively says it is offline.\n */\nfunction browserIsOffline(): boolean {\n return typeof navigator !== \"undefined\" && navigator.onLine === false;\n}\n\n/**\n * Turn any caught value into a sentence worth showing.\n *\n * The funnel, in order:\n *\n * 0. `codes[error.code]` — the sentence you wrote for that exact backend case.\n * Checked first because nothing the funnel derives can beat it, and because a\n * request that never landed carries no `code` for it to shadow.\n * 1. A request that never reached the server — `status === 0`, or a non-API\n * error thrown while the browser reports itself offline — produces the\n * offline sentence. This is the step apps skip, and skipping it renders\n * \"erro 0\" or a raw `TypeError` at the user.\n * 2. A validation rejection — `error.fields` is set — produces the validation\n * sentence, **not** `detail`. On a `422` the `detail` line is assembled from\n * the backend's field paths and the validator's own wording\n * (`\"items.0.price: Input should be greater than 0\"`), which is right for a\n * log and wrong for a person: it is half English in a pt-BR screen and it\n * names internals. The per-field messages stay on `fields`, where a form can\n * attach them to the inputs that failed.\n * 3. The backend's own `detail`, which is the most specific thing available and\n * is already written for a person — unless `useDetail: false` says that text\n * is for developers.\n * 4. `fallback`, with `(HTTP <status>)` appended when a status is known, so the\n * screenshot in the support ticket carries the one fact a developer needs.\n *\n * Pure on purpose: it works in an interceptor, in a logger and anywhere outside\n * the React tree. {@link useDescribeApiError} is the same funnel with the\n * sentences resolved through `I18nProvider`.\n *\n * @example\n * catch (error) {\n * toast(describeApiError(error, \"Não foi possível salvar o pedido\"));\n * }\n *\n * @example\n * catch (error) {\n * toast(\n * describeApiError(error, \"Não foi possível se candidatar\", {\n * codes: {\n * SERVICE_FULL: \"Este serviço atingiu o limite de vagas.\",\n * CANDIDATE_ALREADY_EXISTS: \"Você já se candidatou a este serviço.\",\n * },\n * useDetail: false,\n * }),\n * );\n * }\n *\n * @param error - The caught value, of any shape.\n * @param fallback - What to say when the error carries nothing better.\n * @param options - A `codes` catalog, `useDetail`, and overrides for the fixed\n * sentences.\n * @returns A sentence to show the user.\n */\nexport function describeApiError(\n error: unknown,\n fallback: string,\n options?: DescribeApiErrorOptions,\n): string {\n const offline = options?.offline ?? DEFAULT_API_ERROR_STRINGS.offline;\n\n if (isApiError(error)) {\n const mapped = error.code === undefined ? undefined : options?.codes?.[error.code];\n if (mapped !== undefined) return mapped;\n if (error.status === 0) return offline;\n if (error.fields && Object.keys(error.fields).length > 0) {\n return options?.validation ?? DEFAULT_API_ERROR_STRINGS.validation;\n }\n const detail = error.detail.trim();\n if (\n options?.useDetail !== false &&\n detail !== \"\" &&\n detail !== syntheticDetail(error.status)\n ) {\n return detail;\n }\n return `${fallback} (HTTP ${error.status})`;\n }\n\n if (browserIsOffline()) return offline;\n\n return fallback;\n}\n"],"mappings":"gCA2BA,IAAa,EAA6C,CACtD,QAAS,sEACT,WAAY,+CAChB,EAUa,EAAwB,wBAMxB,EAA2B,2BAuCxC,SAAS,GAA4B,CACjC,OAAO,OAAO,UAAc,KAAe,UAAU,SAAW,EACpE,CAuDA,SAAgB,EACZ,EACA,EACA,EACM,CACN,IAAM,EAAU,GAAS,SAAW,EAA0B,QAE9D,GAAI,EAAA,WAAW,CAAK,EAAG,CACnB,IAAM,EAAS,EAAM,OAAS,IAAA,GAAY,IAAA,GAAY,GAAS,QAAQ,EAAM,MAC7E,GAAI,IAAW,IAAA,GAAW,OAAO,EACjC,GAAI,EAAM,SAAW,EAAG,OAAO,EAC/B,GAAI,EAAM,QAAU,OAAO,KAAK,EAAM,MAAM,CAAC,CAAC,OAAS,EACnD,OAAO,GAAS,YAAc,EAA0B,WAE5D,IAAM,EAAS,EAAM,OAAO,KAAK,EAQjC,OANI,GAAS,YAAc,IACvB,IAAW,IACX,IAAW,EAAA,gBAAgB,EAAM,MAAM,EAEhC,EAEJ,GAAG,EAAS,SAAS,EAAM,OAAO,EAC7C,CAIA,OAFI,EAAiB,EAAU,EAExB,CACX"}
@@ -10,10 +10,12 @@ function a() {
10
10
  function o(r, i, o) {
11
11
  let s = o?.offline ?? n.offline;
12
12
  if (e(r)) {
13
+ let e = r.code === void 0 ? void 0 : o?.codes?.[r.code];
14
+ if (e !== void 0) return e;
13
15
  if (r.status === 0) return s;
14
16
  if (r.fields && Object.keys(r.fields).length > 0) return o?.validation ?? n.validation;
15
- let e = r.detail.trim();
16
- return e !== "" && e !== t(r.status) ? e : `${i} (HTTP ${r.status})`;
17
+ let a = r.detail.trim();
18
+ return o?.useDetail !== !1 && a !== "" && a !== t(r.status) ? a : `${i} (HTTP ${r.status})`;
17
19
  }
18
20
  return a() ? s : i;
19
21
  }
@@ -1 +1 @@
1
- {"version":3,"file":"describe-api-error.js","names":[],"sources":["../../src/http/describe-api-error.ts"],"sourcesContent":["// The last mile of error handling: a typed error is what code reads, a sentence\n// is what a person reads, and every app was writing the funnel between the two.\n// The case everyone forgets is the request that never reached the server, which\n// without special handling renders as the nonsense \"erro 0\".\n\nimport { isApiError, syntheticDetail } from \"./errors\";\n\n/** The fixed sentences {@link describeApiError} may need. */\nexport interface ApiErrorStrings {\n /** Shown when the request never reached the server. */\n offline: string;\n /**\n * Shown when the backend rejected the payload field by field.\n *\n * The per-field messages are on `error.fields`, to be attached to the inputs\n * themselves; this sentence is what the toast says.\n */\n validation: string;\n}\n\n/**\n * PT-BR defaults, used when no strings are supplied and no catalog answers.\n *\n * The SDK's copy is pt-BR everywhere else (`FilterBar`, `DataTable`, `Chat`), so\n * the default here matches rather than introducing an English string that only\n * shows up on a network failure.\n */\nexport const DEFAULT_API_ERROR_STRINGS: ApiErrorStrings = {\n offline: \"Sem conexão com o servidor. Verifique sua internet e tente de novo.\",\n validation: \"Confira os campos destacados e tente de novo.\",\n};\n\n/**\n * Translation key the {@link useDescribeApiError} hook looks up.\n *\n * A catalog that does not define it falls back to\n * {@link DEFAULT_API_ERROR_STRINGS}, because `t` returns the key itself when the\n * lookup misses and printing `tempest.error.offline` at the user would be worse\n * than printing pt-BR at them.\n */\nexport const API_ERROR_OFFLINE_KEY = \"tempest.error.offline\";\n\n/**\n * Translation key for the validation sentence, looked up the same way as\n * {@link API_ERROR_OFFLINE_KEY}.\n */\nexport const API_ERROR_VALIDATION_KEY = \"tempest.error.validation\";\n\n/**\n * Whether the browser currently reports itself as offline.\n *\n * `fetch` rejects a network failure with a plain `TypeError` whose message\n * differs per browser (\"Failed to fetch\", \"NetworkError when attempting to fetch\n * resource.\", \"Load failed\"), so sniffing the message is not portable. The online\n * flag is, and it is the signal that matters for the sentence being chosen.\n *\n * @returns `true` only when the environment positively says it is offline.\n */\nfunction browserIsOffline(): boolean {\n return typeof navigator !== \"undefined\" && navigator.onLine === false;\n}\n\n/**\n * Turn any caught value into a sentence worth showing.\n *\n * The funnel, in order:\n *\n * 1. A request that never reached the server — `status === 0`, or a non-API\n * error thrown while the browser reports itself offline — produces the\n * offline sentence. This is the step apps skip, and skipping it renders\n * \"erro 0\" or a raw `TypeError` at the user.\n * 2. A validation rejection — `error.fields` is set — produces the validation\n * sentence, **not** `detail`. On a `422` the `detail` line is assembled from\n * the backend's field paths and the validator's own wording\n * (`\"items.0.price: Input should be greater than 0\"`), which is right for a\n * log and wrong for a person: it is half English in a pt-BR screen and it\n * names internals. The per-field messages stay on `fields`, where a form can\n * attach them to the inputs that failed.\n * 3. The backend's own `detail`, which is the most specific thing available and\n * is already written for a person.\n * 4. `fallback`, with `(HTTP <status>)` appended when a status is known, so the\n * screenshot in the support ticket carries the one fact a developer needs.\n *\n * Pure on purpose: it works in an interceptor, in a logger and anywhere outside\n * the React tree. {@link useDescribeApiError} is the same funnel with the\n * sentences resolved through `I18nProvider`.\n *\n * @example\n * catch (error) {\n * toast(describeApiError(error, \"Não foi possível salvar o pedido\"));\n * }\n *\n * @param error - The caught value, of any shape.\n * @param fallback - What to say when the error carries nothing better.\n * @param strings - Overrides for the fixed sentences.\n * @returns A sentence to show the user.\n */\nexport function describeApiError(\n error: unknown,\n fallback: string,\n strings?: Partial<ApiErrorStrings>,\n): string {\n const offline = strings?.offline ?? DEFAULT_API_ERROR_STRINGS.offline;\n\n if (isApiError(error)) {\n if (error.status === 0) return offline;\n if (error.fields && Object.keys(error.fields).length > 0) {\n return strings?.validation ?? DEFAULT_API_ERROR_STRINGS.validation;\n }\n const detail = error.detail.trim();\n if (detail !== \"\" && detail !== syntheticDetail(error.status)) return detail;\n return `${fallback} (HTTP ${error.status})`;\n }\n\n if (browserIsOffline()) return offline;\n\n return fallback;\n}\n"],"mappings":";;AA2BA,IAAa,IAA6C;CACtD,SAAS;CACT,YAAY;AAChB,GAUa,IAAwB,yBAMxB,IAA2B;AAYxC,SAAS,IAA4B;CACjC,OAAO,OAAO,YAAc,OAAe,UAAU,WAAW;AACpE;AAqCA,SAAgB,EACZ,GACA,GACA,GACM;CACN,IAAM,IAAU,GAAS,WAAW,EAA0B;CAE9D,IAAI,EAAW,CAAK,GAAG;EACnB,IAAI,EAAM,WAAW,GAAG,OAAO;EAC/B,IAAI,EAAM,UAAU,OAAO,KAAK,EAAM,MAAM,CAAC,CAAC,SAAS,GACnD,OAAO,GAAS,cAAc,EAA0B;EAE5D,IAAM,IAAS,EAAM,OAAO,KAAK;EAEjC,OADI,MAAW,MAAM,MAAW,EAAgB,EAAM,MAAM,IAAU,IAC/D,GAAG,EAAS,SAAS,EAAM,OAAO;CAC7C;CAIA,OAFI,EAAiB,IAAU,IAExB;AACX"}
1
+ {"version":3,"file":"describe-api-error.js","names":[],"sources":["../../src/http/describe-api-error.ts"],"sourcesContent":["// The last mile of error handling: a typed error is what code reads, a sentence\n// is what a person reads, and every app was writing the funnel between the two.\n// The case everyone forgets is the request that never reached the server, which\n// without special handling renders as the nonsense \"erro 0\".\n\nimport { isApiError, syntheticDetail } from \"./errors\";\n\n/** The fixed sentences {@link describeApiError} may need. */\nexport interface ApiErrorStrings {\n /** Shown when the request never reached the server. */\n offline: string;\n /**\n * Shown when the backend rejected the payload field by field.\n *\n * The per-field messages are on `error.fields`, to be attached to the inputs\n * themselves; this sentence is what the toast says.\n */\n validation: string;\n}\n\n/**\n * PT-BR defaults, used when no strings are supplied and no catalog answers.\n *\n * The SDK's copy is pt-BR everywhere else (`FilterBar`, `DataTable`, `Chat`), so\n * the default here matches rather than introducing an English string that only\n * shows up on a network failure.\n */\nexport const DEFAULT_API_ERROR_STRINGS: ApiErrorStrings = {\n offline: \"Sem conexão com o servidor. Verifique sua internet e tente de novo.\",\n validation: \"Confira os campos destacados e tente de novo.\",\n};\n\n/**\n * Translation key the {@link useDescribeApiError} hook looks up.\n *\n * A catalog that does not define it falls back to\n * {@link DEFAULT_API_ERROR_STRINGS}, because `t` returns the key itself when the\n * lookup misses and printing `tempest.error.offline` at the user would be worse\n * than printing pt-BR at them.\n */\nexport const API_ERROR_OFFLINE_KEY = \"tempest.error.offline\";\n\n/**\n * Translation key for the validation sentence, looked up the same way as\n * {@link API_ERROR_OFFLINE_KEY}.\n */\nexport const API_ERROR_VALIDATION_KEY = \"tempest.error.validation\";\n\n/**\n * Everything {@link describeApiError} accepts beyond the error and the fallback.\n *\n * Extends the fixed sentences rather than sitting beside them, so a caller that\n * already passed `{ offline, validation }` keeps compiling untouched.\n */\nexport interface DescribeApiErrorOptions extends Partial<ApiErrorStrings> {\n /**\n * Maps the backend's programmatic `code` to a sentence in your language.\n *\n * The client already surfaces `code` on `ApiError`, but without this every\n * app writes the same `switch` over it. A hit here wins over every other\n * step: it is the only sentence written for that exact case, by someone who\n * knew both the backend contract and the screen it lands on.\n */\n codes?: Readonly<Record<string, string>>;\n /**\n * Whether the backend's `detail` may be shown when no `code` matched.\n * Default `true`.\n *\n * Set it to `false` when `detail` is written for developers rather than\n * users, or when it could echo internals — the result is then always either\n * a sentence you wrote or the fallback.\n */\n useDetail?: boolean;\n}\n\n/**\n * Whether the browser currently reports itself as offline.\n *\n * `fetch` rejects a network failure with a plain `TypeError` whose message\n * differs per browser (\"Failed to fetch\", \"NetworkError when attempting to fetch\n * resource.\", \"Load failed\"), so sniffing the message is not portable. The online\n * flag is, and it is the signal that matters for the sentence being chosen.\n *\n * @returns `true` only when the environment positively says it is offline.\n */\nfunction browserIsOffline(): boolean {\n return typeof navigator !== \"undefined\" && navigator.onLine === false;\n}\n\n/**\n * Turn any caught value into a sentence worth showing.\n *\n * The funnel, in order:\n *\n * 0. `codes[error.code]` — the sentence you wrote for that exact backend case.\n * Checked first because nothing the funnel derives can beat it, and because a\n * request that never landed carries no `code` for it to shadow.\n * 1. A request that never reached the server — `status === 0`, or a non-API\n * error thrown while the browser reports itself offline — produces the\n * offline sentence. This is the step apps skip, and skipping it renders\n * \"erro 0\" or a raw `TypeError` at the user.\n * 2. A validation rejection — `error.fields` is set — produces the validation\n * sentence, **not** `detail`. On a `422` the `detail` line is assembled from\n * the backend's field paths and the validator's own wording\n * (`\"items.0.price: Input should be greater than 0\"`), which is right for a\n * log and wrong for a person: it is half English in a pt-BR screen and it\n * names internals. The per-field messages stay on `fields`, where a form can\n * attach them to the inputs that failed.\n * 3. The backend's own `detail`, which is the most specific thing available and\n * is already written for a person — unless `useDetail: false` says that text\n * is for developers.\n * 4. `fallback`, with `(HTTP <status>)` appended when a status is known, so the\n * screenshot in the support ticket carries the one fact a developer needs.\n *\n * Pure on purpose: it works in an interceptor, in a logger and anywhere outside\n * the React tree. {@link useDescribeApiError} is the same funnel with the\n * sentences resolved through `I18nProvider`.\n *\n * @example\n * catch (error) {\n * toast(describeApiError(error, \"Não foi possível salvar o pedido\"));\n * }\n *\n * @example\n * catch (error) {\n * toast(\n * describeApiError(error, \"Não foi possível se candidatar\", {\n * codes: {\n * SERVICE_FULL: \"Este serviço atingiu o limite de vagas.\",\n * CANDIDATE_ALREADY_EXISTS: \"Você já se candidatou a este serviço.\",\n * },\n * useDetail: false,\n * }),\n * );\n * }\n *\n * @param error - The caught value, of any shape.\n * @param fallback - What to say when the error carries nothing better.\n * @param options - A `codes` catalog, `useDetail`, and overrides for the fixed\n * sentences.\n * @returns A sentence to show the user.\n */\nexport function describeApiError(\n error: unknown,\n fallback: string,\n options?: DescribeApiErrorOptions,\n): string {\n const offline = options?.offline ?? DEFAULT_API_ERROR_STRINGS.offline;\n\n if (isApiError(error)) {\n const mapped = error.code === undefined ? undefined : options?.codes?.[error.code];\n if (mapped !== undefined) return mapped;\n if (error.status === 0) return offline;\n if (error.fields && Object.keys(error.fields).length > 0) {\n return options?.validation ?? DEFAULT_API_ERROR_STRINGS.validation;\n }\n const detail = error.detail.trim();\n if (\n options?.useDetail !== false &&\n detail !== \"\" &&\n detail !== syntheticDetail(error.status)\n ) {\n return detail;\n }\n return `${fallback} (HTTP ${error.status})`;\n }\n\n if (browserIsOffline()) return offline;\n\n return fallback;\n}\n"],"mappings":";;AA2BA,IAAa,IAA6C;CACtD,SAAS;CACT,YAAY;AAChB,GAUa,IAAwB,yBAMxB,IAA2B;AAuCxC,SAAS,IAA4B;CACjC,OAAO,OAAO,YAAc,OAAe,UAAU,WAAW;AACpE;AAuDA,SAAgB,EACZ,GACA,GACA,GACM;CACN,IAAM,IAAU,GAAS,WAAW,EAA0B;CAE9D,IAAI,EAAW,CAAK,GAAG;EACnB,IAAM,IAAS,EAAM,SAAS,KAAA,IAAY,KAAA,IAAY,GAAS,QAAQ,EAAM;EAC7E,IAAI,MAAW,KAAA,GAAW,OAAO;EACjC,IAAI,EAAM,WAAW,GAAG,OAAO;EAC/B,IAAI,EAAM,UAAU,OAAO,KAAK,EAAM,MAAM,CAAC,CAAC,SAAS,GACnD,OAAO,GAAS,cAAc,EAA0B;EAE5D,IAAM,IAAS,EAAM,OAAO,KAAK;EAQjC,OANI,GAAS,cAAc,MACvB,MAAW,MACX,MAAW,EAAgB,EAAM,MAAM,IAEhC,IAEJ,GAAG,EAAS,SAAS,EAAM,OAAO;CAC7C;CAIA,OAFI,EAAiB,IAAU,IAExB;AACX"}
@@ -1,2 +1,2 @@
1
- const e=require("./describe-api-error.cjs"),t=require("../i18n/I18nProvider.cjs");let n=require("react");function r(t,n,r){let i=e.DEFAULT_API_ERROR_STRINGS[r];return t?.(n,void 0,{default:i})??i}function i(){let i=t.useOptionalI18n()?.t;return(0,n.useCallback)((t,n)=>e.describeApiError(t,n,{offline:r(i,e.API_ERROR_OFFLINE_KEY,`offline`),validation:r(i,e.API_ERROR_VALIDATION_KEY,`validation`)}),[i])}exports.useDescribeApiError=i;
1
+ const e=require("./describe-api-error.cjs"),t=require("../i18n/I18nProvider.cjs");let n=require("react");function r(t,n,r){let i=e.DEFAULT_API_ERROR_STRINGS[r];return t?.(n,void 0,{default:i})??i}function i(){let i=t.useOptionalI18n()?.t;return(0,n.useCallback)((t,n,a)=>e.describeApiError(t,n,{offline:r(i,e.API_ERROR_OFFLINE_KEY,`offline`),validation:r(i,e.API_ERROR_VALIDATION_KEY,`validation`),...a}),[i])}exports.useDescribeApiError=i;
2
2
  //# sourceMappingURL=use-describe-api-error.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-describe-api-error.cjs","names":[],"sources":["../../src/http/use-describe-api-error.ts"],"sourcesContent":["import { useCallback } from \"react\";\n\nimport type { I18n } from \"../i18n/create-i18n\";\nimport { useOptionalI18n } from \"../i18n/I18nProvider\";\nimport {\n API_ERROR_OFFLINE_KEY,\n API_ERROR_VALIDATION_KEY,\n DEFAULT_API_ERROR_STRINGS,\n describeApiError,\n} from \"./describe-api-error\";\n\n/**\n * {@link describeApiError} with its fixed sentences resolved through the active\n * `I18nProvider`.\n *\n * The funnel is not duplicated — this hook only supplies the strings and calls\n * the pure function. Which is also why both exist: the pure one runs in an\n * interceptor or a logger, where there is no React tree to read a context from,\n * and this one runs in a component without every caller passing translations\n * down by hand.\n *\n * Works with no provider at all: i18n is opt-in in this SDK, so a missing\n * provider — or a catalog that never defined `tempest.error.offline` — falls\n * back to the pt-BR default rather than crashing or printing the raw key.\n *\n * @example\n * const describe = useDescribeApiError();\n * const { mutate } = useMutation({\n * mutationFn: save,\n * onError: (error) => toast(describe(error, t(\"orders.saveFailed\"))),\n * });\n *\n * @returns A stable `(error, fallback) => string` function.\n */\n/**\n * Look one sentence up in the active catalog, falling back to the pt-BR default.\n *\n * The miss is the i18n layer's answer, through `t`'s `default`. It used to be\n * re-derived here by comparing the result against the key that had just been\n * passed in, which is wrong for a catalog that maps a key to itself —\n * `{ \"tempest.error.offline\": \"tempest.error.offline\" }`, which is what a\n * machine-generated or placeholder catalog produces. There the app's own\n * translation lost to the pt-BR default. Only the catalog's owner can answer\n * \"was this key defined\", and `lookup()` already knows.\n *\n * @param translate - The active catalog's `t`, if any provider is mounted.\n * @param key - The translation key to look up.\n * @param fallbackKey - Which {@link DEFAULT_API_ERROR_STRINGS} entry to use on a miss.\n * @returns The sentence to hand to `describeApiError`.\n */\nfunction resolve(\n translate: I18n[\"t\"] | undefined,\n key: string,\n fallbackKey: keyof typeof DEFAULT_API_ERROR_STRINGS,\n): string {\n const fallback = DEFAULT_API_ERROR_STRINGS[fallbackKey];\n return translate?.(key, undefined, { default: fallback }) ?? fallback;\n}\n\nexport function useDescribeApiError(): (error: unknown, fallback: string) => string {\n const i18n = useOptionalI18n();\n const translate = i18n?.t;\n\n return useCallback(\n (error: unknown, fallback: string) => {\n return describeApiError(error, fallback, {\n offline: resolve(translate, API_ERROR_OFFLINE_KEY, \"offline\"),\n validation: resolve(translate, API_ERROR_VALIDATION_KEY, \"validation\"),\n });\n },\n [translate],\n );\n}\n"],"mappings":"yGAkDA,SAAS,EACL,EACA,EACA,EACM,CACN,IAAM,EAAW,EAAA,0BAA0B,GAC3C,OAAO,IAAY,EAAK,IAAA,GAAW,CAAE,QAAS,CAAS,CAAC,GAAK,CACjE,CAEA,SAAgB,GAAoE,CAEhF,IAAM,EADO,EAAA,gBACK,CAAA,EAAM,EAExB,OAAA,EAAO,EAAA,YAAA,EACF,EAAgB,IACN,EAAA,iBAAiB,EAAO,EAAU,CACrC,QAAS,EAAQ,EAAW,EAAA,sBAAuB,SAAS,EAC5D,WAAY,EAAQ,EAAW,EAAA,yBAA0B,YAAY,CACzE,CAAC,EAEL,CAAC,CAAS,CACd,CACJ"}
1
+ {"version":3,"file":"use-describe-api-error.cjs","names":[],"sources":["../../src/http/use-describe-api-error.ts"],"sourcesContent":["import { useCallback } from \"react\";\n\nimport type { I18n } from \"../i18n/create-i18n\";\nimport { useOptionalI18n } from \"../i18n/I18nProvider\";\nimport type { DescribeApiErrorOptions } from \"./describe-api-error\";\nimport {\n API_ERROR_OFFLINE_KEY,\n API_ERROR_VALIDATION_KEY,\n DEFAULT_API_ERROR_STRINGS,\n describeApiError,\n} from \"./describe-api-error\";\n\n/**\n * {@link describeApiError} with its fixed sentences resolved through the active\n * `I18nProvider`.\n *\n * The funnel is not duplicated — this hook only supplies the strings and calls\n * the pure function. Which is also why both exist: the pure one runs in an\n * interceptor or a logger, where there is no React tree to read a context from,\n * and this one runs in a component without every caller passing translations\n * down by hand.\n *\n * Works with no provider at all: i18n is opt-in in this SDK, so a missing\n * provider — or a catalog that never defined `tempest.error.offline` — falls\n * back to the pt-BR default rather than crashing or printing the raw key.\n *\n * The per-call options are the pure function's, so a screen that knows the\n * backend codes it can hit passes them at the call site while the translated\n * sentences keep coming from the provider.\n *\n * @example\n * const describe = useDescribeApiError();\n * const { mutate } = useMutation({\n * mutationFn: save,\n * onError: (error) => toast(describe(error, t(\"orders.saveFailed\"))),\n * });\n *\n * @returns A stable `(error, fallback, options?) => string` function.\n */\n/**\n * Look one sentence up in the active catalog, falling back to the pt-BR default.\n *\n * The miss is the i18n layer's answer, through `t`'s `default`. It used to be\n * re-derived here by comparing the result against the key that had just been\n * passed in, which is wrong for a catalog that maps a key to itself —\n * `{ \"tempest.error.offline\": \"tempest.error.offline\" }`, which is what a\n * machine-generated or placeholder catalog produces. There the app's own\n * translation lost to the pt-BR default. Only the catalog's owner can answer\n * \"was this key defined\", and `lookup()` already knows.\n *\n * @param translate - The active catalog's `t`, if any provider is mounted.\n * @param key - The translation key to look up.\n * @param fallbackKey - Which {@link DEFAULT_API_ERROR_STRINGS} entry to use on a miss.\n * @returns The sentence to hand to `describeApiError`.\n */\nfunction resolve(\n translate: I18n[\"t\"] | undefined,\n key: string,\n fallbackKey: keyof typeof DEFAULT_API_ERROR_STRINGS,\n): string {\n const fallback = DEFAULT_API_ERROR_STRINGS[fallbackKey];\n return translate?.(key, undefined, { default: fallback }) ?? fallback;\n}\n\nexport function useDescribeApiError(): (\n error: unknown,\n fallback: string,\n options?: DescribeApiErrorOptions,\n) => string {\n const i18n = useOptionalI18n();\n const translate = i18n?.t;\n\n return useCallback(\n (error: unknown, fallback: string, options?: DescribeApiErrorOptions) => {\n return describeApiError(error, fallback, {\n offline: resolve(translate, API_ERROR_OFFLINE_KEY, \"offline\"),\n validation: resolve(translate, API_ERROR_VALIDATION_KEY, \"validation\"),\n ...options,\n });\n },\n [translate],\n );\n}\n"],"mappings":"yGAuDA,SAAS,EACL,EACA,EACA,EACM,CACN,IAAM,EAAW,EAAA,0BAA0B,GAC3C,OAAO,IAAY,EAAK,IAAA,GAAW,CAAE,QAAS,CAAS,CAAC,GAAK,CACjE,CAEA,SAAgB,GAIJ,CAER,IAAM,EADO,EAAA,gBACK,CAAA,EAAM,EAExB,OAAA,EAAO,EAAA,YAAA,EACF,EAAgB,EAAkB,IACxB,EAAA,iBAAiB,EAAO,EAAU,CACrC,QAAS,EAAQ,EAAW,EAAA,sBAAuB,SAAS,EAC5D,WAAY,EAAQ,EAAW,EAAA,yBAA0B,YAAY,EACrE,GAAG,CACP,CAAC,EAEL,CAAC,CAAS,CACd,CACJ"}
@@ -8,9 +8,10 @@ function o(e, t, r) {
8
8
  }
9
9
  function s() {
10
10
  let n = i()?.t;
11
- return a((i, a) => r(i, a, {
11
+ return a((i, a, s) => r(i, a, {
12
12
  offline: o(n, e, "offline"),
13
- validation: o(n, t, "validation")
13
+ validation: o(n, t, "validation"),
14
+ ...s
14
15
  }), [n]);
15
16
  }
16
17
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"use-describe-api-error.js","names":[],"sources":["../../src/http/use-describe-api-error.ts"],"sourcesContent":["import { useCallback } from \"react\";\n\nimport type { I18n } from \"../i18n/create-i18n\";\nimport { useOptionalI18n } from \"../i18n/I18nProvider\";\nimport {\n API_ERROR_OFFLINE_KEY,\n API_ERROR_VALIDATION_KEY,\n DEFAULT_API_ERROR_STRINGS,\n describeApiError,\n} from \"./describe-api-error\";\n\n/**\n * {@link describeApiError} with its fixed sentences resolved through the active\n * `I18nProvider`.\n *\n * The funnel is not duplicated — this hook only supplies the strings and calls\n * the pure function. Which is also why both exist: the pure one runs in an\n * interceptor or a logger, where there is no React tree to read a context from,\n * and this one runs in a component without every caller passing translations\n * down by hand.\n *\n * Works with no provider at all: i18n is opt-in in this SDK, so a missing\n * provider — or a catalog that never defined `tempest.error.offline` — falls\n * back to the pt-BR default rather than crashing or printing the raw key.\n *\n * @example\n * const describe = useDescribeApiError();\n * const { mutate } = useMutation({\n * mutationFn: save,\n * onError: (error) => toast(describe(error, t(\"orders.saveFailed\"))),\n * });\n *\n * @returns A stable `(error, fallback) => string` function.\n */\n/**\n * Look one sentence up in the active catalog, falling back to the pt-BR default.\n *\n * The miss is the i18n layer's answer, through `t`'s `default`. It used to be\n * re-derived here by comparing the result against the key that had just been\n * passed in, which is wrong for a catalog that maps a key to itself —\n * `{ \"tempest.error.offline\": \"tempest.error.offline\" }`, which is what a\n * machine-generated or placeholder catalog produces. There the app's own\n * translation lost to the pt-BR default. Only the catalog's owner can answer\n * \"was this key defined\", and `lookup()` already knows.\n *\n * @param translate - The active catalog's `t`, if any provider is mounted.\n * @param key - The translation key to look up.\n * @param fallbackKey - Which {@link DEFAULT_API_ERROR_STRINGS} entry to use on a miss.\n * @returns The sentence to hand to `describeApiError`.\n */\nfunction resolve(\n translate: I18n[\"t\"] | undefined,\n key: string,\n fallbackKey: keyof typeof DEFAULT_API_ERROR_STRINGS,\n): string {\n const fallback = DEFAULT_API_ERROR_STRINGS[fallbackKey];\n return translate?.(key, undefined, { default: fallback }) ?? fallback;\n}\n\nexport function useDescribeApiError(): (error: unknown, fallback: string) => string {\n const i18n = useOptionalI18n();\n const translate = i18n?.t;\n\n return useCallback(\n (error: unknown, fallback: string) => {\n return describeApiError(error, fallback, {\n offline: resolve(translate, API_ERROR_OFFLINE_KEY, \"offline\"),\n validation: resolve(translate, API_ERROR_VALIDATION_KEY, \"validation\"),\n });\n },\n [translate],\n );\n}\n"],"mappings":";;;;AAkDA,SAAS,EACL,GACA,GACA,GACM;CACN,IAAM,IAAW,EAA0B;CAC3C,OAAO,IAAY,GAAK,KAAA,GAAW,EAAE,SAAS,EAAS,CAAC,KAAK;AACjE;AAEA,SAAgB,IAAoE;CAEhF,IAAM,IADO,EACK,CAAA,EAAM;CAExB,OAAO,GACF,GAAgB,MACN,EAAiB,GAAO,GAAU;EACrC,SAAS,EAAQ,GAAW,GAAuB,SAAS;EAC5D,YAAY,EAAQ,GAAW,GAA0B,YAAY;CACzE,CAAC,GAEL,CAAC,CAAS,CACd;AACJ"}
1
+ {"version":3,"file":"use-describe-api-error.js","names":[],"sources":["../../src/http/use-describe-api-error.ts"],"sourcesContent":["import { useCallback } from \"react\";\n\nimport type { I18n } from \"../i18n/create-i18n\";\nimport { useOptionalI18n } from \"../i18n/I18nProvider\";\nimport type { DescribeApiErrorOptions } from \"./describe-api-error\";\nimport {\n API_ERROR_OFFLINE_KEY,\n API_ERROR_VALIDATION_KEY,\n DEFAULT_API_ERROR_STRINGS,\n describeApiError,\n} from \"./describe-api-error\";\n\n/**\n * {@link describeApiError} with its fixed sentences resolved through the active\n * `I18nProvider`.\n *\n * The funnel is not duplicated — this hook only supplies the strings and calls\n * the pure function. Which is also why both exist: the pure one runs in an\n * interceptor or a logger, where there is no React tree to read a context from,\n * and this one runs in a component without every caller passing translations\n * down by hand.\n *\n * Works with no provider at all: i18n is opt-in in this SDK, so a missing\n * provider — or a catalog that never defined `tempest.error.offline` — falls\n * back to the pt-BR default rather than crashing or printing the raw key.\n *\n * The per-call options are the pure function's, so a screen that knows the\n * backend codes it can hit passes them at the call site while the translated\n * sentences keep coming from the provider.\n *\n * @example\n * const describe = useDescribeApiError();\n * const { mutate } = useMutation({\n * mutationFn: save,\n * onError: (error) => toast(describe(error, t(\"orders.saveFailed\"))),\n * });\n *\n * @returns A stable `(error, fallback, options?) => string` function.\n */\n/**\n * Look one sentence up in the active catalog, falling back to the pt-BR default.\n *\n * The miss is the i18n layer's answer, through `t`'s `default`. It used to be\n * re-derived here by comparing the result against the key that had just been\n * passed in, which is wrong for a catalog that maps a key to itself —\n * `{ \"tempest.error.offline\": \"tempest.error.offline\" }`, which is what a\n * machine-generated or placeholder catalog produces. There the app's own\n * translation lost to the pt-BR default. Only the catalog's owner can answer\n * \"was this key defined\", and `lookup()` already knows.\n *\n * @param translate - The active catalog's `t`, if any provider is mounted.\n * @param key - The translation key to look up.\n * @param fallbackKey - Which {@link DEFAULT_API_ERROR_STRINGS} entry to use on a miss.\n * @returns The sentence to hand to `describeApiError`.\n */\nfunction resolve(\n translate: I18n[\"t\"] | undefined,\n key: string,\n fallbackKey: keyof typeof DEFAULT_API_ERROR_STRINGS,\n): string {\n const fallback = DEFAULT_API_ERROR_STRINGS[fallbackKey];\n return translate?.(key, undefined, { default: fallback }) ?? fallback;\n}\n\nexport function useDescribeApiError(): (\n error: unknown,\n fallback: string,\n options?: DescribeApiErrorOptions,\n) => string {\n const i18n = useOptionalI18n();\n const translate = i18n?.t;\n\n return useCallback(\n (error: unknown, fallback: string, options?: DescribeApiErrorOptions) => {\n return describeApiError(error, fallback, {\n offline: resolve(translate, API_ERROR_OFFLINE_KEY, \"offline\"),\n validation: resolve(translate, API_ERROR_VALIDATION_KEY, \"validation\"),\n ...options,\n });\n },\n [translate],\n );\n}\n"],"mappings":";;;;AAuDA,SAAS,EACL,GACA,GACA,GACM;CACN,IAAM,IAAW,EAA0B;CAC3C,OAAO,IAAY,GAAK,KAAA,GAAW,EAAE,SAAS,EAAS,CAAC,KAAK;AACjE;AAEA,SAAgB,IAIJ;CAER,IAAM,IADO,EACK,CAAA,EAAM;CAExB,OAAO,GACF,GAAgB,GAAkB,MACxB,EAAiB,GAAO,GAAU;EACrC,SAAS,EAAQ,GAAW,GAAuB,SAAS;EAC5D,YAAY,EAAQ,GAAW,GAA0B,YAAY;EACrE,GAAG;CACP,CAAC,GAEL,CAAC,CAAS,CACd;AACJ"}
@@ -0,0 +1,2 @@
1
+ const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("./create-offline-store.cjs");let n=require("dexie");n=e.__toESM(n,1);var r=class extends n.default{constructor(e,t,n){super(e),this.version(t).stores(n)}};function i(e){let{databaseName:n,version:i,tables:a}=e,o={};for(let e of Object.keys(a))o[e]=a[e].indexes;let s=new r(n,i,o),c=new Map;function l(e){let r=c.get(e);if(r)return r;if(!(e in a))throw Error(`Table "${e}" is not declared in ${n}. Available: ${Object.keys(a).join(`, `)}.`);let i=s.table(e),o=a[e],l=t.buildStore(s,i,o);return c.set(e,l),l}return{store:l,db:s,destroy:()=>s.delete()}}exports.createOfflineDatabase=i;
2
+ //# sourceMappingURL=create-offline-database.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-offline-database.cjs","names":[],"sources":["../../src/offline/create-offline-database.ts"],"sourcesContent":["import Dexie, { type Table } from \"dexie\";\n\nimport { buildStore, type OfflineStore, type OfflineStoreConfig } from \"./create-offline-store\";\n\nexport interface OfflineTableConfig<TItem> {\n /**\n * Dexie index definition for this table. Use `&` for a unique primary key,\n * e.g. `\"&id, service_id, created_at\"`.\n */\n indexes: string;\n /** Property used as the primary key (default: `\"id\"`). */\n keyPath?: keyof TItem & string;\n /**\n * Optional owner scoping for this table. Set per table, since one database\n * commonly mixes scoped and unscoped data.\n */\n ownerField?: keyof TItem & string;\n}\n\n/** Maps each table name to the record type it stores. */\nexport type OfflineSchema = Record<string, unknown>;\n\nexport type OfflineTablesConfig<TSchema extends OfflineSchema> = {\n [K in keyof TSchema]: OfflineTableConfig<TSchema[K]>;\n};\n\nexport interface OfflineDatabaseConfig<TSchema extends OfflineSchema> {\n /** IndexedDB database name. */\n databaseName: string;\n /** Schema version. Bump when changing any table's indexes. */\n version: number;\n /** One entry per object store, all inside this single database. */\n tables: OfflineTablesConfig<TSchema>;\n}\n\nexport interface OfflineDatabase<TSchema extends OfflineSchema> {\n /**\n * The {@link OfflineStore} for one table.\n *\n * The name is checked against the declared schema; the record type is\n * supplied by the caller — `store<Chat>(\"chats\")`. Deriving it from the\n * schema instead (`OfflineStore<TSchema[K], string>`) is what the shape\n * below documents as unavailable: Dexie's `Table<T>` expands `UpdateSpec<T>`\n * over the keys of `T`, and an unresolved indexed access there makes the\n * checker answer TS2589 no matter how the value is cast.\n *\n * Stores are created once and memoised, so repeated calls with the same\n * name return the same object.\n */\n store: <TItem>(name: keyof TSchema & string) => OfflineStore<TItem, string>;\n /** The Dexie instance shared by every store. */\n db: Dexie;\n /** Delete the whole database from the browser. */\n destroy: () => Promise<void>;\n}\n\nclass MultiTableDb extends Dexie {\n constructor(name: string, version: number, stores: Record<string, string>) {\n super(name);\n this.version(version).stores(stores);\n }\n}\n\n/**\n * Build several {@link OfflineStore}s that share one IndexedDB database.\n *\n * `createOfflineStore` gives each store a database of its own, which is the\n * right shape for one isolated cache. It is the wrong shape as soon as the\n * tables belong together: chats and their messages, an entity and its drafts,\n * anything you would read or clear as a unit. Splitting those across databases\n * costs a real transaction — Dexie runs one atomically only *within* a single\n * database — and it splits the version bump for a related change across two\n * places.\n *\n * This keeps them in one database at one version, so a schema change is one\n * bump and a multi-table write can be wrapped in `db.transaction(...)`.\n *\n * Stores are reached through `store<TItem>(name)` rather than a prebuilt map.\n * That is forced rather than chosen: Dexie's `Table<T>` expands `UpdateSpec<T>`\n * over the keys of `T`, so building `{ [K in keyof TSchema]: OfflineStore<…> }`\n * — or even naming `OfflineStore<TSchema[K], string>` inside the accessor —\n * makes the checker answer TS2589 (\"excessively deep\"). Taking the record type\n * as a parameter keeps it a plain type argument, which resolves fine. The table\n * name is still checked against the declared schema.\n *\n * The store surface is identical to `createOfflineStore`; only ownership of the\n * database changes. `ownerField` is set per table, since a database commonly\n * mixes per-user data with shared data.\n *\n * @param config - Database name, version, and one entry per table.\n * @returns A `store(name)` accessor, the shared Dexie instance, and a\n * `destroy()` that drops the database.\n *\n * @example\n * type Chat = { id: string; service_id: string; updated_at: string };\n * type Message = { id: string; service_chat_id: string; created_at: string };\n *\n * const database = createOfflineDatabase<{ chats: Chat; messages: Message }>({\n * databaseName: \"ChatDatabase\",\n * version: 1,\n * tables: {\n * chats: { indexes: \"&id, service_id, updated_at\" },\n * messages: { indexes: \"&id, service_chat_id, created_at\" },\n * },\n * });\n *\n * const chats = database.store<Chat>(\"chats\");\n * const messages = database.store<Message>(\"messages\");\n *\n * // Both tables in one atomic transaction — impossible across two databases.\n * await database.db.transaction(\"rw\", chats.raw, messages.raw, async () => {\n * await chats.put(chat);\n * await messages.bulkPut(pending);\n * });\n */\nexport function createOfflineDatabase<TSchema extends OfflineSchema>(\n config: OfflineDatabaseConfig<TSchema>,\n): OfflineDatabase<TSchema> {\n const { databaseName, version, tables } = config;\n\n const schema: Record<string, string> = {};\n for (const name of Object.keys(tables)) {\n schema[name] = tables[name as keyof TSchema].indexes;\n }\n\n const db = new MultiTableDb(databaseName, version, schema);\n const built = new Map<string, unknown>();\n\n function store<TItem>(name: keyof TSchema & string): OfflineStore<TItem, string> {\n const cached = built.get(name);\n if (cached) return cached as OfflineStore<TItem, string>;\n\n if (!(name in tables)) {\n throw new Error(\n `Table \"${name}\" is not declared in ${databaseName}. ` +\n `Available: ${Object.keys(tables).join(\", \")}.`,\n );\n }\n\n const table = db.table(name) as Table<TItem>;\n const tableConfig = tables[name] as Pick<\n OfflineStoreConfig<TItem>,\n \"keyPath\" | \"ownerField\"\n >;\n // Dexie's `Table<T>` drags in `UpdateSpec<T>`, which maps over the keys\n // of `T`. Instantiating that from inside a second generic function is\n // past what the checker will unfold, and it answers TS2589\n // (\"excessively deep\") — for every shape tried: `unknown`, `object`,\n // `Record<string, unknown>`, a closed interface, an explicit type\n // argument, and a cast through `never`. `createOfflineStore` calls this\n // same `buildStore` without complaint, so it is the nesting, not the\n // store.\n //\n // Suppressed rather than worked around: the emitted types and the\n // runtime are both correct — `create-offline-database.test.ts` covers\n // the full surface, cross-table transactions included.\n // `@ts-expect-error` over `@ts-ignore` on purpose: if a later\n // TypeScript raises the limit, this line starts failing and says so.\n // @ts-expect-error TS2589 — see above\n const created: OfflineStore<TItem> = buildStore<TItem>(db, table, tableConfig);\n built.set(name, created);\n return created;\n }\n\n return {\n store,\n db,\n destroy: () => db.delete(),\n };\n}\n"],"mappings":"qIAwDA,IAAM,EAAN,cAA2B,EAAA,OAAM,CAC7B,YAAY,EAAc,EAAiB,EAAgC,CACvE,MAAM,CAAI,EACV,KAAK,QAAQ,CAAO,CAAC,CAAC,OAAO,CAAM,CACvC,CACJ,EAsDA,SAAgB,EACZ,EACwB,CACxB,GAAM,CAAE,eAAc,UAAS,UAAW,EAEpC,EAAiC,CAAC,EACxC,IAAK,IAAM,KAAQ,OAAO,KAAK,CAAM,EACjC,EAAO,GAAQ,EAAO,EAAsB,CAAC,QAGjD,IAAM,EAAK,IAAI,EAAa,EAAc,EAAS,CAAM,EACnD,EAAQ,IAAI,IAElB,SAAS,EAAa,EAA2D,CAC7E,IAAM,EAAS,EAAM,IAAI,CAAI,EAC7B,GAAI,EAAQ,OAAO,EAEnB,GAAI,EAAE,KAAQ,GACV,MAAU,MACN,UAAU,EAAK,uBAAuB,EAAa,eACjC,OAAO,KAAK,CAAM,CAAC,CAAC,KAAK,IAAI,EAAE,EACrD,EAGJ,IAAM,EAAQ,EAAG,MAAM,CAAI,EACrB,EAAc,EAAO,GAmBrB,EAA+B,EAAA,WAAkB,EAAI,EAAO,CAAW,EAE7E,OADA,EAAM,IAAI,EAAM,CAAO,EAChB,CACX,CAEA,MAAO,CACH,QACA,KACA,YAAe,EAAG,OAAO,CAC7B,CACJ"}
@@ -0,0 +1,29 @@
1
+ import { buildStore as e } from "./create-offline-store.js";
2
+ import t from "dexie";
3
+ //#region src/offline/create-offline-database.ts
4
+ var n = class extends t {
5
+ constructor(e, t, n) {
6
+ super(e), this.version(t).stores(n);
7
+ }
8
+ };
9
+ function r(t) {
10
+ let { databaseName: r, version: i, tables: a } = t, o = {};
11
+ for (let e of Object.keys(a)) o[e] = a[e].indexes;
12
+ let s = new n(r, i, o), c = /* @__PURE__ */ new Map();
13
+ function l(t) {
14
+ let n = c.get(t);
15
+ if (n) return n;
16
+ if (!(t in a)) throw Error(`Table "${t}" is not declared in ${r}. Available: ${Object.keys(a).join(", ")}.`);
17
+ let i = s.table(t), o = a[t], l = e(s, i, o);
18
+ return c.set(t, l), l;
19
+ }
20
+ return {
21
+ store: l,
22
+ db: s,
23
+ destroy: () => s.delete()
24
+ };
25
+ }
26
+ //#endregion
27
+ export { r as createOfflineDatabase };
28
+
29
+ //# sourceMappingURL=create-offline-database.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-offline-database.js","names":[],"sources":["../../src/offline/create-offline-database.ts"],"sourcesContent":["import Dexie, { type Table } from \"dexie\";\n\nimport { buildStore, type OfflineStore, type OfflineStoreConfig } from \"./create-offline-store\";\n\nexport interface OfflineTableConfig<TItem> {\n /**\n * Dexie index definition for this table. Use `&` for a unique primary key,\n * e.g. `\"&id, service_id, created_at\"`.\n */\n indexes: string;\n /** Property used as the primary key (default: `\"id\"`). */\n keyPath?: keyof TItem & string;\n /**\n * Optional owner scoping for this table. Set per table, since one database\n * commonly mixes scoped and unscoped data.\n */\n ownerField?: keyof TItem & string;\n}\n\n/** Maps each table name to the record type it stores. */\nexport type OfflineSchema = Record<string, unknown>;\n\nexport type OfflineTablesConfig<TSchema extends OfflineSchema> = {\n [K in keyof TSchema]: OfflineTableConfig<TSchema[K]>;\n};\n\nexport interface OfflineDatabaseConfig<TSchema extends OfflineSchema> {\n /** IndexedDB database name. */\n databaseName: string;\n /** Schema version. Bump when changing any table's indexes. */\n version: number;\n /** One entry per object store, all inside this single database. */\n tables: OfflineTablesConfig<TSchema>;\n}\n\nexport interface OfflineDatabase<TSchema extends OfflineSchema> {\n /**\n * The {@link OfflineStore} for one table.\n *\n * The name is checked against the declared schema; the record type is\n * supplied by the caller — `store<Chat>(\"chats\")`. Deriving it from the\n * schema instead (`OfflineStore<TSchema[K], string>`) is what the shape\n * below documents as unavailable: Dexie's `Table<T>` expands `UpdateSpec<T>`\n * over the keys of `T`, and an unresolved indexed access there makes the\n * checker answer TS2589 no matter how the value is cast.\n *\n * Stores are created once and memoised, so repeated calls with the same\n * name return the same object.\n */\n store: <TItem>(name: keyof TSchema & string) => OfflineStore<TItem, string>;\n /** The Dexie instance shared by every store. */\n db: Dexie;\n /** Delete the whole database from the browser. */\n destroy: () => Promise<void>;\n}\n\nclass MultiTableDb extends Dexie {\n constructor(name: string, version: number, stores: Record<string, string>) {\n super(name);\n this.version(version).stores(stores);\n }\n}\n\n/**\n * Build several {@link OfflineStore}s that share one IndexedDB database.\n *\n * `createOfflineStore` gives each store a database of its own, which is the\n * right shape for one isolated cache. It is the wrong shape as soon as the\n * tables belong together: chats and their messages, an entity and its drafts,\n * anything you would read or clear as a unit. Splitting those across databases\n * costs a real transaction — Dexie runs one atomically only *within* a single\n * database — and it splits the version bump for a related change across two\n * places.\n *\n * This keeps them in one database at one version, so a schema change is one\n * bump and a multi-table write can be wrapped in `db.transaction(...)`.\n *\n * Stores are reached through `store<TItem>(name)` rather than a prebuilt map.\n * That is forced rather than chosen: Dexie's `Table<T>` expands `UpdateSpec<T>`\n * over the keys of `T`, so building `{ [K in keyof TSchema]: OfflineStore<…> }`\n * — or even naming `OfflineStore<TSchema[K], string>` inside the accessor —\n * makes the checker answer TS2589 (\"excessively deep\"). Taking the record type\n * as a parameter keeps it a plain type argument, which resolves fine. The table\n * name is still checked against the declared schema.\n *\n * The store surface is identical to `createOfflineStore`; only ownership of the\n * database changes. `ownerField` is set per table, since a database commonly\n * mixes per-user data with shared data.\n *\n * @param config - Database name, version, and one entry per table.\n * @returns A `store(name)` accessor, the shared Dexie instance, and a\n * `destroy()` that drops the database.\n *\n * @example\n * type Chat = { id: string; service_id: string; updated_at: string };\n * type Message = { id: string; service_chat_id: string; created_at: string };\n *\n * const database = createOfflineDatabase<{ chats: Chat; messages: Message }>({\n * databaseName: \"ChatDatabase\",\n * version: 1,\n * tables: {\n * chats: { indexes: \"&id, service_id, updated_at\" },\n * messages: { indexes: \"&id, service_chat_id, created_at\" },\n * },\n * });\n *\n * const chats = database.store<Chat>(\"chats\");\n * const messages = database.store<Message>(\"messages\");\n *\n * // Both tables in one atomic transaction — impossible across two databases.\n * await database.db.transaction(\"rw\", chats.raw, messages.raw, async () => {\n * await chats.put(chat);\n * await messages.bulkPut(pending);\n * });\n */\nexport function createOfflineDatabase<TSchema extends OfflineSchema>(\n config: OfflineDatabaseConfig<TSchema>,\n): OfflineDatabase<TSchema> {\n const { databaseName, version, tables } = config;\n\n const schema: Record<string, string> = {};\n for (const name of Object.keys(tables)) {\n schema[name] = tables[name as keyof TSchema].indexes;\n }\n\n const db = new MultiTableDb(databaseName, version, schema);\n const built = new Map<string, unknown>();\n\n function store<TItem>(name: keyof TSchema & string): OfflineStore<TItem, string> {\n const cached = built.get(name);\n if (cached) return cached as OfflineStore<TItem, string>;\n\n if (!(name in tables)) {\n throw new Error(\n `Table \"${name}\" is not declared in ${databaseName}. ` +\n `Available: ${Object.keys(tables).join(\", \")}.`,\n );\n }\n\n const table = db.table(name) as Table<TItem>;\n const tableConfig = tables[name] as Pick<\n OfflineStoreConfig<TItem>,\n \"keyPath\" | \"ownerField\"\n >;\n // Dexie's `Table<T>` drags in `UpdateSpec<T>`, which maps over the keys\n // of `T`. Instantiating that from inside a second generic function is\n // past what the checker will unfold, and it answers TS2589\n // (\"excessively deep\") — for every shape tried: `unknown`, `object`,\n // `Record<string, unknown>`, a closed interface, an explicit type\n // argument, and a cast through `never`. `createOfflineStore` calls this\n // same `buildStore` without complaint, so it is the nesting, not the\n // store.\n //\n // Suppressed rather than worked around: the emitted types and the\n // runtime are both correct — `create-offline-database.test.ts` covers\n // the full surface, cross-table transactions included.\n // `@ts-expect-error` over `@ts-ignore` on purpose: if a later\n // TypeScript raises the limit, this line starts failing and says so.\n // @ts-expect-error TS2589 — see above\n const created: OfflineStore<TItem> = buildStore<TItem>(db, table, tableConfig);\n built.set(name, created);\n return created;\n }\n\n return {\n store,\n db,\n destroy: () => db.delete(),\n };\n}\n"],"mappings":";;;AAwDA,IAAM,IAAN,cAA2B,EAAM;CAC7B,YAAY,GAAc,GAAiB,GAAgC;EAEvE,AADA,MAAM,CAAI,GACV,KAAK,QAAQ,CAAO,CAAC,CAAC,OAAO,CAAM;CACvC;AACJ;AAsDA,SAAgB,EACZ,GACwB;CACxB,IAAM,EAAE,iBAAc,YAAS,cAAW,GAEpC,IAAiC,CAAC;CACxC,KAAK,IAAM,KAAQ,OAAO,KAAK,CAAM,GACjC,EAAO,KAAQ,EAAO,EAAsB,CAAC;CAGjD,IAAM,IAAK,IAAI,EAAa,GAAc,GAAS,CAAM,GACnD,oBAAQ,IAAI,IAAqB;CAEvC,SAAS,EAAa,GAA2D;EAC7E,IAAM,IAAS,EAAM,IAAI,CAAI;EAC7B,IAAI,GAAQ,OAAO;EAEnB,IAAI,EAAE,KAAQ,IACV,MAAU,MACN,UAAU,EAAK,uBAAuB,EAAa,eACjC,OAAO,KAAK,CAAM,CAAC,CAAC,KAAK,IAAI,EAAE,EACrD;EAGJ,IAAM,IAAQ,EAAG,MAAM,CAAI,GACrB,IAAc,EAAO,IAmBrB,IAA+B,EAAkB,GAAI,GAAO,CAAW;EAE7E,OADA,EAAM,IAAI,GAAM,CAAO,GAChB;CACX;CAEA,OAAO;EACH;EACA;EACA,eAAe,EAAG,OAAO;CAC7B;AACJ"}
@@ -1,2 +1,2 @@
1
- const e=require("../_virtual/_rolldown/runtime.cjs");let t=require("dexie");t=e.__toESM(t,1);var n=class extends t.default{store;constructor(e,t,n,r){super(e),this.version(t).stores({[n]:r}),this.store=this.table(n)}};function r(e){let{databaseName:t,version:r,tableName:i,indexes:a,keyPath:o=`id`,ownerField:s}=e,c=new n(t,r,i,a),l=c.store;function u(e,t){return!s||!t?e:{...e,[s]:t}}async function d(e,t={}){let{orderBy:n=o,reverse:r=!1,limit:i,offset:a,filter:c}=t,u=s&&e?l.where(s).equals(e):l.toCollection();c&&(u=u.filter(c));let d=n===o?await u.toArray():await u.sortBy(n);return r&&(d=d.reverse()),a&&(d=d.slice(a)),typeof i==`number`&&(d=d.slice(0,i)),d}return{put:(e,t)=>l.put(u(e,t)),bulkPut:(e,t)=>l.bulkPut(e.map(e=>u(e,t))),get:e=>l.get(e),list:d,update:(e,t)=>l.update(e,t),updateMany:async(e,t)=>{let n=t;return s&&e?l.where(s).equals(e).modify(n):l.toCollection().modify(n)},delete:e=>l.delete(e),clear:async e=>{if(s&&e){await l.where(s).equals(e).delete();return}await l.clear()},count:e=>s&&e?l.where(s).equals(e).count():l.count(),raw:l,db:c}}exports.createOfflineStore=r;
1
+ const e=require("../_virtual/_rolldown/runtime.cjs");let t=require("dexie");t=e.__toESM(t,1);var n=class extends t.default{store;constructor(e,t,n,r){super(e),this.version(t).stores({[n]:r}),this.store=this.table(n)}};function r(e){let{databaseName:t,version:r,tableName:a,indexes:o}=e,s=new n(t,r,a,o);return i(s,s.store,e)}function i(e,t,n){let{keyPath:r=`id`,ownerField:i}=n;function a(e,t){return!i||!t?e:{...e,[i]:t}}async function o(e,n={}){let{orderBy:a=r,reverse:o=!1,limit:s,offset:c,filter:l}=n,u=i&&e?t.where(i).equals(e):t.toCollection();l&&(u=u.filter(l));let d=a===r?await u.toArray():await u.sortBy(a);return o&&(d=d.reverse()),c&&(d=d.slice(c)),typeof s==`number`&&(d=d.slice(0,s)),d}return{put:(e,n)=>t.put(a(e,n)),bulkPut:(e,n)=>t.bulkPut(e.map(e=>a(e,n))),get:e=>t.get(e),list:o,update:(e,n)=>t.update(e,n),updateMany:async(e,n)=>{let r=n;return i&&e?t.where(i).equals(e).modify(r):t.toCollection().modify(r)},delete:e=>t.delete(e),clear:async e=>{if(i&&e){await t.where(i).equals(e).delete();return}await t.clear()},count:e=>i&&e?t.where(i).equals(e).count():t.count(),raw:t,db:e}}exports.buildStore=i,exports.createOfflineStore=r;
2
2
  //# sourceMappingURL=create-offline-store.cjs.map