@webority/mobile-core 0.167.0 → 0.169.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 (76) hide show
  1. package/README.md +6 -1
  2. package/lib/commonjs/api/contractCaller.js +1 -1
  3. package/lib/commonjs/appLock/index.js +1 -1
  4. package/lib/commonjs/errors/extractApiError.js +1 -1
  5. package/lib/commonjs/formatters/house.js +1 -1
  6. package/lib/commonjs/idle/idleTimeout.js +1 -0
  7. package/lib/commonjs/idle/index.js +1 -0
  8. package/lib/commonjs/index.js +1 -1
  9. package/lib/commonjs/india/fieldRules.js +1 -0
  10. package/lib/commonjs/india/index.js +1 -1
  11. package/lib/commonjs/outbox/backgroundUpload.js +1 -0
  12. package/lib/commonjs/outbox/files.js +1 -1
  13. package/lib/commonjs/outbox/index.js +1 -1
  14. package/lib/commonjs/outbox/outbox.js +1 -1
  15. package/lib/commonjs/outbox/progress.js +1 -0
  16. package/lib/commonjs/outbox/resumable.js +1 -0
  17. package/lib/commonjs/outbox/useOutboxProgress.js +1 -0
  18. package/lib/commonjs/query/apiBaseQuery.js +1 -1
  19. package/lib/commonjs/query/contractQuery.js +1 -1
  20. package/lib/commonjs/validators/fieldRules.js +1 -1
  21. package/lib/commonjs/validators/index.js +1 -1
  22. package/lib/module/api/contractCaller.js +1 -1
  23. package/lib/module/appLock/index.js +1 -1
  24. package/lib/module/errors/extractApiError.js +1 -1
  25. package/lib/module/formatters/house.js +1 -1
  26. package/lib/module/idle/idleTimeout.js +1 -0
  27. package/lib/module/idle/index.js +1 -0
  28. package/lib/module/index.js +1 -1
  29. package/lib/module/india/fieldRules.js +1 -0
  30. package/lib/module/india/index.js +1 -1
  31. package/lib/module/outbox/backgroundUpload.js +1 -0
  32. package/lib/module/outbox/files.js +1 -1
  33. package/lib/module/outbox/index.js +1 -1
  34. package/lib/module/outbox/outbox.js +1 -1
  35. package/lib/module/outbox/progress.js +1 -0
  36. package/lib/module/outbox/resumable.js +1 -0
  37. package/lib/module/outbox/useOutboxProgress.js +1 -0
  38. package/lib/module/query/apiBaseQuery.js +1 -1
  39. package/lib/module/query/contractQuery.js +1 -1
  40. package/lib/module/validators/fieldRules.js +1 -1
  41. package/lib/module/validators/index.js +1 -1
  42. package/lib/typescript/commonjs/appLock/index.d.ts +4 -0
  43. package/lib/typescript/commonjs/auth/authStore.d.ts +2 -1
  44. package/lib/typescript/commonjs/idle/idleTimeout.d.ts +29 -0
  45. package/lib/typescript/commonjs/idle/index.d.ts +3 -0
  46. package/lib/typescript/commonjs/index.d.ts +4 -2
  47. package/lib/typescript/commonjs/india/fieldRules.d.ts +10 -0
  48. package/lib/typescript/commonjs/india/index.d.ts +1 -0
  49. package/lib/typescript/commonjs/outbox/backgroundUpload.d.ts +18 -0
  50. package/lib/typescript/commonjs/outbox/index.d.ts +2 -0
  51. package/lib/typescript/commonjs/outbox/progress.d.ts +11 -0
  52. package/lib/typescript/commonjs/outbox/resumable.d.ts +27 -0
  53. package/lib/typescript/commonjs/outbox/types.d.ts +22 -1
  54. package/lib/typescript/commonjs/outbox/useOutboxProgress.d.ts +3 -0
  55. package/lib/typescript/commonjs/query/apiBaseQuery.d.ts +7 -2
  56. package/lib/typescript/commonjs/query/contractQuery.d.ts +1 -1
  57. package/lib/typescript/commonjs/query/entityVersion.d.ts +1 -1
  58. package/lib/typescript/commonjs/validators/fieldRules.d.ts +3 -0
  59. package/lib/typescript/module/appLock/index.d.ts +4 -0
  60. package/lib/typescript/module/auth/authStore.d.ts +2 -1
  61. package/lib/typescript/module/idle/idleTimeout.d.ts +29 -0
  62. package/lib/typescript/module/idle/index.d.ts +3 -0
  63. package/lib/typescript/module/index.d.ts +4 -2
  64. package/lib/typescript/module/india/fieldRules.d.ts +10 -0
  65. package/lib/typescript/module/india/index.d.ts +1 -0
  66. package/lib/typescript/module/outbox/backgroundUpload.d.ts +18 -0
  67. package/lib/typescript/module/outbox/index.d.ts +2 -0
  68. package/lib/typescript/module/outbox/progress.d.ts +11 -0
  69. package/lib/typescript/module/outbox/resumable.d.ts +27 -0
  70. package/lib/typescript/module/outbox/types.d.ts +22 -1
  71. package/lib/typescript/module/outbox/useOutboxProgress.d.ts +3 -0
  72. package/lib/typescript/module/query/apiBaseQuery.d.ts +7 -2
  73. package/lib/typescript/module/query/contractQuery.d.ts +1 -1
  74. package/lib/typescript/module/query/entityVersion.d.ts +1 -1
  75. package/lib/typescript/module/validators/fieldRules.d.ts +3 -0
  76. package/package.json +2 -2
