@webority/mobile-core 0.178.4 → 0.180.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -2
- package/app.plugin.js +1 -0
- package/lib/commonjs/certificatePinning/plugin.js +1 -0
- package/lib/commonjs/formatters/house.js +1 -1
- package/lib/commonjs/formatters/index.js +1 -1
- package/lib/commonjs/jest/setup.js +1 -1
- package/lib/commonjs/outbox/outbox.js +1 -1
- package/lib/module/certificatePinning/plugin.js +1 -0
- package/lib/module/formatters/house.js +1 -1
- package/lib/module/formatters/index.js +1 -1
- package/lib/module/jest/setup.js +1 -1
- package/lib/module/outbox/outbox.js +1 -1
- package/lib/typescript/commonjs/certificatePinning/plugin.d.ts +23 -0
- package/lib/typescript/commonjs/formatters/house.d.ts +17 -0
- package/lib/typescript/commonjs/formatters/index.d.ts +1 -1
- package/lib/typescript/commonjs/outbox/types.d.ts +4 -0
- package/lib/typescript/module/certificatePinning/plugin.d.ts +23 -0
- package/lib/typescript/module/formatters/house.d.ts +17 -0
- package/lib/typescript/module/formatters/index.d.ts +1 -1
- package/lib/typescript/module/outbox/types.d.ts +4 -0
- package/package.json +11 -2
package/README.md
CHANGED
|
@@ -197,7 +197,7 @@ Sending happens while the app is open. `flush()` sends each due entry of the sig
|
|
|
197
197
|
one queue, a save waits behind its oldest waiting entry, so saves arrive in the order they were made.
|
|
198
198
|
A save the server refuses is listed as `Failed` and steps aside, so the queue moves on. Queues do not
|
|
199
199
|
wait for each other. `send()` to a queue that has an older waiting entry returns `Queued` without
|
|
200
|
-
trying, and the older entry goes first.
|
|
200
|
+
trying, and the older entry goes first. A one-file save on iOS goes through the background transfer, so it finishes after the app moves to the background. On Android it runs in the app's process. `createOutbox` takes `backgroundUploads` (default `true`; `false` keeps every send in the app) and `baseUrl` (the origin a relative url is sent to; without it only absolute urls go in the background). A queued entry waits for
|
|
201
201
|
the next time the app is open and online. `subscribe(listener)` reports `changed`, `sent` and
|
|
202
202
|
`failed` events, so a screen can refresh.
|
|
203
203
|
|
|
@@ -354,7 +354,7 @@ module.exports = {
|
|
|
354
354
|
};
|
|
355
355
|
```
|
|
356
356
|
|
|
357
|
-
The entry stubs `expo-application`, `expo-network`, `expo-secure-store`, `expo-
|
|
357
|
+
The entry stubs the required peers `expo-application`, `expo-network`, `expo-secure-store`, `expo-sqlite` and `expo-sqlite/kv-store`, and the optional peers `expo-file-system`, `expo-location` and `expo-image-manipulator` as virtual modules, so a consumer that leaves an optional peer out still loads the setup. Other modules (`expo-haptics`, `expo-image`, `expo-device`, reanimated, safe-area, optional peers) are the consumer's own.
|
|
358
358
|
|
|
359
359
|
## Build number header and forced updates
|
|
360
360
|
|
|
@@ -408,6 +408,56 @@ const { locked, enabled, biometricAvailable, availabilityKnown, ready, setEnable
|
|
|
408
408
|
- `setEnabled(next)` and `unlock(reason)` return an `AppLockResult`: `{ ok: true }`, or `{ ok: false, reason }` with the reason `cancelled`, `lockout`, `not-enrolled`, `not-available` or `failed`.
|
|
409
409
|
- `policy` overrides the delay and the two storage keys; the defaults are used for any key left out.
|
|
410
410
|
|
|
411
|
+
## Certificate pinning
|
|
412
|
+
|
|
413
|
+
`@webority/mobile-core` pins the public key of the API's certificate authority, and the operating system enforces the pin: an Android network security config and the iOS App Transport Security `NSPinnedDomains`. A request to a pinned host fails unless the server's certificate chain carries one of its pins.
|
|
414
|
+
|
|
415
|
+
Add the plugin to `app.json`:
|
|
416
|
+
|
|
417
|
+
```json
|
|
418
|
+
{
|
|
419
|
+
"expo": {
|
|
420
|
+
"plugins": [
|
|
421
|
+
[
|
|
422
|
+
"@webority/mobile-core",
|
|
423
|
+
{
|
|
424
|
+
"certificatePinning": {
|
|
425
|
+
"domains": [
|
|
426
|
+
{
|
|
427
|
+
"host": "api.example.com",
|
|
428
|
+
"includeSubdomains": false,
|
|
429
|
+
"pins": [
|
|
430
|
+
"<base64 SHA-256 of the current CA public key>",
|
|
431
|
+
"<base64 SHA-256 of a backup CA public key>"
|
|
432
|
+
]
|
|
433
|
+
}
|
|
434
|
+
],
|
|
435
|
+
"expiration": "2027-12-31"
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
]
|
|
439
|
+
]
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
```
|
|
443
|
+
|
|
444
|
+
- `host` is a bare hostname: no scheme, path or port.
|
|
445
|
+
- `includeSubdomains` defaults to `false`. `expiration` is optional and takes `YYYY-MM-DD`; after that date Android stops enforcing the pins.
|
|
446
|
+
- Each pin is the base64 SHA-256 of a CA's public key (SPKI), written without a `sha256/` prefix.
|
|
447
|
+
- Every domain needs two or more distinct pins, so the app keeps working when a CA changes.
|
|
448
|
+
|
|
449
|
+
Compute a pin from the issuing CA certificate in the server's chain:
|
|
450
|
+
|
|
451
|
+
```bash
|
|
452
|
+
openssl s_client -connect api.example.com:443 -showcerts </dev/null
|
|
453
|
+
# save the issuing CA certificate from the chain as ca.pem, then:
|
|
454
|
+
openssl x509 -pubkey -noout < ca.pem | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
Pick the backup pin from a CA that is not in the live chain, so a change of CA does not lock users out.
|
|
458
|
+
|
|
459
|
+
The pins are written into the native files at prebuild, so a prebuild is required after any change to them. The pins are fixed in the build: rotating a CA needs an app release. An invalid option, or an app whose Android manifest already declares a network security config, stops the prebuild with a plain message.
|
|
460
|
+
|
|
411
461
|
## Idle timeout
|
|
412
462
|
|
|
413
463
|
`useIdleTimeout` and `reportIdleActivity` end a session, or lock the app, after a set time with no touch, counting time in the background; the session ends with reason `idle`. Spread `IdleTouchProps` on the app's root view so touches count.
|
package/app.plugin.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
module.exports = require("./lib/commonjs/certificatePinning/plugin").default;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.applyNetworkSecurityConfigAttribute=applyNetworkSecurityConfigAttribute,exports.applyPinnedDomains=applyPinnedDomains,exports.buildNetworkSecurityConfig=buildNetworkSecurityConfig,exports.default=withWeborityCertificatePinning,exports.validateCertificatePinning=validateCertificatePinning;var _nodeFs=require("node:fs"),_nodePath=require("node:path"),_configPlugins=require("expo/config-plugins");const NETWORK_SECURITY_CONFIG_NAME="webority_network_security_config",NETWORK_SECURITY_CONFIG_REF=`@xml/${NETWORK_SECURITY_CONFIG_NAME}`,NETWORK_SECURITY_CONFIG_ATTRIBUTE="android:networkSecurityConfig",SHA256_BYTES=32,HOSTNAME=/^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,BASE64=/^[A-Za-z0-9+/]+={0,2}$/,EXPIRATION=/^\d{4}-\d{2}-\d{2}$/,isPlistObject=i=>"object"==typeof i&&null!==i&&!Array.isArray(i),isPin=i=>{if(!BASE64.test(i))return!1;const e=Buffer.from(i,"base64");return 32===e.length&&e.toString("base64")===i},isRealDate=i=>{const e=new Date(`${i}T00:00:00Z`);return!Number.isNaN(e.getTime())&&e.toISOString().slice(0,10)===i};function validateCertificatePinning(i){if(void 0===i)throw new Error("certificatePinning options are required");const{domains:e,expiration:n}=i;if(!Array.isArray(e)||0===e.length)throw new Error("certificatePinning.domains must list at least one domain");for(const i of e){if(!HOSTNAME.test(i.host))throw new Error(`domain host must be a bare hostname, with no scheme, path or port: ${i.host}`);const e=new Set(i.pins);if(e.size<2)throw new Error(`${i.host} needs two or more distinct pins, the current CA and a backup`);for(const n of e)if(!isPin(n))throw new Error(`${i.host} has a pin that is not a base64 SHA-256 digest (32 bytes)`)}if(!(void 0===n||EXPIRATION.test(n)&&isRealDate(n)))throw new Error("certificatePinning.expiration must be a date in YYYY-MM-DD form")}const escapeXml=i=>i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");function buildNetworkSecurityConfig(i){const e=void 0===i.expiration?"":` expiration="${escapeXml(i.expiration)}"`;return['<?xml version="1.0" encoding="utf-8"?>',"<network-security-config>",...i.domains.map(i=>[" <domain-config>",` <domain includeSubdomains="${!0===i.includeSubdomains?"true":"false"}">${escapeXml(i.host)}</domain>`,` <pin-set${e}>`,...i.pins.map(i=>` <pin digest="SHA-256">${escapeXml(i)}</pin>`)," </pin-set>"," </domain-config>"].join("\n")),"</network-security-config>",""].join("\n")}function applyPinnedDomains(i,e){const n=i.NSAppTransportSecurity,t=isPlistObject(n)?n:{},o=t.NSPinnedDomains,r={...isPlistObject(o)?o:{}};for(const i of e.domains)r[i.host]={NSIncludesSubdomains:!0===i.includeSubdomains,NSPinnedCAIdentities:i.pins.map(i=>({"SPKI-SHA256-BASE64":i}))};return{...i,NSAppTransportSecurity:{...t,NSPinnedDomains:r}}}function applyNetworkSecurityConfigAttribute(i){const e=i[NETWORK_SECURITY_CONFIG_ATTRIBUTE];if(void 0!==e&&e!==NETWORK_SECURITY_CONFIG_REF)throw new Error("The app already declares a network security config; certificate pinning cannot be added beside it.");i[NETWORK_SECURITY_CONFIG_ATTRIBUTE]=NETWORK_SECURITY_CONFIG_REF}function withWeborityCertificatePinning(i,e){const n=e?.certificatePinning;validateCertificatePinning(n);const t=(0,_configPlugins.withDangerousMod)(i,["android",async i=>{const e=(0,_nodePath.join)(i.modRequest.platformProjectRoot,"app","src","main","res","xml");return(0,_nodeFs.mkdirSync)(e,{recursive:!0}),(0,_nodeFs.writeFileSync)((0,_nodePath.join)(e,`${NETWORK_SECURITY_CONFIG_NAME}.xml`),buildNetworkSecurityConfig(n)),i}]),o=(0,_configPlugins.withAndroidManifest)(t,i=>(applyNetworkSecurityConfigAttribute(_configPlugins.AndroidConfig.Manifest.getMainApplicationOrThrow(i.modResults).$),i));return(0,_configPlugins.withInfoPlist)(o,i=>(i.modResults=applyPinnedDomains(i.modResults,n),i))}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatTime=exports.formatRelative=exports.formatPercent=exports.formatNumber=exports.formatMinor=exports.formatDateTime=exports.formatDate=void 0;var _formatConfig=require("./formatConfig.js"),_intlCache=require("./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??(0,_formatConfig.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),o=r%60;return`GMT${e}${Math.floor(r/60)}${0===o?"":`:${pad2(o)}`}`},shifted=(t,e,r)=>{const o=new Date(t.getTime()+6e4*e);return{year:o.getUTCFullYear(),month:o.getUTCMonth(),day:o.getUTCDate(),hour:o.getUTCHours(),minute:o.getUTCMinutes(),label:r}},inIanaZone=(t,e)=>{const r=(0,_intlCache.dateTimeFormat)("en-US",{timeZone:e,year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",hour12:!1}).format(t),o=r.match(/\d+/g)??[];if(5!==o.length)throw new Error(`Unexpected date text from Intl for zone ${e}: ${r}`);const[n="",i="",a="",m="",l=""]=o,c=Number.parseInt(a,10),u=Number.parseInt(n,10)-1,s=Number.parseInt(i,10),f=Number.parseInt(m,10)%24,g=Number.parseInt(l,10),p=Date.UTC(c,u,s,f,g),d=Math.round((p-6e4*Math.floor(t.getTime()/6e4))/6e4);return{year:c,month:u,day:s,hour:f,minute:g,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),o=pad2(t.month+1),n=String(t.year).padStart(4,"0");return"DayMonthYear"===e?`${r}/${o}/${n}`:"MonthDayYear"===e?`${o}/${r}/${n}`:`${n}-${o}-${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,o)=>labelled(r,o)?`${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}),o=new Set;for(let t=0;t<=9;t++)o.add(r.format(t));return digitSets.set(t,o),o},digitsIn=(t,e)=>Array.from(t).filter(t=>e.has(t)).join(""),hasFormatToParts=t=>"function"==typeof t.formatToParts,localeDayMonthYear=(t,e,r)=>{const o=(0,_intlCache.dateTimeFormat)(e,{day:"2-digit",month:"short",year:"numeric",timeZone:r});if(!hasFormatToParts(o)){const o=localeDigits(e);return`${digitsIn((0,_intlCache.dateTimeFormat)(e,{day:"2-digit",timeZone:r}).format(t),o)}-${(0,_intlCache.dateTimeFormat)(e,{month:"short",timeZone:r}).format(t).trim().replace(".","")}-${digitsIn((0,_intlCache.dateTimeFormat)(e,{year:"numeric",timeZone:r}).format(t),o)}`}const n=o.formatToParts(t),part=t=>n.find(e=>e.type===t)?.value??"";return`${part("day")}-${part("month").replace(".","")}-${part("year")}`},dateText=(t,e)=>{const r=(0,_formatConfig.getFormatterConfig)().dateOrder??"DayMonthNameYear";if("DayMonthNameYear"!==r)return numericDate(wallClock(t,e),r);const o=(0,_formatConfig.configuredLocale)();return o?localeDayMonthYear(t,o,intlZone(e)):dayMonthYear(wallClock(t,e))},localeClock=(t,e,r,o)=>(0,_intlCache.dateTimeFormat)(e,{hour:"2-digit",minute:"2-digit",timeZone:intlZone(r),timeZoneName:labelled(r,o.zoneLabel)?"short":void 0,hourCycle:void 0===o.hourCycle?void 0:24===o.hourCycle?"h23":"h12"}).format(t),formatDate=(t,e={})=>{const r=toInstant(t);return r?dateText(r,isDateOnly(t)?"UTC":e.zone??(0,_formatConfig.getFormatterConfig)().zone):emptyOf(e.empty)};exports.formatDate=formatDate;const formatTime=(t,e={})=>{const r=toInstant(t);if(!r)return emptyOf(e.empty);const o=e.zone??(0,_formatConfig.getFormatterConfig)().zone,n=(0,_formatConfig.configuredLocale)();if(n)return localeClock(r,n,o,e);const i=wallClock(r,o);return withLabel(clockTime(i,hourCycleOf(e)),i,o,e.zoneLabel)};exports.formatTime=formatTime;const formatDateTime=(t,e={})=>{const r=toInstant(t);if(!r)return emptyOf(e.empty);const o=e.zone??(0,_formatConfig.getFormatterConfig)().zone,n=(0,_formatConfig.configuredLocale)();if(n)return`${dateText(r,o)}, ${localeClock(r,n,o,e)}`;const i=wallClock(r,o);return withLabel(`${dateText(r,o)}, ${clockTime(i,hourCycleOf(e))}`,i,o,e.zoneLabel)};exports.formatDateTime=formatDateTime;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]],formatRelative=(t,e={})=>{const r=toInstant(t),o=toInstant(e.now??Date.now());if(!r||!o)return emptyOf(e.empty);const n=r.getTime()-o.getTime(),i=Math.abs(n),a=(0,_formatConfig.configuredLocale)();if(null!==a||!0===e.intl){const t=(0,_intlCache.relativeTimeFormat)(Intl.RelativeTimeFormat,a??(0,_formatConfig.getFormatterConfig)().locale),[e,r]=INTL_UNITS.find(([,t])=>i>=t)??["second",1e3];return t.format(Math.round(n/r),e)}if(i<6e4)return"just now";const[m,l]=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/l),u=`${c} ${m}${1===c?"":"s"}`;return n<0?`${u} ago`:`in ${u}`};exports.formatRelative=formatRelative;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=()=>(0,_formatConfig.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)}`},plainDigits=(t,e)=>(0,_intlCache.numberFormat)("en-US",{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}).format(t),decimalText=(t,e,r,o)=>{const n=Math.max(clampDigits(r),clampDigits(e)),i=clampDigits(e),a=plainDigits(Math.abs(t),n),[m="0",l=""]=a.split(".");let c=l.padEnd(i,"0");for(;c.length>i&&c.endsWith("0");)c=c.slice(0,-1);const u=houseSeparators(),s=groupInteger(m,o,u.group)+(c?`${u.decimal}${c}`:"");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:o,scale:n,...i}=t;return"none"===e&&void 0===i.useGrouping?{...i,useGrouping:!1}:i},localeOf=t=>t.locale??(0,_formatConfig.getFormatterConfig)().locale,intlTextLocale=t=>{const e=(0,_formatConfig.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}:{},formatNumber=(t,e={})=>{const r=toNumber(t);if(null===r)return emptyOf(e.empty);const o=intlNumberOptions(e);if(o)return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(localeOf(e),o),r);const n=intlTextLocale(e);return n?(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(n,{...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??3),...groupingOption(e.grouping)}),r):decimalText(r,e.minimumFractionDigits??0,e.maximumFractionDigits??3,e.grouping??(0,_formatConfig.groupingForLocale)(localeOf(e)))};exports.formatNumber=formatNumber;const formatPercent=(t,e={})=>{const r=toNumber(t);if(null===r)return emptyOf(e.empty);const o=intlNumberOptions(e);if(o){const t="percent"===e.scale?shiftDecimal(r,-2):r;return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(localeOf(e),{style:"percent",...o}),t)}const n=intlTextLocale(e);if(n){const t="percent"===e.scale?shiftDecimal(r,-2):r;return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(n,{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??(0,_formatConfig.groupingForLocale)(localeOf(e)))}%`};exports.formatPercent=formatPercent;const SYMBOLS={INR:"₹",USD:"$",EUR:"€",GBP:"£"},MINOR_DIGITS={JPY:0,KRW:0,VND:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3},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 o=e.currency.toUpperCase(),n=MINOR_DIGITS[o]??2,i=Math.round(Math.abs(r)),a=String(i).padStart(n+1,"0"),m=a.slice(0,a.length-n);let l=a.slice(a.length-n);e.dropZeroDecimals&&/^0*$/.test(l)&&(l="");const c=intlTextLocale({grouping:e.grouping});if(c)try{const t=Number(`${r<0&&0!==i?"-":""}${m}.${a.slice(a.length-n)||"0"}`);return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(c,{...!1===e.symbol?{}:{style:"currency",currency:o},...fractionDigits(l?n:0,n),...groupingOption(e.grouping)}),t)}catch(t){if(t instanceof RangeError)throw new RangeError(`formatMinor rejected currency "${o}" or locale "${c}": ${t.message}`,{cause:t});throw t}const u=e.grouping??("INR"===o?"indian":"international"),s=houseSeparators(),f=groupInteger(m,u,s.group)+(l?`${s.decimal}${l}`:""),g=r<0&&0!==i?"-":"";if(!1===e.symbol)return`${g}${f}`;const p=SYMBOLS[o];return p?`${g}${p}${f}`:`${g}${o} ${f}`};exports.formatMinor=formatMinor;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseHundredthMinor=exports.formatTime=exports.formatRelative=exports.formatPercent=exports.formatNumber=exports.formatMinor=exports.formatHundredthMinor=exports.formatDateTime=exports.formatDate=void 0;var _formatConfig=require("./formatConfig.js"),_intlCache=require("./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??(0,_formatConfig.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=(0,_intlCache.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="",s=""]=n,l=Number.parseInt(a,10),c=Number.parseInt(o,10)-1,u=Number.parseInt(i,10),f=Number.parseInt(m,10)%24,g=Number.parseInt(s,10),h=Date.UTC(l,c,u,f,g),d=Math.round((h-6e4*Math.floor(t.getTime()/6e4))/6e4);return{year:l,month:c,day:u,hour:f,minute:g,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=(0,_intlCache.dateTimeFormat)(e,{day:"2-digit",month:"short",year:"numeric",timeZone:r});if(!hasFormatToParts(n)){const n=localeDigits(e);return`${digitsIn((0,_intlCache.dateTimeFormat)(e,{day:"2-digit",timeZone:r}).format(t),n)}-${(0,_intlCache.dateTimeFormat)(e,{month:"short",timeZone:r}).format(t).trim().replace(".","")}-${digitsIn((0,_intlCache.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=(0,_formatConfig.getFormatterConfig)().dateOrder??"DayMonthNameYear";if("DayMonthNameYear"!==r)return numericDate(wallClock(t,e),r);const n=(0,_formatConfig.configuredLocale)();return n?localeDayMonthYear(t,n,intlZone(e)):dayMonthYear(wallClock(t,e))},localeClock=(t,e,r,n)=>(0,_intlCache.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),formatDate=(t,e={})=>{const r=toInstant(t);return r?dateText(r,isDateOnly(t)?"UTC":e.zone??(0,_formatConfig.getFormatterConfig)().zone):emptyOf(e.empty)};exports.formatDate=formatDate;const formatTime=(t,e={})=>{const r=toInstant(t);if(!r)return emptyOf(e.empty);const n=e.zone??(0,_formatConfig.getFormatterConfig)().zone,o=(0,_formatConfig.configuredLocale)();if(o)return localeClock(r,o,n,e);const i=wallClock(r,n);return withLabel(clockTime(i,hourCycleOf(e)),i,n,e.zoneLabel)};exports.formatTime=formatTime;const formatDateTime=(t,e={})=>{const r=toInstant(t);if(!r)return emptyOf(e.empty);const n=e.zone??(0,_formatConfig.getFormatterConfig)().zone,o=(0,_formatConfig.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)};exports.formatDateTime=formatDateTime;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]],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=(0,_formatConfig.configuredLocale)();if(null!==a||!0===e.intl){const t=(0,_intlCache.relativeTimeFormat)(Intl.RelativeTimeFormat,a??(0,_formatConfig.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[m,s]=i<HOUR?["minute",6e4]:i<DAY?["hour",HOUR]:i<WEEK?["day",DAY]:i<MONTH?["week",WEEK]:i<YEAR?["month",MONTH]:["year",YEAR],l=Math.floor(i/s),c=`${l} ${m}${1===l?"":"s"}`;return o<0?`${c} ago`:`in ${c}`};exports.formatRelative=formatRelative;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=()=>(0,_formatConfig.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)}`},plainDigits=(t,e)=>(0,_intlCache.numberFormat)("en-US",{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}).format(t),decimalText=(t,e,r,n)=>{const o=Math.max(clampDigits(r),clampDigits(e)),i=clampDigits(e),a=plainDigits(Math.abs(t),o),[m="0",s=""]=a.split(".");let l=s.padEnd(i,"0");for(;l.length>i&&l.endsWith("0");)l=l.slice(0,-1);const c=houseSeparators(),u=groupInteger(m,n,c.group)+(l?`${c.decimal}${l}`:"");return t<0&&/[1-9]/.test(a)?`-${u}`:u},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??(0,_formatConfig.getFormatterConfig)().locale,intlTextLocale=t=>{const e=(0,_formatConfig.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}:{},formatNumber=(t,e={})=>{const r=toNumber(t);if(null===r)return emptyOf(e.empty);const n=intlNumberOptions(e);if(n)return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(localeOf(e),n),r);const o=intlTextLocale(e);return o?(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(o,{...fractionDigits(e.minimumFractionDigits??0,e.maximumFractionDigits??3),...groupingOption(e.grouping)}),r):decimalText(r,e.minimumFractionDigits??0,e.maximumFractionDigits??3,e.grouping??(0,_formatConfig.groupingForLocale)(localeOf(e)))};exports.formatNumber=formatNumber;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(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(localeOf(e),{style:"percent",...n}),t)}const o=intlTextLocale(e);if(o){const t="percent"===e.scale?shiftDecimal(r,-2):r;return(0,_formatConfig.styledNumber)((0,_intlCache.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??(0,_formatConfig.groupingForLocale)(localeOf(e)))}%`};exports.formatPercent=formatPercent;const SYMBOLS={INR:"₹",USD:"$",EUR:"€",GBP:"£"},MINOR_DIGITS={JPY:0,KRW:0,VND:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3},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 s=a.slice(a.length-o);e.dropZeroDecimals&&/^0*$/.test(s)&&(s="");const l=intlTextLocale({grouping:e.grouping});if(l)try{const t=Number(`${r<0&&0!==i?"-":""}${m}.${a.slice(a.length-o)||"0"}`);return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(l,{...!1===e.symbol?{}:{style:"currency",currency:n},...fractionDigits(s?o:0,o),...groupingOption(e.grouping)}),t)}catch(t){if(t instanceof RangeError)throw new RangeError(`formatMinor rejected currency "${n}" or locale "${l}": ${t.message}`,{cause:t});throw t}const c=e.grouping??("INR"===n?"indian":"international"),u=houseSeparators(),f=groupInteger(m,c,u.group)+(s?`${u.decimal}${s}`:""),g=r<0&&0!==i?"-":"";if(!1===e.symbol)return`${g}${f}`;const h=SYMBOLS[n];return h?`${g}${h}${f}`:`${g}${n} ${f}`};exports.formatMinor=formatMinor;const HUNDREDTH_EXTRA_DIGITS=2,RUPEE_SIGN="₹",trimHundredths=(t,e)=>{let r=t.length;for(;r>e&&"0"===t.slice(r-1,r);)r-=1;return t.slice(0,r)},formatHundredthMinor=(t,e)=>{if(!e?.currency)throw new TypeError('formatHundredthMinor needs options.currency, an ISO 4217 code such as "INR".');const r=toNumber(t);if(null===r)return emptyOf(e.empty);if(!Number.isSafeInteger(r))throw new RangeError(`formatHundredthMinor needs a whole number of hundredths within the safe integer range, got ${r}.`);const n=e.currency.toUpperCase(),o=MINOR_DIGITS[n]??2,i=o+2,a=String(Math.abs(r)).padStart(i+1,"0"),m=a.slice(a.length-i),s=a.slice(0,a.length-i);let l=trimHundredths(m,o);e.dropZeroDecimals&&/^0*$/.test(l)&&(l="");const c=r<0?"-":"",u=intlTextLocale({grouping:e.grouping});if(u)try{const t=Number(`${c}${s}.${m}`);return(0,_formatConfig.styledNumber)((0,_intlCache.numberFormat)(u,{...!1===e.symbol?{}:{style:"currency",currency:n},...fractionDigits(l.length,i),...groupingOption(e.grouping)}),t)}catch(t){if(t instanceof RangeError)throw new RangeError(`formatHundredthMinor rejected currency "${n}" or locale "${u}": ${t.message}`,{cause:t});throw t}const f=e.grouping??("INR"===n?"indian":"international"),g=houseSeparators(),h=groupInteger(s,f,g.group)+(l?`${g.decimal}${l}`:"");if(!1===e.symbol)return`${c}${h}`;const d=SYMBOLS[n];return d?`${c}${d}${h}`:`${c}${n} ${h}`};exports.formatHundredthMinor=formatHundredthMinor;const wholeDigitsOf=(t,e)=>{let r="",n=!0;for(const o of t)if(e.includes(o)){if(n)return null;n=!0}else{if(!/\d/.test(o))return null;r+=o,n=!1}return n&&""!==t?null:r},parseHundredthMinor=(t,e)=>{if(!e?.currency)throw new TypeError('parseHundredthMinor needs options.currency, an ISO 4217 code such as "INR".');const r=e.currency.toUpperCase(),n=(MINOR_DIGITS[r]??2)+2,refuse=e=>new RangeError(`parseHundredthMinor cannot read "${t}": ${e}`);let o=t.trim();if(""===o)throw refuse("the text is empty");let i=!1;o.startsWith("-")&&(i=!0,o=o.slice(1).trim());const a=["₹",SYMBOLS[r]];for(const t of a)if(t&&o.startsWith(t)){o=o.slice(t.length).trim();break}const m=houseSeparators(),s=[",",m.group].filter(t=>t!==m.decimal),l=o.split(m.decimal);if(l.length>2)throw refuse("more than one decimal separator");const c=wholeDigitsOf(l[0]??"",s);if(null===c)throw refuse("a character that is not a digit, a group separator or the decimal separator");const u=2===l.length,f=l[1]??"";if(u&&!/^\d+$/.test(f))throw refuse("the decimal part must be one or more digits");if(f.length>n)throw refuse(`more than ${n} decimal places, the most this currency takes`);const g=c+f.padEnd(n,"0");if(""===g)throw refuse("it has no digits");const h=Number(g);if(!Number.isSafeInteger(h))throw refuse("the amount is beyond the safe integer range");return i&&0!==h?-h:h};exports.parseHundredthMinor=parseHundredthMinor;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"AsYouType",{enumerable:!0,get:function(){return _phone.AsYouType}}),Object.defineProperty(exports,"addDays",{enumerable:!0,get:function(){return _dateMath.addDays}}),Object.defineProperty(exports,"clampNationalNumber",{enumerable:!0,get:function(){return _phone.clampNationalNumber}}),Object.defineProperty(exports,"configureFormatters",{enumerable:!0,get:function(){return _formatConfig.configureFormatters}}),Object.defineProperty(exports,"countryFlagEmoji",{enumerable:!0,get:function(){return _phone.countryFlagEmoji}}),Object.defineProperty(exports,"detectPhoneCountry",{enumerable:!0,get:function(){return _phone.detectPhoneCountry}}),Object.defineProperty(exports,"diffMs",{enumerable:!0,get:function(){return _dateMath.diffMs}}),Object.defineProperty(exports,"formatCompactNumber",{enumerable:!0,get:function(){return _number.formatCompactNumber}}),Object.defineProperty(exports,"formatCurrency",{enumerable:!0,get:function(){return _currency.formatCurrency}}),Object.defineProperty(exports,"formatDate",{enumerable:!0,get:function(){return _date.formatDate}}),Object.defineProperty(exports,"formatDateISO",{enumerable:!0,get:function(){return _dateMath.formatDateISO}}),Object.defineProperty(exports,"formatDatePattern",{enumerable:!0,get:function(){return _dateMath.formatDatePattern}}),Object.defineProperty(exports,"formatDateTime",{enumerable:!0,get:function(){return _date.formatDateTime}}),Object.defineProperty(exports,"formatMinor",{enumerable:!0,get:function(){return _house.formatMinor}}),Object.defineProperty(exports,"formatNumber",{enumerable:!0,get:function(){return _number.formatNumber}}),Object.defineProperty(exports,"formatPercent",{enumerable:!0,get:function(){return _number.formatPercent}}),Object.defineProperty(exports,"formatPhone",{enumerable:!0,get:function(){return _phone.formatPhone}}),Object.defineProperty(exports,"formatPhoneAsTyped",{enumerable:!0,get:function(){return _phone.formatPhoneAsTyped}}),Object.defineProperty(exports,"formatRelative",{enumerable:!0,get:function(){return _house.formatRelative}}),Object.defineProperty(exports,"formatRelativeTime",{enumerable:!0,get:function(){return _date.formatRelativeTime}}),Object.defineProperty(exports,"formatTime",{enumerable:!0,get:function(){return _date.formatTime}}),Object.defineProperty(exports,"formatTime12h",{enumerable:!0,get:function(){return _dateMath.formatTime12h}}),Object.defineProperty(exports,"formatTimeInWindowsZone",{enumerable:!0,get:function(){return _dateMath.formatTimeInWindowsZone}}),Object.defineProperty(exports,"formatTimeInZone",{enumerable:!0,get:function(){return _dateMath.formatTimeInZone}}),Object.defineProperty(exports,"getCountries",{enumerable:!0,get:function(){return _phone.getCountries}}),Object.defineProperty(exports,"getCountryCallingCode",{enumerable:!0,get:function(){return _phone.getCountryCallingCode}}),Object.defineProperty(exports,"getFormatterConfig",{enumerable:!0,get:function(){return _formatConfig.getFormatterConfig}}),Object.defineProperty(exports,"getInitials",{enumerable:!0,get:function(){return _initials.getInitials}}),Object.defineProperty(exports,"getPhoneCountries",{enumerable:!0,get:function(){return _phone.getPhoneCountries}}),Object.defineProperty(exports,"groupingForLocale",{enumerable:!0,get:function(){return _formatConfig.groupingForLocale}}),Object.defineProperty(exports,"isDateAfter",{enumerable:!0,get:function(){return _dateMath.isDateAfter}}),Object.defineProperty(exports,"isDateBefore",{enumerable:!0,get:function(){return _dateMath.isDateBefore}}),Object.defineProperty(exports,"isSameDay",{enumerable:!0,get:function(){return _dateMath.isSameDay}}),Object.defineProperty(exports,"isSupportedCountry",{enumerable:!0,get:function(){return _phone.isSupportedCountry}}),Object.defineProperty(exports,"isValidNationalNumber",{enumerable:!0,get:function(){return _phone.isValidNationalNumber}}),Object.defineProperty(exports,"isValidPhoneNumber",{enumerable:!0,get:function(){return _phone.isValidPhoneNumber}}),Object.defineProperty(exports,"maxNationalNumberLength",{enumerable:!0,get:function(){return _phone.maxNationalNumberLength}}),Object.defineProperty(exports,"normalizePhone",{enumerable:!0,get:function(){return _phone.normalizePhone}}),Object.defineProperty(exports,"parsePhoneNumber",{enumerable:!0,get:function(){return _phone.parsePhoneNumber}}),Object.defineProperty(exports,"parsePhoneNumberFromString",{enumerable:!0,get:function(){return _phone.parsePhoneNumberFromString}}),Object.defineProperty(exports,"splitPhoneNumber",{enumerable:!0,get:function(){return _phone.splitPhoneNumber}}),Object.defineProperty(exports,"startOfDay",{enumerable:!0,get:function(){return _dateMath.startOfDay}}),Object.defineProperty(exports,"validatePhoneNumberLength",{enumerable:!0,get:function(){return _phone.validatePhoneNumberLength}});var _currency=require("./currency.js"),_date=require("./date.js"),_dateMath=require("./dateMath.js"),_formatConfig=require("./formatConfig.js"),_house=require("./house.js"),_initials=require("./initials.js"),_number=require("./number.js"),_phone=require("./phone.js");
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"AsYouType",{enumerable:!0,get:function(){return _phone.AsYouType}}),Object.defineProperty(exports,"addDays",{enumerable:!0,get:function(){return _dateMath.addDays}}),Object.defineProperty(exports,"clampNationalNumber",{enumerable:!0,get:function(){return _phone.clampNationalNumber}}),Object.defineProperty(exports,"configureFormatters",{enumerable:!0,get:function(){return _formatConfig.configureFormatters}}),Object.defineProperty(exports,"countryFlagEmoji",{enumerable:!0,get:function(){return _phone.countryFlagEmoji}}),Object.defineProperty(exports,"detectPhoneCountry",{enumerable:!0,get:function(){return _phone.detectPhoneCountry}}),Object.defineProperty(exports,"diffMs",{enumerable:!0,get:function(){return _dateMath.diffMs}}),Object.defineProperty(exports,"formatCompactNumber",{enumerable:!0,get:function(){return _number.formatCompactNumber}}),Object.defineProperty(exports,"formatCurrency",{enumerable:!0,get:function(){return _currency.formatCurrency}}),Object.defineProperty(exports,"formatDate",{enumerable:!0,get:function(){return _date.formatDate}}),Object.defineProperty(exports,"formatDateISO",{enumerable:!0,get:function(){return _dateMath.formatDateISO}}),Object.defineProperty(exports,"formatDatePattern",{enumerable:!0,get:function(){return _dateMath.formatDatePattern}}),Object.defineProperty(exports,"formatDateTime",{enumerable:!0,get:function(){return _date.formatDateTime}}),Object.defineProperty(exports,"formatHundredthMinor",{enumerable:!0,get:function(){return _house.formatHundredthMinor}}),Object.defineProperty(exports,"formatMinor",{enumerable:!0,get:function(){return _house.formatMinor}}),Object.defineProperty(exports,"formatNumber",{enumerable:!0,get:function(){return _number.formatNumber}}),Object.defineProperty(exports,"formatPercent",{enumerable:!0,get:function(){return _number.formatPercent}}),Object.defineProperty(exports,"formatPhone",{enumerable:!0,get:function(){return _phone.formatPhone}}),Object.defineProperty(exports,"formatPhoneAsTyped",{enumerable:!0,get:function(){return _phone.formatPhoneAsTyped}}),Object.defineProperty(exports,"formatRelative",{enumerable:!0,get:function(){return _house.formatRelative}}),Object.defineProperty(exports,"formatRelativeTime",{enumerable:!0,get:function(){return _date.formatRelativeTime}}),Object.defineProperty(exports,"formatTime",{enumerable:!0,get:function(){return _date.formatTime}}),Object.defineProperty(exports,"formatTime12h",{enumerable:!0,get:function(){return _dateMath.formatTime12h}}),Object.defineProperty(exports,"formatTimeInWindowsZone",{enumerable:!0,get:function(){return _dateMath.formatTimeInWindowsZone}}),Object.defineProperty(exports,"formatTimeInZone",{enumerable:!0,get:function(){return _dateMath.formatTimeInZone}}),Object.defineProperty(exports,"getCountries",{enumerable:!0,get:function(){return _phone.getCountries}}),Object.defineProperty(exports,"getCountryCallingCode",{enumerable:!0,get:function(){return _phone.getCountryCallingCode}}),Object.defineProperty(exports,"getFormatterConfig",{enumerable:!0,get:function(){return _formatConfig.getFormatterConfig}}),Object.defineProperty(exports,"getInitials",{enumerable:!0,get:function(){return _initials.getInitials}}),Object.defineProperty(exports,"getPhoneCountries",{enumerable:!0,get:function(){return _phone.getPhoneCountries}}),Object.defineProperty(exports,"groupingForLocale",{enumerable:!0,get:function(){return _formatConfig.groupingForLocale}}),Object.defineProperty(exports,"isDateAfter",{enumerable:!0,get:function(){return _dateMath.isDateAfter}}),Object.defineProperty(exports,"isDateBefore",{enumerable:!0,get:function(){return _dateMath.isDateBefore}}),Object.defineProperty(exports,"isSameDay",{enumerable:!0,get:function(){return _dateMath.isSameDay}}),Object.defineProperty(exports,"isSupportedCountry",{enumerable:!0,get:function(){return _phone.isSupportedCountry}}),Object.defineProperty(exports,"isValidNationalNumber",{enumerable:!0,get:function(){return _phone.isValidNationalNumber}}),Object.defineProperty(exports,"isValidPhoneNumber",{enumerable:!0,get:function(){return _phone.isValidPhoneNumber}}),Object.defineProperty(exports,"maxNationalNumberLength",{enumerable:!0,get:function(){return _phone.maxNationalNumberLength}}),Object.defineProperty(exports,"normalizePhone",{enumerable:!0,get:function(){return _phone.normalizePhone}}),Object.defineProperty(exports,"parseHundredthMinor",{enumerable:!0,get:function(){return _house.parseHundredthMinor}}),Object.defineProperty(exports,"parsePhoneNumber",{enumerable:!0,get:function(){return _phone.parsePhoneNumber}}),Object.defineProperty(exports,"parsePhoneNumberFromString",{enumerable:!0,get:function(){return _phone.parsePhoneNumberFromString}}),Object.defineProperty(exports,"splitPhoneNumber",{enumerable:!0,get:function(){return _phone.splitPhoneNumber}}),Object.defineProperty(exports,"startOfDay",{enumerable:!0,get:function(){return _dateMath.startOfDay}}),Object.defineProperty(exports,"validatePhoneNumberLength",{enumerable:!0,get:function(){return _phone.validatePhoneNumberLength}});var _currency=require("./currency.js"),_date=require("./date.js"),_dateMath=require("./dateMath.js"),_formatConfig=require("./formatConfig.js"),_house=require("./house.js"),_initials=require("./initials.js"),_number=require("./number.js"),_phone=require("./phone.js");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),jest.mock("expo-network",()=>({getNetworkStateAsync:jest.fn(()=>Promise.resolve({type:"WIFI",isConnected:!0,isInternetReachable:!0})),addNetworkStateListener:jest.fn(()=>({remove:jest.fn()}))})),jest.mock("expo-sqlite/kv-store",()=>{const e=new Map;return{__esModule:!0,default:{getItem:jest.fn(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),jest.mock("expo-network",()=>({getNetworkStateAsync:jest.fn(()=>Promise.resolve({type:"WIFI",isConnected:!0,isInternetReachable:!0})),addNetworkStateListener:jest.fn(()=>({remove:jest.fn()}))})),jest.mock("expo-sqlite/kv-store",()=>{const e=new Map;return{__esModule:!0,default:{getItem:jest.fn(t=>Promise.resolve(e.has(t)?e.get(t):null)),setItem:jest.fn((t,s)=>(e.set(t,s),Promise.resolve())),removeItem:jest.fn(t=>(e.delete(t),Promise.resolve())),clear:jest.fn(()=>(e.clear(),Promise.resolve())),getAllKeys:jest.fn(()=>Promise.resolve([...e.keys()])),multiGet:jest.fn(t=>Promise.resolve(t.map(t=>[t,e.get(t)??null]))),multiSet:jest.fn(t=>{for(const[s,n]of t)e.set(s,n);return Promise.resolve()}),multiRemove:jest.fn(t=>{for(const s of t)e.delete(s);return Promise.resolve()})}}}),jest.mock("expo-image-manipulator",()=>{const e={width:4e3,height:3e3,saveAsync:jest.fn(()=>Promise.resolve({uri:"file:///cache/out.jpg",width:1,height:1})),release:jest.fn()},t=jest.fn(()=>Promise.resolve(e)),s={resize:jest.fn(),renderAsync:t,release:jest.fn()};return s.resize.mockReturnValue(s),{ImageManipulator:{manipulate:jest.fn(()=>s)},SaveFormat:{JPEG:"jpeg",PNG:"png",WEBP:"webp"}}},{virtual:!0}),jest.mock("expo-file-system",()=>{const joinUri=e=>e.map(e=>"string"==typeof e?e:e.uri).reduce((e,t)=>`${e.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`);class MockFile{static sizes=new Map;constructor(...e){const t=joinUri(e);this.uri=t,this.exists=MockFile.sizes.has(t);const s=MockFile.sizes.get(t);this.size=void 0===s?0:s,this.delete=jest.fn(()=>{MockFile.sizes.delete(t)})}create(){MockFile.sizes.set(this.uri,0)}async write(e){MockFile.sizes.set(this.uri,e.byteLength)}}const under=e=>[...MockFile.sizes.keys()].filter(t=>t.startsWith(`${e.replace(/\/+$/,"")}/`));return{File:MockFile,Directory:class MockDirectory{constructor(...e){this.uri=joinUri(e)}get exists(){return under(this.uri).length>0}create(){}list(){return under(this.uri).map(e=>new MockFile(e))}delete(){for(const e of under(this.uri))MockFile.sizes.delete(e)}},Paths:{document:{uri:"file:///documents/"},cache:{uri:"file:///cache/"}}}},{virtual:!0}),jest.mock("expo-location",()=>({getCurrentPositionAsync:jest.fn(()=>Promise.resolve({coords:{latitude:0,longitude:0,accuracy:5},timestamp:0})),watchPositionAsync:jest.fn(()=>Promise.resolve({remove:jest.fn()})),getForegroundPermissionsAsync:jest.fn(()=>Promise.resolve({status:"granted",granted:!0,canAskAgain:!0})),requestForegroundPermissionsAsync:jest.fn(()=>Promise.resolve({status:"granted",granted:!0,canAskAgain:!0})),getBackgroundPermissionsAsync:jest.fn(()=>Promise.resolve({status:"granted",granted:!0,canAskAgain:!0})),requestBackgroundPermissionsAsync:jest.fn(()=>Promise.resolve({status:"granted",granted:!0,canAskAgain:!0}))}),{virtual:!0}),jest.mock("expo-sqlite",()=>({openDatabaseAsync:jest.fn(()=>Promise.resolve({prepareAsync:jest.fn(()=>Promise.resolve({executeAsync:jest.fn(()=>Promise.resolve({lastInsertRowId:0,changes:0,getAllAsync:jest.fn(()=>Promise.resolve([]))})),finalizeAsync:jest.fn(()=>Promise.resolve())})),closeAsync:jest.fn(()=>Promise.resolve())}))})),jest.mock("expo-secure-store",()=>({getItemAsync:jest.fn(()=>Promise.resolve(null)),setItemAsync:jest.fn(()=>Promise.resolve()),deleteItemAsync:jest.fn(()=>Promise.resolve())})),globalThis.__expoApplicationMock={applicationId:"com.webority.test",nativeApplicationVersion:"1.0.0",nativeBuildVersion:"1"},jest.mock("expo-application",()=>({get applicationId(){return globalThis.__expoApplicationMock.applicationId},get nativeApplicationVersion(){return globalThis.__expoApplicationMock.nativeApplicationVersion},get nativeBuildVersion(){return globalThis.__expoApplicationMock.nativeBuildVersion}})),jest.mock("react-native/src/private/devsupport/devmenu/specs/NativeDevMenu",()=>({__esModule:!0,default:{show:jest.fn(),reload:jest.fn(),setProfilingEnabled:jest.fn(),setHotLoadingEnabled:jest.fn()}}),{virtual:!0}),jest.mock("react-native-worklets",()=>{const noop=()=>{},passthrough=e=>"function"==typeof e?e:noop;return{__esModule:!0,runOnJS:passthrough,scheduleOnRN:(e,...t)=>{"function"==typeof e&&e(...t)},runOnUI:passthrough,runOnRuntime:passthrough,createWorkletRuntime:()=>({}),isWorkletFunction:()=>!1,makeShareableCloneRecursive:e=>e,makeShareable:e=>e,executeOnUIRuntimeSync:e=>e,Worklets:{}}},{virtual:!0}),jest.mock("react-native-reanimated",()=>{const e=require("react"),{View:t}=require("react-native"),noop=()=>{},passthrough=e=>"function"==typeof e?e:noop,chainable=()=>{const e={};for(const t of["duration","delay","springify","reduceMotion","easing","damping","stiffness","mass","withInitialValues","withCallback","build"])e[t]=()=>e;return e},s=Symbol("mockSharedValue"),makeSharedValue=e=>{let t=e;return{[s]:!0,get value(){return t},set value(e){t=e},addListener:noop,removeListener:noop,modify:e=>{t="function"==typeof e?e(t):e}}},animatedComponent=t=>{const s=e.forwardRef((s,n)=>e.createElement(t,{...s,ref:n}));return s.displayName=`Animated(${t?.displayName||t?.name||"Component"})`,s},n={View:animatedComponent(t),Text:animatedComponent(t),ScrollView:animatedComponent(t),Image:animatedComponent(t),FlatList:animatedComponent(t),createAnimatedComponent:animatedComponent},withCallback=(e,t,s)=>("function"==typeof s&&s(!0),e);return{__esModule:!0,default:n,...n,useSharedValue:t=>{const s=e.useRef(null);return null===s.current&&(s.current=makeSharedValue(t)),s.current},useDerivedValue:e=>makeSharedValue("function"==typeof e?e():void 0),useAnimatedStyle:e=>"function"==typeof e?e():{},useAnimatedProps:()=>({}),useAnimatedReaction:noop,useAnimatedScrollHandler:()=>noop,useAnimatedGestureHandler:()=>({}),useAnimatedRef:()=>({current:null}),useFrameCallback:()=>({setActive:noop}),useScrollViewOffset:makeSharedValue,useEvent:()=>noop,useHandler:()=>({context:{},doDependenciesDiffer:!1}),useAnimatedSensor:()=>({sensor:makeSharedValue(0)}),useWorkletCallback:passthrough,useComposedEventHandler:()=>noop,useReducedMotion:()=>!1,isSharedValue:e=>"object"==typeof e&&null!==e&&s in e,withTiming:withCallback,withSpring:withCallback,withDecay:e=>e,withSequence:(...e)=>e[e.length-1],withDelay:(e,t)=>t,withRepeat:e=>e,cancelAnimation:noop,runOnJS:passthrough,runOnUI:passthrough,measure:()=>null,interpolate:()=>0,interpolateColor:()=>"#000",Extrapolate:{CLAMP:"clamp",EXTEND:"extend",IDENTITY:"identity"},Extrapolation:{CLAMP:"clamp",EXTEND:"extend",IDENTITY:"identity"},Easing:new Proxy({},{get:()=>()=>0}),ReduceMotion:{System:"system",Always:"always",Never:"never"},Layout:chainable(),FadeIn:chainable(),FadeOut:chainable(),SlideInDown:{duration:()=>({})},SlideOutDown:{duration:()=>({})},FadeInUp:{duration:()=>({})},FadeInDown:{duration:()=>({})},FadeOutUp:{duration:()=>({})},FadeOutDown:{duration:()=>({})},ZoomIn:{duration:()=>({})},ZoomOut:{duration:()=>({})}}},{virtual:!0}),jest.mock("react-native-keyboard-controller",()=>require("react-native-keyboard-controller/jest"),{virtual:!0}),jest.mock("react-native-safe-area-context",()=>{const e=require("react"),t={top:0,right:0,bottom:0,left:0};return{SafeAreaProvider:({children:e})=>e,SafeAreaView:({children:e})=>e,SafeAreaInsetsContext:e.createContext(t),useSafeAreaInsets:()=>t,useSafeAreaFrame:()=>({x:0,y:0,width:390,height:844})}},{virtual:!0}),jest.mock("expo",()=>({isRunningInExpoGo:()=>!1}),{virtual:!0}),jest.mock("expo-haptics",()=>({selectionAsync:jest.fn(()=>Promise.resolve()),impactAsync:jest.fn(()=>Promise.resolve()),notificationAsync:jest.fn(()=>Promise.resolve()),performAndroidHapticsAsync:jest.fn(()=>Promise.resolve()),ImpactFeedbackStyle:{Light:"light",Medium:"medium",Heavy:"heavy"},NotificationFeedbackType:{Success:"success",Warning:"warning",Error:"error"},AndroidHaptics:{Confirm:"confirm",Reject:"reject",Gesture_Start:"gesture-start",Long_Press:"long-press",Segment_Tick:"segment-tick",Segment_Frequent_Tick:"segment-frequent-tick"}}),{virtual:!0}),jest.mock("expo-crypto",()=>({randomUUID:jest.fn(()=>"00000000-0000-4000-8000-000000000000"),getRandomValues:jest.fn(e=>e),getRandomBytes:jest.fn(e=>new Uint8Array(e)),digestStringAsync:jest.fn(()=>Promise.resolve("")),CryptoDigestAlgorithm:{SHA256:"SHA-256"}}),{virtual:!0}),jest.mock("expo-clipboard",()=>({setStringAsync:jest.fn(()=>Promise.resolve(!0)),getStringAsync:jest.fn(()=>Promise.resolve(""))}),{virtual:!0}),jest.mock("expo-image",()=>{const e=require("react"),{Image:t}=require("react-native"),s=e.forwardRef((s,n)=>e.createElement(t,{...s,ref:n}));return s.displayName="ExpoImage",{__esModule:!0,Image:s}},{virtual:!0});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createOutbox=void 0;var _axios=_interopRequireDefault(require("axios")),_reactNative=require("react-native"),_clientHeaders=require("../api/clientHeaders.js"),_idempotencyKey=require("../api/idempotencyKey.js"),_retry=require("../api/retry.js"),_tokenRefresh=require("../api/tokenRefresh.js"),_authStore=require("../auth/authStore.js"),_jwt=require("../auth/jwt.js"),_extractApiError=require("../errors/extractApiError.js"),_index=require("../logger/index.js"),_networkStatus=require("../network/networkStatus.js"),_index2=require("../sqlite/index.js"),_guards=require("../utils/guards.js"),_errors=require("./errors.js"),_files=require("./files.js"),_progress=require("./progress.js"),_resumable=require("./resumable.js");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const TABLE="outbox_entry",DEFAULT_DATABASE_NAME="webority-outbox",DEFAULT_MAX_ENTRIES=50,DEFAULT_TIMEOUT_MS=3e5,DEFAULT_CHUNK_BYTES=1048576,BASE_BACKOFF_MS=3e4,MAX_BACKOFF_MS=9e5,REPLAY_WINDOW_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`]},{version:3,name:"outbox_entry_outcome_unknown_since_utc",up:[`ALTER TABLE ${TABLE} ADD COLUMN outcome_unknown_since_utc TEXT NULL`,`UPDATE ${TABLE} SET outcome_unknown_since_utc = created_utc WHERE attempts > 0 OR state = 'Sending'`]}],nowIso=()=>new Date(Date.now()).toISOString(),inMs=e=>new Date(Date.now()+e).toISOString(),parseFilePart=e=>{if(!(0,_guards.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((0,_guards.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(!(0,_guards.isRecord)(e))throw new Error("[outbox] a stored resumable body has no metadata object.");const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)throw new Error(`[outbox] the stored metadata "${r}" is not a string.`);t[r]=n}return t},parseBody=e=>{if((0,_guards.isRecord)(e)&&"json"===e.kind)return{kind:"json",value:e.value};if((0,_guards.isRecord)(e)&&"multipart"===e.kind&&Array.isArray(e.fields))return{kind:"multipart",fields:e.fields.map(parseFormField)};if((0,_guards.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(!(0,_guards.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(!(0,_guards.isRecord)(e))throw new Error("[outbox] a stored request has no headers object.");const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)throw new Error(`[outbox] the stored header "${r}" is not a string.`);t[r]=n}return t},parseOutboxRequest=e=>{if(!(0,_guards.isRecord)(e)||!(0,_guards.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(!(0,_guards.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:n,request_json:o,state:a,attempts:s,last_failure_json:i,created_utc:u,next_attempt_utc:d,upload_json:l,outcome_unknown_since_utc:c}=e;if("string"!=typeof t)throw rowFieldMissing("id");if("string"!=typeof r)throw rowFieldMissing("queue");if("string"!=typeof n)throw rowFieldMissing("label");if("string"!=typeof o)throw rowFieldMissing("request_json");if(!(0,_guards.isOneOf)(ENTRY_STATES,a))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");if(null!==l&&"string"!=typeof l)throw rowFieldMissing("upload_json");if(null!==c&&"string"!=typeof c)throw rowFieldMissing("outcome_unknown_since_utc");return{id:t,queue:r,label:n,request_json:o,state:a,attempts:s,last_failure_json:i,created_utc:u,next_attempt_utc:d,upload_json:l,outcome_unknown_since_utc:c}},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,outcomeUnknownSinceDateTimeUtc:e.outcome_unknown_since_utc}),currentIdentity=async()=>{const e=(await(0,_authStore.getToken)(_authStore.ACCESS_TOKEN_KEY))?.token,t=e?(0,_jwt.decodeJWT)(e)?.sub:void 0;if(!t)return null;const r=await(0,_clientHeaders.readAccountId)((0,_tokenRefresh.getAccountIdProvider)());return{owner:`${t}|${r??""}`,accountId:r}},assertRequestHeaders=e=>{const t=Object.keys(e),r=_clientHeaders.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 n=_retry.IDEMPOTENCY_KEY_HEADER.toLowerCase(),o=t.find(e=>e.toLowerCase()===n),a=void 0===o?void 0:e[o];if(void 0===a||!UUID_SHAPE.test(a))throw new _errors.OutboxMissingKeyError},isOfflineError=e=>e instanceof Error&&"RequestOfflineError"===e.name,provablyNotSent=e=>!!isOfflineError(e)||_axios.default.isAxiosError(e)&&((0,_retry.isNeverSentError)(e)||429===e.response?.status),isTransient=e=>{if(isOfflineError(e))return!0;if(!_axios.default.isAxiosError(e))return!1;if(!e.response||(0,_retry.isNeverSentError)(e))return!0;const t=e.response.status;return 408===t||429===t||t>=500},retryDelayMs=(e,t)=>(_axios.default.isAxiosError(e)?(0,_retry.retryAfterMs)(e):null)??Math.min(9e5,3e4*2**(t-1)),failureOf=e=>{const t=(0,_extractApiError.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},createOutbox=e=>{const{http:t}=e,r=e.databaseName??"webority-outbox",n=e.maxEntriesPerOwner??50,o=e.chunkBytes??1048576;if(!Number.isSafeInteger(o)||o<=0)throw new RangeError("The outbox chunkBytes option must be a positive integer.");const a=new Set,s=new Map;let i=null,u=null,d=!1,l=null,c=0,_=null;const store=()=>(i||(i=(0,_index2.openDatabase)(r).then(async e=>(await e.migrate(MIGRATIONS),e)).catch(e=>{throw i=null,e})),i),logFailure=e=>_index.Logger.error("[outbox] background work failed",e),emit=e=>{for(const t of a)t(e)},clearTimer=()=>{null!==l&&(clearTimeout(l),l=null)},flushNow=()=>(_||(_=runFlush().finally(()=>{_=null})),_),scheduleNext=async()=>{const e=++c;if(clearTimer(),!d||!u)return;const t=await store(),r=await currentIdentity();if(!r)return;const n=await t.selectOne(`SELECT MIN(next_attempt_utc) AS next FROM ${TABLE} WHERE owner = ? AND state != 'Failed'`,[r.owner],parseNextAttempt);if(e!==c||!n)return;const o=Math.min(Math.max(0,Date.parse(n)-Date.now()),9e5);l=setTimeout(()=>{l=null,flushNow().catch(logFailure)},o)},notifyChanged=e=>{emit({type:"changed",queue:e}),scheduleNext().catch(logFailure)},runFlush=async()=>{const e=await store(),t=await currentIdentity();if(!t)return;const r=await e.findAll(TABLE,{sql:"owner = ? AND state != 'Failed'",params:[t.owner]},{orderBy:"created_utc, rowid"},parseEntryRow),n=new Set;for(const e of r){if(n.has(e.queue))continue;if(e.next_attempt_utc>nowIso()){n.add(e.queue);continue}const r=await deliver(e.id,t,"auto");"Queued"===r?.status&&n.add(e.queue)}await scheduleNext()},runDelivery=async(e,r,n)=>{const a=await store(),s=await a.findOne(TABLE,{id:e,owner:r.owner},parseEntryRow);if(!s)return null;if("auto"===n&&null!==s.outcome_unknown_since_utc&&Date.now()-Date.parse(s.outcome_unknown_since_utc)>864e5){const t={code:"outbox_outcome_unknown",message:"We could not confirm this was sent. Check whether it arrived, then send it again or discard it.",status:null};await a.update(TABLE,{state:"Failed",last_failure_json:JSON.stringify(t)},{id:e});const r={...toEntry(s),state:"Failed",lastFailure:t};return notifyChanged(r.queue),emit({type:"failed",entry:r}),{status:"Failed",entry:r,failure:t}}const i=null===s.outcome_unknown_since_utc,u=s.outcome_unknown_since_utc??new Date(Date.now()).toISOString(),d={...toEntry(s),state:"Sending",outcomeUnknownSinceDateTimeUtc:u};await a.update(TABLE,{state:"Sending",outcome_unknown_since_utc:u},{id:e}),notifyChanged(d.queue);const{request:l}=d,c={...l.headers};r.accountId&&(c[_clientHeaders.ACCOUNT_ID_HEADER]=r.accountId);const _=(0,_progress.createProgressReporter)(d,e=>emit({type:"progress",progress:e}));let w;try{w=await(async()=>{if("resumable"===l.body.kind)return(0,_resumable.uploadResumable)({http:t,createUrl:l.url,headers:c,metadata:l.body.metadata,fileUri:l.body.file.uri,chunkBytes:o,timeoutMs:l.timeoutMs??3e5,state:null===s.upload_json?null:parseUploadState(JSON.parse(s.upload_json)),onState:async t=>{await a.update(TABLE,{upload_json:JSON.stringify(t)},{id:e})},onProgress:(e,t)=>_({loaded:e,total:t})});const r="json"===l.body.kind?l.body.value:buildFormData(l.body.fields),n={method:l.method,url:l.url,headers:c,data:r,timeout:l.timeoutMs??3e5,retry:!1,onUploadProgress:_},i=await t.request(n);return{httpStatus:i.status,data:i.data}})()}catch(e){return(async(e,t,r,n,o)=>{if(isTransient(r)){const n=t.attempts+1,a=inMs(retryDelayMs(r,n)),s=o&&provablyNotSent(r)?null:t.outcomeUnknownSinceDateTimeUtc;return await e.update(TABLE,{state:"Pending",attempts:n,next_attempt_utc:a,outcome_unknown_since_utc:s},{id:t.id}),notifyChanged(t.queue),{status:"Queued",entry:{...t,state:"Pending",attempts:n,nextAttemptDateTimeUtc:a,outcomeUnknownSinceDateTimeUtc:s}}}const a=failureOf(r);if("first"===n)return await e.remove(TABLE,{id:t.id}),await(0,_files.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,d,e,n,i)}return await a.remove(TABLE,{id:e}),await(0,_files.deleteEntryFiles)(e),notifyChanged(d.queue),emit({type:"sent",entry:d,httpStatus:w.httpStatus,data:w.data}),{status:"Sent",entry:d,httpStatus:w.httpStatus,data:w.data}},deliver=(e,t,r)=>{const n=s.get(e);if(void 0!==n)return n;const o=runDelivery(e,t,r).finally(()=>{s.delete(e)});return s.set(e,o),o},start=async()=>{const e=await store();return u||((()=>{d="active"===_reactNative.AppState.currentState;const e=(0,_networkStatus.addNetworkStatusListener)(e=>{e.isConnected&&flushNow().catch(logFailure)}),t=_reactNative.AppState.addEventListener("change",e=>{d="active"===e,d?flushNow().catch(logFailure):clearTimer()});u=()=>{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 _errors.OutboxSignedOutError;if(await t.count(TABLE,{owner:r.owner})>=n)throw new _errors.OutboxFullError;const o=(0,_idempotencyKey.newIdempotencyKey)(),a=await(0,_files.persistRequestFiles)(o,e.request),s=nowIso();try{await t.insert(TABLE,{id:o,owner:r.owner,queue:e.queue,label:e.label,request_json:JSON.stringify(a),state:"Pending",attempts:0,last_failure_json:null,created_utc:s,next_attempt_utc:s,outcome_unknown_since_utc:null})}catch(e){throw await(0,_files.deleteEntryFiles)(o),e}const i=await t.findOne(TABLE,{id:o},parseEntryRow);if(!i)throw new Error("The outbox entry was removed before it was sent.");notifyChanged(e.queue);if(await t.count(TABLE,{sql:`owner = ? AND queue = ? AND state != 'Failed' AND (created_utc < ? OR (created_utc = ? AND rowid < (SELECT rowid FROM ${TABLE} WHERE id = ?)))`,params:[r.owner,e.queue,s,s,o]})>0)return flushNow().catch(logFailure),{status:"Queued",entry:toEntry(i)};const u=await deliver(o,r,"first");if(!u)throw new Error("The outbox entry was removed before it was sent.");return u},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, rowid"},parseEntryRow)).map(toEntry)},async retry(e){const t=await start(),r=await currentIdentity();if(!r)throw new _errors.OutboxSignedOutError;const n=0===await t.update(TABLE,{state:"Pending",last_failure_json:null,next_attempt_utc:nowIso(),outcome_unknown_since_utc:null},{id:e,owner:r.owner})?null:await deliver(e,r,"user");if(!n)throw new Error("The outbox entry was not found.");return n},async discard(e){const t=await start(),r=await currentIdentity();if(!r)return;await Promise.allSettled([s.get(e)]);const n=await t.findOne(TABLE,{id:e,owner:r.owner},parseEntryRow);n&&(await t.remove(TABLE,{id:e,owner:r.owner}),await(0,_files.deleteEntryFiles)(e),notifyChanged(n.queue))},flush:async()=>(await start(),flushNow()),subscribe:e=>(a.add(e),()=>{a.delete(e)}),async close(){c+=1,clearTimer(),u?.(),u=null,d=!1}}};exports.createOutbox=createOutbox;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createOutbox=void 0;var cache,_axios=_interopRequireWildcard(require("axios")),_reactNative=require("react-native"),_clientHeaders=require("../api/clientHeaders.js"),_idempotencyKey=require("../api/idempotencyKey.js"),_retry=require("../api/retry.js"),_tokenRefresh=require("../api/tokenRefresh.js"),_authStore=require("../auth/authStore.js"),_jwt=require("../auth/jwt.js"),_extractApiError=require("../errors/extractApiError.js"),_index=require("../logger/index.js"),_networkStatus=require("../network/networkStatus.js"),_index2=require("../sqlite/index.js"),_guards=require("../utils/guards.js"),_backgroundUpload=require("./backgroundUpload.js"),_errors=require("./errors.js"),_files=require("./files.js"),_progress=require("./progress.js"),_resumable=require("./resumable.js");function _interopRequireWildcard(e,t){if(!t&&e&&e.__esModule)return e;var r,a,o=Object.defineProperty,n={__proto__:null,default:e};if(Object(e)!==e)return n;if(cache||"function"!=typeof WeakMap||(cache=new WeakMap),cache){if(cache.has(e))return cache.get(e);cache.set(e,n)}for(a in e)"default"!==a&&{}.hasOwnProperty.call(e,a)&&((r=o&&Object.getOwnPropertyDescriptor(e,a))&&(r.get||r.set)?o(n,a,r):n[a]=e[a]);return n}const TABLE="outbox_entry",DEFAULT_DATABASE_NAME="webority-outbox",DEFAULT_MAX_ENTRIES=50,DEFAULT_TIMEOUT_MS=3e5,DEFAULT_CHUNK_BYTES=1048576,BASE_BACKOFF_MS=3e4,MAX_BACKOFF_MS=9e5,REPLAY_WINDOW_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`]},{version:3,name:"outbox_entry_outcome_unknown_since_utc",up:[`ALTER TABLE ${TABLE} ADD COLUMN outcome_unknown_since_utc TEXT NULL`,`UPDATE ${TABLE} SET outcome_unknown_since_utc = created_utc WHERE attempts > 0 OR state = 'Sending'`]}],nowIso=()=>new Date(Date.now()).toISOString(),inMs=e=>new Date(Date.now()+e).toISOString(),parseFilePart=e=>{if(!(0,_guards.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((0,_guards.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(!(0,_guards.isRecord)(e))throw new Error("[outbox] a stored resumable body has no metadata object.");const t={};for(const[r,a]of Object.entries(e)){if("string"!=typeof a)throw new Error(`[outbox] the stored metadata "${r}" is not a string.`);t[r]=a}return t},parseBody=e=>{if((0,_guards.isRecord)(e)&&"json"===e.kind)return{kind:"json",value:e.value};if((0,_guards.isRecord)(e)&&"multipart"===e.kind&&Array.isArray(e.fields))return{kind:"multipart",fields:e.fields.map(parseFormField)};if((0,_guards.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(!(0,_guards.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(!(0,_guards.isRecord)(e))throw new Error("[outbox] a stored request has no headers object.");const t={};for(const[r,a]of Object.entries(e)){if("string"!=typeof a)throw new Error(`[outbox] the stored header "${r}" is not a string.`);t[r]=a}return t},parseOutboxRequest=e=>{if(!(0,_guards.isRecord)(e)||!(0,_guards.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(!(0,_guards.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:a,request_json:o,state:n,attempts:s,last_failure_json:i,created_utc:u,next_attempt_utc:d,upload_json:c,outcome_unknown_since_utc:l}=e;if("string"!=typeof t)throw rowFieldMissing("id");if("string"!=typeof r)throw rowFieldMissing("queue");if("string"!=typeof a)throw rowFieldMissing("label");if("string"!=typeof o)throw rowFieldMissing("request_json");if(!(0,_guards.isOneOf)(ENTRY_STATES,n))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");if(null!==c&&"string"!=typeof c)throw rowFieldMissing("upload_json");if(null!==l&&"string"!=typeof l)throw rowFieldMissing("outcome_unknown_since_utc");return{id:t,queue:r,label:a,request_json:o,state:n,attempts:s,last_failure_json:i,created_utc:u,next_attempt_utc:d,upload_json:c,outcome_unknown_since_utc: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,outcomeUnknownSinceDateTimeUtc:e.outcome_unknown_since_utc}),currentIdentity=async()=>{const e=(await(0,_authStore.getToken)(_authStore.ACCESS_TOKEN_KEY))?.token,t=e?(0,_jwt.decodeJWT)(e)?.sub:void 0;if(!t)return null;const r=await(0,_clientHeaders.readAccountId)((0,_tokenRefresh.getAccountIdProvider)());return{owner:`${t}|${r??""}`,accountId:r}},assertRequestHeaders=e=>{const t=Object.keys(e),r=_clientHeaders.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 a=_retry.IDEMPOTENCY_KEY_HEADER.toLowerCase(),o=t.find(e=>e.toLowerCase()===a),n=void 0===o?void 0:e[o];if(void 0===n||!UUID_SHAPE.test(n))throw new _errors.OutboxMissingKeyError},isOfflineError=e=>e instanceof Error&&"RequestOfflineError"===e.name,provablyNotSent=e=>!!isOfflineError(e)||_axios.default.isAxiosError(e)&&((0,_retry.isNeverSentError)(e)||429===e.response?.status),isTransient=e=>{if(isOfflineError(e))return!0;if(!_axios.default.isAxiosError(e))return!1;if(!e.response||(0,_retry.isNeverSentError)(e))return!0;const t=e.response.status;return 408===t||429===t||t>=500},retryDelayMs=(e,t)=>(_axios.default.isAxiosError(e)?(0,_retry.retryAfterMs)(e):null)??Math.min(9e5,3e4*2**(t-1)),failureOf=e=>{const t=(0,_extractApiError.extractApiError)(e);return{code:t.code??"unknown",message:t.message,status:0===t.status?null:t.status}},backgroundFailure=(e,t)=>new _axios.AxiosError(`The background upload failed with status ${e}.`,e>=500?_axios.AxiosError.ERR_BAD_RESPONSE:_axios.AxiosError.ERR_BAD_REQUEST,void 0,void 0,{status:e,statusText:"",data:t,headers:{},config:{headers:new _axios.AxiosHeaders}}),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},createOutbox=e=>{const{http:t}=e,r=e.databaseName??"webority-outbox",a=e.backgroundUploads??!0,o=e.baseUrl,n=e.maxEntriesPerOwner??50,s=e.chunkBytes??1048576;if(!Number.isSafeInteger(s)||s<=0)throw new RangeError("The outbox chunkBytes option must be a positive integer.");const i=new Set,u=new Map;let d=null,c=null,l=!1,_=null,w=0,f=null;const store=()=>(d||(d=(0,_index2.openDatabase)(r).then(async e=>(await e.migrate(MIGRATIONS),e)).catch(e=>{throw d=null,e})),d),logFailure=e=>_index.Logger.error("[outbox] background work failed",e),emit=e=>{for(const t of i)t(e)},clearTimer=()=>{null!==_&&(clearTimeout(_),_=null)},flushNow=()=>(f||(f=runFlush().finally(()=>{f=null})),f),scheduleNext=async()=>{const e=++w;if(clearTimer(),!l||!c)return;const t=await store(),r=await currentIdentity();if(!r)return;const a=await t.selectOne(`SELECT MIN(next_attempt_utc) AS next FROM ${TABLE} WHERE owner = ? AND state != 'Failed'`,[r.owner],parseNextAttempt);if(e!==w||!a)return;const o=Math.min(Math.max(0,Date.parse(a)-Date.now()),9e5);_=setTimeout(()=>{_=null,flushNow().catch(logFailure)},o)},notifyChanged=e=>{emit({type:"changed",queue:e}),scheduleNext().catch(logFailure)},runFlush=async()=>{const e=await store(),t=await currentIdentity();if(!t)return;const r=await e.findAll(TABLE,{sql:"owner = ? AND state != 'Failed'",params:[t.owner]},{orderBy:"created_utc, rowid"},parseEntryRow),a=new Set;for(const e of r){if(a.has(e.queue))continue;if(e.next_attempt_utc>nowIso()){a.add(e.queue);continue}const r=await deliver(e.id,t,"auto");"Queued"===r?.status&&a.add(e.queue)}await scheduleNext()},runDelivery=async(e,r,n)=>{const i=await store(),u=await i.findOne(TABLE,{id:e,owner:r.owner},parseEntryRow);if(!u)return null;if("auto"===n&&null!==u.outcome_unknown_since_utc&&Date.now()-Date.parse(u.outcome_unknown_since_utc)>864e5){const t={code:"outbox_outcome_unknown",message:"We could not confirm this was sent. Check whether it arrived, then send it again or discard it.",status:null};await i.update(TABLE,{state:"Failed",last_failure_json:JSON.stringify(t)},{id:e});const r={...toEntry(u),state:"Failed",lastFailure:t};return notifyChanged(r.queue),emit({type:"failed",entry:r}),{status:"Failed",entry:r,failure:t}}const d=null===u.outcome_unknown_since_utc,c=u.outcome_unknown_since_utc??new Date(Date.now()).toISOString(),l={...toEntry(u),state:"Sending",outcomeUnknownSinceDateTimeUtc:c};await i.update(TABLE,{state:"Sending",outcome_unknown_since_utc:c},{id:e}),notifyChanged(l.queue);const{request:_}=l,w={..._.headers};r.accountId&&(w[_clientHeaders.ACCOUNT_ID_HEADER]=r.accountId);const f=(0,_progress.createProgressReporter)(l,e=>emit({type:"progress",progress:e}));let p;try{p=await(async()=>{if(a&&(0,_backgroundUpload.isBackgroundEligible)(_)&&(o||/^https?:\/\//i.test(_.url))){const e=(await(0,_authStore.getToken)(_authStore.ACCESS_TOKEN_KEY))?.token,t=await(0,_backgroundUpload.uploadInBackground)({request:_,url:(0,_backgroundUpload.resolveUploadUrl)(_.url,o??null),headers:e?{...w,Authorization:`Bearer ${e}`}:w,onProgress:(e,t)=>f({loaded:e,total:t})}).catch(e=>{throw new _axios.AxiosError(e instanceof Error?e.message:"The background upload failed.",_axios.AxiosError.ERR_NETWORK)});if(t.status>=200&&t.status<=299)return{httpStatus:t.status,data:t.data};if(401!==t.status)throw backgroundFailure(t.status,t.data)}if("resumable"===_.body.kind)return(0,_resumable.uploadResumable)({http:t,createUrl:_.url,headers:w,metadata:_.body.metadata,fileUri:_.body.file.uri,chunkBytes:s,timeoutMs:_.timeoutMs??3e5,state:null===u.upload_json?null:parseUploadState(JSON.parse(u.upload_json)),onState:async t=>{await i.update(TABLE,{upload_json:JSON.stringify(t)},{id:e})},onProgress:(e,t)=>f({loaded:e,total:t})});const r="json"===_.body.kind?_.body.value:buildFormData(_.body.fields),n={method:_.method,url:_.url,headers:w,data:r,timeout:_.timeoutMs??3e5,retry:!1,onUploadProgress:f},d=await t.request(n);return{httpStatus:d.status,data:d.data}})()}catch(e){return(async(e,t,r,a,o)=>{if(isTransient(r)){const a=t.attempts+1,n=inMs(retryDelayMs(r,a)),s=o&&provablyNotSent(r)?null:t.outcomeUnknownSinceDateTimeUtc;return await e.update(TABLE,{state:"Pending",attempts:a,next_attempt_utc:n,outcome_unknown_since_utc:s},{id:t.id}),notifyChanged(t.queue),{status:"Queued",entry:{...t,state:"Pending",attempts:a,nextAttemptDateTimeUtc:n,outcomeUnknownSinceDateTimeUtc:s}}}const n=failureOf(r);if("first"===a)return await e.remove(TABLE,{id:t.id}),await(0,_files.deleteEntryFiles)(t.id),notifyChanged(t.queue),{status:"Failed",entry:{...t,state:"Failed",lastFailure:n},failure:n};await e.update(TABLE,{state:"Failed",last_failure_json:JSON.stringify(n)},{id:t.id});const s={...t,state:"Failed",lastFailure:n};return notifyChanged(t.queue),emit({type:"failed",entry:s}),{status:"Failed",entry:s,failure:n}})(i,l,e,n,d)}return await i.remove(TABLE,{id:e}),await(0,_files.deleteEntryFiles)(e),notifyChanged(l.queue),emit({type:"sent",entry:l,httpStatus:p.httpStatus,data:p.data}),{status:"Sent",entry:l,httpStatus:p.httpStatus,data:p.data}},deliver=(e,t,r)=>{const a=u.get(e);if(void 0!==a)return a;const o=runDelivery(e,t,r).finally(()=>{u.delete(e)});return u.set(e,o),o},start=async()=>{const e=await store();return c||((()=>{l="active"===_reactNative.AppState.currentState;const e=(0,_networkStatus.addNetworkStatusListener)(e=>{e.isConnected&&flushNow().catch(logFailure)}),t=_reactNative.AppState.addEventListener("change",e=>{l="active"===e,l?flushNow().catch(logFailure):clearTimer()});c=()=>{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 _errors.OutboxSignedOutError;if(await t.count(TABLE,{owner:r.owner})>=n)throw new _errors.OutboxFullError;const a=(0,_idempotencyKey.newIdempotencyKey)(),o=await(0,_files.persistRequestFiles)(a,e.request),s=nowIso();try{await t.insert(TABLE,{id:a,owner:r.owner,queue:e.queue,label:e.label,request_json:JSON.stringify(o),state:"Pending",attempts:0,last_failure_json:null,created_utc:s,next_attempt_utc:s,outcome_unknown_since_utc:null})}catch(e){throw await(0,_files.deleteEntryFiles)(a),e}const i=await t.findOne(TABLE,{id:a},parseEntryRow);if(!i)throw new Error("The outbox entry was removed before it was sent.");notifyChanged(e.queue);if(await t.count(TABLE,{sql:`owner = ? AND queue = ? AND state != 'Failed' AND (created_utc < ? OR (created_utc = ? AND rowid < (SELECT rowid FROM ${TABLE} WHERE id = ?)))`,params:[r.owner,e.queue,s,s,a]})>0)return flushNow().catch(logFailure),{status:"Queued",entry:toEntry(i)};const u=await deliver(a,r,"first");if(!u)throw new Error("The outbox entry was removed before it was sent.");return u},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, rowid"},parseEntryRow)).map(toEntry)},async retry(e){const t=await start(),r=await currentIdentity();if(!r)throw new _errors.OutboxSignedOutError;const a=0===await t.update(TABLE,{state:"Pending",last_failure_json:null,next_attempt_utc:nowIso(),outcome_unknown_since_utc:null},{id:e,owner:r.owner})?null:await deliver(e,r,"user");if(!a)throw new Error("The outbox entry was not found.");return a},async discard(e){const t=await start(),r=await currentIdentity();if(!r)return;await Promise.allSettled([u.get(e)]);const a=await t.findOne(TABLE,{id:e,owner:r.owner},parseEntryRow);a&&(await t.remove(TABLE,{id:e,owner:r.owner}),await(0,_files.deleteEntryFiles)(e),notifyChanged(a.queue))},flush:async()=>(await start(),flushNow()),subscribe:e=>(i.add(e),()=>{i.delete(e)}),async close(){w+=1,clearTimer(),c?.(),c=null,l=!1}}};exports.createOutbox=createOutbox;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";import{mkdirSync,writeFileSync}from"node:fs";import{join}from"node:path";import{AndroidConfig,withAndroidManifest,withDangerousMod,withInfoPlist}from"expo/config-plugins";const NETWORK_SECURITY_CONFIG_NAME="webority_network_security_config",NETWORK_SECURITY_CONFIG_REF=`@xml/${NETWORK_SECURITY_CONFIG_NAME}`,NETWORK_SECURITY_CONFIG_ATTRIBUTE="android:networkSecurityConfig",SHA256_BYTES=32,HOSTNAME=/^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,BASE64=/^[A-Za-z0-9+/]+={0,2}$/,EXPIRATION=/^\d{4}-\d{2}-\d{2}$/,isPlistObject=i=>"object"==typeof i&&null!==i&&!Array.isArray(i),isPin=i=>{if(!BASE64.test(i))return!1;const n=Buffer.from(i,"base64");return 32===n.length&&n.toString("base64")===i},isRealDate=i=>{const n=new Date(`${i}T00:00:00Z`);return!Number.isNaN(n.getTime())&&n.toISOString().slice(0,10)===i};export function validateCertificatePinning(i){if(void 0===i)throw new Error("certificatePinning options are required");const{domains:n,expiration:t}=i;if(!Array.isArray(n)||0===n.length)throw new Error("certificatePinning.domains must list at least one domain");for(const i of n){if(!HOSTNAME.test(i.host))throw new Error(`domain host must be a bare hostname, with no scheme, path or port: ${i.host}`);const n=new Set(i.pins);if(n.size<2)throw new Error(`${i.host} needs two or more distinct pins, the current CA and a backup`);for(const t of n)if(!isPin(t))throw new Error(`${i.host} has a pin that is not a base64 SHA-256 digest (32 bytes)`)}if(!(void 0===t||EXPIRATION.test(t)&&isRealDate(t)))throw new Error("certificatePinning.expiration must be a date in YYYY-MM-DD form")}const escapeXml=i=>i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");export function buildNetworkSecurityConfig(i){const n=void 0===i.expiration?"":` expiration="${escapeXml(i.expiration)}"`;return['<?xml version="1.0" encoding="utf-8"?>',"<network-security-config>",...i.domains.map(i=>[" <domain-config>",` <domain includeSubdomains="${!0===i.includeSubdomains?"true":"false"}">${escapeXml(i.host)}</domain>`,` <pin-set${n}>`,...i.pins.map(i=>` <pin digest="SHA-256">${escapeXml(i)}</pin>`)," </pin-set>"," </domain-config>"].join("\n")),"</network-security-config>",""].join("\n")}export function applyPinnedDomains(i,n){const t=i.NSAppTransportSecurity,e=isPlistObject(t)?t:{},o=e.NSPinnedDomains,r={...isPlistObject(o)?o:{}};for(const i of n.domains)r[i.host]={NSIncludesSubdomains:!0===i.includeSubdomains,NSPinnedCAIdentities:i.pins.map(i=>({"SPKI-SHA256-BASE64":i}))};return{...i,NSAppTransportSecurity:{...e,NSPinnedDomains:r}}}export function applyNetworkSecurityConfigAttribute(i){const n=i["android:networkSecurityConfig"];if(void 0!==n&&n!==NETWORK_SECURITY_CONFIG_REF)throw new Error("The app already declares a network security config; certificate pinning cannot be added beside it.");i["android:networkSecurityConfig"]=NETWORK_SECURITY_CONFIG_REF}export default function withWeborityCertificatePinning(i,n){const t=n?.certificatePinning;validateCertificatePinning(t);const e=withDangerousMod(i,["android",async i=>{const n=join(i.modRequest.platformProjectRoot,"app","src","main","res","xml");return mkdirSync(n,{recursive:!0}),writeFileSync(join(n,`${NETWORK_SECURITY_CONFIG_NAME}.xml`),buildNetworkSecurityConfig(t)),i}]),o=withAndroidManifest(e,i=>(applyNetworkSecurityConfigAttribute(AndroidConfig.Manifest.getMainApplicationOrThrow(i.modResults).$),i));return withInfoPlist(o,i=>(i.modResults=applyPinnedDomains(i.modResults,t),i))}
|
|
@@ -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_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,p=Number.parseInt(l,10),f=Date.UTC(u,c,s,g,p),d=Math.round((f-6e4*Math.floor(t.getTime()/6e4))/6e4);return{year:u,month:c,day:s,hour:g,minute:p,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=configuredLocale();if(null!==a||!0===e.intl){const t=relativeTimeFormat(Intl.RelativeTimeFormat,a??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[m,l]=i<HOUR?["minute",6e4]:i<DAY?["hour",HOUR]:i<WEEK?["day",DAY]:i<MONTH?["week",WEEK]:i<YEAR?["month",MONTH]:["year",YEAR],u=Math.floor(i/l),c=`${u} ${m}${1===u?"":"s"}`;return o<0?`${c} ago`:`in ${c}`};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)}`},plainDigits=(t,e)=>numberFormat("en-US",{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}).format(t),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}`:""),p=r<0&&0!==i?"-":"";if(!1===e.symbol)return`${p}${g}`;const f=SYMBOLS[n];return f?`${p}${f}${g}`:`${p}${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="",s="",c=""]=n,m=Number.parseInt(a,10),l=Number.parseInt(o,10)-1,u=Number.parseInt(i,10),g=Number.parseInt(s,10)%24,p=Number.parseInt(c,10),d=Date.UTC(m,l,u,g,p),f=Math.round((d-6e4*Math.floor(t.getTime()/6e4))/6e4);return{year:m,month:l,day:u,hour:g,minute:p,label:gmtLabel(f)}},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=configuredLocale();if(null!==a||!0===e.intl){const t=relativeTimeFormat(Intl.RelativeTimeFormat,a??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[s,c]=i<HOUR?["minute",6e4]:i<DAY?["hour",HOUR]:i<WEEK?["day",DAY]:i<MONTH?["week",WEEK]:i<YEAR?["month",MONTH]:["year",YEAR],m=Math.floor(i/c),l=`${m} ${s}${1===m?"":"s"}`;return o<0?`${l} ago`:`in ${l}`};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)}`},plainDigits=(t,e)=>numberFormat("en-US",{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}).format(t),decimalText=(t,e,r,n)=>{const o=Math.max(clampDigits(r),clampDigits(e)),i=clampDigits(e),a=plainDigits(Math.abs(t),o),[s="0",c=""]=a.split(".");let m=c.padEnd(i,"0");for(;m.length>i&&m.endsWith("0");)m=m.slice(0,-1);const l=houseSeparators(),u=groupInteger(s,n,l.group)+(m?`${l.decimal}${m}`:"");return t<0&&/[1-9]/.test(a)?`-${u}`:u},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"),s=a.slice(0,a.length-o);let c=a.slice(a.length-o);e.dropZeroDecimals&&/^0*$/.test(c)&&(c="");const m=intlTextLocale({grouping:e.grouping});if(m)try{const t=Number(`${r<0&&0!==i?"-":""}${s}.${a.slice(a.length-o)||"0"}`);return styledNumber(numberFormat(m,{...!1===e.symbol?{}:{style:"currency",currency:n},...fractionDigits(c?o:0,o),...groupingOption(e.grouping)}),t)}catch(t){if(t instanceof RangeError)throw new RangeError(`formatMinor rejected currency "${n}" or locale "${m}": ${t.message}`,{cause:t});throw t}const l=e.grouping??("INR"===n?"indian":"international"),u=houseSeparators(),g=groupInteger(s,l,u.group)+(c?`${u.decimal}${c}`:""),p=r<0&&0!==i?"-":"";if(!1===e.symbol)return`${p}${g}`;const d=SYMBOLS[n];return d?`${p}${d}${g}`:`${p}${n} ${g}`};const HUNDREDTH_EXTRA_DIGITS=2,RUPEE_SIGN="₹",trimHundredths=(t,e)=>{let r=t.length;for(;r>e&&"0"===t.slice(r-1,r);)r-=1;return t.slice(0,r)};export const formatHundredthMinor=(t,e)=>{if(!e?.currency)throw new TypeError('formatHundredthMinor needs options.currency, an ISO 4217 code such as "INR".');const r=toNumber(t);if(null===r)return emptyOf(e.empty);if(!Number.isSafeInteger(r))throw new RangeError(`formatHundredthMinor needs a whole number of hundredths within the safe integer range, got ${r}.`);const n=e.currency.toUpperCase(),o=MINOR_DIGITS[n]??2,i=o+2,a=String(Math.abs(r)).padStart(i+1,"0"),s=a.slice(a.length-i),c=a.slice(0,a.length-i);let m=trimHundredths(s,o);e.dropZeroDecimals&&/^0*$/.test(m)&&(m="");const l=r<0?"-":"",u=intlTextLocale({grouping:e.grouping});if(u)try{const t=Number(`${l}${c}.${s}`);return styledNumber(numberFormat(u,{...!1===e.symbol?{}:{style:"currency",currency:n},...fractionDigits(m.length,i),...groupingOption(e.grouping)}),t)}catch(t){if(t instanceof RangeError)throw new RangeError(`formatHundredthMinor rejected currency "${n}" or locale "${u}": ${t.message}`,{cause:t});throw t}const g=e.grouping??("INR"===n?"indian":"international"),p=houseSeparators(),d=groupInteger(c,g,p.group)+(m?`${p.decimal}${m}`:"");if(!1===e.symbol)return`${l}${d}`;const f=SYMBOLS[n];return f?`${l}${f}${d}`:`${l}${n} ${d}`};const wholeDigitsOf=(t,e)=>{let r="",n=!0;for(const o of t)if(e.includes(o)){if(n)return null;n=!0}else{if(!/\d/.test(o))return null;r+=o,n=!1}return n&&""!==t?null:r};export const parseHundredthMinor=(t,e)=>{if(!e?.currency)throw new TypeError('parseHundredthMinor needs options.currency, an ISO 4217 code such as "INR".');const r=e.currency.toUpperCase(),n=(MINOR_DIGITS[r]??2)+2,refuse=e=>new RangeError(`parseHundredthMinor cannot read "${t}": ${e}`);let o=t.trim();if(""===o)throw refuse("the text is empty");let i=!1;o.startsWith("-")&&(i=!0,o=o.slice(1).trim());const a=["₹",SYMBOLS[r]];for(const t of a)if(t&&o.startsWith(t)){o=o.slice(t.length).trim();break}const s=houseSeparators(),c=[",",s.group].filter(t=>t!==s.decimal),m=o.split(s.decimal);if(m.length>2)throw refuse("more than one decimal separator");const l=wholeDigitsOf(m[0]??"",c);if(null===l)throw refuse("a character that is not a digit, a group separator or the decimal separator");const u=2===m.length,g=m[1]??"";if(u&&!/^\d+$/.test(g))throw refuse("the decimal part must be one or more digits");if(g.length>n)throw refuse(`more than ${n} decimal places, the most this currency takes`);const p=l+g.padEnd(n,"0");if(""===p)throw refuse("it has no digits");const d=Number(p);if(!Number.isSafeInteger(d))throw refuse("the amount is beyond the safe integer range");return i&&0!==d?-d:d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";export{formatCurrency}from"./currency.js";export{formatDate,formatDateTime,formatRelativeTime,formatTime}from"./date.js";export{addDays,diffMs,formatDateISO,formatDatePattern,formatTime12h,formatTimeInWindowsZone,formatTimeInZone,isDateAfter,isDateBefore,isSameDay,startOfDay}from"./dateMath.js";export{configureFormatters,getFormatterConfig,groupingForLocale}from"./formatConfig.js";export{formatMinor,formatRelative}from"./house.js";export{getInitials}from"./initials.js";export{formatCompactNumber,formatNumber,formatPercent}from"./number.js";export{AsYouType,clampNationalNumber,countryFlagEmoji,detectPhoneCountry,formatPhone,formatPhoneAsTyped,getCountries,getCountryCallingCode,getPhoneCountries,isSupportedCountry,isValidNationalNumber,isValidPhoneNumber,maxNationalNumberLength,normalizePhone,parsePhoneNumber,parsePhoneNumberFromString,splitPhoneNumber,validatePhoneNumberLength}from"./phone.js";
|
|
1
|
+
"use strict";export{formatCurrency}from"./currency.js";export{formatDate,formatDateTime,formatRelativeTime,formatTime}from"./date.js";export{addDays,diffMs,formatDateISO,formatDatePattern,formatTime12h,formatTimeInWindowsZone,formatTimeInZone,isDateAfter,isDateBefore,isSameDay,startOfDay}from"./dateMath.js";export{configureFormatters,getFormatterConfig,groupingForLocale}from"./formatConfig.js";export{formatHundredthMinor,formatMinor,formatRelative,parseHundredthMinor}from"./house.js";export{getInitials}from"./initials.js";export{formatCompactNumber,formatNumber,formatPercent}from"./number.js";export{AsYouType,clampNationalNumber,countryFlagEmoji,detectPhoneCountry,formatPhone,formatPhoneAsTyped,getCountries,getCountryCallingCode,getPhoneCountries,isSupportedCountry,isValidNationalNumber,isValidPhoneNumber,maxNationalNumberLength,normalizePhone,parsePhoneNumber,parsePhoneNumberFromString,splitPhoneNumber,validatePhoneNumberLength}from"./phone.js";
|
package/lib/module/jest/setup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";jest.mock("expo-network",()=>({getNetworkStateAsync:jest.fn(()=>Promise.resolve({type:"WIFI",isConnected:!0,isInternetReachable:!0})),addNetworkStateListener:jest.fn(()=>({remove:jest.fn()}))})),jest.mock("expo-sqlite/kv-store",()=>{const e=new Map;return{__esModule:!0,default:{getItem:jest.fn(
|
|
1
|
+
"use strict";jest.mock("expo-network",()=>({getNetworkStateAsync:jest.fn(()=>Promise.resolve({type:"WIFI",isConnected:!0,isInternetReachable:!0})),addNetworkStateListener:jest.fn(()=>({remove:jest.fn()}))})),jest.mock("expo-sqlite/kv-store",()=>{const e=new Map;return{__esModule:!0,default:{getItem:jest.fn(t=>Promise.resolve(e.has(t)?e.get(t):null)),setItem:jest.fn((t,s)=>(e.set(t,s),Promise.resolve())),removeItem:jest.fn(t=>(e.delete(t),Promise.resolve())),clear:jest.fn(()=>(e.clear(),Promise.resolve())),getAllKeys:jest.fn(()=>Promise.resolve([...e.keys()])),multiGet:jest.fn(t=>Promise.resolve(t.map(t=>[t,e.get(t)??null]))),multiSet:jest.fn(t=>{for(const[s,n]of t)e.set(s,n);return Promise.resolve()}),multiRemove:jest.fn(t=>{for(const s of t)e.delete(s);return Promise.resolve()})}}}),jest.mock("expo-image-manipulator",()=>{const e={width:4e3,height:3e3,saveAsync:jest.fn(()=>Promise.resolve({uri:"file:///cache/out.jpg",width:1,height:1})),release:jest.fn()},t=jest.fn(()=>Promise.resolve(e)),s={resize:jest.fn(),renderAsync:t,release:jest.fn()};return s.resize.mockReturnValue(s),{ImageManipulator:{manipulate:jest.fn(()=>s)},SaveFormat:{JPEG:"jpeg",PNG:"png",WEBP:"webp"}}},{virtual:!0}),jest.mock("expo-file-system",()=>{const joinUri=e=>e.map(e=>"string"==typeof e?e:e.uri).reduce((e,t)=>`${e.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`);class MockFile{static sizes=new Map;constructor(...e){const t=joinUri(e);this.uri=t,this.exists=MockFile.sizes.has(t);const s=MockFile.sizes.get(t);this.size=void 0===s?0:s,this.delete=jest.fn(()=>{MockFile.sizes.delete(t)})}create(){MockFile.sizes.set(this.uri,0)}async write(e){MockFile.sizes.set(this.uri,e.byteLength)}}const under=e=>[...MockFile.sizes.keys()].filter(t=>t.startsWith(`${e.replace(/\/+$/,"")}/`));return{File:MockFile,Directory:class MockDirectory{constructor(...e){this.uri=joinUri(e)}get exists(){return under(this.uri).length>0}create(){}list(){return under(this.uri).map(e=>new MockFile(e))}delete(){for(const e of under(this.uri))MockFile.sizes.delete(e)}},Paths:{document:{uri:"file:///documents/"},cache:{uri:"file:///cache/"}}}},{virtual:!0}),jest.mock("expo-location",()=>({getCurrentPositionAsync:jest.fn(()=>Promise.resolve({coords:{latitude:0,longitude:0,accuracy:5},timestamp:0})),watchPositionAsync:jest.fn(()=>Promise.resolve({remove:jest.fn()})),getForegroundPermissionsAsync:jest.fn(()=>Promise.resolve({status:"granted",granted:!0,canAskAgain:!0})),requestForegroundPermissionsAsync:jest.fn(()=>Promise.resolve({status:"granted",granted:!0,canAskAgain:!0})),getBackgroundPermissionsAsync:jest.fn(()=>Promise.resolve({status:"granted",granted:!0,canAskAgain:!0})),requestBackgroundPermissionsAsync:jest.fn(()=>Promise.resolve({status:"granted",granted:!0,canAskAgain:!0}))}),{virtual:!0}),jest.mock("expo-sqlite",()=>({openDatabaseAsync:jest.fn(()=>Promise.resolve({prepareAsync:jest.fn(()=>Promise.resolve({executeAsync:jest.fn(()=>Promise.resolve({lastInsertRowId:0,changes:0,getAllAsync:jest.fn(()=>Promise.resolve([]))})),finalizeAsync:jest.fn(()=>Promise.resolve())})),closeAsync:jest.fn(()=>Promise.resolve())}))})),jest.mock("expo-secure-store",()=>({getItemAsync:jest.fn(()=>Promise.resolve(null)),setItemAsync:jest.fn(()=>Promise.resolve()),deleteItemAsync:jest.fn(()=>Promise.resolve())})),globalThis.__expoApplicationMock={applicationId:"com.webority.test",nativeApplicationVersion:"1.0.0",nativeBuildVersion:"1"},jest.mock("expo-application",()=>({get applicationId(){return globalThis.__expoApplicationMock.applicationId},get nativeApplicationVersion(){return globalThis.__expoApplicationMock.nativeApplicationVersion},get nativeBuildVersion(){return globalThis.__expoApplicationMock.nativeBuildVersion}})),jest.mock("react-native/src/private/devsupport/devmenu/specs/NativeDevMenu",()=>({__esModule:!0,default:{show:jest.fn(),reload:jest.fn(),setProfilingEnabled:jest.fn(),setHotLoadingEnabled:jest.fn()}}),{virtual:!0}),jest.mock("react-native-worklets",()=>{const noop=()=>{},passthrough=e=>"function"==typeof e?e:noop;return{__esModule:!0,runOnJS:passthrough,scheduleOnRN:(e,...t)=>{"function"==typeof e&&e(...t)},runOnUI:passthrough,runOnRuntime:passthrough,createWorkletRuntime:()=>({}),isWorkletFunction:()=>!1,makeShareableCloneRecursive:e=>e,makeShareable:e=>e,executeOnUIRuntimeSync:e=>e,Worklets:{}}},{virtual:!0}),jest.mock("react-native-reanimated",()=>{const e=require("react"),{View:t}=require("react-native"),noop=()=>{},passthrough=e=>"function"==typeof e?e:noop,chainable=()=>{const e={};for(const t of["duration","delay","springify","reduceMotion","easing","damping","stiffness","mass","withInitialValues","withCallback","build"])e[t]=()=>e;return e},s=Symbol("mockSharedValue"),makeSharedValue=e=>{let t=e;return{[s]:!0,get value(){return t},set value(e){t=e},addListener:noop,removeListener:noop,modify:e=>{t="function"==typeof e?e(t):e}}},animatedComponent=t=>{const s=e.forwardRef((s,n)=>e.createElement(t,{...s,ref:n}));return s.displayName=`Animated(${t?.displayName||t?.name||"Component"})`,s},n={View:animatedComponent(t),Text:animatedComponent(t),ScrollView:animatedComponent(t),Image:animatedComponent(t),FlatList:animatedComponent(t),createAnimatedComponent:animatedComponent},withCallback=(e,t,s)=>("function"==typeof s&&s(!0),e);return{__esModule:!0,default:n,...n,useSharedValue:t=>{const s=e.useRef(null);return null===s.current&&(s.current=makeSharedValue(t)),s.current},useDerivedValue:e=>makeSharedValue("function"==typeof e?e():void 0),useAnimatedStyle:e=>"function"==typeof e?e():{},useAnimatedProps:()=>({}),useAnimatedReaction:noop,useAnimatedScrollHandler:()=>noop,useAnimatedGestureHandler:()=>({}),useAnimatedRef:()=>({current:null}),useFrameCallback:()=>({setActive:noop}),useScrollViewOffset:makeSharedValue,useEvent:()=>noop,useHandler:()=>({context:{},doDependenciesDiffer:!1}),useAnimatedSensor:()=>({sensor:makeSharedValue(0)}),useWorkletCallback:passthrough,useComposedEventHandler:()=>noop,useReducedMotion:()=>!1,isSharedValue:e=>"object"==typeof e&&null!==e&&s in e,withTiming:withCallback,withSpring:withCallback,withDecay:e=>e,withSequence:(...e)=>e[e.length-1],withDelay:(e,t)=>t,withRepeat:e=>e,cancelAnimation:noop,runOnJS:passthrough,runOnUI:passthrough,measure:()=>null,interpolate:()=>0,interpolateColor:()=>"#000",Extrapolate:{CLAMP:"clamp",EXTEND:"extend",IDENTITY:"identity"},Extrapolation:{CLAMP:"clamp",EXTEND:"extend",IDENTITY:"identity"},Easing:new Proxy({},{get:()=>()=>0}),ReduceMotion:{System:"system",Always:"always",Never:"never"},Layout:chainable(),FadeIn:chainable(),FadeOut:chainable(),SlideInDown:{duration:()=>({})},SlideOutDown:{duration:()=>({})},FadeInUp:{duration:()=>({})},FadeInDown:{duration:()=>({})},FadeOutUp:{duration:()=>({})},FadeOutDown:{duration:()=>({})},ZoomIn:{duration:()=>({})},ZoomOut:{duration:()=>({})}}},{virtual:!0}),jest.mock("react-native-keyboard-controller",()=>require("react-native-keyboard-controller/jest"),{virtual:!0}),jest.mock("react-native-safe-area-context",()=>{const e=require("react"),t={top:0,right:0,bottom:0,left:0};return{SafeAreaProvider:({children:e})=>e,SafeAreaView:({children:e})=>e,SafeAreaInsetsContext:e.createContext(t),useSafeAreaInsets:()=>t,useSafeAreaFrame:()=>({x:0,y:0,width:390,height:844})}},{virtual:!0}),jest.mock("expo",()=>({isRunningInExpoGo:()=>!1}),{virtual:!0}),jest.mock("expo-haptics",()=>({selectionAsync:jest.fn(()=>Promise.resolve()),impactAsync:jest.fn(()=>Promise.resolve()),notificationAsync:jest.fn(()=>Promise.resolve()),performAndroidHapticsAsync:jest.fn(()=>Promise.resolve()),ImpactFeedbackStyle:{Light:"light",Medium:"medium",Heavy:"heavy"},NotificationFeedbackType:{Success:"success",Warning:"warning",Error:"error"},AndroidHaptics:{Confirm:"confirm",Reject:"reject",Gesture_Start:"gesture-start",Long_Press:"long-press",Segment_Tick:"segment-tick",Segment_Frequent_Tick:"segment-frequent-tick"}}),{virtual:!0}),jest.mock("expo-crypto",()=>({randomUUID:jest.fn(()=>"00000000-0000-4000-8000-000000000000"),getRandomValues:jest.fn(e=>e),getRandomBytes:jest.fn(e=>new Uint8Array(e)),digestStringAsync:jest.fn(()=>Promise.resolve("")),CryptoDigestAlgorithm:{SHA256:"SHA-256"}}),{virtual:!0}),jest.mock("expo-clipboard",()=>({setStringAsync:jest.fn(()=>Promise.resolve(!0)),getStringAsync:jest.fn(()=>Promise.resolve(""))}),{virtual:!0}),jest.mock("expo-image",()=>{const e=require("react"),{Image:t}=require("react-native"),s=e.forwardRef((s,n)=>e.createElement(t,{...s,ref:n}));return s.displayName="ExpoImage",{__esModule:!0,Image:s}},{virtual:!0});export{};
|
|
@@ -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";import{createProgressReporter}from"./progress.js";import{uploadResumable}from"./resumable.js";const TABLE="outbox_entry",DEFAULT_DATABASE_NAME="webority-outbox",DEFAULT_MAX_ENTRIES=50,DEFAULT_TIMEOUT_MS=3e5,DEFAULT_CHUNK_BYTES=1048576,BASE_BACKOFF_MS=3e4,MAX_BACKOFF_MS=9e5,REPLAY_WINDOW_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`]},{version:3,name:"outbox_entry_outcome_unknown_since_utc",up:[`ALTER TABLE ${TABLE} ADD COLUMN outcome_unknown_since_utc TEXT NULL`,`UPDATE ${TABLE} SET outcome_unknown_since_utc = created_utc WHERE attempts > 0 OR state = 'Sending'`]}],nowIso=()=>new Date(Date.now()).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:n,state:a,attempts:s,last_failure_json:i,created_utc:u,next_attempt_utc:d,upload_json:c,outcome_unknown_since_utc: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 n)throw rowFieldMissing("request_json");if(!isOneOf(ENTRY_STATES,a))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");if(null!==c&&"string"!=typeof c)throw rowFieldMissing("upload_json");if(null!==l&&"string"!=typeof l)throw rowFieldMissing("outcome_unknown_since_utc");return{id:t,queue:r,label:o,request_json:n,state:a,attempts:s,last_failure_json:i,created_utc:u,next_attempt_utc:d,upload_json:c,outcome_unknown_since_utc: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,outcomeUnknownSinceDateTimeUtc:e.outcome_unknown_since_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(),n=t.find(e=>e.toLowerCase()===o),a=void 0===n?void 0:e[n];if(void 0===a||!UUID_SHAPE.test(a))throw new OutboxMissingKeyError},isOfflineError=e=>e instanceof Error&&"RequestOfflineError"===e.name,provablyNotSent=e=>!!isOfflineError(e)||axios.isAxiosError(e)&&(isNeverSentError(e)||429===e.response?.status),isTransient=e=>{if(isOfflineError(e))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,n=e.chunkBytes??1048576;if(!Number.isSafeInteger(n)||n<=0)throw new RangeError("The outbox chunkBytes option must be a positive integer.");const a=new Set,s=new Map;let i=null,u=null,d=!1,c=null,l=0,w=null;const store=()=>(i||(i=openDatabase(r).then(async e=>(await e.migrate(MIGRATIONS),e)).catch(e=>{throw i=null,e})),i),logFailure=e=>Logger.error("[outbox] background work failed",e),emit=e=>{for(const t of a)t(e)},clearTimer=()=>{null!==c&&(clearTimeout(c),c=null)},flushNow=()=>(w||(w=runFlush().finally(()=>{w=null})),w),scheduleNext=async()=>{const e=++l;if(clearTimer(),!d||!u)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!==l||!o)return;const n=Math.min(Math.max(0,Date.parse(o)-Date.now()),9e5);c=setTimeout(()=>{c=null,flushNow().catch(logFailure)},n)},notifyChanged=e=>{emit({type:"changed",queue:e}),scheduleNext().catch(logFailure)},runFlush=async()=>{const e=await store(),t=await currentIdentity();if(!t)return;const r=await e.findAll(TABLE,{sql:"owner = ? AND state != 'Failed'",params:[t.owner]},{orderBy:"created_utc, rowid"},parseEntryRow),o=new Set;for(const e of r){if(o.has(e.queue))continue;if(e.next_attempt_utc>nowIso()){o.add(e.queue);continue}const r=await deliver(e.id,t,"auto");"Queued"===r?.status&&o.add(e.queue)}await scheduleNext()},runDelivery=async(e,r,o)=>{const a=await store(),s=await a.findOne(TABLE,{id:e,owner:r.owner},parseEntryRow);if(!s)return null;if("auto"===o&&null!==s.outcome_unknown_since_utc&&Date.now()-Date.parse(s.outcome_unknown_since_utc)>864e5){const t={code:"outbox_outcome_unknown",message:"We could not confirm this was sent. Check whether it arrived, then send it again or discard it.",status:null};await a.update(TABLE,{state:"Failed",last_failure_json:JSON.stringify(t)},{id:e});const r={...toEntry(s),state:"Failed",lastFailure:t};return notifyChanged(r.queue),emit({type:"failed",entry:r}),{status:"Failed",entry:r,failure:t}}const i=null===s.outcome_unknown_since_utc,u=s.outcome_unknown_since_utc??new Date(Date.now()).toISOString(),d={...toEntry(s),state:"Sending",outcomeUnknownSinceDateTimeUtc:u};await a.update(TABLE,{state:"Sending",outcome_unknown_since_utc:u},{id:e}),notifyChanged(d.queue);const{request:c}=d,l={...c.headers};r.accountId&&(l[ACCOUNT_ID_HEADER]=r.accountId);const w=createProgressReporter(d,e=>emit({type:"progress",progress:e}));let f;try{f=await(async()=>{if("resumable"===c.body.kind)return uploadResumable({http:t,createUrl:c.url,headers:l,metadata:c.body.metadata,fileUri:c.body.file.uri,chunkBytes:n,timeoutMs:c.timeoutMs??3e5,state:null===s.upload_json?null:parseUploadState(JSON.parse(s.upload_json)),onState:async t=>{await a.update(TABLE,{upload_json:JSON.stringify(t)},{id:e})},onProgress:(e,t)=>w({loaded:e,total:t})});const r="json"===c.body.kind?c.body.value:buildFormData(c.body.fields),o={method:c.method,url:c.url,headers:l,data:r,timeout:c.timeoutMs??3e5,retry:!1,onUploadProgress:w},i=await t.request(o);return{httpStatus:i.status,data:i.data}})()}catch(e){return(async(e,t,r,o,n)=>{if(isTransient(r)){const o=t.attempts+1,a=inMs(retryDelayMs(r,o)),s=n&&provablyNotSent(r)?null:t.outcomeUnknownSinceDateTimeUtc;return await e.update(TABLE,{state:"Pending",attempts:o,next_attempt_utc:a,outcome_unknown_since_utc:s},{id:t.id}),notifyChanged(t.queue),{status:"Queued",entry:{...t,state:"Pending",attempts:o,nextAttemptDateTimeUtc:a,outcomeUnknownSinceDateTimeUtc:s}}}const a=failureOf(r);if("first"===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,d,e,o,i)}return await a.remove(TABLE,{id:e}),await deleteEntryFiles(e),notifyChanged(d.queue),emit({type:"sent",entry:d,httpStatus:f.httpStatus,data:f.data}),{status:"Sent",entry:d,httpStatus:f.httpStatus,data:f.data}},deliver=(e,t,r)=>{const o=s.get(e);if(void 0!==o)return o;const n=runDelivery(e,t,r).finally(()=>{s.delete(e)});return s.set(e,n),n},start=async()=>{const e=await store();return u||((()=>{d="active"===AppState.currentState;const e=addNetworkStatusListener(e=>{e.isConnected&&flushNow().catch(logFailure)}),t=AppState.addEventListener("change",e=>{d="active"===e,d?flushNow().catch(logFailure):clearTimer()});u=()=>{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 n=newIdempotencyKey(),a=await persistRequestFiles(n,e.request),s=nowIso();try{await t.insert(TABLE,{id:n,owner:r.owner,queue:e.queue,label:e.label,request_json:JSON.stringify(a),state:"Pending",attempts:0,last_failure_json:null,created_utc:s,next_attempt_utc:s,outcome_unknown_since_utc:null})}catch(e){throw await deleteEntryFiles(n),e}const i=await t.findOne(TABLE,{id:n},parseEntryRow);if(!i)throw new Error("The outbox entry was removed before it was sent.");notifyChanged(e.queue);if(await t.count(TABLE,{sql:`owner = ? AND queue = ? AND state != 'Failed' AND (created_utc < ? OR (created_utc = ? AND rowid < (SELECT rowid FROM ${TABLE} WHERE id = ?)))`,params:[r.owner,e.queue,s,s,n]})>0)return flushNow().catch(logFailure),{status:"Queued",entry:toEntry(i)};const u=await deliver(n,r,"first");if(!u)throw new Error("The outbox entry was removed before it was sent.");return u},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, rowid"},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(),outcome_unknown_since_utc:null},{id:e,owner:r.owner})?null:await deliver(e,r,"user");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([s.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=>(a.add(e),()=>{a.delete(e)}),async close(){l+=1,clearTimer(),u?.(),u=null,d=!1}}};
|
|
1
|
+
"use strict";import axios,{AxiosError,AxiosHeaders}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{isBackgroundEligible,resolveUploadUrl,uploadInBackground}from"./backgroundUpload.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_TIMEOUT_MS=3e5,DEFAULT_CHUNK_BYTES=1048576,BASE_BACKOFF_MS=3e4,MAX_BACKOFF_MS=9e5,REPLAY_WINDOW_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`]},{version:3,name:"outbox_entry_outcome_unknown_since_utc",up:[`ALTER TABLE ${TABLE} ADD COLUMN outcome_unknown_since_utc TEXT NULL`,`UPDATE ${TABLE} SET outcome_unknown_since_utc = created_utc WHERE attempts > 0 OR state = 'Sending'`]}],nowIso=()=>new Date(Date.now()).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:n,state:a,attempts:s,last_failure_json:i,created_utc:u,next_attempt_utc:d,upload_json:l,outcome_unknown_since_utc:c}=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 n)throw rowFieldMissing("request_json");if(!isOneOf(ENTRY_STATES,a))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");if(null!==l&&"string"!=typeof l)throw rowFieldMissing("upload_json");if(null!==c&&"string"!=typeof c)throw rowFieldMissing("outcome_unknown_since_utc");return{id:t,queue:r,label:o,request_json:n,state:a,attempts:s,last_failure_json:i,created_utc:u,next_attempt_utc:d,upload_json:l,outcome_unknown_since_utc:c}},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,outcomeUnknownSinceDateTimeUtc:e.outcome_unknown_since_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(),n=t.find(e=>e.toLowerCase()===o),a=void 0===n?void 0:e[n];if(void 0===a||!UUID_SHAPE.test(a))throw new OutboxMissingKeyError},isOfflineError=e=>e instanceof Error&&"RequestOfflineError"===e.name,provablyNotSent=e=>!!isOfflineError(e)||axios.isAxiosError(e)&&(isNeverSentError(e)||429===e.response?.status),isTransient=e=>{if(isOfflineError(e))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}},backgroundFailure=(e,t)=>new AxiosError(`The background upload failed with status ${e}.`,e>=500?AxiosError.ERR_BAD_RESPONSE:AxiosError.ERR_BAD_REQUEST,void 0,void 0,{status:e,statusText:"",data:t,headers:{},config:{headers:new AxiosHeaders}}),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.backgroundUploads??!0,n=e.baseUrl,a=e.maxEntriesPerOwner??50,s=e.chunkBytes??1048576;if(!Number.isSafeInteger(s)||s<=0)throw new RangeError("The outbox chunkBytes option must be a positive integer.");const i=new Set,u=new Map;let d=null,l=null,c=!1,w=null,f=0,p=null;const store=()=>(d||(d=openDatabase(r).then(async e=>(await e.migrate(MIGRATIONS),e)).catch(e=>{throw d=null,e})),d),logFailure=e=>Logger.error("[outbox] background work failed",e),emit=e=>{for(const t of i)t(e)},clearTimer=()=>{null!==w&&(clearTimeout(w),w=null)},flushNow=()=>(p||(p=runFlush().finally(()=>{p=null})),p),scheduleNext=async()=>{const e=++f;if(clearTimer(),!c||!l)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 n=Math.min(Math.max(0,Date.parse(o)-Date.now()),9e5);w=setTimeout(()=>{w=null,flushNow().catch(logFailure)},n)},notifyChanged=e=>{emit({type:"changed",queue:e}),scheduleNext().catch(logFailure)},runFlush=async()=>{const e=await store(),t=await currentIdentity();if(!t)return;const r=await e.findAll(TABLE,{sql:"owner = ? AND state != 'Failed'",params:[t.owner]},{orderBy:"created_utc, rowid"},parseEntryRow),o=new Set;for(const e of r){if(o.has(e.queue))continue;if(e.next_attempt_utc>nowIso()){o.add(e.queue);continue}const r=await deliver(e.id,t,"auto");"Queued"===r?.status&&o.add(e.queue)}await scheduleNext()},runDelivery=async(e,r,a)=>{const i=await store(),u=await i.findOne(TABLE,{id:e,owner:r.owner},parseEntryRow);if(!u)return null;if("auto"===a&&null!==u.outcome_unknown_since_utc&&Date.now()-Date.parse(u.outcome_unknown_since_utc)>864e5){const t={code:"outbox_outcome_unknown",message:"We could not confirm this was sent. Check whether it arrived, then send it again or discard it.",status:null};await i.update(TABLE,{state:"Failed",last_failure_json:JSON.stringify(t)},{id:e});const r={...toEntry(u),state:"Failed",lastFailure:t};return notifyChanged(r.queue),emit({type:"failed",entry:r}),{status:"Failed",entry:r,failure:t}}const d=null===u.outcome_unknown_since_utc,l=u.outcome_unknown_since_utc??new Date(Date.now()).toISOString(),c={...toEntry(u),state:"Sending",outcomeUnknownSinceDateTimeUtc:l};await i.update(TABLE,{state:"Sending",outcome_unknown_since_utc:l},{id:e}),notifyChanged(c.queue);const{request:w}=c,f={...w.headers};r.accountId&&(f[ACCOUNT_ID_HEADER]=r.accountId);const p=createProgressReporter(c,e=>emit({type:"progress",progress:e}));let m;try{m=await(async()=>{if(o&&isBackgroundEligible(w)&&(n||/^https?:\/\//i.test(w.url))){const e=(await getToken(ACCESS_TOKEN_KEY))?.token,t=await uploadInBackground({request:w,url:resolveUploadUrl(w.url,n??null),headers:e?{...f,Authorization:`Bearer ${e}`}:f,onProgress:(e,t)=>p({loaded:e,total:t})}).catch(e=>{throw new AxiosError(e instanceof Error?e.message:"The background upload failed.",AxiosError.ERR_NETWORK)});if(t.status>=200&&t.status<=299)return{httpStatus:t.status,data:t.data};if(401!==t.status)throw backgroundFailure(t.status,t.data)}if("resumable"===w.body.kind)return uploadResumable({http:t,createUrl:w.url,headers:f,metadata:w.body.metadata,fileUri:w.body.file.uri,chunkBytes:s,timeoutMs:w.timeoutMs??3e5,state:null===u.upload_json?null:parseUploadState(JSON.parse(u.upload_json)),onState:async t=>{await i.update(TABLE,{upload_json:JSON.stringify(t)},{id:e})},onProgress:(e,t)=>p({loaded:e,total:t})});const r="json"===w.body.kind?w.body.value:buildFormData(w.body.fields),a={method:w.method,url:w.url,headers:f,data:r,timeout:w.timeoutMs??3e5,retry:!1,onUploadProgress:p},d=await t.request(a);return{httpStatus:d.status,data:d.data}})()}catch(e){return(async(e,t,r,o,n)=>{if(isTransient(r)){const o=t.attempts+1,a=inMs(retryDelayMs(r,o)),s=n&&provablyNotSent(r)?null:t.outcomeUnknownSinceDateTimeUtc;return await e.update(TABLE,{state:"Pending",attempts:o,next_attempt_utc:a,outcome_unknown_since_utc:s},{id:t.id}),notifyChanged(t.queue),{status:"Queued",entry:{...t,state:"Pending",attempts:o,nextAttemptDateTimeUtc:a,outcomeUnknownSinceDateTimeUtc:s}}}const a=failureOf(r);if("first"===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}})(i,c,e,a,d)}return await i.remove(TABLE,{id:e}),await deleteEntryFiles(e),notifyChanged(c.queue),emit({type:"sent",entry:c,httpStatus:m.httpStatus,data:m.data}),{status:"Sent",entry:c,httpStatus:m.httpStatus,data:m.data}},deliver=(e,t,r)=>{const o=u.get(e);if(void 0!==o)return o;const n=runDelivery(e,t,r).finally(()=>{u.delete(e)});return u.set(e,n),n},start=async()=>{const e=await store();return l||((()=>{c="active"===AppState.currentState;const e=addNetworkStatusListener(e=>{e.isConnected&&flushNow().catch(logFailure)}),t=AppState.addEventListener("change",e=>{c="active"===e,c?flushNow().catch(logFailure):clearTimer()});l=()=>{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})>=a)throw new OutboxFullError;const o=newIdempotencyKey(),n=await persistRequestFiles(o,e.request),s=nowIso();try{await t.insert(TABLE,{id:o,owner:r.owner,queue:e.queue,label:e.label,request_json:JSON.stringify(n),state:"Pending",attempts:0,last_failure_json:null,created_utc:s,next_attempt_utc:s,outcome_unknown_since_utc:null})}catch(e){throw await deleteEntryFiles(o),e}const i=await t.findOne(TABLE,{id:o},parseEntryRow);if(!i)throw new Error("The outbox entry was removed before it was sent.");notifyChanged(e.queue);if(await t.count(TABLE,{sql:`owner = ? AND queue = ? AND state != 'Failed' AND (created_utc < ? OR (created_utc = ? AND rowid < (SELECT rowid FROM ${TABLE} WHERE id = ?)))`,params:[r.owner,e.queue,s,s,o]})>0)return flushNow().catch(logFailure),{status:"Queued",entry:toEntry(i)};const u=await deliver(o,r,"first");if(!u)throw new Error("The outbox entry was removed before it was sent.");return u},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, rowid"},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(),outcome_unknown_since_utc:null},{id:e,owner:r.owner})?null:await deliver(e,r,"user");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([u.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=>(i.add(e),()=>{i.delete(e)}),async close(){f+=1,clearTimer(),l?.(),l=null,c=!1}}};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type ExportedConfig, type IOSConfig } from "expo/config-plugins";
|
|
2
|
+
export interface CertificatePinningDomain {
|
|
3
|
+
host: string;
|
|
4
|
+
pins: string[];
|
|
5
|
+
includeSubdomains?: boolean;
|
|
6
|
+
}
|
|
7
|
+
export interface CertificatePinningOptions {
|
|
8
|
+
domains: CertificatePinningDomain[];
|
|
9
|
+
expiration?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface WeborityCertificatePinningOptions {
|
|
12
|
+
certificatePinning: CertificatePinningOptions;
|
|
13
|
+
}
|
|
14
|
+
type InfoPlist = IOSConfig.InfoPlist;
|
|
15
|
+
export declare function validateCertificatePinning(options: CertificatePinningOptions | undefined): asserts options is CertificatePinningOptions;
|
|
16
|
+
export declare function buildNetworkSecurityConfig(options: CertificatePinningOptions): string;
|
|
17
|
+
export declare function applyPinnedDomains(infoPlist: InfoPlist, options: CertificatePinningOptions): InfoPlist;
|
|
18
|
+
export declare function applyNetworkSecurityConfigAttribute(attributes: {
|
|
19
|
+
[key: string]: string | undefined;
|
|
20
|
+
}): void;
|
|
21
|
+
export default function withWeborityCertificatePinning(config: ExportedConfig, options: WeborityCertificatePinningOptions | undefined): ExportedConfig;
|
|
22
|
+
export {};
|
|
23
|
+
//# sourceMappingURL=plugin.d.ts.map
|
|
@@ -145,4 +145,21 @@ export declare const formatPercent: (value: number | string | null | undefined,
|
|
|
145
145
|
* With a configured locale, Intl writes it in that locale ("150.000,00 €" for de-DE).
|
|
146
146
|
*/
|
|
147
147
|
export declare const formatMinor: (amountMinor: number | string | null | undefined, options: FormatMinorOptions) => string;
|
|
148
|
+
/**
|
|
149
|
+
* Money held in hundredths of the minor unit, the Webority.Domain HundredthMinorUnits value (1 INR is
|
|
150
|
+
* 10000). It shows the exact amount with no rounding: the minor digits plus two, trailing zeros trimmed
|
|
151
|
+
* but never below the minor digits. formatHundredthMinor(2000000000, { currency: 'INR' }) gives
|
|
152
|
+
* "₹2,00,000.00" and formatHundredthMinor(123456, { currency: 'INR' }) gives "₹12.3456".
|
|
153
|
+
*/
|
|
154
|
+
export declare const formatHundredthMinor: (amountHundredths: number | string | null | undefined, options: FormatMinorOptions) => string;
|
|
155
|
+
/**
|
|
156
|
+
* The whole number of hundredths of the minor unit in major-unit text: "2,00,000.00" gives 2000000000
|
|
157
|
+
* for INR and "12.3456" gives 123456. Accepts an optional leading minus, group separators (the house
|
|
158
|
+
* group separator and ","), an optional decimal part of 1 to minor digits + 2 digits, and a rupee sign or
|
|
159
|
+
* the currency's symbol. Throws a RangeError for any other text, for more decimal places than the
|
|
160
|
+
* currency allows, or for a result beyond the safe integer range.
|
|
161
|
+
*/
|
|
162
|
+
export declare const parseHundredthMinor: (text: string, options: {
|
|
163
|
+
currency: string;
|
|
164
|
+
}) => number;
|
|
148
165
|
//# sourceMappingURL=house.d.ts.map
|
|
@@ -6,7 +6,7 @@ export { addDays, diffMs, formatDateISO, formatDatePattern, formatTime12h, forma
|
|
|
6
6
|
export type { DateOrder, FormatterConfig, NumberGrouping, NumberStyle, ZoneMode, } from "./formatConfig";
|
|
7
7
|
export { configureFormatters, getFormatterConfig, groupingForLocale } from "./formatConfig";
|
|
8
8
|
export type { DateValue, FormatDateOptions, FormatDateTimeOptions, FormatMinorOptions, FormatNumberOptions, FormatPercentOptions, FormatRelativeOptions, FormatTimeOptions, ZoneOption, } from "./house";
|
|
9
|
-
export { formatMinor, formatRelative } from "./house";
|
|
9
|
+
export { formatHundredthMinor, formatMinor, formatRelative, parseHundredthMinor } from "./house";
|
|
10
10
|
export { getInitials } from "./initials";
|
|
11
11
|
export { formatCompactNumber, formatNumber, formatPercent } from "./number";
|
|
12
12
|
export type { FormatPhoneOptions, PhoneCountry, PhoneCountryEntry, PhoneNumber, PhoneNumberType, PhoneParts, PhoneValidationKind, } from "./phone";
|
|
@@ -105,6 +105,10 @@ export interface OutboxOptions {
|
|
|
105
105
|
maxEntriesPerOwner?: number | undefined;
|
|
106
106
|
/** A resumable body is sent in chunks of this size. Default 1_048_576. */
|
|
107
107
|
chunkBytes?: number | undefined;
|
|
108
|
+
/** Default true. A one-file multipart save goes through the iOS background transfer; Android sends in the app's process. */
|
|
109
|
+
backgroundUploads?: boolean | undefined;
|
|
110
|
+
/** The origin a relative request url is sent to on a background send. Absolute urls need none. */
|
|
111
|
+
baseUrl?: string | undefined;
|
|
108
112
|
}
|
|
109
113
|
export interface Outbox {
|
|
110
114
|
/** 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,23 @@
|
|
|
1
|
+
import { type ExportedConfig, type IOSConfig } from "expo/config-plugins";
|
|
2
|
+
export interface CertificatePinningDomain {
|
|
3
|
+
host: string;
|
|
4
|
+
pins: string[];
|
|
5
|
+
includeSubdomains?: boolean;
|
|
6
|
+
}
|
|
7
|
+
export interface CertificatePinningOptions {
|
|
8
|
+
domains: CertificatePinningDomain[];
|
|
9
|
+
expiration?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface WeborityCertificatePinningOptions {
|
|
12
|
+
certificatePinning: CertificatePinningOptions;
|
|
13
|
+
}
|
|
14
|
+
type InfoPlist = IOSConfig.InfoPlist;
|
|
15
|
+
export declare function validateCertificatePinning(options: CertificatePinningOptions | undefined): asserts options is CertificatePinningOptions;
|
|
16
|
+
export declare function buildNetworkSecurityConfig(options: CertificatePinningOptions): string;
|
|
17
|
+
export declare function applyPinnedDomains(infoPlist: InfoPlist, options: CertificatePinningOptions): InfoPlist;
|
|
18
|
+
export declare function applyNetworkSecurityConfigAttribute(attributes: {
|
|
19
|
+
[key: string]: string | undefined;
|
|
20
|
+
}): void;
|
|
21
|
+
export default function withWeborityCertificatePinning(config: ExportedConfig, options: WeborityCertificatePinningOptions | undefined): ExportedConfig;
|
|
22
|
+
export {};
|
|
23
|
+
//# sourceMappingURL=plugin.d.ts.map
|
|
@@ -145,4 +145,21 @@ export declare const formatPercent: (value: number | string | null | undefined,
|
|
|
145
145
|
* With a configured locale, Intl writes it in that locale ("150.000,00 €" for de-DE).
|
|
146
146
|
*/
|
|
147
147
|
export declare const formatMinor: (amountMinor: number | string | null | undefined, options: FormatMinorOptions) => string;
|
|
148
|
+
/**
|
|
149
|
+
* Money held in hundredths of the minor unit, the Webority.Domain HundredthMinorUnits value (1 INR is
|
|
150
|
+
* 10000). It shows the exact amount with no rounding: the minor digits plus two, trailing zeros trimmed
|
|
151
|
+
* but never below the minor digits. formatHundredthMinor(2000000000, { currency: 'INR' }) gives
|
|
152
|
+
* "₹2,00,000.00" and formatHundredthMinor(123456, { currency: 'INR' }) gives "₹12.3456".
|
|
153
|
+
*/
|
|
154
|
+
export declare const formatHundredthMinor: (amountHundredths: number | string | null | undefined, options: FormatMinorOptions) => string;
|
|
155
|
+
/**
|
|
156
|
+
* The whole number of hundredths of the minor unit in major-unit text: "2,00,000.00" gives 2000000000
|
|
157
|
+
* for INR and "12.3456" gives 123456. Accepts an optional leading minus, group separators (the house
|
|
158
|
+
* group separator and ","), an optional decimal part of 1 to minor digits + 2 digits, and a rupee sign or
|
|
159
|
+
* the currency's symbol. Throws a RangeError for any other text, for more decimal places than the
|
|
160
|
+
* currency allows, or for a result beyond the safe integer range.
|
|
161
|
+
*/
|
|
162
|
+
export declare const parseHundredthMinor: (text: string, options: {
|
|
163
|
+
currency: string;
|
|
164
|
+
}) => number;
|
|
148
165
|
//# sourceMappingURL=house.d.ts.map
|
|
@@ -6,7 +6,7 @@ export { addDays, diffMs, formatDateISO, formatDatePattern, formatTime12h, forma
|
|
|
6
6
|
export type { DateOrder, FormatterConfig, NumberGrouping, NumberStyle, ZoneMode, } from "./formatConfig.js";
|
|
7
7
|
export { configureFormatters, getFormatterConfig, groupingForLocale } from "./formatConfig.js";
|
|
8
8
|
export type { DateValue, FormatDateOptions, FormatDateTimeOptions, FormatMinorOptions, FormatNumberOptions, FormatPercentOptions, FormatRelativeOptions, FormatTimeOptions, ZoneOption, } from "./house.js";
|
|
9
|
-
export { formatMinor, formatRelative } from "./house.js";
|
|
9
|
+
export { formatHundredthMinor, formatMinor, formatRelative, parseHundredthMinor } from "./house.js";
|
|
10
10
|
export { getInitials } from "./initials.js";
|
|
11
11
|
export { formatCompactNumber, formatNumber, formatPercent } from "./number.js";
|
|
12
12
|
export type { FormatPhoneOptions, PhoneCountry, PhoneCountryEntry, PhoneNumber, PhoneNumberType, PhoneParts, PhoneValidationKind, } from "./phone.js";
|
|
@@ -105,6 +105,10 @@ export interface OutboxOptions {
|
|
|
105
105
|
maxEntriesPerOwner?: number | undefined;
|
|
106
106
|
/** A resumable body is sent in chunks of this size. Default 1_048_576. */
|
|
107
107
|
chunkBytes?: number | undefined;
|
|
108
|
+
/** Default true. A one-file multipart save goes through the iOS background transfer; Android sends in the app's process. */
|
|
109
|
+
backgroundUploads?: boolean | undefined;
|
|
110
|
+
/** The origin a relative request url is sent to on a background send. Absolute urls need none. */
|
|
111
|
+
baseUrl?: string | undefined;
|
|
108
112
|
}
|
|
109
113
|
export interface Outbox {
|
|
110
114
|
/** Stores the entry (files copied first), then tries it once. Definitive refusal on this first try deletes the entry and returns Failed. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webority/mobile-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.180.0",
|
|
4
4
|
"description": "Platform layer for Webority React Native apps: HTTP clients, auth/token storage, config, logging, formatters, validators, network status, permissions, storage, version checks and over-the-air updates. No UI.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react-native",
|
|
@@ -372,6 +372,10 @@
|
|
|
372
372
|
"default": "./lib/commonjs/jest/setup.js"
|
|
373
373
|
}
|
|
374
374
|
},
|
|
375
|
+
"./app.plugin.js": {
|
|
376
|
+
"types": "./lib/typescript/commonjs/certificatePinning/plugin.d.ts",
|
|
377
|
+
"default": "./app.plugin.js"
|
|
378
|
+
},
|
|
375
379
|
"./package.json": "./package.json"
|
|
376
380
|
},
|
|
377
381
|
"main": "./lib/commonjs/index.js",
|
|
@@ -380,6 +384,7 @@
|
|
|
380
384
|
"types": "./lib/typescript/commonjs/index.d.ts",
|
|
381
385
|
"files": [
|
|
382
386
|
"lib",
|
|
387
|
+
"app.plugin.js",
|
|
383
388
|
"src/specs",
|
|
384
389
|
"android",
|
|
385
390
|
"!android/build",
|
|
@@ -399,7 +404,7 @@
|
|
|
399
404
|
}
|
|
400
405
|
},
|
|
401
406
|
"dependencies": {
|
|
402
|
-
"@webority/api-contract": "0.
|
|
407
|
+
"@webority/api-contract": "0.180.0",
|
|
403
408
|
"axios": "^1.19.0",
|
|
404
409
|
"libphonenumber-js": "^1.12.41"
|
|
405
410
|
},
|
|
@@ -430,6 +435,7 @@
|
|
|
430
435
|
"expo-updates": ">=58.0.0",
|
|
431
436
|
"react": "^19.3.0",
|
|
432
437
|
"react-native": ">=0.88.0",
|
|
438
|
+
"react-native-keyboard-controller": ">=1.21.9",
|
|
433
439
|
"react-redux": "^9.3.0"
|
|
434
440
|
},
|
|
435
441
|
"peerDependenciesMeta": {
|
|
@@ -487,6 +493,9 @@
|
|
|
487
493
|
"expo-updates": {
|
|
488
494
|
"optional": true
|
|
489
495
|
},
|
|
496
|
+
"react-native-keyboard-controller": {
|
|
497
|
+
"optional": true
|
|
498
|
+
},
|
|
490
499
|
"react-redux": {
|
|
491
500
|
"optional": true
|
|
492
501
|
}
|