@@ -1 +1 @@
1
- "use strict";import{configuredLocale,getFormatterConfig,groupingForLocale,numberSeparators,styledNumber}from"./formatConfig.js";import{dateTimeFormat,numberFormat,relativeTimeFormat}from"./intlCache.js";const MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],IST_OFFSET_MINUTES=330,IST_NAMES=["IST","Asia/Kolkata","Asia/Calcutta"],DATE_ONLY=/^\d{4}-\d{2}-\d{2}$/,pad2=t=>t<10?`0${t}`:`${t}`,emptyOf=t=>t??getFormatterConfig().empty,toInstant=t=>{if(null==t||""===t)return null;const e=t instanceof Date?t:new Date("string"==typeof t?t.trim():t);return Number.isNaN(e.getTime())?null:e},isDateOnly=t=>"string"==typeof t&&DATE_ONLY.test(t.trim()),gmtLabel=t=>{if(0===t)return"GMT";const e=t>0?"+":"-",r=Math.abs(t),n=r%60;return`GMT${e}${Math.floor(r/60)}${0===n?"":`:${pad2(n)}`}`},shifted=(t,e,r)=>{const n=new Date(t.getTime()+6e4*e);return{year:n.getUTCFullYear(),month:n.getUTCMonth(),day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),label:r}},inIanaZone=(t,e)=>{const r=dateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",hour12:!1}).format(t),n=r.match(/\d+/g)??[];if(5!==n.length)throw new Error(`Unexpected date text from Intl for zone ${e}: ${r}`);const[o="",i="",a="",m="",l=""]=n,u=Number.parseInt(a,10),c=Number.parseInt(o,10)-1,s=Number.parseInt(i,10),g=Number.parseInt(m,10)%24,f=Number.parseInt(l,10),p=Date.UTC(u,c,s,g,f),d=Math.round((p-6e4*Math.floor(t.getTime()/6e4))/6e4);return{year:u,month:c,day:s,hour:g,minute:f,label:gmtLabel(d)}},wallClock=(t,e)=>IST_NAMES.includes(e)?shifted(t,330,"IST"):"UTC"===e?shifted(t,0,"UTC"):"viewer"===e?{year:t.getFullYear(),month:t.getMonth(),day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),label:gmtLabel(-t.getTimezoneOffset())}:inIanaZone(t,e),hourCycleOf=t=>t.hourCycle??12,dayMonthYear=t=>`${pad2(t.day)}-${MONTHS[t.month]}-${t.year}`,numericDate=(t,e)=>{const r=pad2(t.day),n=pad2(t.month+1),o=String(t.year).padStart(4,"0");return"DayMonthYear"===e?`${r}/${n}/${o}`:"MonthDayYear"===e?`${n}/${r}/${o}`:`${o}-${n}-${r}`},clockTime=(t,e)=>24===e?`${pad2(t.hour)}:${pad2(t.minute)}`:`${t.hour%12||12}:${pad2(t.minute)} ${t.hour<12?"AM":"PM"}`,labelled=(t,e)=>e??!IST_NAMES.includes(t),withLabel=(t,e,r,n)=>labelled(r,n)?`${t} ${e.label}`:t,intlZone=t=>{if("viewer"!==t)return IST_NAMES.includes(t)?"Asia/Kolkata":t},digitSets=new Map,localeDigits=t=>{const e=digitSets.get(t);if(void 0!==e)return e;const r=new Intl.NumberFormat(t,{useGrouping:!1}),n=new Set;for(let t=0;t<=9;t++)n.add(r.format(t));return digitSets.set(t,n),n},digitsIn=(t,e)=>Array.from(t).filter(t=>e.has(t)).join(""),hasFormatToParts=t=>"function"==typeof t.formatToParts,localeDayMonthYear=(t,e,r)=>{const n=dateTimeFormat(e,{day:"2-digit",month:"short",year:"numeric",timeZone:r});if(!hasFormatToParts(n)){const n=localeDigits(e);return`${digitsIn(dateTimeFormat(e,{day:"2-digit",timeZone:r}).format(t),n)}-${dateTimeFormat(e,{month:"short",timeZone:r}).format(t).trim().replace(".","")}-${digitsIn(dateTimeFormat(e,{year:"numeric",timeZone:r}).format(t),n)}`}const o=n.formatToParts(t),part=t=>o.find(e=>e.type===t)?.value??"";return`${part("day")}-${part("month").replace(".","")}-${part("year")}`},dateText=(t,e)=>{const r=getFormatterConfig().dateOrder??"DayMonthNameYear";if("DayMonthNameYear"!==r)return numericDate(wallClock(t,e),r);const n=configuredLocale();return n?localeDayMonthYear(t,n,intlZone(e)):dayMonthYear(wallClock(t,e))},localeClock=(t,e,r,n)=>dateTimeFormat(e,{hour:"2-digit",minute:"2-digit",timeZone:intlZone(r),timeZoneName:labelled(r,n.zoneLabel)?"short":void 0,hourCycle:void 0===n.hourCycle?void 0:24===n.hourCycle?"h23":"h12"}).format(t);export const formatDate=(t,e={})=>{const r=toInstant(t);return r?dateText(r,isDateOnly(t)?"UTC":e.zone??getFormatterConfig().zone):emptyOf(e.empty)};export const formatTime=(t,e={})=>{const r=toInstant(t);if(!r)return emptyOf(e.empty);const n=e.zone??getFormatterConfig().zone,o=configuredLocale();if(o)return localeClock(r,o,n,e);const i=wallClock(r,n);return withLabel(clockTime(i,hourCycleOf(e)),i,n,e.zoneLabel)};export const formatDateTime=(t,e={})=>{const r=toInstant(t);if(!r)return emptyOf(e.empty);const n=e.zone??getFormatterConfig().zone,o=configuredLocale();if(o)return`${dateText(r,n)}, ${localeClock(r,o,n,e)}`;const i=wallClock(r,n);return withLabel(`${dateText(r,n)}, ${clockTime(i,hourCycleOf(e))}`,i,n,e.zoneLabel)};const SECOND=1e3,MINUTE=6e4,HOUR=36e5,DAY=24*HOUR,WEEK=7*DAY,MONTH=30*DAY,YEAR=365*DAY,INTL_UNITS=[["year",YEAR],["month",MONTH],["day",DAY],["hour",HOUR],["minute",6e4]];export const formatRelative=(t,e={})=>{const r=toInstant(t),n=toInstant(e.now??Date.now());if(!r||!n)return emptyOf(e.empty);const o=r.getTime()-n.getTime(),i=Math.abs(o),a="function"==typeof Intl.RelativeTimeFormat?Intl.RelativeTimeFormat:void 0,m=configuredLocale();if((null!==m||!0===e.intl)&&"function"==typeof a){const t=relativeTimeFormat(a,m??getFormatterConfig().locale),[e,r]=INTL_UNITS.find(([,t])=>i>=t)??["second",1e3];return t.format(Math.round(o/r),e)}if(i<6e4)return"just now";const[l,u]=i<HOUR?["minute",6e4]:i<DAY?["hour",HOUR]:i<WEEK?["day",DAY]:i<MONTH?["week",WEEK]:i<YEAR?["month",MONTH]:["year",YEAR],c=Math.floor(i/u),s=`${c} ${l}${1===c?"":"s"}`;return o<0?`${s} ago`:`in ${s}`};const toNumber=t=>{if(null==t)return null;if("string"==typeof t&&""===t.trim())return null;const e="number"==typeof t?t:Number(t);return Number.isFinite(e)?e:null},clampDigits=t=>Math.min(20,Math.max(0,Math.trunc(t))),shiftDecimal=(t,e)=>/e/i.test(String(t))?t*10**e:Number(`${t}e${e}`),houseSeparators=()=>numberSeparators()??{decimal:".",group:","},groupInteger=(t,e,r)=>{if("none"===e||t.length<=3)return t;if("international"===e)return t.replace(/\B(?=(\d{3})+(?!\d))/g,r);return`${t.slice(0,-3).replace(/\B(?=(\d{2})+(?!\d))/g,r)}${r}${t.slice(-3)}`},hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,plainDigits=(t,e)=>{if(hasIntlNumber())return numberFormat("en-US",{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}).format(t);const r=Math.min(e,15);return shiftDecimal(Math.round(shiftDecimal(t,r)),-r).toFixed(r)},decimalText=(t,e,r,n)=>{const o=Math.max(clampDigits(r),clampDigits(e)),i=clampDigits(e),a=plainDigits(Math.abs(t),o),[m="0",l=""]=a.split(".");let u=l.padEnd(i,"0");for(;u.length>i&&u.endsWith("0");)u=u.slice(0,-1);const c=houseSeparators(),s=groupInteger(m,n,c.group)+(u?`${c.decimal}${u}`:"");return t<0&&/[1-9]/.test(a)?`-${s}`:s},HOUSE_NUMBER_KEYS=new Set(["grouping","minimumFractionDigits","maximumFractionDigits","locale","empty","scale"]),intlNumberOptions=t=>{if(!Object.entries(t).some(([t,e])=>void 0!==e&&!HOUSE_NUMBER_KEYS.has(t)))return null;const{grouping:e,locale:r,empty:n,scale:o,...i}=t;return"none"===e&&void 0===i.useGrouping?{...i,useGrouping:!1}:i},localeOf=t=>t.locale??getFormatterConfig().locale,intlTextLocale=t=>{const e=configuredLocale();return null===e||"indian"===t.grouping||"international"===t.grouping?null:t.locale??e},fractionDigits=(t,e)=>{const r=clampDigits(t);return{minimumFractionDigits:r,maximumFractionDigits:Math.max(r,clampDigits(e))}},groupingOption=t=>"none"===t?{useGrouping:!1}:{};export const formatNumber=(t,e={})=>{const r=toNumber(t);if(null===r)return emptyOf(e.empty);const n=intlNumberOptions(e);if(n)return styledNumber(numberFormat(localeOf(e),n),r);const o=intlTextLocale(e);return o?styledNumber(numberFormat(o,{...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??3),...groupingOption(e.grouping)}),r):decimalText(r,e.minimumFractionDigits??0,e.maximumFractionDigits??3,e.grouping??groupingForLocale(localeOf(e)))};export const formatPercent=(t,e={})=>{const r=toNumber(t);if(null===r)return emptyOf(e.empty);const n=intlNumberOptions(e);if(n){const t="percent"===e.scale?shiftDecimal(r,-2):r;return styledNumber(numberFormat(localeOf(e),{style:"percent",...n}),t)}const o=intlTextLocale(e);if(o){const t="percent"===e.scale?shiftDecimal(r,-2):r;return styledNumber(numberFormat(o,{style:"percent",...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??e.minimumFractionDigits??0),...groupingOption(e.grouping)}),t)}const i="percent"===e.scale?r:shiftDecimal(r,2);return`${decimalText(i,e.minimumFractionDigits??0,e.maximumFractionDigits??e.minimumFractionDigits??0,e.grouping??groupingForLocale(localeOf(e)))}%`};const SYMBOLS={INR:"₹",USD:"$",EUR:"€",GBP:"£"},MINOR_DIGITS={JPY:0,KRW:0,VND:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3};export const formatMinor=(t,e)=>{if(!e?.currency)throw new TypeError('formatMinor needs options.currency, an ISO 4217 code such as "INR".');const r=toNumber(t);if(null===r)return emptyOf(e.empty);const n=e.currency.toUpperCase(),o=MINOR_DIGITS[n]??2,i=Math.round(Math.abs(r)),a=String(i).padStart(o+1,"0"),m=a.slice(0,a.length-o);let l=a.slice(a.length-o);e.dropZeroDecimals&&/^0*$/.test(l)&&(l="");const u=intlTextLocale({grouping:e.grouping});if(u)try{const t=Number(`${r<0&&0!==i?"-":""}${m}.${a.slice(a.length-o)||"0"}`);return styledNumber(numberFormat(u,{...!1===e.symbol?{}:{style:"currency",currency:n},...fractionDigits(l?o:0,o),...groupingOption(e.grouping)}),t)}catch(t){if(t instanceof RangeError)throw new RangeError(`formatMinor rejected currency "${n}" or locale "${u}": ${t.message}`,{cause:t});throw t}const c=e.grouping??("INR"===n?"indian":"international"),s=houseSeparators(),g=groupInteger(m,c,s.group)+(l?`${s.decimal}${l}`:""),f=r<0&&0!==i?"-":"";if(!1===e.symbol)return`${f}${g}`;const p=SYMBOLS[n];return p?`${f}${p}${g}`:`${f}${n} ${g}`};
1
+ "use strict";import{configuredLocale,getFormatterConfig,groupingForLocale,numberSeparators,styledNumber}from"./formatConfig.js";import{dateTimeFormat,numberFormat,relativeTimeFormat}from"./intlCache.js";const MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],IST_OFFSET_MINUTES=330,IST_TIME_ZONE="Asia/Kolkata",IST_NAMES=["IST",IST_TIME_ZONE,"Asia/Calcutta"],DATE_ONLY=/^\d{4}-\d{2}-\d{2}$/,pad2=t=>t<10?`0${t}`:`${t}`,emptyOf=t=>t??getFormatterConfig().empty,toInstant=t=>{if(null==t||""===t)return null;const e=t instanceof Date?t:new Date("string"==typeof t?t.trim():t);return Number.isNaN(e.getTime())?null:e},isDateOnly=t=>"string"==typeof t&&DATE_ONLY.test(t.trim()),gmtLabel=t=>{if(0===t)return"GMT";const e=t>0?"+":"-",r=Math.abs(t),n=r%60;return`GMT${e}${Math.floor(r/60)}${0===n?"":`:${pad2(n)}`}`},shifted=(t,e,r)=>{const n=new Date(t.getTime()+6e4*e);return{year:n.getUTCFullYear(),month:n.getUTCMonth(),day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),label:r}},inIanaZone=(t,e)=>{const r=dateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",hour12:!1}).format(t),n=r.match(/\d+/g)??[];if(5!==n.length)throw new Error(`Unexpected date text from Intl for zone ${e}: ${r}`);const[o="",i="",a="",m="",l=""]=n,u=Number.parseInt(a,10),c=Number.parseInt(o,10)-1,s=Number.parseInt(i,10),g=Number.parseInt(m,10)%24,f=Number.parseInt(l,10),p=Date.UTC(u,c,s,g,f),d=Math.round((p-6e4*Math.floor(t.getTime()/6e4))/6e4);return{year:u,month:c,day:s,hour:g,minute:f,label:gmtLabel(d)}},wallClock=(t,e)=>IST_NAMES.includes(e)?shifted(t,330,"IST"):"UTC"===e?shifted(t,0,"UTC"):"viewer"===e?{year:t.getFullYear(),month:t.getMonth(),day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),label:gmtLabel(-t.getTimezoneOffset())}:inIanaZone(t,e),hourCycleOf=t=>t.hourCycle??12,dayMonthYear=t=>`${pad2(t.day)}-${MONTHS[t.month]}-${t.year}`,numericDate=(t,e)=>{const r=pad2(t.day),n=pad2(t.month+1),o=String(t.year).padStart(4,"0");return"DayMonthYear"===e?`${r}/${n}/${o}`:"MonthDayYear"===e?`${n}/${r}/${o}`:`${o}-${n}-${r}`},clockTime=(t,e)=>24===e?`${pad2(t.hour)}:${pad2(t.minute)}`:`${t.hour%12||12}:${pad2(t.minute)} ${t.hour<12?"AM":"PM"}`,labelled=(t,e)=>e??!IST_NAMES.includes(t),withLabel=(t,e,r,n)=>labelled(r,n)?`${t} ${e.label}`:t,intlZone=t=>{if("viewer"!==t)return IST_NAMES.includes(t)?IST_TIME_ZONE:t},digitSets=new Map,localeDigits=t=>{const e=digitSets.get(t);if(void 0!==e)return e;const r=new Intl.NumberFormat(t,{useGrouping:!1}),n=new Set;for(let t=0;t<=9;t++)n.add(r.format(t));return digitSets.set(t,n),n},digitsIn=(t,e)=>Array.from(t).filter(t=>e.has(t)).join(""),hasFormatToParts=t=>"function"==typeof t.formatToParts,localeDayMonthYear=(t,e,r)=>{const n=dateTimeFormat(e,{day:"2-digit",month:"short",year:"numeric",timeZone:r});if(!hasFormatToParts(n)){const n=localeDigits(e);return`${digitsIn(dateTimeFormat(e,{day:"2-digit",timeZone:r}).format(t),n)}-${dateTimeFormat(e,{month:"short",timeZone:r}).format(t).trim().replace(".","")}-${digitsIn(dateTimeFormat(e,{year:"numeric",timeZone:r}).format(t),n)}`}const o=n.formatToParts(t),part=t=>o.find(e=>e.type===t)?.value??"";return`${part("day")}-${part("month").replace(".","")}-${part("year")}`},dateText=(t,e)=>{const r=getFormatterConfig().dateOrder??"DayMonthNameYear";if("DayMonthNameYear"!==r)return numericDate(wallClock(t,e),r);const n=configuredLocale();return n?localeDayMonthYear(t,n,intlZone(e)):dayMonthYear(wallClock(t,e))},localeClock=(t,e,r,n)=>dateTimeFormat(e,{hour:"2-digit",minute:"2-digit",timeZone:intlZone(r),timeZoneName:labelled(r,n.zoneLabel)?"short":void 0,hourCycle:void 0===n.hourCycle?void 0:24===n.hourCycle?"h23":"h12"}).format(t);export const formatDate=(t,e={})=>{const r=toInstant(t);return r?dateText(r,isDateOnly(t)?"UTC":e.zone??getFormatterConfig().zone):emptyOf(e.empty)};export const formatTime=(t,e={})=>{const r=toInstant(t);if(!r)return emptyOf(e.empty);const n=e.zone??getFormatterConfig().zone,o=configuredLocale();if(o)return localeClock(r,o,n,e);const i=wallClock(r,n);return withLabel(clockTime(i,hourCycleOf(e)),i,n,e.zoneLabel)};export const formatDateTime=(t,e={})=>{const r=toInstant(t);if(!r)return emptyOf(e.empty);const n=e.zone??getFormatterConfig().zone,o=configuredLocale();if(o)return`${dateText(r,n)}, ${localeClock(r,o,n,e)}`;const i=wallClock(r,n);return withLabel(`${dateText(r,n)}, ${clockTime(i,hourCycleOf(e))}`,i,n,e.zoneLabel)};const SECOND=1e3,MINUTE=6e4,HOUR=36e5,DAY=24*HOUR,WEEK=7*DAY,MONTH=30*DAY,YEAR=365*DAY,INTL_UNITS=[["year",YEAR],["month",MONTH],["day",DAY],["hour",HOUR],["minute",6e4]];export const formatRelative=(t,e={})=>{const r=toInstant(t),n=toInstant(e.now??Date.now());if(!r||!n)return emptyOf(e.empty);const o=r.getTime()-n.getTime(),i=Math.abs(o),a="function"==typeof Intl.RelativeTimeFormat?Intl.RelativeTimeFormat:void 0,m=configuredLocale();if((null!==m||!0===e.intl)&&"function"==typeof a){const t=relativeTimeFormat(a,m??getFormatterConfig().locale),[e,r]=INTL_UNITS.find(([,t])=>i>=t)??["second",1e3];return t.format(Math.round(o/r),e)}if(i<6e4)return"just now";const[l,u]=i<HOUR?["minute",6e4]:i<DAY?["hour",HOUR]:i<WEEK?["day",DAY]:i<MONTH?["week",WEEK]:i<YEAR?["month",MONTH]:["year",YEAR],c=Math.floor(i/u),s=`${c} ${l}${1===c?"":"s"}`;return o<0?`${s} ago`:`in ${s}`};const toNumber=t=>{if(null==t)return null;if("string"==typeof t&&""===t.trim())return null;const e="number"==typeof t?t:Number(t);return Number.isFinite(e)?e:null},clampDigits=t=>Math.min(20,Math.max(0,Math.trunc(t))),shiftDecimal=(t,e)=>/e/i.test(String(t))?t*10**e:Number(`${t}e${e}`),houseSeparators=()=>numberSeparators()??{decimal:".",group:","},groupInteger=(t,e,r)=>{if("none"===e||t.length<=3)return t;if("international"===e)return t.replace(/\B(?=(\d{3})+(?!\d))/g,r);return`${t.slice(0,-3).replace(/\B(?=(\d{2})+(?!\d))/g,r)}${r}${t.slice(-3)}`},hasIntlNumber=()=>"undefined"!=typeof Intl&&"function"==typeof Intl.NumberFormat,plainDigits=(t,e)=>{if(hasIntlNumber())return numberFormat("en-US",{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}).format(t);const r=Math.min(e,15);return shiftDecimal(Math.round(shiftDecimal(t,r)),-r).toFixed(r)},decimalText=(t,e,r,n)=>{const o=Math.max(clampDigits(r),clampDigits(e)),i=clampDigits(e),a=plainDigits(Math.abs(t),o),[m="0",l=""]=a.split(".");let u=l.padEnd(i,"0");for(;u.length>i&&u.endsWith("0");)u=u.slice(0,-1);const c=houseSeparators(),s=groupInteger(m,n,c.group)+(u?`${c.decimal}${u}`:"");return t<0&&/[1-9]/.test(a)?`-${s}`:s},HOUSE_NUMBER_KEYS=new Set(["grouping","minimumFractionDigits","maximumFractionDigits","locale","empty","scale"]),intlNumberOptions=t=>{if(!Object.entries(t).some(([t,e])=>void 0!==e&&!HOUSE_NUMBER_KEYS.has(t)))return null;const{grouping:e,locale:r,empty:n,scale:o,...i}=t;return"none"===e&&void 0===i.useGrouping?{...i,useGrouping:!1}:i},localeOf=t=>t.locale??getFormatterConfig().locale,intlTextLocale=t=>{const e=configuredLocale();return null===e||"indian"===t.grouping||"international"===t.grouping?null:t.locale??e},fractionDigits=(t,e)=>{const r=clampDigits(t);return{minimumFractionDigits:r,maximumFractionDigits:Math.max(r,clampDigits(e))}},groupingOption=t=>"none"===t?{useGrouping:!1}:{};export const formatNumber=(t,e={})=>{const r=toNumber(t);if(null===r)return emptyOf(e.empty);const n=intlNumberOptions(e);if(n)return styledNumber(numberFormat(localeOf(e),n),r);const o=intlTextLocale(e);return o?styledNumber(numberFormat(o,{...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??3),...groupingOption(e.grouping)}),r):decimalText(r,e.minimumFractionDigits??0,e.maximumFractionDigits??3,e.grouping??groupingForLocale(localeOf(e)))};export const formatPercent=(t,e={})=>{const r=toNumber(t);if(null===r)return emptyOf(e.empty);const n=intlNumberOptions(e);if(n){const t="percent"===e.scale?shiftDecimal(r,-2):r;return styledNumber(numberFormat(localeOf(e),{style:"percent",...n}),t)}const o=intlTextLocale(e);if(o){const t="percent"===e.scale?shiftDecimal(r,-2):r;return styledNumber(numberFormat(o,{style:"percent",...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??e.minimumFractionDigits??0),...groupingOption(e.grouping)}),t)}const i="percent"===e.scale?r:shiftDecimal(r,2);return`${decimalText(i,e.minimumFractionDigits??0,e.maximumFractionDigits??e.minimumFractionDigits??0,e.grouping??groupingForLocale(localeOf(e)))}%`};const SYMBOLS={INR:"₹",USD:"$",EUR:"€",GBP:"£"},MINOR_DIGITS={JPY:0,KRW:0,VND:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3};export const formatMinor=(t,e)=>{if(!e?.currency)throw new TypeError('formatMinor needs options.currency, an ISO 4217 code such as "INR".');const r=toNumber(t);if(null===r)return emptyOf(e.empty);const n=e.currency.toUpperCase(),o=MINOR_DIGITS[n]??2,i=Math.round(Math.abs(r)),a=String(i).padStart(o+1,"0"),m=a.slice(0,a.length-o);let l=a.slice(a.length-o);e.dropZeroDecimals&&/^0*$/.test(l)&&(l="");const u=intlTextLocale({grouping:e.grouping});if(u)try{const t=Number(`${r<0&&0!==i?"-":""}${m}.${a.slice(a.length-o)||"0"}`);return styledNumber(numberFormat(u,{...!1===e.symbol?{}:{style:"currency",currency:n},...fractionDigits(l?o:0,o),...groupingOption(e.grouping)}),t)}catch(t){if(t instanceof RangeError)throw new RangeError(`formatMinor rejected currency "${n}" or locale "${u}": ${t.message}`,{cause:t});throw t}const c=e.grouping??("INR"===n?"indian":"international"),s=houseSeparators(),g=groupInteger(m,c,s.group)+(l?`${s.decimal}${l}`:""),f=r<0&&0!==i?"-":"";if(!1===e.symbol)return`${f}${g}`;const p=SYMBOLS[n];return p?`${f}${p}${g}`:`${f}${n} ${g}`};
@@ -0,0 +1 @@
1
+ "use strict";import{useCallback,useEffect,useMemo,useRef,useState}from"react";import{AppState}from"react-native";import{endSessionAndLogout}from"../api/tokenRefresh.js";import{Logger}from"../logger/index.js";import{Storage}from"../storage/index.js";export const IDLE_LAST_ACTIVITY_KEY="webority.idle.lastActivityAt";const MIN_TIMEOUT_MS=6e4,SAVE_INTERVAL_MS=5e3,CLOCK_SKEW_MS=5e3,TICK_MS=1e3,MAX_TIMER_MS=2147483647,activityCallbacks=new Set;export function reportIdleActivity(){for(const e of activityCallbacks)e()}const signOutOnTimeout=()=>endSessionAndLogout("idle",null,null),assertOptions=(e,t)=>{if(!Number.isInteger(e)||e<6e4)throw new RangeError(`useIdleTimeout: timeoutMs must be a whole number of at least 60000, got ${e}`);if(!(t>=0&&t<e))throw new RangeError(`useIdleTimeout: warningMs must be 0 or more and less than timeoutMs, got ${t}`)};export function useIdleTimeout({timeoutMs:e,warningMs:t,active:r,onTimeout:n}){assertOptions(e,t);const[o,i]=useState("active"),[u,a]=useState(e),c=useRef("active"),s=useRef(!1),l=useRef(0),m=useRef(Number.NEGATIVE_INFINITY),d=useRef(!1),v=useRef(signOutOnTimeout),f=useRef(()=>{}),g=useCallback(e=>{const t=Date.now();!e&&t-m.current<5e3||(m.current=t,Storage.setItem(IDLE_LAST_ACTIVITY_KEY,String(l.current)).then(e=>{e||d.current||(d.current=!0,Logger.warn("[Idle] the last activity time could not be saved; the timer runs from memory"))}))},[]),I=useCallback(()=>{s.current&&"active"===c.current&&(l.current=Date.now(),g(!1))},[g]),T=useCallback(()=>f.current(),[]),S=useMemo(()=>({onStartShouldSetResponderCapture:()=>(I(),!1),onMoveShouldSetResponderCapture:()=>(I(),!1)}),[I]);return useEffect(()=>{v.current=n??signOutOnTimeout}),useEffect(()=>{if(!r)return s.current=!1,c.current="active",i("active"),a(e),void Storage.removeItem(IDLE_LAST_ACTIVITY_KEY).then(e=>{e||Logger.warn("[Idle] the saved activity time could not be cleared")});let n,o,u=!1;s.current=!0,0===l.current&&(l.current=Date.now());const stopTimers=()=>{void 0!==n&&(clearTimeout(n),n=void 0),void 0!==o&&(clearInterval(o),o=void 0)},timeOut=()=>{if("timedOut"===c.current)return;stopTimers(),c.current="timedOut",i("timedOut"),a(0);(async()=>{await v.current()})().catch(e=>{Logger.error("[Idle] the timeout handler failed:",e)})},evaluate=()=>{if("timedOut"===c.current)return;const r=Date.now(),n=l.current+e;r>=n?timeOut():t>0&&r>=n-t?showWarning(n-r):showActive()},showActive=()=>{void 0!==o&&(clearInterval(o),o=void 0),c.current="active",i("active"),a(e),void 0!==n&&clearTimeout(n);const r=l.current+e-t;n=setTimeout(evaluate,Math.min(2147483647,Math.max(0,r-Date.now())))},showWarning=e=>{void 0!==n&&(clearTimeout(n),n=void 0),c.current="warning",i("warning"),a(e),void 0===o&&(o=setInterval(evaluate,1e3))},restore=async()=>{const t=await Storage.getItem(IDLE_LAST_ACTIVITY_KEY);if(!u&&"timedOut"!==c.current){if(null!==t){const r=Number(t),n=Date.now();if(!Number.isFinite(r)||r>n+5e3||n-r>=e)return void timeOut();l.current=r}evaluate()}};f.current=()=>{"warning"===c.current&&(l.current=Date.now(),g(!0),showActive())},activityCallbacks.add(I);const m=AppState.addEventListener("change",e=>{"background"===e?g(!0):"active"===e&&restore()});return restore(),()=>{u=!0,s.current=!1,stopTimers(),activityCallbacks.delete(I),m.remove()}},[r,e,t,I,g]),{phase:o,remainingMs:u,stayActive:T,touchProps:S}}
@@ -0,0 +1 @@
1
+ "use strict";export{IDLE_LAST_ACTIVITY_KEY,reportIdleActivity,useIdleTimeout}from"./idleTimeout.js";
@@ -1 +1 @@
1
- "use strict";export{listQuery}from"@webority/api-contract/call";export{ACCOUNT_ID_HEADER,CLIENT_BUILD_HEADER,CLIENT_KIND,CLIENT_KIND_HEADER,getClientBuild}from"./api/clientHeaders.js";export{createContractCaller}from"./api/contractCaller.js";export{buildCurl,logCurl}from"./api/curl.js";export{fetchWithRetry}from"./api/fetchRetry.js";export{newIdempotencyKey}from"./api/idempotencyKey.js";export{addMinAppVersionListener,getMinAppVersion,MIN_APP_VERSION_HEADER}from"./api/minAppVersion.js";export{default as publicClient}from"./api/publicClient.js";export{applyRequestDefaults,newTraceparent,TRACEPARENT_HEADER}from"./api/requestDefaults.js";export{attachRetry,IDEMPOTENCY_KEY_HEADER,isNeverSentError,isRetryableFailure,isRetryableStatus,resendWhenUnanswered,retryAfterMs}from"./api/retry.js";export{refreshAccessToken}from"./api/tokenRefresh.js";export{default as userClient,injectStore,injectUserAuth,RequestOfflineError,resetRefreshState,SESSION_EXPIRED_CODE,SESSION_REVOKED_CODE}from"./api/userClient.js";export{isWorkspaceChangedError,WORKSPACE_CHANGED_CODE,WorkspaceChangedError}from"./api/workspace.js";export{ACCESS_TOKEN_KEY,addSessionEndedListener,clearSession,getSessionUser,getToken,LEGACY_REFRESH_TOKEN_LIFETIME_MS,REFRESH_TOKEN_KEY,removeSessionUser,removeToken,SESSION_USER_KEY,setKeychainImplementation,setLegacyTokenKeys,storeSessionUser,storeToken}from"./auth/authStore.js";export{decodeJWT,getJWTExpiry,isJWTExpired}from"./auth/jwt.js";export{getConfig,getConfigValue,resetConfig,setConfig}from"./config/index.js";export{ENVIRONMENT_APP_ID_SUFFIX,installedAppId}from"./config/appIdentity.js";export{DeepLink,parseDeepLink,useDeepLink}from"./deepLink/index.js";export{apiErrorMessage,CONTRACT_ERROR_CODE,extractApiError,isApiError,isNoResponse,NETWORK_CODE,OFFLINE_CODE,OFFLINE_MESSAGE,parseResponse,REQUEST_CANCELED_CODE,SERVER_FAILURE_MESSAGE,TIMEOUT_CODE,TIMEOUT_MESSAGE,toFieldPath,UNEXPECTED_MESSAGE,UNREACHABLE_MESSAGE}from"./errors/index.js";export{AsYouType,addDays,clampNationalNumber,configureFormatters,countryFlagEmoji,detectPhoneCountry,diffMs,formatCompactNumber,formatCurrency,formatDate,formatDateDDMMMYYYY,formatDateISO,formatDatePattern,formatDateTime,formatMinor,formatNumber,formatPercent,formatPhone,formatPhoneAsTyped,formatRelative,formatRelativeTime,formatTime,formatTime12h,formatTimeInWindowsZone,formatTimeInZone,getCountries,getCountryCallingCode,getFormatterConfig,getInitials,getPhoneCountries,groupingForLocale,isDateAfter,isDateBefore,isSameDay,isSupportedCountry,isValidNationalNumber,isValidPhoneNumber,maxNationalNumberLength,normalizePhone,parsePhoneNumber,parsePhoneNumberFromString,splitPhoneNumber,startOfDay,validatePhoneNumberLength}from"./formatters/index.js";export{initWebority}from"./initSDK.js";export{initUserAuth}from"./initUserAuth.js";export{configureLogger,getDeviceContext,Logger,setDeviceContext}from"./logger/index.js";export{crashlyticsRemoteLogger}from"./logger/crashlytics.js";export{addNetworkStatusListener,getNetworkStatus,setNetworkStatusImplementation,useNetworkStatus}from"./network/index.js";export{PUSH_STATUS}from"./push/status.js";export{isStorageAvailable,Storage,setStorageImplementation}from"./storage/index.js";export{encodeBase64}from"./utils/base64.js";export{checkFields,FIELD_RULE_MESSAGES,fieldRules,isAlphanumeric,isBetween,isEmail,isHexColor,isInteger,isNonEmpty,isNumeric,isPhone,isStrongPassword,isUrl,maxLength,minLength,refineWith}from"./validators/index.js";export{isBuildBelowMinimum,parseBuildNumber,setDeviceInfoImplementation,useVersionCheck,VersionCheck}from"./versionCheck/index.js";
1
+ "use strict";export{listQuery,mergeContracts,withBaseUrl}from"@webority/api-contract/call";export{ACCOUNT_ID_HEADER,CLIENT_BUILD_HEADER,CLIENT_KIND,CLIENT_KIND_HEADER,getClientBuild}from"./api/clientHeaders.js";export{createContractCaller}from"./api/contractCaller.js";export{buildCurl,logCurl}from"./api/curl.js";export{fetchWithRetry}from"./api/fetchRetry.js";export{newIdempotencyKey}from"./api/idempotencyKey.js";export{addMinAppVersionListener,getMinAppVersion,MIN_APP_VERSION_HEADER}from"./api/minAppVersion.js";export{default as publicClient}from"./api/publicClient.js";export{applyRequestDefaults,newTraceparent,TRACEPARENT_HEADER}from"./api/requestDefaults.js";export{attachRetry,IDEMPOTENCY_KEY_HEADER,isNeverSentError,isRetryableFailure,isRetryableStatus,resendWhenUnanswered,retryAfterMs}from"./api/retry.js";export{refreshAccessToken}from"./api/tokenRefresh.js";export{default as userClient,injectStore,injectUserAuth,RequestOfflineError,resetRefreshState,SESSION_EXPIRED_CODE,SESSION_REVOKED_CODE}from"./api/userClient.js";export{isWorkspaceChangedError,WORKSPACE_CHANGED_CODE,WorkspaceChangedError}from"./api/workspace.js";export{ACCESS_TOKEN_KEY,addSessionEndedListener,clearSession,getSessionUser,getToken,LEGACY_REFRESH_TOKEN_LIFETIME_MS,REFRESH_TOKEN_KEY,removeSessionUser,removeToken,SESSION_USER_KEY,setKeychainImplementation,setLegacyTokenKeys,storeSessionUser,storeToken}from"./auth/authStore.js";export{decodeJWT,getJWTExpiry,isJWTExpired}from"./auth/jwt.js";export{getConfig,getConfigValue,resetConfig,setConfig}from"./config/index.js";export{ENVIRONMENT_APP_ID_SUFFIX,installedAppId}from"./config/appIdentity.js";export{DeepLink,parseDeepLink,useDeepLink}from"./deepLink/index.js";export{apiErrorMessage,CONTRACT_ERROR_CODE,extractApiError,isApiError,isNoResponse,NETWORK_CODE,OFFLINE_CODE,OFFLINE_MESSAGE,parseResponse,REQUEST_CANCELED_CODE,SERVER_FAILURE_MESSAGE,TIMEOUT_CODE,TIMEOUT_MESSAGE,toFieldPath,UNEXPECTED_MESSAGE,UNREACHABLE_MESSAGE}from"./errors/index.js";export{AsYouType,addDays,clampNationalNumber,configureFormatters,countryFlagEmoji,detectPhoneCountry,diffMs,formatCompactNumber,formatCurrency,formatDate,formatDateDDMMMYYYY,formatDateISO,formatDatePattern,formatDateTime,formatMinor,formatNumber,formatPercent,formatPhone,formatPhoneAsTyped,formatRelative,formatRelativeTime,formatTime,formatTime12h,formatTimeInWindowsZone,formatTimeInZone,getCountries,getCountryCallingCode,getFormatterConfig,getInitials,getPhoneCountries,groupingForLocale,isDateAfter,isDateBefore,isSameDay,isSupportedCountry,isValidNationalNumber,isValidPhoneNumber,maxNationalNumberLength,normalizePhone,parsePhoneNumber,parsePhoneNumberFromString,splitPhoneNumber,startOfDay,validatePhoneNumberLength}from"./formatters/index.js";export{IDLE_LAST_ACTIVITY_KEY,reportIdleActivity,useIdleTimeout}from"./idle/index.js";export{initWebority}from"./initSDK.js";export{initUserAuth}from"./initUserAuth.js";export{configureLogger,getDeviceContext,Logger,setDeviceContext}from"./logger/index.js";export{crashlyticsRemoteLogger}from"./logger/crashlytics.js";export{addNetworkStatusListener,getNetworkStatus,setNetworkStatusImplementation,useNetworkStatus}from"./network/index.js";export{PUSH_STATUS}from"./push/status.js";export{isStorageAvailable,Storage,setStorageImplementation}from"./storage/index.js";export{encodeBase64}from"./utils/base64.js";export{checkFields,FIELD_RULE_MESSAGES,fieldRules,isAlphanumeric,isBetween,isEmail,isHexColor,isInteger,isNonEmpty,isNumeric,isPhone,isStrongPassword,isUrl,maxLength,minLength,refineWith}from"./validators/index.js";export{isBuildBelowMinimum,parseBuildNumber,setDeviceInfoImplementation,useVersionCheck,VersionCheck}from"./versionCheck/index.js";
@@ -0,0 +1 @@
1
+ "use strict";import{isIndianMobile}from"./indianMobile.js";import{isPincode}from"./pincode.js";export const INDIA_FIELD_RULE_MESSAGES={mobile:"Enter a valid 10-digit mobile number.",pincode:"Enter a valid 6-digit PIN code."};const isEmptyValue=i=>null==i||"string"==typeof i&&""===i.trim(),failWhen=(i,e)=>o=>!isEmptyValue(o)&&i(o)?e:void 0;export const indiaFieldRules={mobile:(i=INDIA_FIELD_RULE_MESSAGES.mobile)=>failWhen(i=>!isIndianMobile(i),i),pincode:(i=INDIA_FIELD_RULE_MESSAGES.pincode)=>failWhen(i=>!isPincode(i),i)};
@@ -1 +1 @@
1
- "use strict";export{aadhaarLastFour,isAadhaar,maskAadhaar,normalizeAadhaar}from"./aadhaar.js";export{currentFinancialYear,financialYearLabel,financialYearOf,parseFinancialYear,recentFinancialYears}from"./financialYear.js";export{gstinHolderPan,gstinProblem,gstinState,gstinStateCode,isGstin,normalizeGstin,sanitizeGstinInput}from"./gstin.js";export{currentStateForGstin,gstStateFromPlaceOfSupply,placeOfSupplyLabel}from"./gstStates.js";export{isIfsc,normalizeIfsc}from"./ifsc.js";export{formatIndianMobile,isIndianMobile,normalizeIndianMobile}from"./indianMobile.js";export{istDateOf,istDayBoundsUtc,istToday}from"./indiaTime.js";export{formatPaise,formatRupees,PAISE_PER_RUPEE,paiseFromRupees}from"./paise.js";export{isPan,maskPan,normalizePan}from"./pan.js";export{isPincode,normalizePincode}from"./pincode.js";
1
+ "use strict";export{aadhaarLastFour,isAadhaar,maskAadhaar,normalizeAadhaar}from"./aadhaar.js";export{INDIA_FIELD_RULE_MESSAGES,indiaFieldRules}from"./fieldRules.js";export{currentFinancialYear,financialYearLabel,financialYearOf,parseFinancialYear,recentFinancialYears}from"./financialYear.js";export{gstinHolderPan,gstinProblem,gstinState,gstinStateCode,isGstin,normalizeGstin,sanitizeGstinInput}from"./gstin.js";export{currentStateForGstin,gstStateFromPlaceOfSupply,placeOfSupplyLabel}from"./gstStates.js";export{isIfsc,normalizeIfsc}from"./ifsc.js";export{formatIndianMobile,isIndianMobile,normalizeIndianMobile}from"./indianMobile.js";export{istDateOf,istDayBoundsUtc,istToday}from"./indiaTime.js";export{formatPaise,formatRupees,PAISE_PER_RUPEE,paiseFromRupees}from"./paise.js";export{isPan,maskPan,normalizePan}from"./pan.js";export{isPincode,normalizePincode}from"./pincode.js";
@@ -0,0 +1 @@
1
+ "use strict";import{File,UploadType}from"expo-file-system";const ABSOLUTE_URL=/^https?:\/\//i,splitBackgroundBody=e=>{if("multipart"!==e.body.kind)return null;const r={},t=[];for(const o of e.body.fields)"file"in o?t.push({name:o.name,file:o.file}):r[o.name]=o.value;const[o]=t;return 1===t.length&&void 0!==o?{file:o,parameters:r}:null},parseBody=e=>{if(""===e)return null;try{return JSON.parse(e)}catch(r){if(r instanceof SyntaxError)return e;throw r}};export const isBackgroundEligible=e=>null!==splitBackgroundBody(e);export const resolveUploadUrl=(e,r)=>{if(ABSOLUTE_URL.test(e))return e;if(null===r||""===r)throw new Error("[outbox] a background upload needs an absolute url or a configured base url.");return`${r.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`};export const uploadInBackground=async e=>{const r=splitBackgroundBody(e.request);if(null===r)throw new TypeError("[outbox] this request cannot be sent in the background.");const t=new File(r.file.file.uri).createUploadTask(e.url,{httpMethod:e.request.method,uploadType:UploadType.MULTIPART,headers:e.headers,fieldName:r.file.name,mimeType:r.file.file.type,parameters:r.parameters,sessionType:"background",onProgress:({bytesSent:r,totalBytes:t})=>e.onProgress?.(r,t),...e.signal?{signal:e.signal}:{}});try{const e=await t.uploadAsync();return{status:e.status,data:parseBody(e.body)}}finally{t.release()}};
@@ -1 +1 @@
1
- "use strict";import{Directory,File,Paths}from"expo-file-system";const ROOT="webority-outbox",SAVE_FAILED="A file to send could not be saved. Attach it again.",safeFileName=e=>{const t=e.split(/[/\\]/).pop()??"",i=Array.from(t).filter(e=>(e.codePointAt(0)??0)>31).join("").trim();return""===i||"."===i||".."===i?"attachment":i},entryFolder=e=>new Directory(Paths.document,ROOT,e),saveFailed=e=>(e.exists&&e.delete(),new Error(SAVE_FAILED));export const persistRequestFiles=async(e,t)=>{if("multipart"!==t.body.kind)return t;const i=entryFolder(e);i.create({intermediates:!0,idempotent:!0});const r=[];for(const[e,o]of t.body.fields.entries()){if(!("file"in o)){r.push(o);continue}const t=new File(i,`${e}-${safeFileName(o.file.name)}`);try{await new File(o.file.uri).copy(t,{overwrite:!0})}catch{throw saveFailed(i)}if(!t.exists||0===t.size)throw saveFailed(i);r.push({name:o.name,file:{...o.file,uri:t.uri}})}return{...t,body:{kind:"multipart",fields:r}}};export const deleteEntryFiles=async e=>{const t=entryFolder(e);t.exists&&t.delete()};
1
+ "use strict";import{Directory,File,Paths}from"expo-file-system";const ROOT="webority-outbox",SAVE_FAILED="A file to send could not be saved. Attach it again.",safeFileName=e=>{const t=e.split(/[/\\]/).pop()??"",o=Array.from(t).filter(e=>(e.codePointAt(0)??0)>31).join("").trim();return""===o||"."===o||".."===o?"attachment":o},entryFolder=e=>new Directory(Paths.document,ROOT,e),saveFailed=e=>(e.exists&&e.delete(),new Error(SAVE_FAILED)),copyIntoFolder=async(e,t,o)=>{const i=new File(e,`${t}-${safeFileName(o.name)}`);try{await new File(o.uri).copy(i,{overwrite:!0})}catch{throw saveFailed(e)}if(!i.exists||0===i.size)throw saveFailed(e);return{...o,uri:i.uri}};export const persistRequestFiles=async(e,t)=>{if("json"===t.body.kind)return t;const o=entryFolder(e);if(o.create({intermediates:!0,idempotent:!0}),"resumable"===t.body.kind){const e=await copyIntoFolder(o,0,t.body.file);return{...t,body:{...t.body,file:e}}}const i=[];for(const[e,r]of t.body.fields.entries())"file"in r?i.push({name:r.name,file:await copyIntoFolder(o,e,r.file)}):i.push(r);return{...t,body:{kind:"multipart",fields:i}}};export const deleteEntryFiles=async e=>{const t=entryFolder(e);t.exists&&t.delete()};
@@ -1 +1 @@
1
- "use strict";export{OutboxFullError,OutboxMissingKeyError,OutboxSignedOutError}from"./errors.js";export{createOutbox}from"./outbox.js";
1
+ "use strict";export{OutboxFullError,OutboxMissingKeyError,OutboxSignedOutError}from"./errors.js";export{createOutbox}from"./outbox.js";export{createProgressReporter}from"./progress.js";export{useOutboxProgress}from"./useOutboxProgress.js";
@@ -1 +1 @@
1
- "use strict";import axios from"axios";import{AppState}from"react-native";import{ACCOUNT_ID_HEADER,readAccountId}from"../api/clientHeaders.js";import{newIdempotencyKey}from"../api/idempotencyKey.js";import{IDEMPOTENCY_KEY_HEADER,isNeverSentError,retryAfterMs}from"../api/retry.js";import{getAccountIdProvider}from"../api/tokenRefresh.js";import{ACCESS_TOKEN_KEY,getToken}from"../auth/authStore.js";import{decodeJWT}from"../auth/jwt.js";import{extractApiError}from"../errors/extractApiError.js";import{Logger}from"../logger/index.js";import{addNetworkStatusListener}from"../network/networkStatus.js";import{openDatabase}from"../sqlite/index.js";import{isOneOf,isRecord}from"../utils/guards.js";import{OutboxFullError,OutboxMissingKeyError,OutboxSignedOutError}from"./errors.js";import{deleteEntryFiles,persistRequestFiles}from"./files.js";const TABLE="outbox_entry",DEFAULT_DATABASE_NAME="webority-outbox",DEFAULT_MAX_ENTRIES=50,DEFAULT_KEEP_DAYS=14,DEFAULT_TIMEOUT_MS=3e5,BASE_BACKOFF_MS=3e4,MAX_BACKOFF_MS=9e5,DAY_MS=864e5,UUID_SHAPE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,MIGRATIONS=[{version:1,name:"outbox_entry",up:[`CREATE TABLE ${TABLE} (\n id TEXT PRIMARY KEY,\n owner TEXT NOT NULL,\n queue TEXT NOT NULL,\n label TEXT NOT NULL,\n request_json TEXT NOT NULL,\n state TEXT NOT NULL,\n attempts INTEGER NOT NULL,\n last_failure_json TEXT NULL,\n created_utc TEXT NOT NULL,\n next_attempt_utc TEXT NOT NULL\n )`,`CREATE INDEX outbox_entry_owner_queue_created ON ${TABLE} (owner, queue, created_utc)`]}],nowIso=()=>(new Date).toISOString(),inMs=t=>new Date(Date.now()+t).toISOString(),parseFilePart=t=>{if(!isRecord(t)||"string"!=typeof t.uri||"string"!=typeof t.name||"string"!=typeof t.type)throw new Error("[outbox] a stored file part has no uri, name and type.");return{uri:t.uri,name:t.name,type:t.type}},parseFormField=t=>{if(isRecord(t)&&"string"==typeof t.name){if("string"==typeof t.value)return{name:t.name,value:t.value};if(void 0!==t.file)return{name:t.name,file:parseFilePart(t.file)}}throw new Error("[outbox] a stored form field has no name and no value or file.")},parseBody=t=>{if(isRecord(t)&&"json"===t.kind)return{kind:"json",value:t.value};if(isRecord(t)&&"multipart"===t.kind&&Array.isArray(t.fields))return{kind:"multipart",fields:t.fields.map(parseFormField)};throw new Error("[outbox] a stored request body has no known kind.")},parseHeaders=t=>{if(!isRecord(t))throw new Error("[outbox] a stored request has no headers object.");const e={};for(const[r,a]of Object.entries(t)){if("string"!=typeof a)throw new Error(`[outbox] the stored header "${r}" is not a string.`);e[r]=a}return e},parseOutboxRequest=t=>{if(!isRecord(t)||!isOneOf(["POST","PUT","PATCH"],t.method)||"string"!=typeof t.url)throw new Error("[outbox] a stored request has no method of the right kind or no url.");const{timeoutMs:e}=t;if(void 0!==e&&"number"!=typeof e)throw new Error("[outbox] a stored request has a timeout that is not a number.");return{method:t.method,url:t.url,headers:parseHeaders(t.headers),body:parseBody(t.body),timeoutMs:"number"==typeof e?e:void 0}},parseOutboxFailure=t=>{if(!isRecord(t)||"string"!=typeof t.code||"string"!=typeof t.message)throw new Error("[outbox] a stored failure has no code or message.");if(null!==t.status&&"number"!=typeof t.status)throw new Error("[outbox] a stored failure has a status that is neither a number nor null.");return{code:t.code,message:t.message,status:t.status}},ENTRY_STATES=["Pending","Sending","Failed"],rowFieldMissing=t=>new Error(`[outbox] row has no ${t}`),parseEntryRow=t=>{const{id:e,queue:r,label:a,request_json:n,state:o,attempts:s,last_failure_json:i,created_utc:u,next_attempt_utc:d}=t;if("string"!=typeof e)throw rowFieldMissing("id");if("string"!=typeof r)throw rowFieldMissing("queue");if("string"!=typeof a)throw rowFieldMissing("label");if("string"!=typeof n)throw rowFieldMissing("request_json");if(!isOneOf(ENTRY_STATES,o))throw rowFieldMissing("state");if("number"!=typeof s)throw rowFieldMissing("attempts");if(null!==i&&"string"!=typeof i)throw rowFieldMissing("last_failure_json");if("string"!=typeof u)throw rowFieldMissing("created_utc");if("string"!=typeof d)throw rowFieldMissing("next_attempt_utc");return{id:e,queue:r,label:a,request_json:n,state:o,attempts:s,last_failure_json:i,created_utc:u,next_attempt_utc:d}},parseNextAttempt=t=>{const{next:e}=t;if(null!==e&&"string"!=typeof e)throw rowFieldMissing("next");return e},toEntry=t=>({id:t.id,queue:t.queue,label:t.label,request:parseOutboxRequest(JSON.parse(t.request_json)),state:t.state,attempts:t.attempts,lastFailure:null===t.last_failure_json?null:parseOutboxFailure(JSON.parse(t.last_failure_json)),createdDateTimeUtc:t.created_utc,nextAttemptDateTimeUtc:t.next_attempt_utc}),currentIdentity=async()=>{const t=(await getToken(ACCESS_TOKEN_KEY))?.token,e=t?decodeJWT(t)?.sub:void 0;if(!e)return null;const r=await readAccountId(getAccountIdProvider());return{owner:`${e}|${r??""}`,accountId:r}},assertRequestHeaders=t=>{const e=Object.keys(t),r=ACCOUNT_ID_HEADER.toLowerCase();for(const t of e){const e=t.toLowerCase();if("authorization"===e||e===r)throw new TypeError(`Outbox requests must not set the ${t} header.`)}const a=IDEMPOTENCY_KEY_HEADER.toLowerCase(),n=e.find(t=>t.toLowerCase()===a),o=void 0===n?void 0:t[n];if(void 0===o||!UUID_SHAPE.test(o))throw new OutboxMissingKeyError},isTransient=t=>{if(t instanceof Error&&"RequestOfflineError"===t.name)return!0;if(!axios.isAxiosError(t))return!1;if(!t.response||isNeverSentError(t))return!0;const e=t.response.status;return 408===e||429===e||e>=500},retryDelayMs=(t,e)=>(axios.isAxiosError(t)?retryAfterMs(t):null)??Math.min(9e5,3e4*2**(e-1)),failureOf=t=>{const e=extractApiError(t);return{code:e.code??"unknown",message:e.message,status:0===e.status?null:e.status}},buildFormData=t=>{const e=new FormData;for(const r of t)"file"in r?e.append(r.name,r.file):e.append(r.name,r.value);return e};export const createOutbox=t=>{const{http:e}=t,r=t.databaseName??"webority-outbox",a=t.maxEntriesPerOwner??50,n=t.keepDays??14,o=new Set,s=new Map;let i=null,u=null,d=!1,l=null,c=0,w=null;const store=()=>(i||(i=openDatabase(r).then(async t=>(await t.migrate(MIGRATIONS),t)).catch(t=>{throw i=null,t})),i),logFailure=t=>Logger.error("[outbox] background work failed",t),emit=t=>{for(const e of o)e(t)},clearTimer=()=>{null!==l&&(clearTimeout(l),l=null)},flushNow=()=>(w||(w=runFlush().finally(()=>{w=null})),w),scheduleNext=async()=>{const t=++c;if(clearTimer(),!d||!u)return;const e=await store(),r=await currentIdentity();if(!r)return;const a=await e.selectOne(`SELECT MIN(next_attempt_utc) AS next FROM ${TABLE} WHERE owner = ? AND state != 'Failed'`,[r.owner],parseNextAttempt);if(t!==c||!a)return;const n=Math.min(Math.max(0,Date.parse(a)-Date.now()),9e5);l=setTimeout(()=>{l=null,flushNow().catch(logFailure)},n)},notifyChanged=t=>{emit({type:"changed",queue:t}),scheduleNext().catch(logFailure)},runFlush=async()=>{const t=await store(),e=await currentIdentity();if(!e)return;await(async t=>{const e=new Date(Date.now()-n*DAY_MS).toISOString(),r=await t.findAll(TABLE,{sql:"created_utc < ?",params:[e]},void 0,parseEntryRow);for(const{id:e}of r)await t.remove(TABLE,{id:e}),await deleteEntryFiles(e)})(t);const r=await t.findAll(TABLE,{sql:"owner = ? AND state != 'Failed' AND next_attempt_utc <= ?",params:[e.owner,nowIso()]},{orderBy:"created_utc"},parseEntryRow);for(const t of r)await deliver(t.id,e,!1);await scheduleNext()},runDelivery=async(t,r,a)=>{const n=await store(),o=await n.findOne(TABLE,{id:t,owner:r.owner},parseEntryRow);if(!o)return null;const s={...toEntry(o),state:"Sending"};await n.update(TABLE,{state:"Sending"},{id:t}),notifyChanged(s.queue);const{request:i}=s,u={...i.headers};r.accountId&&(u[ACCOUNT_ID_HEADER]=r.accountId);const d="json"===i.body.kind?i.body.value:buildFormData(i.body.fields),l={method:i.method,url:i.url,headers:u,data:d,timeout:i.timeoutMs??3e5,retry:!1};let c;try{c=await e.request(l)}catch(t){return(async(t,e,r,a)=>{if(isTransient(r)){const a=e.attempts+1,n=inMs(retryDelayMs(r,a));return await t.update(TABLE,{state:"Pending",attempts:a,next_attempt_utc:n},{id:e.id}),notifyChanged(e.queue),{status:"Queued",entry:{...e,state:"Pending",attempts:a,nextAttemptDateTimeUtc:n}}}const n=failureOf(r);if(a)return await t.remove(TABLE,{id:e.id}),await deleteEntryFiles(e.id),notifyChanged(e.queue),{status:"Failed",entry:{...e,state:"Failed",lastFailure:n},failure:n};await t.update(TABLE,{state:"Failed",last_failure_json:JSON.stringify(n)},{id:e.id});const o={...e,state:"Failed",lastFailure:n};return notifyChanged(e.queue),emit({type:"failed",entry:o}),{status:"Failed",entry:o,failure:n}})(n,s,t,a)}return await n.remove(TABLE,{id:t}),await deleteEntryFiles(t),notifyChanged(s.queue),emit({type:"sent",entry:s,httpStatus:c.status,data:c.data}),{status:"Sent",entry:s,httpStatus:c.status,data:c.data}},deliver=(t,e,r)=>{const a=s.get(t);if(a)return a;const n=runDelivery(t,e,r).finally(()=>{s.delete(t)});return s.set(t,n),n},start=async()=>{const t=await store();return u||((()=>{d="active"===AppState.currentState;const t=addNetworkStatusListener(t=>{t.isConnected&&flushNow().catch(logFailure)}),e=AppState.addEventListener("change",t=>{d="active"===t,d?flushNow().catch(logFailure):clearTimer()});u=()=>{t(),e.remove()}})(),flushNow().catch(logFailure)),t};return{async send(t){assertRequestHeaders(t.request.headers);const e=await start(),r=await currentIdentity();if(!r)throw new OutboxSignedOutError;if(await e.count(TABLE,{owner:r.owner})>=a)throw new OutboxFullError;const n=newIdempotencyKey(),o=await persistRequestFiles(n,t.request),s=nowIso();try{await e.insert(TABLE,{id:n,owner:r.owner,queue:t.queue,label:t.label,request_json:JSON.stringify(o),state:"Pending",attempts:0,last_failure_json:null,created_utc:s,next_attempt_utc:s})}catch(t){throw await deleteEntryFiles(n),t}notifyChanged(t.queue);const i=await deliver(n,r,!0);if(!i)throw new Error("The outbox entry was removed before it was sent.");return i},async list(t){const e=await start(),r=await currentIdentity();if(!r)return[];return(await e.findAll(TABLE,{owner:r.owner,queue:t},{orderBy:"created_utc"},parseEntryRow)).map(toEntry)},async retry(t){const e=await start(),r=await currentIdentity();if(!r)throw new OutboxSignedOutError;const a=0===await e.update(TABLE,{state:"Pending",last_failure_json:null,next_attempt_utc:nowIso()},{id:t,owner:r.owner})?null:await deliver(t,r,!1);if(!a)throw new Error("The outbox entry was not found.");return a},async discard(t){const e=await start(),r=await currentIdentity();if(!r)return;await Promise.allSettled([s.get(t)]);const a=await e.findOne(TABLE,{id:t,owner:r.owner},parseEntryRow);a&&(await e.remove(TABLE,{id:t,owner:r.owner}),await deleteEntryFiles(t),notifyChanged(a.queue))},flush:async()=>(await start(),flushNow()),subscribe:t=>(o.add(t),()=>{o.delete(t)}),async close(){c+=1,clearTimer(),u?.(),u=null,d=!1}}};
1
+ "use strict";import axios from"axios";import{AppState}from"react-native";import{ACCOUNT_ID_HEADER,readAccountId}from"../api/clientHeaders.js";import{newIdempotencyKey}from"../api/idempotencyKey.js";import{IDEMPOTENCY_KEY_HEADER,isNeverSentError,retryAfterMs}from"../api/retry.js";import{getAccountIdProvider}from"../api/tokenRefresh.js";import{ACCESS_TOKEN_KEY,getToken}from"../auth/authStore.js";import{decodeJWT}from"../auth/jwt.js";import{extractApiError}from"../errors/extractApiError.js";import{Logger}from"../logger/index.js";import{addNetworkStatusListener}from"../network/networkStatus.js";import{openDatabase}from"../sqlite/index.js";import{isOneOf,isRecord}from"../utils/guards.js";import{OutboxFullError,OutboxMissingKeyError,OutboxSignedOutError}from"./errors.js";import{deleteEntryFiles,persistRequestFiles}from"./files.js";import{createProgressReporter}from"./progress.js";import{uploadResumable}from"./resumable.js";const TABLE="outbox_entry",DEFAULT_DATABASE_NAME="webority-outbox",DEFAULT_MAX_ENTRIES=50,DEFAULT_KEEP_DAYS=14,DEFAULT_TIMEOUT_MS=3e5,DEFAULT_CHUNK_BYTES=1048576,BASE_BACKOFF_MS=3e4,MAX_BACKOFF_MS=9e5,DAY_MS=864e5,UUID_SHAPE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,MIGRATIONS=[{version:1,name:"outbox_entry",up:[`CREATE TABLE ${TABLE} (\n id TEXT PRIMARY KEY,\n owner TEXT NOT NULL,\n queue TEXT NOT NULL,\n label TEXT NOT NULL,\n request_json TEXT NOT NULL,\n state TEXT NOT NULL,\n attempts INTEGER NOT NULL,\n last_failure_json TEXT NULL,\n created_utc TEXT NOT NULL,\n next_attempt_utc TEXT NOT NULL\n )`,`CREATE INDEX outbox_entry_owner_queue_created ON ${TABLE} (owner, queue, created_utc)`]},{version:2,name:"outbox_entry_upload_json",up:[`ALTER TABLE ${TABLE} ADD COLUMN upload_json TEXT NULL`]}],nowIso=()=>(new Date).toISOString(),inMs=e=>new Date(Date.now()+e).toISOString(),parseFilePart=e=>{if(!isRecord(e)||"string"!=typeof e.uri||"string"!=typeof e.name||"string"!=typeof e.type)throw new Error("[outbox] a stored file part has no uri, name and type.");return{uri:e.uri,name:e.name,type:e.type}},parseFormField=e=>{if(isRecord(e)&&"string"==typeof e.name){if("string"==typeof e.value)return{name:e.name,value:e.value};if(void 0!==e.file)return{name:e.name,file:parseFilePart(e.file)}}throw new Error("[outbox] a stored form field has no name and no value or file.")},parseMetadata=e=>{if(!isRecord(e))throw new Error("[outbox] a stored resumable body has no metadata object.");const t={};for(const[r,o]of Object.entries(e)){if("string"!=typeof o)throw new Error(`[outbox] the stored metadata "${r}" is not a string.`);t[r]=o}return t},parseBody=e=>{if(isRecord(e)&&"json"===e.kind)return{kind:"json",value:e.value};if(isRecord(e)&&"multipart"===e.kind&&Array.isArray(e.fields))return{kind:"multipart",fields:e.fields.map(parseFormField)};if(isRecord(e)&&"resumable"===e.kind)return{kind:"resumable",file:parseFilePart(e.file),metadata:parseMetadata(e.metadata)};throw new Error("[outbox] a stored request body has no known kind.")},isNonNegativeInteger=e=>"number"==typeof e&&Number.isSafeInteger(e)&&e>=0,parseUploadState=e=>{if(!isRecord(e)||"string"!=typeof e.sessionUrl||!isNonNegativeInteger(e.offset)||!isNonNegativeInteger(e.size)||e.offset>e.size)throw new Error("[outbox] a stored upload state is not valid.");return{sessionUrl:e.sessionUrl,offset:e.offset,size:e.size}},parseHeaders=e=>{if(!isRecord(e))throw new Error("[outbox] a stored request has no headers object.");const t={};for(const[r,o]of Object.entries(e)){if("string"!=typeof o)throw new Error(`[outbox] the stored header "${r}" is not a string.`);t[r]=o}return t},parseOutboxRequest=e=>{if(!isRecord(e)||!isOneOf(["POST","PUT","PATCH"],e.method)||"string"!=typeof e.url)throw new Error("[outbox] a stored request has no method of the right kind or no url.");const{timeoutMs:t}=e;if(void 0!==t&&"number"!=typeof t)throw new Error("[outbox] a stored request has a timeout that is not a number.");return{method:e.method,url:e.url,headers:parseHeaders(e.headers),body:parseBody(e.body),timeoutMs:"number"==typeof t?t:void 0}},parseOutboxFailure=e=>{if(!isRecord(e)||"string"!=typeof e.code||"string"!=typeof e.message)throw new Error("[outbox] a stored failure has no code or message.");if(null!==e.status&&"number"!=typeof e.status)throw new Error("[outbox] a stored failure has a status that is neither a number nor null.");return{code:e.code,message:e.message,status:e.status}},ENTRY_STATES=["Pending","Sending","Failed"],rowFieldMissing=e=>new Error(`[outbox] row has no ${e}`),parseEntryRow=e=>{const{id:t,queue:r,label:o,request_json:a,state:s,attempts:n,last_failure_json:i,created_utc:u,next_attempt_utc:d,upload_json:l}=e;if("string"!=typeof t)throw rowFieldMissing("id");if("string"!=typeof r)throw rowFieldMissing("queue");if("string"!=typeof o)throw rowFieldMissing("label");if("string"!=typeof a)throw rowFieldMissing("request_json");if(!isOneOf(ENTRY_STATES,s))throw rowFieldMissing("state");if("number"!=typeof n)throw rowFieldMissing("attempts");if(null!==i&&"string"!=typeof i)throw rowFieldMissing("last_failure_json");if("string"!=typeof u)throw rowFieldMissing("created_utc");if("string"!=typeof d)throw rowFieldMissing("next_attempt_utc");if(null!==l&&"string"!=typeof l)throw rowFieldMissing("upload_json");return{id:t,queue:r,label:o,request_json:a,state:s,attempts:n,last_failure_json:i,created_utc:u,next_attempt_utc:d,upload_json:l}},parseNextAttempt=e=>{const{next:t}=e;if(null!==t&&"string"!=typeof t)throw rowFieldMissing("next");return t},toEntry=e=>({id:e.id,queue:e.queue,label:e.label,request:parseOutboxRequest(JSON.parse(e.request_json)),state:e.state,attempts:e.attempts,lastFailure:null===e.last_failure_json?null:parseOutboxFailure(JSON.parse(e.last_failure_json)),createdDateTimeUtc:e.created_utc,nextAttemptDateTimeUtc:e.next_attempt_utc}),currentIdentity=async()=>{const e=(await getToken(ACCESS_TOKEN_KEY))?.token,t=e?decodeJWT(e)?.sub:void 0;if(!t)return null;const r=await readAccountId(getAccountIdProvider());return{owner:`${t}|${r??""}`,accountId:r}},assertRequestHeaders=e=>{const t=Object.keys(e),r=ACCOUNT_ID_HEADER.toLowerCase();for(const e of t){const t=e.toLowerCase();if("authorization"===t||t===r)throw new TypeError(`Outbox requests must not set the ${e} header.`)}const o=IDEMPOTENCY_KEY_HEADER.toLowerCase(),a=t.find(e=>e.toLowerCase()===o),s=void 0===a?void 0:e[a];if(void 0===s||!UUID_SHAPE.test(s))throw new OutboxMissingKeyError},isTransient=e=>{if(e instanceof Error&&"RequestOfflineError"===e.name)return!0;if(!axios.isAxiosError(e))return!1;if(!e.response||isNeverSentError(e))return!0;const t=e.response.status;return 408===t||429===t||t>=500},retryDelayMs=(e,t)=>(axios.isAxiosError(e)?retryAfterMs(e):null)??Math.min(9e5,3e4*2**(t-1)),failureOf=e=>{const t=extractApiError(e);return{code:t.code??"unknown",message:t.message,status:0===t.status?null:t.status}},buildFormData=e=>{const t=new FormData;for(const r of e)"file"in r?t.append(r.name,r.file):t.append(r.name,r.value);return t};export const createOutbox=e=>{const{http:t}=e,r=e.databaseName??"webority-outbox",o=e.maxEntriesPerOwner??50,a=e.keepDays??14,s=e.chunkBytes??1048576;if(!Number.isSafeInteger(s)||s<=0)throw new RangeError("The outbox chunkBytes option must be a positive integer.");const n=new Set,i=new Map;let u=null,d=null,l=!1,c=null,f=0,w=null;const store=()=>(u||(u=openDatabase(r).then(async e=>(await e.migrate(MIGRATIONS),e)).catch(e=>{throw u=null,e})),u),logFailure=e=>Logger.error("[outbox] background work failed",e),emit=e=>{for(const t of n)t(e)},clearTimer=()=>{null!==c&&(clearTimeout(c),c=null)},flushNow=()=>(w||(w=runFlush().finally(()=>{w=null})),w),scheduleNext=async()=>{const e=++f;if(clearTimer(),!l||!d)return;const t=await store(),r=await currentIdentity();if(!r)return;const o=await t.selectOne(`SELECT MIN(next_attempt_utc) AS next FROM ${TABLE} WHERE owner = ? AND state != 'Failed'`,[r.owner],parseNextAttempt);if(e!==f||!o)return;const a=Math.min(Math.max(0,Date.parse(o)-Date.now()),9e5);c=setTimeout(()=>{c=null,flushNow().catch(logFailure)},a)},notifyChanged=e=>{emit({type:"changed",queue:e}),scheduleNext().catch(logFailure)},runFlush=async()=>{const e=await store(),t=await currentIdentity();if(!t)return;await(async e=>{const t=new Date(Date.now()-a*DAY_MS).toISOString(),r=await e.findAll(TABLE,{sql:"created_utc < ?",params:[t]},void 0,parseEntryRow);for(const{id:t}of r)await e.remove(TABLE,{id:t}),await deleteEntryFiles(t)})(e);const r=await e.findAll(TABLE,{sql:"owner = ? AND state != 'Failed' AND next_attempt_utc <= ?",params:[t.owner,nowIso()]},{orderBy:"created_utc"},parseEntryRow);for(const e of r)await deliver(e.id,t,!1);await scheduleNext()},runDelivery=async(e,r,o)=>{const a=await store(),n=await a.findOne(TABLE,{id:e,owner:r.owner},parseEntryRow);if(!n)return null;const i={...toEntry(n),state:"Sending"};await a.update(TABLE,{state:"Sending"},{id:e}),notifyChanged(i.queue);const{request:u}=i,d={...u.headers};r.accountId&&(d[ACCOUNT_ID_HEADER]=r.accountId);const l=createProgressReporter(i,e=>emit({type:"progress",progress:e}));let c;try{c=await(async()=>{if("resumable"===u.body.kind)return uploadResumable({http:t,createUrl:u.url,headers:d,metadata:u.body.metadata,fileUri:u.body.file.uri,chunkBytes:s,timeoutMs:u.timeoutMs??3e5,state:null===n.upload_json?null:parseUploadState(JSON.parse(n.upload_json)),onState:async t=>{await a.update(TABLE,{upload_json:JSON.stringify(t)},{id:e})},onProgress:(e,t)=>l({loaded:e,total:t})});const r="json"===u.body.kind?u.body.value:buildFormData(u.body.fields),o={method:u.method,url:u.url,headers:d,data:r,timeout:u.timeoutMs??3e5,retry:!1,onUploadProgress:l},i=await t.request(o);return{httpStatus:i.status,data:i.data}})()}catch(e){return(async(e,t,r,o)=>{if(isTransient(r)){const o=t.attempts+1,a=inMs(retryDelayMs(r,o));return await e.update(TABLE,{state:"Pending",attempts:o,next_attempt_utc:a},{id:t.id}),notifyChanged(t.queue),{status:"Queued",entry:{...t,state:"Pending",attempts:o,nextAttemptDateTimeUtc:a}}}const a=failureOf(r);if(o)return await e.remove(TABLE,{id:t.id}),await deleteEntryFiles(t.id),notifyChanged(t.queue),{status:"Failed",entry:{...t,state:"Failed",lastFailure:a},failure:a};await e.update(TABLE,{state:"Failed",last_failure_json:JSON.stringify(a)},{id:t.id});const s={...t,state:"Failed",lastFailure:a};return notifyChanged(t.queue),emit({type:"failed",entry:s}),{status:"Failed",entry:s,failure:a}})(a,i,e,o)}return await a.remove(TABLE,{id:e}),await deleteEntryFiles(e),notifyChanged(i.queue),emit({type:"sent",entry:i,httpStatus:c.httpStatus,data:c.data}),{status:"Sent",entry:i,httpStatus:c.httpStatus,data:c.data}},deliver=(e,t,r)=>{const o=i.get(e);if(o)return o;const a=runDelivery(e,t,r).finally(()=>{i.delete(e)});return i.set(e,a),a},start=async()=>{const e=await store();return d||((()=>{l="active"===AppState.currentState;const e=addNetworkStatusListener(e=>{e.isConnected&&flushNow().catch(logFailure)}),t=AppState.addEventListener("change",e=>{l="active"===e,l?flushNow().catch(logFailure):clearTimer()});d=()=>{e(),t.remove()}})(),flushNow().catch(logFailure)),e};return{async send(e){assertRequestHeaders(e.request.headers);const t=await start(),r=await currentIdentity();if(!r)throw new OutboxSignedOutError;if(await t.count(TABLE,{owner:r.owner})>=o)throw new OutboxFullError;const a=newIdempotencyKey(),s=await persistRequestFiles(a,e.request),n=nowIso();try{await t.insert(TABLE,{id:a,owner:r.owner,queue:e.queue,label:e.label,request_json:JSON.stringify(s),state:"Pending",attempts:0,last_failure_json:null,created_utc:n,next_attempt_utc:n})}catch(e){throw await deleteEntryFiles(a),e}notifyChanged(e.queue);const i=await deliver(a,r,!0);if(!i)throw new Error("The outbox entry was removed before it was sent.");return i},async list(e){const t=await start(),r=await currentIdentity();if(!r)return[];return(await t.findAll(TABLE,{owner:r.owner,queue:e},{orderBy:"created_utc"},parseEntryRow)).map(toEntry)},async retry(e){const t=await start(),r=await currentIdentity();if(!r)throw new OutboxSignedOutError;const o=0===await t.update(TABLE,{state:"Pending",last_failure_json:null,next_attempt_utc:nowIso()},{id:e,owner:r.owner})?null:await deliver(e,r,!1);if(!o)throw new Error("The outbox entry was not found.");return o},async discard(e){const t=await start(),r=await currentIdentity();if(!r)return;await Promise.allSettled([i.get(e)]);const o=await t.findOne(TABLE,{id:e,owner:r.owner},parseEntryRow);o&&(await t.remove(TABLE,{id:e,owner:r.owner}),await deleteEntryFiles(e),notifyChanged(o.queue))},flush:async()=>(await start(),flushNow()),subscribe:e=>(n.add(e),()=>{n.delete(e)}),async close(){f+=1,clearTimer(),d?.(),d=null,l=!1}}};
@@ -0,0 +1 @@
1
+ "use strict";export const PROGRESS_INTERVAL_MS=100;export const PROGRESS_MIN_STEP=.01;export const createProgressReporter=(t,e)=>{let l=Number.NEGATIVE_INFINITY,o=null,n=!1;return r=>{if(n)return;const u="number"==typeof r.total&&r.total>0?r.total:null,a=null===u?null:Math.min(1,r.loaded/u),d=null!==u&&r.loaded>=u,s=Date.now();(d||s-l>=100&&(null===a||null===o||a-o>=.01))&&(n=d,l=s,o=a,e({entryId:t.id,queue:t.queue,loaded:r.loaded,total:u,fraction:a}))}};
@@ -0,0 +1 @@
1
+ "use strict";import axios from"axios";import{File,FileMode}from"expo-file-system";import{encodeBase64}from"../utils/base64.js";const TUS_VERSION="1.0.0",OFFSET_CONTENT_TYPE="application/offset+octet-stream",SESSION_GONE_STATUSES=[404,410],MAX_CONFLICT_RETRIES=2,EMPTY_FILE="The file to send is empty. Attach it again.",FILE_CHANGED="The file to send changed. Attach it again.",NO_SESSION="The upload could not be started. Try again.",BAD_OFFSET="The upload position from the server was not valid. Try again.",SESSION_EXPIRED="The upload expired and could not be restarted. Try again.",KEPT_CONFLICTING="The upload position kept changing on the server. Try again.",curated=(e,t)=>Object.assign(new Error(t),{code:e}),currentSize=e=>new File(e).size??0,encodeMetadata=e=>Object.entries(e).map(([e,t])=>`${e} ${encodeBase64((new TextEncoder).encode(t).buffer)}`).join(","),tusHeaders=(e,t)=>({...e.headers,"Tus-Resumable":"1.0.0",...t}),createSession=async e=>{const t=currentSize(e.fileUri);if(0===t)throw curated("resumable_empty",EMPTY_FILE);const a=encodeMetadata(e.metadata),r=(await e.http.request({method:"POST",url:e.createUrl,headers:tusHeaders(e,{"Upload-Length":String(t),...""===a?{}:{"Upload-Metadata":a}}),timeout:e.timeoutMs,retry:!1})).headers.location;if("string"!=typeof r||""===r)throw curated("resumable_no_location",NO_SESSION);const s={sessionUrl:r,offset:0,size:t};return await e.onState(s),s},readHead=async(e,t)=>{try{return await e.http.request({method:"HEAD",url:t,headers:tusHeaders(e,{}),timeout:e.timeoutMs,retry:!1})}catch(e){if(axios.isAxiosError(e)&&SESSION_GONE_STATUSES.includes(e.response?.status??0))return null;throw e}},parseOffset=(e,t)=>{const a=String(e??""),r=Number(a);if(!/^\d+$/.test(a)||!Number.isSafeInteger(r)||r>t)throw curated("resumable_bad_offset",BAD_OFFSET);return r},readChunk=async(e,t,a)=>{let r;try{r=new File(e).open(FileMode.ReadOnly)}catch{throw curated("resumable_changed",FILE_CHANGED)}try{r.offset=t;const e=await r.readBytes(a);if(e.byteLength!==a)throw curated("resumable_changed",FILE_CHANGED);return e}finally{r.close()}},exactBuffer=e=>0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer;export const uploadResumable=async e=>{if(null!==e.state&&currentSize(e.fileUri)!==e.state.size)throw curated("resumable_changed",FILE_CHANGED);let t=e.state??await createSession(e),a=await readHead(e,t.sessionUrl);if(null===a&&(t=await createSession(e),a=await readHead(e,t.sessionUrl),null===a))throw curated("resumable_expired",SESSION_EXPIRED);let r=parseOffset(a.headers["upload-offset"],t.size),s={httpStatus:a.status,data:a.data},o=0;for(;r<t.size;){const a=Math.min(e.chunkBytes,t.size-r),i=await readChunk(e.fileUri,r,a);let n;try{n=await e.http.request({method:"PATCH",url:t.sessionUrl,headers:tusHeaders(e,{"Upload-Offset":String(r),"Content-Type":OFFSET_CONTENT_TYPE}),data:exactBuffer(i),timeout:e.timeoutMs,retry:!1})}catch(a){if(!axios.isAxiosError(a)||409!==a.response?.status)throw a;if(o>=2)throw curated("resumable_conflict",KEPT_CONFLICTING);o+=1;const s=await readHead(e,t.sessionUrl);if(null===s)throw curated("resumable_expired",SESSION_EXPIRED);r=parseOffset(s.headers["upload-offset"],t.size);continue}o=0;const d=parseOffset(n.headers["upload-offset"],t.size);if(d<=r)throw curated("resumable_bad_offset",BAD_OFFSET);r=d,t={...t,offset:r},await e.onState(t),e.onProgress(r,t.size),s={httpStatus:n.status,data:n.data}}return s};
@@ -0,0 +1 @@
1
+ "use strict";import{useEffect,useState}from"react";export const useOutboxProgress=(e,s)=>{const[t,r]=useState(null);return useEffect(()=>(r(null),e.subscribe(e=>{"progress"===e.type&&e.progress.queue===s?r(e.progress):"changed"===e.type&&e.queue===s&&r(null)})),[e,s]),t};
@@ -1 +1 @@
1
- "use strict";import axios from"axios";import{extractApiError}from"../errors/index.js";import{Logger}from"../logger/index.js";const checkedMaxRetries=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t)||t<0)throw new Error(`createApiBaseQuery: "${e}" sets extraOptions.maxRetries to ${String(t)}; it must be a whole number of 0 or more.`);return t},encodeParam=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent("object"==typeof e?JSON.stringify(e):String(e));export const strongEntityTag=e=>{if("string"==typeof e&&!e.startsWith("W/"))return/^"([^"]*)"$/.exec(e)?.[1]};export const ifMatchValue=e=>`"${e}"`;const requestHeaders=e=>{const t={};if(e.ifMatch&&(t["If-Match"]=ifMatchValue(e.ifMatch)),e.idempotencyKey&&(t["Idempotency-Key"]=e.idempotencyKey),0===Object.keys(t).length)return e.headers;const r=Object.keys(t).map(e=>e.toLowerCase()),s=Object.entries(e.headers??{}).filter(([e])=>!r.includes(e.toLowerCase()));return{...Object.fromEntries(s),...t}},PRECONDITION_FAILED_CODE="precondition_failed",asPreconditionFailure=e=>412===e.status?{...e,code:"precondition_failed"}:e,serializeParams=e=>t=>{const r=[];for(const[s,o]of Object.entries(t)){if(null==o)continue;const t=encodeURIComponent(s);if(Array.isArray(o))if("comma"===e)r.push(`${t}=${o.map(encodeParam).join(",")}`);else{const s="brackets"===e?`${t}[]`:t;for(const e of o)r.push(`${s}=${encodeParam(e)}`)}else r.push(`${t}=${encodeParam(o)}`)}return r.join("&")};export const createApiBaseQuery=({client:e,publicClient:t})=>async(r,{signal:s},o)=>{const a="string"==typeof r?{url:r}:r,i=a.silent??o?.silent??!1,n=a.expectedStatuses??o?.expectedStatuses,c=a.paramsFormat??o?.paramsFormat,d=void 0===o?.maxRetries?void 0:checkedMaxRetries(a.url,o.maxRetries),p=a.public?t:e;if(!p)throw new Error(`createApiBaseQuery: "${a.url}" is marked public but no publicClient was passed.`);const u=requestHeaders(a),m={url:a.url,method:a.method??"GET",data:a.data,params:a.params,...c?{paramsSerializer:serializeParams(c)}:{},...void 0!==u?{headers:u}:{},...void 0!==a.responseType?{responseType:a.responseType}:{},...void 0!==a.timeout?{timeout:a.timeout}:{},...void 0===d?{}:{retry:{retries:d}},signal:s,skipErrorLog:!0};try{const e=await p.request(m),t=strongEntityTag(e.headers?.etag);return{data:e.data,meta:{silent:i,status:e.status,...void 0!==t&&{entityTag:t}}}}catch(e){const t=asPreconditionFailure(extractApiError(e)),r=axios.isCancel(e);r||Logger.requestFailed(e,{expectedStatuses:n});const s=axios.isAxiosError(e)?strongEntityTag(e.response?.headers?.etag):void 0;return{error:t,meta:{silent:i||r,status:t.status,...n&&{expectedStatuses:n},...void 0!==s&&{entityTag:s}}}}};
1
+ "use strict";import axios from"axios";import{extractApiError}from"../errors/index.js";import{Logger}from"../logger/index.js";const checkedMaxRetries=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t)||t<0)throw new Error(`createApiBaseQuery: "${e}" sets extraOptions.maxRetries to ${String(t)}; it must be a whole number of 0 or more.`);return t},encodeParam=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent("object"==typeof e?JSON.stringify(e):String(e));export const strongEntityTag=e=>{if("string"==typeof e&&!e.startsWith("W/"))return/^"([^"]*)"$/.exec(e)?.[1]};export const ifMatchValue=e=>{if("string"!=typeof e||""===e.trim())throw new Error("mobile-core: the record version is missing, so the update cannot be sent with If-Match. Read the record first and pass its version.");return`"${e}"`};const requestHeaders=e=>{const t={};if(void 0!==e.ifMatch&&(t["If-Match"]=ifMatchValue(e.ifMatch)),e.idempotencyKey&&(t["Idempotency-Key"]=e.idempotencyKey),0===Object.keys(t).length)return e.headers;const r=Object.keys(t).map(e=>e.toLowerCase()),s=Object.entries(e.headers??{}).filter(([e])=>!r.includes(e.toLowerCase()));return{...Object.fromEntries(s),...t}},PRECONDITION_FAILED_CODE="precondition_failed",asPreconditionFailure=e=>412===e.status?{...e,code:"precondition_failed"}:e,serializeParams=e=>t=>{const r=[];for(const[s,o]of Object.entries(t)){if(null==o)continue;const t=encodeURIComponent(s);if(Array.isArray(o))if("comma"===e)r.push(`${t}=${o.map(encodeParam).join(",")}`);else{const s="brackets"===e?`${t}[]`:t;for(const e of o)r.push(`${s}=${encodeParam(e)}`)}else r.push(`${t}=${encodeParam(o)}`)}return r.join("&")};export const createApiBaseQuery=({client:e,publicClient:t})=>async(r,{signal:s},o)=>{const i="string"==typeof r?{url:r}:r,a=i.silent??o?.silent??!1,n=i.expectedStatuses??o?.expectedStatuses,c=i.paramsFormat??o?.paramsFormat,d=void 0===o?.maxRetries?void 0:checkedMaxRetries(i.url,o.maxRetries),p=i.public?t:e;if(!p)throw new Error(`createApiBaseQuery: "${i.url}" is marked public but no publicClient was passed.`);const u=requestHeaders(i),m={url:i.url,...void 0!==i.baseUrl?{baseURL:i.baseUrl}:{},method:i.method??"GET",data:i.data,params:i.params,...c?{paramsSerializer:serializeParams(c)}:{},...void 0!==u?{headers:u}:{},...void 0!==i.responseType?{responseType:i.responseType}:{},...void 0!==i.timeout?{timeout:i.timeout}:{},...void 0===d?{}:{retry:{retries:d}},signal:s,skipErrorLog:!0};try{const e=await p.request(m),t=strongEntityTag(e.headers?.etag);return{data:e.data,meta:{silent:a,status:e.status,...void 0!==t&&{entityTag:t}}}}catch(e){const t=asPreconditionFailure(extractApiError(e)),r=axios.isCancel(e);r||Logger.requestFailed(e,{expectedStatuses:n});const s=axios.isAxiosError(e)?strongEntityTag(e.response?.headers?.etag):void 0;return{error:t,meta:{silent:a||r,status:t.status,...n&&{expectedStatuses:n},...void 0!==s&&{entityTag:s}}}}};
@@ -1 +1 @@
1
- "use strict";import{buildContractRequest,ContractCallError}from"@webority/api-contract/call";export const createContractQuery=t=>(e,r,o)=>{const a=t[e],d=buildContractRequest(a,r);if("blob"===a.replyKind)throw new ContractCallError(`${a.method} ${a.path} replies with a file; a file download goes through the contract caller, not a store query`);if("QUERY"===d.method)throw new ContractCallError(`${a.method} ${a.path} uses the QUERY method, which the base query does not send`);return{...o,url:d.url,method:d.method,...void 0===d.data?{}:{data:d.data},...void 0===d.headers?{}:{headers:d.headers}}};
1
+ "use strict";import{buildContractRequest,ContractCallError}from"@webority/api-contract/call";export const createContractQuery=t=>(e,r,o)=>{const a=t[e],l=buildContractRequest(a,r);if("blob"===a.replyKind)throw new ContractCallError(`${a.method} ${a.path} replies with a file; a file download goes through the contract caller, not a store query`);if("QUERY"===l.method)throw new ContractCallError(`${a.method} ${a.path} uses the QUERY method, which the base query does not send`);return{...o,url:l.url,method:l.method,...void 0===l.baseUrl?{}:{baseUrl:l.baseUrl},...void 0===l.data?{}:{data:l.data},...void 0===l.headers?{}:{headers:l.headers}}};
@@ -1 +1 @@
1
- "use strict";import{isBetween,isEmail,isInteger,isPhone,isUrl,maxLength,minLength}from"./index.js";export const FIELD_RULE_MESSAGES={required:"This field is required.",minLength:e=>`Use at least ${e} characters.`,maxLength:e=>`Use ${e} characters or fewer.`,email:"Enter a valid email address.",phone:"Enter a valid phone number.",url:"Enter a valid web address.",integer:"Enter a whole number.",between:(e,n)=>`Enter a number from ${e} to ${n}.`};const isEmptyValue=e=>null==e||"string"==typeof e&&""===e.trim(),failWhen=(e,n)=>t=>!isEmptyValue(t)&&e(t)?n:void 0;export const fieldRules={required:(e=FIELD_RULE_MESSAGES.required)=>n=>isEmptyValue(n)?e:void 0,minLength:(e,n=FIELD_RULE_MESSAGES.minLength(e))=>failWhen(n=>!minLength(n,e),n),maxLength:(e,n=FIELD_RULE_MESSAGES.maxLength(e))=>failWhen(n=>!maxLength(n,e),n),pattern:(e,n)=>t=>{if(!isEmptyValue(t))return e.lastIndex=0,e.test(String(t))?void 0:n},email:(e=FIELD_RULE_MESSAGES.email)=>failWhen(e=>!isEmail(e),e),phone:(e=FIELD_RULE_MESSAGES.phone)=>failWhen(e=>!isPhone(e),e),url:(e=FIELD_RULE_MESSAGES.url)=>failWhen(e=>!isUrl(e),e),integer:(e=FIELD_RULE_MESSAGES.integer)=>failWhen(e=>!isInteger(e),e),between:(e,n,t=FIELD_RULE_MESSAGES.between(e,n))=>failWhen(t=>!isBetween(t,e,n),t),all:(...e)=>n=>{for(const t of e){const e=t(n);if(void 0!==e)return e}}};export function checkFields(e,n){const t={};for(const[i,r]of Object.entries(n)){const n=r(e[i]);void 0!==n&&(t[i]=n)}return t}export function refineWith(e){return(n,t)=>{const i=e(n);void 0!==i&&t.addIssue({code:"custom",message:i})}}
1
+ "use strict";import{isBetween,isEmail,isInteger,isPhone,isStrongPassword,isUrl,maxLength,minLength}from"./index.js";export const FIELD_RULE_MESSAGES={required:"This field is required.",minLength:e=>`Use at least ${e} characters.`,maxLength:e=>`Use ${e} characters or fewer.`,email:"Enter a valid email address.",phone:"Enter a valid phone number.",url:"Enter a valid web address.",integer:"Enter a whole number.",between:(e,n)=>`Enter a number from ${e} to ${n}.`,strongPassword:"Use a stronger password."};const isEmptyValue=e=>null==e||"string"==typeof e&&""===e.trim(),failWhen=(e,n)=>t=>!isEmptyValue(t)&&e(t)?n:void 0;export const fieldRules={required:(e=FIELD_RULE_MESSAGES.required)=>n=>isEmptyValue(n)?e:void 0,minLength:(e,n=FIELD_RULE_MESSAGES.minLength(e))=>failWhen(n=>!minLength(n,e),n),maxLength:(e,n=FIELD_RULE_MESSAGES.maxLength(e))=>failWhen(n=>!maxLength(n,e),n),pattern:(e,n)=>t=>{if(!isEmptyValue(t))return e.lastIndex=0,e.test(String(t))?void 0:n},email:(e=FIELD_RULE_MESSAGES.email)=>failWhen(e=>!isEmail(e),e),phone:(e=FIELD_RULE_MESSAGES.phone)=>failWhen(e=>!isPhone(e),e),url:(e=FIELD_RULE_MESSAGES.url)=>failWhen(e=>!isUrl(e),e),integer:(e=FIELD_RULE_MESSAGES.integer)=>failWhen(e=>!isInteger(e),e),between:(e,n,t=FIELD_RULE_MESSAGES.between(e,n))=>failWhen(t=>!isBetween(t,e,n),t),strongPassword:(e={},n=FIELD_RULE_MESSAGES.strongPassword)=>failWhen(n=>!isStrongPassword(n,e),n),all:(...e)=>n=>{for(const t of e){const e=t(n);if(void 0!==e)return e}}};export function checkFields(e,n){const t={};for(const[r,i]of Object.entries(n)){const n=i(e[r]);void 0!==n&&(t[r]=n)}return t}export function refineWith(e){return(n,t)=>{const r=e(n);void 0!==r&&t.addIssue({code:"custom",message:r})}}
@@ -1 +1 @@
1
- "use strict";const RE_EMAIL=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,RE_NUMERIC=/^-?\d+(?:\.\d+)?$/,RE_INTEGER=/^-?\d+$/,RE_ALPHANUMERIC=/^[a-zA-Z0-9]+$/,RE_HEX_COLOR=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/,asString=t=>"string"==typeof t?t.trim():null;export const isNonEmpty=t=>{const e=asString(t);return!!e&&e.length>0};export const isEmail=t=>{const e=asString(t);return!!e&&RE_EMAIL.test(e)};export const isPhone=t=>{const e=asString(t);if(!e)return!1;const r=e.replace(/[^\d+]/g,"").replace(/^\+/,"");return r.length>=7&&r.length<=15&&/^\d+$/.test(r)};export const isUrl=t=>{const e=asString(t);if(!e)return!1;try{return new URL(e),/^https?:\/\//i.test(e)||/^[a-z][a-z0-9+\-.]*:\/\//i.test(e)}catch{return!1}};export const isNumeric=t=>{if("number"==typeof t)return Number.isFinite(t);const e=asString(t);return!!e&&RE_NUMERIC.test(e)};export const isInteger=t=>{if("number"==typeof t)return Number.isInteger(t);const e=asString(t);return!!e&&RE_INTEGER.test(e)};export const isAlphanumeric=t=>{const e=asString(t);return!!e&&RE_ALPHANUMERIC.test(e)};export const isStrongPassword=(t,e={})=>{if("string"!=typeof t)return!1;const{minLength:r=8,requireUppercase:n=!0,requireLowercase:s=!0,requireNumber:o=!0,requireSymbol:i=!1}=e;return!(t.length<r)&&(!(n&&!/[A-Z]/.test(t))&&(!(s&&!/[a-z]/.test(t))&&(!(o&&!/\d/.test(t))&&!(i&&!/[^A-Za-z0-9]/.test(t)))))};export const isHexColor=t=>{const e=asString(t);return!!e&&RE_HEX_COLOR.test(e)};export const isBetween=(t,e,r,n=!0)=>{const s="number"==typeof t?t:Number(asString(t));return!!Number.isFinite(s)&&(n?s>=e&&s<=r:s>e&&s<r)};export const minLength=(t,e)=>{const r=asString(t);return!!r&&r.length>=e};export const maxLength=(t,e)=>{const r=asString(t);return null==r||r.length<=e};export*from"./fieldRules.js";
1
+ "use strict";const RE_EMAIL=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,RE_NUMERIC=/^-?\d+(?:\.\d+)?$/,RE_INTEGER=/^-?\d+$/,RE_ALPHANUMERIC=/^[a-zA-Z0-9]+$/,RE_HEX_COLOR=/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/,asString=t=>"string"==typeof t?t.trim():null;export const isNonEmpty=t=>{const e=asString(t);return!!e&&e.length>0};export const isEmail=t=>{const e=asString(t);return!!e&&RE_EMAIL.test(e)};export const isPhone=t=>{const e=asString(t);if(!e)return!1;const r=e.replace(/[^\d+]/g,"").replace(/^\+/,"");return r.length>=7&&r.length<=15&&/^\d+$/.test(r)};export const isUrl=t=>{const e=asString(t);if(!e)return!1;try{return new URL(e),/^https?:\/\//i.test(e)||/^[a-z][a-z0-9+\-.]*:\/\//i.test(e)}catch{return!1}};export const isNumeric=t=>{if("number"==typeof t)return Number.isFinite(t);const e=asString(t);return!!e&&RE_NUMERIC.test(e)};export const isInteger=t=>{if("number"==typeof t)return Number.isInteger(t);const e=asString(t);return!!e&&RE_INTEGER.test(e)};export const isAlphanumeric=t=>{const e=asString(t);return!!e&&RE_ALPHANUMERIC.test(e)};export const isStrongPassword=(t,e={})=>{if("string"!=typeof t)return!1;const{minLength:r=10,requireUppercase:n=!0,requireLowercase:s=!0,requireNumber:o=!0,requireSymbol:i=!0}=e;return!(t.length<r)&&(!(n&&!/[A-Z]/.test(t))&&(!(s&&!/[a-z]/.test(t))&&(!(o&&!/\d/.test(t))&&!(i&&!/[^A-Za-z0-9]/.test(t)))))};export const isHexColor=t=>{const e=asString(t);return!!e&&RE_HEX_COLOR.test(e)};export const isBetween=(t,e,r,n=!0)=>{const s="number"==typeof t?t:Number(asString(t));return!!Number.isFinite(s)&&(n?s>=e&&s<=r:s>e&&s<r)};export const minLength=(t,e)=>{const r=asString(t);return!!r&&r.length>=e};export const maxLength=(t,e)=>{const r=asString(t);return null==r||r.length<=e};export*from"./fieldRules.js";
@@ -16,8 +16,12 @@ export interface AppLockState {
16
16
  biometricAvailable: boolean;
17
17
  /** False until the first biometric availability check settles, so `biometricAvailable` is not yet a real answer. */
18
18
  availabilityKnown: boolean;
19
+ /** False until the first lock check for the current `active` value has settled; keep the splash up until it is true. */
20
+ ready: boolean;
19
21
  setEnabled: (enabled: boolean) => Promise<AppLockResult>;
20
22
  unlock: (reason: string) => Promise<AppLockResult>;
23
+ /** Locks now when signed in and the lock is enabled. Returns whether it locked. */
24
+ lock: () => boolean;
21
25
  }
22
26
  export declare function isBiometricAvailable(): Promise<boolean>;
23
27
  /** A second call while a prompt is open shares that prompt. */
@@ -28,8 +28,9 @@ export interface StoredToken {
28
28
  * - `corrupt`: a stored token could not be read back as a token.
29
29
  * - `otherTab`: web only. Another tab signed out of the shared session; never
30
30
  * emitted here, declared so both platforms share one type.
31
+ * - `idle`: the idle timeout ended the session after a period with no activity.
31
32
  */
32
- export type SessionEndReason = "signedOut" | "rejected" | "terminated" | "corrupt" | "otherTab";
33
+ export type SessionEndReason = "signedOut" | "rejected" | "terminated" | "corrupt" | "otherTab" | "idle";
33
34
  /** What else is known about a session end, beside its reason. */
34
35
  export interface SessionEndDetail {
35
36
  /**
@@ -0,0 +1,29 @@
1
+ export declare const IDLE_LAST_ACTIVITY_KEY = "webority.idle.lastActivityAt";
2
+ export type IdlePhase = "active" | "warning" | "timedOut";
3
+ export interface IdleTimeoutOptions {
4
+ /** No activity for this long ends the session. A whole number of milliseconds, at least 60 000. */
5
+ timeoutMs: number;
6
+ /** The warning phase starts this long before the end. 0 gives no warning. Less than `timeoutMs`. */
7
+ warningMs: number;
8
+ /** True while a person is signed in. False watches nothing and clears the saved activity time. */
9
+ active: boolean;
10
+ /** Runs once when the time is up. Default: end the session with reason "idle". */
11
+ onTimeout?: (() => void | Promise<void>) | undefined;
12
+ }
13
+ export interface IdleTouchProps {
14
+ onStartShouldSetResponderCapture: () => false;
15
+ onMoveShouldSetResponderCapture: () => false;
16
+ }
17
+ export interface IdleTimeoutState {
18
+ phase: IdlePhase;
19
+ /** Time left before the end. Updates once a second in the warning phase; `timeoutMs` in the active phase; 0 once timed out. */
20
+ remainingMs: number;
21
+ /** The answer to the warning: counts as activity and returns to the active phase. */
22
+ stayActive: () => void;
23
+ /** Spread on the app's root View: every touch below it counts as activity, and no touch is taken from a child. */
24
+ touchProps: IdleTouchProps;
25
+ }
26
+ /** Counts as activity for a mounted useIdleTimeout. For input the root View cannot see, such as keys on the system keyboard. */
27
+ export declare function reportIdleActivity(): void;
28
+ export declare function useIdleTimeout({ timeoutMs, warningMs, active, onTimeout }: IdleTimeoutOptions): IdleTimeoutState;
29
+ //# sourceMappingURL=idleTimeout.d.ts.map
@@ -0,0 +1,3 @@
1
+ export type { IdlePhase, IdleTimeoutOptions, IdleTimeoutState, IdleTouchProps } from "./idleTimeout";
2
+ export { IDLE_LAST_ACTIVITY_KEY, reportIdleActivity, useIdleTimeout } from "./idleTimeout";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -36,8 +36,8 @@
36
36
  * client reads the bearer token. It needs no optional peer: the backend is
37
37
  * expo-secure-store, and `expo` is required anyway.
38
38
  */
39
- export type { ContractFullReply, ContractListQueryInput } from "@webority/api-contract/call";
40
- export { listQuery } from "@webority/api-contract/call";
39
+ export type { ContractFullReply, ContractListQueryInput, OperationTable } from "@webority/api-contract/call";
40
+ export { listQuery, mergeContracts, withBaseUrl } from "@webority/api-contract/call";
41
41
  export type { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
42
42
  export type { AccountIdProvider, ClientKind } from "./api/clientHeaders";
43
43
  export { ACCOUNT_ID_HEADER, CLIENT_BUILD_HEADER, CLIENT_KIND, CLIENT_KIND_HEADER, getClientBuild, } from "./api/clientHeaders";
@@ -70,6 +70,8 @@ export type { ApiError, ResponseSchema } from "./errors";
70
70
  export { apiErrorMessage, CONTRACT_ERROR_CODE, extractApiError, isApiError, isNoResponse, NETWORK_CODE, OFFLINE_CODE, OFFLINE_MESSAGE, parseResponse, REQUEST_CANCELED_CODE, SERVER_FAILURE_MESSAGE, TIMEOUT_CODE, TIMEOUT_MESSAGE, toFieldPath, UNEXPECTED_MESSAGE, UNREACHABLE_MESSAGE, } from "./errors";
71
71
  export type { DateInput, DateOrder, DateStyle, DateValue, FormatCurrencyOptions, FormatDateOptions, FormatDateTimeOptions, FormatMinorOptions, FormatNumberOptions, FormatPercentOptions, FormatPhoneOptions, FormatRelativeOptions, FormatTimeOptions, FormatterConfig, NumberGrouping, NumberStyle, PhoneCountry, PhoneCountryEntry, PhoneNumber, PhoneNumberType, PhoneParts, PhoneValidationKind, TimeStyle, ZoneMode, ZoneOption, } from "./formatters";
72
72
  export { AsYouType, addDays, clampNationalNumber, configureFormatters, countryFlagEmoji, detectPhoneCountry, diffMs, formatCompactNumber, formatCurrency, formatDate, formatDateDDMMMYYYY, formatDateISO, formatDatePattern, formatDateTime, formatMinor, formatNumber, formatPercent, formatPhone, formatPhoneAsTyped, formatRelative, formatRelativeTime, formatTime, formatTime12h, formatTimeInWindowsZone, formatTimeInZone, getCountries, getCountryCallingCode, getFormatterConfig, getInitials, getPhoneCountries, groupingForLocale, isDateAfter, isDateBefore, isSameDay, isSupportedCountry, isValidNationalNumber, isValidPhoneNumber, maxNationalNumberLength, normalizePhone, parsePhoneNumber, parsePhoneNumberFromString, splitPhoneNumber, startOfDay, validatePhoneNumberLength, } from "./formatters";
73
+ export type { IdlePhase, IdleTimeoutOptions, IdleTimeoutState, IdleTouchProps } from "./idle";
74
+ export { IDLE_LAST_ACTIVITY_KEY, reportIdleActivity, useIdleTimeout } from "./idle";
73
75
  export type { InitConfig } from "./initSDK";
74
76
  export { initWebority } from "./initSDK";
75
77
  export type { TokenRefreshConfig, TokenRefreshResult, UserAuthOptions } from "./initUserAuth";
@@ -0,0 +1,10 @@
1
+ import type { FieldRule } from "../validators/fieldRules";
2
+ export declare const INDIA_FIELD_RULE_MESSAGES: Readonly<{
3
+ mobile: string;
4
+ pincode: string;
5
+ }>;
6
+ export declare const indiaFieldRules: Readonly<{
7
+ mobile: (message?: string) => FieldRule;
8
+ pincode: (message?: string) => FieldRule;
9
+ }>;
10
+ //# sourceMappingURL=fieldRules.d.ts.map
@@ -1,4 +1,5 @@
1
1
  export { aadhaarLastFour, isAadhaar, maskAadhaar, normalizeAadhaar } from "./aadhaar";
2
+ export { INDIA_FIELD_RULE_MESSAGES, indiaFieldRules } from "./fieldRules";
2
3
  export type { FinancialYear } from "./financialYear";
3
4
  export { currentFinancialYear, financialYearLabel, financialYearOf, parseFinancialYear, recentFinancialYears } from "./financialYear";
4
5
  export type { GstinProblem } from "./gstin";
@@ -0,0 +1,18 @@
1
+ import type { OutboxRequest } from "./types";
2
+ export interface BackgroundUploadResult {
3
+ status: number;
4
+ data: unknown;
5
+ }
6
+ export interface BackgroundUploadInput {
7
+ request: OutboxRequest;
8
+ /** Absolute URL; see resolveUploadUrl. */
9
+ url: string;
10
+ /** The final header set; the caller adds Authorization and Account-Id. */
11
+ headers: Record<string, string>;
12
+ onProgress?: ((bytesSent: number, totalBytes: number) => void) | undefined;
13
+ signal?: AbortSignal | undefined;
14
+ }
15
+ export declare const isBackgroundEligible: (request: OutboxRequest) => boolean;
16
+ export declare const resolveUploadUrl: (url: string, baseUrl: string | null) => string;
17
+ export declare const uploadInBackground: (input: BackgroundUploadInput) => Promise<BackgroundUploadResult>;
18
+ //# sourceMappingURL=backgroundUpload.d.ts.map
@@ -1,4 +1,6 @@
1
1
  export { OutboxFullError, OutboxMissingKeyError, OutboxSignedOutError } from "./errors";
2
2
  export { createOutbox } from "./outbox";
3
+ export { createProgressReporter } from "./progress";
3
4
  export type * from "./types";
5
+ export { useOutboxProgress } from "./useOutboxProgress";
4
6
  //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,11 @@
1
+ import type { OutboxProgress } from "./types";
2
+ export declare const PROGRESS_INTERVAL_MS = 100;
3
+ export declare const PROGRESS_MIN_STEP = 0.01;
4
+ export declare const createProgressReporter: (entry: {
5
+ id: string;
6
+ queue: string;
7
+ }, emit: (progress: OutboxProgress) => void) => (event: {
8
+ loaded: number;
9
+ total?: number | undefined;
10
+ }) => void;
11
+ //# sourceMappingURL=progress.d.ts.map
@@ -0,0 +1,27 @@
1
+ import type { OutboxHttpClient } from "./types";
2
+ export interface ResumableUploadState {
3
+ sessionUrl: string;
4
+ offset: number;
5
+ size: number;
6
+ }
7
+ type ResumableUploadInput = {
8
+ http: OutboxHttpClient;
9
+ createUrl: string;
10
+ headers: Record<string, string>;
11
+ metadata: Record<string, string>;
12
+ fileUri: string;
13
+ chunkBytes: number;
14
+ /** Applies to each request (create, offset read, one chunk), never to the whole upload. */
15
+ timeoutMs: number;
16
+ state: ResumableUploadState | null;
17
+ onState: (state: ResumableUploadState) => Promise<void>;
18
+ onProgress: (sentBytes: number, totalBytes: number) => void;
19
+ };
20
+ type ResumableUploadResult = {
21
+ httpStatus: number;
22
+ data: unknown;
23
+ };
24
+ /** Sends the file to a tus 1.0.0 upload session in chunks, continuing from the offset the server reports. */
25
+ export declare const uploadResumable: (input: ResumableUploadInput) => Promise<ResumableUploadResult>;
26
+ export {};
27
+ //# sourceMappingURL=resumable.d.ts.map
@@ -18,10 +18,16 @@ export type OutboxBody = {
18
18
  } | {
19
19
  kind: "multipart";
20
20
  fields: OutboxFormField[];
21
+ }
22
+ /** The file goes to the tus 1.0.0 session that the request's url creates with POST. */
23
+ | {
24
+ kind: "resumable";
25
+ file: OutboxFilePart;
26
+ metadata: Record<string, string>;
21
27
  };
22
28
  export interface OutboxRequest {
23
29
  method: OutboxMethod;
24
- /** As the http client takes it (relative to its base URL). */
30
+ /** As the http client takes it (relative to its base URL); for a resumable body, the session creation endpoint. */
25
31
  url: string;
26
32
  /** Must carry Idempotency-Key (a uuid); Authorization and Account-Id are refused, the outbox sets the workspace itself. */
27
33
  headers: Record<string, string>;
@@ -60,6 +66,16 @@ export type OutboxSendResult = {
60
66
  entry: OutboxEntry;
61
67
  failure: OutboxFailure;
62
68
  };
69
+ export interface OutboxProgress {
70
+ entryId: string;
71
+ queue: string;
72
+ /** Bytes sent so far, counted from the start of the body. */
73
+ loaded: number;
74
+ /** Bytes in the whole body; null when the platform cannot tell. */
75
+ total: number | null;
76
+ /** loaded / total clamped to 0-1; null when total is null or 0. */
77
+ fraction: number | null;
78
+ }
63
79
  export type OutboxEvent = {
64
80
  type: "changed";
65
81
  queue: string;
@@ -71,6 +87,9 @@ export type OutboxEvent = {
71
87
  } | {
72
88
  type: "failed";
73
89
  entry: OutboxEntry;
90
+ } | {
91
+ type: "progress";
92
+ progress: OutboxProgress;
74
93
  };
75
94
  export type OutboxListener = (event: OutboxEvent) => void;
76
95
  /** The slice of the app's signed-in axios instance (mobile-core's userClient) the outbox sends through. */
@@ -83,6 +102,8 @@ export interface OutboxOptions {
83
102
  maxEntriesPerOwner?: number | undefined;
84
103
  /** Default 14; older entries are deleted with their files. */
85
104
  keepDays?: number | undefined;
105
+ /** A resumable body is sent in chunks of this size. Default 1_048_576. */
106
+ chunkBytes?: number | undefined;
86
107
  }
87
108
  export interface Outbox {
88
109
  /** Stores the entry (files copied first), then tries it once. Definitive refusal on this first try deletes the entry and returns Failed. */
@@ -0,0 +1,3 @@
1
+ import type { Outbox, OutboxProgress } from "./types";
2
+ export declare const useOutboxProgress: (outbox: Pick<Outbox, "subscribe">, queue: string) => OutboxProgress | null;
3
+ //# sourceMappingURL=useOutboxProgress.d.ts.map
@@ -16,6 +16,8 @@ import { type ApiError } from "../errors";
16
16
  export type ParamsFormat = "repeat" | "brackets" | "comma";
17
17
  export interface ApiRequest {
18
18
  url: string;
19
+ /** The base address of the API that serves the call; absent means the client's own base address. */
20
+ baseUrl?: string | undefined;
19
21
  method?: Method | undefined;
20
22
  /** The request body. FormData is sent as multipart by the client. */
21
23
  data?: unknown;
@@ -47,8 +49,11 @@ export interface ApiExtraOptions {
47
49
  maxRetries?: number | undefined;
48
50
  }
49
51
  export declare const strongEntityTag: (value: unknown) => string | undefined;
50
- /** The `If-Match` header value for a version: the version in quotes, as an ETag is sent. */
51
- export declare const ifMatchValue: (version: string) => string;
52
+ /**
53
+ * The `If-Match` header value for a version: the version in quotes, as an ETag is sent. A missing or blank
54
+ * version throws here, before any request is sent, so a write never goes out with no version to guard it.
55
+ */
56
+ export declare const ifMatchValue: (version: string | null | undefined) => string;
52
57
  /**
53
58
  * Returned as the base query's `meta`, which RTK Query copies onto the
54
59
  * fulfilled and rejected actions as `action.meta.baseQueryMeta`. The toast
@@ -1,7 +1,7 @@
1
1
  import { type OperationEntry, type OperationShape } from "@webority/api-contract/call";
2
2
  import type { ApiRequest } from "./apiBaseQuery";
3
3
  /** Base query options a contract call keeps: every ApiRequest field the contract does not decide. */
4
- export type ContractQueryOptions = Omit<ApiRequest, "url" | "method" | "data" | "headers" | "responseType" | "params" | "paramsFormat">;
4
+ export type ContractQueryOptions = Omit<ApiRequest, "url" | "method" | "baseUrl" | "data" | "headers" | "responseType" | "params" | "paramsFormat">;
5
5
  /** The reply type of one contract operation, for an endpoint's result type. */
6
6
  export type ContractResponse<TOperations extends {
7
7
  readonly [K in keyof TOperations]: OperationShape;
@@ -6,7 +6,7 @@ import { type ApiError } from "../errors";
6
6
  */
7
7
  export declare const versionOf: (record: unknown, entityTag?: string | undefined) => string | undefined;
8
8
  /** A copy of `cfg` that sends `version` as `If-Match`, replacing an `If-Match` under any casing; `cfg` itself is not changed. */
9
- export declare const withIfMatch: (version: string, cfg?: AxiosRequestConfig) => AxiosRequestConfig;
9
+ export declare const withIfMatch: (version: string | null | undefined, cfg?: AxiosRequestConfig) => AxiosRequestConfig;
10
10
  /** The strong ETag of a response's `etag` header, without quotes; undefined when there is none or it is weak. */
11
11
  export declare const entityTagOf: (response: {
12
12
  headers: unknown;
@@ -1,3 +1,4 @@
1
+ import type { PasswordRules } from "./index";
1
2
  /** Checks one value: the message when it fails, undefined when it passes. Fits react-hook-form's `rules.validate` as it stands. */
2
3
  export type FieldRule = (value: unknown) => string | undefined;
3
4
  /** Field name to its rule. */
@@ -11,6 +12,7 @@ export declare const FIELD_RULE_MESSAGES: Readonly<{
11
12
  url: string;
12
13
  integer: string;
13
14
  between: (min: number, max: number) => string;
15
+ strongPassword: string;
14
16
  }>;
15
17
  /** Every rule but `required` passes an empty value (null, undefined, or a string of spaces). */
16
18
  export declare const fieldRules: Readonly<{
@@ -23,6 +25,7 @@ export declare const fieldRules: Readonly<{
23
25
  url: (message?: string) => FieldRule;
24
26
  integer: (message?: string) => FieldRule;
25
27
  between: (min: number, max: number, message?: string) => FieldRule;
28
+ strongPassword: (rules?: PasswordRules, message?: string) => FieldRule;
26
29
  /** The first failing rule's message. */
27
30
  all: (...rules: readonly FieldRule[]) => FieldRule;
28
31
  }>;
@@ -16,8 +16,12 @@ export interface AppLockState {
16
16
  biometricAvailable: boolean;
17
17
  /** False until the first biometric availability check settles, so `biometricAvailable` is not yet a real answer. */
18
18
  availabilityKnown: boolean;
19
+ /** False until the first lock check for the current `active` value has settled; keep the splash up until it is true. */
20
+ ready: boolean;
19
21
  setEnabled: (enabled: boolean) => Promise<AppLockResult>;
20
22
  unlock: (reason: string) => Promise<AppLockResult>;
23
+ /** Locks now when signed in and the lock is enabled. Returns whether it locked. */
24
+ lock: () => boolean;
21
25
  }
22
26
  export declare function isBiometricAvailable(): Promise<boolean>;
23
27
  /** A second call while a prompt is open shares that prompt. */
@@ -28,8 +28,9 @@ export interface StoredToken {
28
28
  * - `corrupt`: a stored token could not be read back as a token.
29
29
  * - `otherTab`: web only. Another tab signed out of the shared session; never
30
30
  * emitted here, declared so both platforms share one type.
31
+ * - `idle`: the idle timeout ended the session after a period with no activity.
31
32
  */
32
- export type SessionEndReason = "signedOut" | "rejected" | "terminated" | "corrupt" | "otherTab";
33
+ export type SessionEndReason = "signedOut" | "rejected" | "terminated" | "corrupt" | "otherTab" | "idle";
33
34
  /** What else is known about a session end, beside its reason. */
34
35
  export interface SessionEndDetail {
35
36
  /**