@everfur/sdk 0.12.0 → 0.13.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/CHANGELOG.md +174 -0
- package/README.md +2 -1
- package/dist/{Chat-BOG0SXKV.d.cts → Chat.d-DUNTfzqC.d.ts} +170 -8
- package/dist/{Chat-CIolBgjJ.d.ts → Chat.d-Dts8u_1a.d.cts} +170 -8
- package/dist/{DepthViews-BR6VQ3Ta.d.cts → DepthViews.d-BIp599lz.d.cts} +1 -1
- package/dist/{DepthViews-280t3BcQ.d.ts → DepthViews.d-BMU2jFPw.d.cts} +1 -1
- package/dist/{DepthViews-DlBuFsgN.d.ts → DepthViews.d-Ce2Zhnrb.d.ts} +1 -1
- package/dist/{DepthViews-BTbF_DJY.d.cts → DepthViews.d-CubkMPbU.d.ts} +1 -1
- package/dist/{ErrorPolicyPort-10s3HJCt.d.cts → ErrorPolicyPort.d-68yrE3BE.d.ts} +1 -1
- package/dist/{ErrorPolicyPort-C3nNSS_j.d.ts → ErrorPolicyPort.d-DirW9hgO.d.cts} +1 -1
- package/dist/{EverfurError-DeBqRpQV.d.cts → EverfurError.d-8NHtlgzA.d.cts} +11 -1
- package/dist/{EverfurError-DeBqRpQV.d.ts → EverfurError.d-8NHtlgzA.d.ts} +11 -1
- package/dist/{EverfurResult-ClPTS0P2.d.ts → EverfurResult.d-BFH-3s6E.d.cts} +1 -1
- package/dist/{EverfurResult-COlXj1wq.d.cts → EverfurResult.d-D_-254ZY.d.ts} +1 -1
- package/dist/{IntakeMedia-BH0fYDT2.d.cts → IntakeMedia.d-4a89XrP7.d.ts} +1 -1
- package/dist/{IntakeMedia-B-_vA9ZB.d.cts → IntakeMedia.d-DGxrhgIW.d.ts} +1 -1
- package/dist/{IntakeMedia-CIoTXAWs.d.ts → IntakeMedia.d-DUPR4lVM.d.cts} +1 -1
- package/dist/{IntakeMedia-Bavl7E4Z.d.ts → IntakeMedia.d-JJCUvQu7.d.cts} +1 -1
- package/dist/LifecyclePort.d-Cr1p33a7.d.cts +23 -0
- package/dist/LifecyclePort.d-Cr1p33a7.d.ts +23 -0
- package/dist/{PhotoController-vzY5bfY_.d.ts → PhotoController.d-BzCJOE7e.d.cts} +2 -2
- package/dist/{PhotoController-3l7MT9jA.d.cts → PhotoController.d-D0XiUUOl.d.ts} +2 -2
- package/dist/animations/index.cjs +5 -1
- package/dist/animations/index.d.cts +24 -24
- package/dist/animations/index.d.ts +24 -24
- package/dist/animations/index.js +5 -1
- package/dist/{attachments-CGxvnYu4.d.ts → attachments.d-Bp2qbHxn.d.cts} +22 -26
- package/dist/{attachments-CWNj1ZkM.d.ts → attachments.d-D1yhJjcZ.d.ts} +4 -4
- package/dist/{attachments-waXcJWCp.d.cts → attachments.d-DisnvB9R.d.cts} +4 -4
- package/dist/{attachments-B6h4cJU-.d.cts → attachments.d-Djy9z_0Z.d.ts} +22 -26
- package/dist/{bookingCopy-CjPKeg75.d.ts → bookingCopy.d-BJF6gd1A.d.ts} +24 -9
- package/dist/{bookingCopy-8aEU6ZmR.d.cts → bookingCopy.d-BlBmhAJc.d.cts} +24 -9
- package/dist/{branding-DJf4h12Q.d.ts → branding.d-DI8S400y.d.cts} +9 -2
- package/dist/{branding-BCfwLj0h.d.cts → branding.d-OIGLbQeM.d.ts} +9 -2
- package/dist/{callRoom-BhIdadyV.d.cts → callRoom.d-B1DoYdJe.d.cts} +1 -1
- package/dist/{callRoom-B92eH_ij.d.ts → callRoom.d-Dqm1rUqT.d.ts} +1 -1
- package/dist/{casesRepository-CGdhvzTu.d.cts → casesRepository.d-CT2LTicS.d.cts} +3 -3
- package/dist/{casesRepository-ZG9Sg0e4.d.ts → casesRepository.d-UsWOz9bv.d.ts} +3 -3
- package/dist/chat/index.cjs +132 -57
- package/dist/chat/index.d.cts +18 -16
- package/dist/chat/index.d.ts +18 -16
- package/dist/chat/index.js +133 -58
- package/dist/client/index.cjs +15 -10
- package/dist/client/index.d.cts +19 -18
- package/dist/client/index.d.ts +19 -18
- package/dist/client/index.js +15 -10
- package/dist/{config-B0p6Lygh.d.cts → config.d-BR3DT9ho.d.cts} +3 -3
- package/dist/{config-DmFAZJOx.d.ts → config.d-Dy6igYlH.d.ts} +3 -3
- package/dist/consent/index.cjs +5 -1
- package/dist/consent/index.d.cts +10 -10
- package/dist/consent/index.d.ts +10 -10
- package/dist/consent/index.js +5 -1
- package/dist/{context-BNreNLtL.d.ts → context.d-Cwks0p3C.d.cts} +15 -15
- package/dist/{context-BgS2a57J.d.cts → context.d-QcCgguzA.d.ts} +15 -15
- package/dist/{copy-DLJriGQS.d.ts → copy.d-CiMn2IIt.d.ts} +6 -6
- package/dist/{copy-lWp-Lkv5.d.cts → copy.d-DLJTyRfT.d.cts} +6 -6
- package/dist/core/index.cjs +17 -13
- package/dist/core/index.d.cts +33 -29
- package/dist/core/index.d.ts +33 -29
- package/dist/core/index.js +17 -13
- package/dist/{depth-BYb3RXoA.d.cts → depth.d-CjPGVPDL.d.cts} +9 -115
- package/dist/{depth-COz-sSG5.d.ts → depth.d-OSALbYM7.d.ts} +9 -115
- package/dist/{entitlementRepository-D-Lse67w.d.cts → entitlementRepository.d-CVQa1DA1.d.cts} +10 -5
- package/dist/{entitlementRepository-CrTOP_-o.d.ts → entitlementRepository.d-Cf3LbTwD.d.ts} +10 -5
- package/dist/features.d-fNsGcg0R.d.cts +108 -0
- package/dist/features.d-fNsGcg0R.d.ts +108 -0
- package/dist/focus.d-DMg2ngHI.d.ts +1178 -0
- package/dist/focus.d-az9cqUz3.d.cts +1178 -0
- package/dist/health-plan/index.cjs +370 -0
- package/dist/health-plan/index.d.cts +251 -0
- package/dist/health-plan/index.d.ts +251 -0
- package/dist/health-plan/index.js +370 -0
- package/dist/idempotency.d-D461_DPD.d.cts +910 -0
- package/dist/idempotency.d-WpXx9zQo.d.ts +910 -0
- package/dist/{identity-Cw07BKZp.d.ts → identity.d-60LeJt_s.d.cts} +3 -3
- package/dist/{identity-DFVGYn1o.d.cts → identity.d-DzTijonw.d.ts} +3 -3
- package/dist/index.cjs +141 -66
- package/dist/index.d.cts +31 -29
- package/dist/index.d.ts +31 -29
- package/dist/index.js +142 -67
- package/dist/{models-A4A5S7AG.d.cts → models.d-BagXhafD.d.ts} +8 -3
- package/dist/{models-CnXY5LuO.d.ts → models.d-BnLm3VAA.d.cts} +8 -3
- package/dist/notifications/index.cjs +5 -1
- package/dist/notifications/index.d.cts +9 -9
- package/dist/notifications/index.d.ts +9 -9
- package/dist/notifications/index.js +5 -1
- package/dist/optInView.d-CEyHR6PK.d.cts +325 -0
- package/dist/optInView.d-acKpV8V2.d.ts +325 -0
- package/dist/parse.d-C8CXyS58.d.ts +210 -0
- package/dist/parse.d-tEzufgJX.d.cts +210 -0
- package/dist/{pets-BYALZTSu.d.ts → pets.d-C_53_fzo.d.ts} +3 -3
- package/dist/{pets-CcyPQS-H.d.cts → pets.d-NbJvP_kh.d.cts} +3 -3
- package/dist/{petsRepository-B_Q1gFkE.d.cts → petsRepository.d-BuGHymNx.d.ts} +4 -4
- package/dist/{petsRepository-518QkPxH.d.ts → petsRepository.d-lp1BHRqM.d.cts} +4 -4
- package/dist/photo/index.cjs +6 -2
- package/dist/photo/index.d.cts +9 -9
- package/dist/photo/index.d.ts +9 -9
- package/dist/photo/index.js +6 -2
- package/dist/{ports-BN6RHF9W.d.ts → ports.d-BX4f4UsB.d.cts} +14 -1
- package/dist/{ports-BN6RHF9W.d.cts → ports.d-BX4f4UsB.d.ts} +14 -1
- package/dist/{ports-RuNJmBA-.d.cts → ports.d-CEROoqnA.d.cts} +16 -10
- package/dist/{ports-DmQeMArX.d.ts → ports.d-COIyN624.d.ts} +16 -10
- package/dist/presentation.d-DMbdad7G.d.cts +90 -0
- package/dist/presentation.d-DMbdad7G.d.ts +90 -0
- package/dist/records/depth/index.cjs +11 -7
- package/dist/records/depth/index.d.cts +14 -12
- package/dist/records/depth/index.d.ts +14 -12
- package/dist/records/depth/index.js +11 -7
- package/dist/records/index.cjs +225 -62
- package/dist/records/index.d.cts +159 -20
- package/dist/records/index.d.ts +159 -20
- package/dist/records/index.js +225 -62
- package/dist/recordsAsk.d-C5CGSi3j.d.cts +14 -0
- package/dist/recordsAsk.d-C5CGSi3j.d.ts +14 -0
- package/dist/{requestFunnel-B9fdXMi5.d.ts → requestFunnel.d-CXUMPw1K.d.ts} +5 -5
- package/dist/{requestFunnel-BBjNNwc9.d.cts → requestFunnel.d-DWQQpjFR.d.cts} +5 -5
- package/dist/{resolve-D4Ywz5OS.d.ts → resolve.d-jI8FmBj3.d.cts} +3 -3
- package/dist/{resolve-D4Ywz5OS.d.cts → resolve.d-jI8FmBj3.d.ts} +3 -3
- package/dist/{runtimeTypes-CstDBX8w.d.cts → runtimeTypes.d-4yFNNuYR.d.ts} +20 -13
- package/dist/{runtimeTypes-N_K4BVZB.d.ts → runtimeTypes.d-D6N_fhxx.d.cts} +20 -13
- package/dist/server/events/index.cjs +7 -3
- package/dist/server/events/index.d.cts +51 -9
- package/dist/server/events/index.d.ts +51 -9
- package/dist/server/events/index.js +7 -3
- package/dist/server/index.cjs +12 -6
- package/dist/server/index.d.cts +152 -8
- package/dist/server/index.d.ts +152 -8
- package/dist/server/index.js +12 -6
- package/dist/sheetCopy.d-CAhLOxjc.d.cts +4 -0
- package/dist/sheetCopy.d-CAhLOxjc.d.ts +4 -0
- package/dist/sheetSeam.d-Cviqk89n.d.ts +45 -0
- package/dist/sheetSeam.d-DCS3LW8g.d.cts +45 -0
- package/dist/shop/index.cjs +262 -0
- package/dist/shop/index.d.cts +193 -0
- package/dist/shop/index.d.ts +193 -0
- package/dist/shop/index.js +262 -0
- package/dist/televet/booking/index.cjs +16 -12
- package/dist/televet/booking/index.d.cts +36 -22
- package/dist/televet/booking/index.d.ts +36 -22
- package/dist/televet/booking/index.js +16 -12
- package/dist/televet/call/index.d.cts +5 -5
- package/dist/televet/call/index.d.ts +5 -5
- package/dist/televet/index.cjs +7 -3
- package/dist/televet/index.d.cts +12 -12
- package/dist/televet/index.d.ts +12 -12
- package/dist/televet/index.js +7 -3
- package/dist/{televetGlobal-C5dTUACe.d.cts → televetGlobal.d-CC-DrqkQ.d.ts} +7 -2
- package/dist/{televetGlobal-CnjrfhT4.d.ts → televetGlobal.d-CKwDCbmN.d.cts} +7 -2
- package/dist/testing/index.cjs +7 -3
- package/dist/testing/index.d.cts +3 -3
- package/dist/testing/index.d.ts +3 -3
- package/dist/testing/index.js +7 -3
- package/dist/testing/rn/index.cjs +5 -1
- package/dist/testing/rn/index.d.cts +23 -22
- package/dist/testing/rn/index.d.ts +23 -22
- package/dist/testing/rn/index.js +5 -1
- package/dist/testing/web/index.cjs +5 -1
- package/dist/testing/web/index.d.cts +23 -22
- package/dist/testing/web/index.d.ts +23 -22
- package/dist/testing/web/index.js +5 -1
- package/dist/texting/index.cjs +158 -0
- package/dist/texting/index.d.cts +36 -0
- package/dist/texting/index.d.ts +36 -0
- package/dist/texting/index.js +158 -0
- package/dist/threadOptions.d-B1pTMmDF.d.cts +260 -0
- package/dist/threadOptions.d-B1pTMmDF.d.ts +260 -0
- package/dist/{timelineRows-7yjHyh8i.d.ts → timelineRows.d-BNxgzYRW.d.cts} +1 -1
- package/dist/{timelineRows-WvnL-Lds.d.cts → timelineRows.d-CU5GvvLk.d.ts} +1 -1
- package/dist/{tokens-DLj8OnLH.d.cts → tokens.d-DarDaV39.d.cts} +10 -2
- package/dist/{tokens-DLj8OnLH.d.ts → tokens.d-DarDaV39.d.ts} +10 -2
- package/dist/{typeStyle-BxVyF71R.d.ts → typeStyle.d-Bl8pzbBy.d.cts} +2 -2
- package/dist/{typeStyle-DJedEu14.d.cts → typeStyle.d-C1HBRAI3.d.ts} +2 -2
- package/dist/{uploadTransport-BM_pnEWj.d.cts → uploadTransport.d-CWL7CdWP.d.cts} +1 -1
- package/dist/{uploadTransport-C6kGP1Kd.d.ts → uploadTransport.d-EGoUl7gX.d.ts} +1 -1
- package/dist/usePresentation.d-D6qsFzBz.d.cts +9 -0
- package/dist/usePresentation.d-DuGQe_Do.d.ts +9 -0
- package/dist/useRecords.d-Cb-36SF5.d.cts +121 -0
- package/dist/useRecords.d-aQTzQZoV.d.ts +121 -0
- package/dist/{useRecordsDepth-Bp6L4M5P.d.ts → useRecordsDepth.d-DFcCfiXm.d.ts} +8 -20
- package/dist/{useRecordsDepth-DPdAK_81.d.cts → useRecordsDepth.d-sAq2Qkhr.d.cts} +8 -20
- package/dist/{useVetVisit-DmWa7lt1.d.ts → useVetVisit.d-BtdwhmgD.d.cts} +15 -4
- package/dist/{useVetVisit-PtBjNwZr.d.cts → useVetVisit.d-DoYQimyt.d.ts} +15 -4
- package/dist/video/index.cjs +6 -2
- package/dist/video/index.d.cts +7 -7
- package/dist/video/index.d.ts +7 -7
- package/dist/video/index.js +6 -2
- package/dist/{view-C6go2uUt.d.ts → view.d-C-SNpDJX.d.ts} +10 -122
- package/dist/{view-CiF_HVFQ.d.cts → view.d-Dps5C8-s.d.cts} +10 -122
- package/dist/web/consent/index.cjs +5 -1
- package/dist/web/consent/index.d.cts +10 -10
- package/dist/web/consent/index.d.ts +10 -10
- package/dist/web/consent/index.js +5 -1
- package/dist/web/health-plan/index.cjs +414 -0
- package/dist/web/health-plan/index.d.cts +335 -0
- package/dist/web/health-plan/index.d.ts +335 -0
- package/dist/web/health-plan/index.js +414 -0
- package/dist/web/index.cjs +150 -82
- package/dist/web/index.d.cts +152 -38
- package/dist/web/index.d.ts +152 -38
- package/dist/web/index.js +150 -82
- package/dist/web/notifications/index.cjs +16 -3
- package/dist/web/notifications/index.d.cts +39 -209
- package/dist/web/notifications/index.d.ts +39 -209
- package/dist/web/notifications/index.js +16 -3
- package/dist/web/records/depth/index.cjs +11 -7
- package/dist/web/records/depth/index.d.cts +14 -12
- package/dist/web/records/depth/index.d.ts +14 -12
- package/dist/web/records/depth/index.js +11 -7
- package/dist/web/records/index.cjs +95 -68
- package/dist/web/records/index.d.cts +66 -21
- package/dist/web/records/index.d.ts +66 -21
- package/dist/web/records/index.js +95 -68
- package/dist/web/records/upload/index.d.cts +2 -2
- package/dist/web/records/upload/index.d.ts +2 -2
- package/dist/web/records-sheet/index.cjs +278 -0
- package/dist/web/records-sheet/index.d.cts +102 -0
- package/dist/web/records-sheet/index.d.ts +102 -0
- package/dist/web/records-sheet/index.js +278 -0
- package/dist/web/shop/index.cjs +301 -0
- package/dist/web/shop/index.d.cts +42 -0
- package/dist/web/shop/index.d.ts +42 -0
- package/dist/web/shop/index.js +301 -0
- package/dist/web/televet/booking/index.cjs +16 -12
- package/dist/web/televet/booking/index.d.cts +37 -23
- package/dist/web/televet/booking/index.d.ts +37 -23
- package/dist/web/televet/booking/index.js +16 -12
- package/dist/web/televet/call/index.d.cts +4 -4
- package/dist/web/televet/call/index.d.ts +4 -4
- package/dist/web/televet/index.cjs +7 -3
- package/dist/web/televet/index.d.cts +12 -12
- package/dist/web/televet/index.d.ts +12 -12
- package/dist/web/televet/index.js +7 -3
- package/dist/web/texting/index.cjs +157 -0
- package/dist/web/texting/index.d.cts +36 -0
- package/dist/web/texting/index.d.ts +36 -0
- package/dist/web/texting/index.js +157 -0
- package/health-plan/package.json +8 -0
- package/package.json +106 -4
- package/shop/package.json +8 -0
- package/texting/package.json +8 -0
- package/web/health-plan/native-blocked.cjs +12 -0
- package/web/health-plan/package.json +8 -0
- package/web/records-sheet/native-blocked.cjs +12 -0
- package/web/records-sheet/package.json +8 -0
- package/web/shop/native-blocked.cjs +12 -0
- package/web/shop/package.json +8 -0
- package/web/texting/native-blocked.cjs +12 -0
- package/web/texting/package.json +8 -0
- /package/dist/{CameraPort-Cv31Pz7g.d.cts → CameraPort.d-Cv31Pz7g.d.cts} +0 -0
- /package/dist/{CameraPort-Cv31Pz7g.d.ts → CameraPort.d-Cv31Pz7g.d.ts} +0 -0
- /package/dist/{TelemetryPort-BDNr00hu.d.cts → TelemetryPort.d-BDNr00hu.d.cts} +0 -0
- /package/dist/{TelemetryPort-BDNr00hu.d.ts → TelemetryPort.d-BDNr00hu.d.ts} +0 -0
- /package/dist/{cacheEpoch-DknKn3S0.d.cts → cacheEpoch.d-DknKn3S0.d.cts} +0 -0
- /package/dist/{cacheEpoch-DknKn3S0.d.ts → cacheEpoch.d-DknKn3S0.d.ts} +0 -0
- /package/dist/{callCopy-Bw6oZT54.d.cts → callCopy.d-Bw6oZT54.d.cts} +0 -0
- /package/dist/{callCopy-Bw6oZT54.d.ts → callCopy.d-Bw6oZT54.d.ts} +0 -0
- /package/dist/{ids-B2GAAifq.d.cts → ids.d-B2GAAifq.d.cts} +0 -0
- /package/dist/{ids-B2GAAifq.d.ts → ids.d-B2GAAifq.d.ts} +0 -0
- /package/dist/{optionalModule-DbJmsq5f.d.cts → optionalModule.d-DbJmsq5f.d.cts} +0 -0
- /package/dist/{optionalModule-DbJmsq5f.d.ts → optionalModule.d-DbJmsq5f.d.ts} +0 -0
- /package/dist/{profile-CSs1wlXT.d.cts → profile.d-CSs1wlXT.d.cts} +0 -0
- /package/dist/{profile-CSs1wlXT.d.ts → profile.d-CSs1wlXT.d.ts} +0 -0
- /package/dist/{projection-CeIUsbSk.d.cts → projection.d-CeIUsbSk.d.cts} +0 -0
- /package/dist/{projection-CeIUsbSk.d.ts → projection.d-CeIUsbSk.d.ts} +0 -0
- /package/dist/{species-BXAIMh7I.d.cts → species.d-BXAIMh7I.d.cts} +0 -0
- /package/dist/{species-BXAIMh7I.d.ts → species.d-BXAIMh7I.d.ts} +0 -0
- /package/dist/{visitIntent-D7_yVp1I.d.cts → visitIntent.d-D7_yVp1I.d.cts} +0 -0
- /package/dist/{visitIntent-D7_yVp1I.d.ts → visitIntent.d-D7_yVp1I.d.ts} +0 -0
package/dist/server/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { E as EverfurResult } from '../EverfurResult-
|
|
2
|
-
import { j as FetchLike } from '../config-
|
|
3
|
-
import { a as PartnerServerClient } from '../pets-
|
|
4
|
-
export { b as PartnerPet, P as PartnerPetProfile, c as PartnerPetTarget, d as PartnerPetWithProfile, e as deletePartnerPet, g as getPartnerPet, u as updatePartnerPet, f as upsertPartnerPet } from '../pets-
|
|
5
|
-
export { b as PetActivityLevel, c as PetAllergy, d as PetAllergySeverity, e as PetBirthDatePrecision, f as PetCondition, a as PetHealthProfile, P as PetHealthProfileInput, g as PetIndoorOutdoor, h as PetMedication, i as PetSex } from '../profile-CSs1wlXT.js';
|
|
6
|
-
export { C as CanonicalPetSpecies, c as canonicalPetSpecies } from '../species-BXAIMh7I.js';
|
|
7
|
-
import '../EverfurError-
|
|
1
|
+
import { E as EverfurResult } from '../EverfurResult.d-D_-254ZY.js';
|
|
2
|
+
import { j as FetchLike } from '../config.d-Dy6igYlH.js';
|
|
3
|
+
import { a as PartnerServerClient } from '../pets.d-C_53_fzo.js';
|
|
4
|
+
export { b as PartnerPet, P as PartnerPetProfile, c as PartnerPetTarget, d as PartnerPetWithProfile, e as deletePartnerPet, g as getPartnerPet, u as updatePartnerPet, f as upsertPartnerPet } from '../pets.d-C_53_fzo.js';
|
|
5
|
+
export { b as PetActivityLevel, c as PetAllergy, d as PetAllergySeverity, e as PetBirthDatePrecision, f as PetCondition, a as PetHealthProfile, P as PetHealthProfileInput, g as PetIndoorOutdoor, h as PetMedication, i as PetSex } from '../profile.d-CSs1wlXT.js';
|
|
6
|
+
export { C as CanonicalPetSpecies, c as canonicalPetSpecies } from '../species.d-BXAIMh7I.js';
|
|
7
|
+
import '../EverfurError.d-8NHtlgzA.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Validate a partner user_ref at the SDK boundary (server re-validates). SPEC-21 section 1.1.
|
|
@@ -95,6 +95,150 @@ interface PartnerMemberNotificationProfile {
|
|
|
95
95
|
*/
|
|
96
96
|
declare function setPartnerMemberNotificationProfile(client: PartnerServerClient, input: SetPartnerMemberNotificationProfileInput): Promise<EverfurResult<PartnerMemberNotificationProfile>>;
|
|
97
97
|
|
|
98
|
+
interface SendMemberTextInput {
|
|
99
|
+
/** Your stable member id (the session mint's user_ref rule). */
|
|
100
|
+
readonly userRef: string;
|
|
101
|
+
/** An approved template on your texting profile. */
|
|
102
|
+
readonly templateKey: string;
|
|
103
|
+
/** Values for the template's `{placeholders}`, exactly the template's own. Strings only, one line each. */
|
|
104
|
+
readonly vars?: Readonly<Record<string, string>>;
|
|
105
|
+
/** Required. Your key for this text (1 to 120 of `A-Z a-z 0-9 . _ : -`). A retry with the same key never texts twice. */
|
|
106
|
+
readonly idempotencyKey: string;
|
|
107
|
+
}
|
|
108
|
+
/** What Everfur accepted. Delivery is asynchronous; this is the acceptance, not the handset's receipt. */
|
|
109
|
+
interface MemberTextReceipt {
|
|
110
|
+
/** Everfur's id for the text, or null when the answer carried none. */
|
|
111
|
+
readonly textId: string | null;
|
|
112
|
+
/** The text's state as Everfur reported it (`queued`, `sending`, `sent`, `withheld`, `failed`), or null. */
|
|
113
|
+
readonly status: string | null;
|
|
114
|
+
/** True when `idempotencyKey` matched an earlier text and this is that text; null when the answer did not say. */
|
|
115
|
+
readonly duplicate: boolean | null;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Text a member one of your approved templates. Settles an `EverfurResult`; throws `EverfurConfigError` only for a
|
|
119
|
+
* request that can never be accepted (a malformed or missing secret key or `idempotencyKey`, `userRef`, template key
|
|
120
|
+
* or vars).
|
|
121
|
+
*/
|
|
122
|
+
declare function sendMemberText(client: PartnerServerClient, input: SendMemberTextInput): Promise<EverfurResult<MemberTextReceipt>>;
|
|
123
|
+
|
|
124
|
+
/** The species a product can be for. */
|
|
125
|
+
type PartnerCatalogSpecies = 'dog' | 'cat';
|
|
126
|
+
/** Why a product suits a pet: a fact the pet can have, and your words shown when it does. */
|
|
127
|
+
interface PartnerCatalogReasonTag {
|
|
128
|
+
/** `species:dog|cat`, `life_stage:young|adult|senior`, `size:small|medium|large` or `breed:<slug>`. */
|
|
129
|
+
readonly tag: string;
|
|
130
|
+
/** Your words, shown as the reason (1 to 120 characters). */
|
|
131
|
+
readonly text: string;
|
|
132
|
+
}
|
|
133
|
+
/** Units a day for a pet up to `maxWeightKg`. */
|
|
134
|
+
interface PartnerCatalogDoseBand {
|
|
135
|
+
/** Above 0, at most 200. Null or absent means no upper bound, and only the last band may leave it out. */
|
|
136
|
+
readonly maxWeightKg?: number | null;
|
|
137
|
+
/** Above 0, at most 50. */
|
|
138
|
+
readonly unitsPerDay: number;
|
|
139
|
+
}
|
|
140
|
+
/** A product's Health Plan subscription terms. A product without them is not subscribable. */
|
|
141
|
+
interface PartnerCatalogSubscription {
|
|
142
|
+
/** Whole units in one box, 1 to 10,000. */
|
|
143
|
+
readonly unitsPerBox: number;
|
|
144
|
+
/** What a unit is called (`chew`, `soft chew`), 1 to 30 letters, spaces or hyphens, starting with a letter. */
|
|
145
|
+
readonly unitLabel: string;
|
|
146
|
+
/** 1 to 10 bands, sorted by `maxWeightKg`, ascending and distinct. */
|
|
147
|
+
readonly doseBands: readonly PartnerCatalogDoseBand[];
|
|
148
|
+
/** Whole percent off the first box, 0 to 90. Default 0. */
|
|
149
|
+
readonly firstBoxDiscountPercent?: number;
|
|
150
|
+
/** Whole percent off a one-time box (no renewal), 0 to 90. Default 0. */
|
|
151
|
+
readonly oneBoxDiscountPercent?: number;
|
|
152
|
+
}
|
|
153
|
+
/** One review you quote for a product, shown as you wrote it. */
|
|
154
|
+
interface PartnerCatalogReview {
|
|
155
|
+
/** Whole stars, 1 to 5. */
|
|
156
|
+
readonly stars: number;
|
|
157
|
+
/** 1 to 300 characters. */
|
|
158
|
+
readonly text: string;
|
|
159
|
+
/** Who wrote it, 1 to 80 characters. */
|
|
160
|
+
readonly by: string;
|
|
161
|
+
}
|
|
162
|
+
/** One product as you sell it. */
|
|
163
|
+
interface PartnerCatalogProduct {
|
|
164
|
+
/** Your own id for the product; unique within your catalog (1 to 120 characters). */
|
|
165
|
+
readonly partnerSku: string;
|
|
166
|
+
/** 1 to 200 characters. */
|
|
167
|
+
readonly title: string;
|
|
168
|
+
/** Up to 600 characters. */
|
|
169
|
+
readonly description?: string | null;
|
|
170
|
+
/** The product form as you name it (for example `chew`, `tablet`), up to 60 characters. */
|
|
171
|
+
readonly form?: string | null;
|
|
172
|
+
/** The species it is for. Empty means any. */
|
|
173
|
+
readonly species?: readonly PartnerCatalogSpecies[];
|
|
174
|
+
/** The price in `currency`, or null when you do not publish one. 0 to 1,000,000. */
|
|
175
|
+
readonly price?: number | null;
|
|
176
|
+
/** ISO 4217 (`USD`). Everfur reads a product without one as USD. */
|
|
177
|
+
readonly currency?: string | null;
|
|
178
|
+
/** Your product page. https only. */
|
|
179
|
+
readonly url?: string | null;
|
|
180
|
+
/** The product picture. https only. */
|
|
181
|
+
readonly imageUrl?: string | null;
|
|
182
|
+
/** Up to 60 characters. */
|
|
183
|
+
readonly category?: string | null;
|
|
184
|
+
/** Up to 20 reasons the plan can show for this product. */
|
|
185
|
+
readonly reasonTags?: readonly PartnerCatalogReasonTag[];
|
|
186
|
+
/** Mark a demo product: the plan labels it as a sample (when your tenant's sample label is on). */
|
|
187
|
+
readonly sample?: boolean;
|
|
188
|
+
/** Subscription terms; needs a `price` above 0. Absent (or null) means the product is not subscribable. */
|
|
189
|
+
readonly subscription?: PartnerCatalogSubscription | null;
|
|
190
|
+
/** The star rating, 0 to 5 (Everfur keeps one decimal). */
|
|
191
|
+
readonly rating?: number | null;
|
|
192
|
+
/** How many reviews the rating rests on, a whole number from 0 to 100,000,000. */
|
|
193
|
+
readonly reviewCount?: number | null;
|
|
194
|
+
/** Up to 5 reviews. */
|
|
195
|
+
readonly reviews?: readonly PartnerCatalogReview[];
|
|
196
|
+
/** Up to 12 ingredients, each 1 to 60 characters (trimmed). */
|
|
197
|
+
readonly ingredients?: readonly string[];
|
|
198
|
+
}
|
|
199
|
+
interface ReplaceCatalogInput {
|
|
200
|
+
readonly products: readonly PartnerCatalogProduct[];
|
|
201
|
+
/**
|
|
202
|
+
* An EMPTY `products` really means "withdraw every product". Without it Everfur refuses an empty list while you
|
|
203
|
+
* still have an active product that is not a sample (409, `reasonCode` `catalog_empty_refused`), so a feed that
|
|
204
|
+
* failed to read never wipes the catalog. Sent only when true.
|
|
205
|
+
*/
|
|
206
|
+
readonly confirmEmpty?: boolean;
|
|
207
|
+
/**
|
|
208
|
+
* Leaving out most of a large catalog is meant. Without it Everfur refuses a list that would deactivate at least 20
|
|
209
|
+
* active real products and more than half of them (409, `reasonCode` `catalog_shrink_refused`). Sent only when true.
|
|
210
|
+
*/
|
|
211
|
+
readonly confirmShrink?: boolean;
|
|
212
|
+
}
|
|
213
|
+
interface MergeCatalogInput {
|
|
214
|
+
/** Products to add or change. An existing SKU is changed field by field (the header says how). */
|
|
215
|
+
readonly products?: readonly PartnerCatalogProduct[];
|
|
216
|
+
/** SKUs to deactivate (never delete). A SKU that is not active is a no-op; none may also be in `products`. */
|
|
217
|
+
readonly remove?: readonly string[];
|
|
218
|
+
}
|
|
219
|
+
/** What the replace changed, as Everfur counted it. A value the answer did not carry is null. */
|
|
220
|
+
interface CatalogReplaceResult {
|
|
221
|
+
/** Products written (new or updated) by this replace. */
|
|
222
|
+
readonly active: number | null;
|
|
223
|
+
/** Products this replace deactivated because the list left them out. */
|
|
224
|
+
readonly deactivated: number | null;
|
|
225
|
+
/** Everfur's id for this sync run, for a support conversation. */
|
|
226
|
+
readonly syncRunId: string | null;
|
|
227
|
+
/** The SKUs this call deactivated, as Everfur stored them; null when the answer did not list them. */
|
|
228
|
+
readonly deactivatedSkus: readonly string[] | null;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Replace your whole product catalog. Settles an `EverfurResult`; throws `EverfurConfigError` only for a request that
|
|
232
|
+
* can never be accepted (a malformed key, a duplicate SKU, a product without a title, a field over its limit).
|
|
233
|
+
*/
|
|
234
|
+
declare function replaceCatalog(client: PartnerServerClient, input: ReplaceCatalogInput): Promise<EverfurResult<CatalogReplaceResult>>;
|
|
235
|
+
/**
|
|
236
|
+
* Add, change or withdraw some products without resending the catalog (`mode: "merge"`). Every product you do not
|
|
237
|
+
* name is left as it is. Settles an `EverfurResult`; throws `EverfurConfigError` only for a request that can never be
|
|
238
|
+
* accepted (nothing to do, a SKU both listed and removed, a field over its limit).
|
|
239
|
+
*/
|
|
240
|
+
declare function mergeCatalog(client: PartnerServerClient, input: MergeCatalogInput): Promise<EverfurResult<CatalogReplaceResult>>;
|
|
241
|
+
|
|
98
242
|
interface MintSessionParams {
|
|
99
243
|
/** env-derived base URL (resolveApiBaseUrl output), no trailing slash. */
|
|
100
244
|
readonly apiBaseUrl: string;
|
|
@@ -125,4 +269,4 @@ interface SessionMint {
|
|
|
125
269
|
*/
|
|
126
270
|
declare function mintPartnerSession(params: MintSessionParams): Promise<EverfurResult<SessionMint>>;
|
|
127
271
|
|
|
128
|
-
export { type MintSessionParams, type PartnerMemberEmailConsent, type PartnerMemberEmailConsentRecord, type PartnerMemberNotificationProfile, type PartnerMemberSessionsRevocation, PartnerServerClient, type RevokePartnerMemberSessionsInput, type SessionMint, type SetPartnerMemberNotificationProfileInput, assertValidUserRef, mintPartnerSession, revokePartnerMemberSessions, setPartnerMemberNotificationProfile };
|
|
272
|
+
export { type CatalogReplaceResult, type MemberTextReceipt, type MergeCatalogInput, type MintSessionParams, type PartnerCatalogDoseBand, type PartnerCatalogProduct, type PartnerCatalogReasonTag, type PartnerCatalogReview, type PartnerCatalogSpecies, type PartnerCatalogSubscription, type PartnerMemberEmailConsent, type PartnerMemberEmailConsentRecord, type PartnerMemberNotificationProfile, type PartnerMemberSessionsRevocation, PartnerServerClient, type ReplaceCatalogInput, type RevokePartnerMemberSessionsInput, type SendMemberTextInput, type SessionMint, type SetPartnerMemberNotificationProfileInput, assertValidUserRef, mergeCatalog, mintPartnerSession, replaceCatalog, revokePartnerMemberSessions, sendMemberText, setPartnerMemberNotificationProfile };
|
package/dist/server/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
function ok(value,warning){/* @__PURE__ */
|
|
2
2
|
return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
|
|
3
|
-
return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var SDK_VERSION="0.
|
|
3
|
+
return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var SDK_VERSION="0.13.0",SDK_PLATFORM="react-native",DEFAULT_CONTRACT_VERSION="2026-09-19",ENV_API_BASE_URL="EVERFUR_API_BASE_URL";function configFailure(reason,message){/* @__PURE__ */
|
|
4
4
|
return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:reason,message:message})})}function tryResolveApiBaseUrl(apiBaseUrl){let explicit=apiBaseUrl?.trim(),candidate=explicit&&explicit.length>0?explicit:readEnv(ENV_API_BASE_URL);return candidate?normalizeBaseUrl(candidate):configFailure("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${ENV_API_BASE_URL}. The SDK never ships a hardcoded host.`)}function resolveApiBaseUrl(apiBaseUrl){let outcome=tryResolveApiBaseUrl(apiBaseUrl);if(!outcome.ok)throw new EverfurConfigError("invalid-argument",outcome.failure.message);return outcome.value}function buildBaseHeaders(cfg){return{"X-Everfur-SDK-Version":cfg.sdkVersion,"X-Everfur-SDK-Platform":cfg.platform,"X-Everfur-Contract":cfg.contractVersion}}var ABSOLUTE_URL=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function hostOf(authority){return authority.slice(authority.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function isPrintableHost(host){return host.length===0||host.includes("@")?false:host.startsWith("[")&&host.endsWith("]")?true:!host.includes(":")}function canEchoOrigin(rawTrimmed,host){let schemeEnd=rawTrimmed.indexOf("://");return schemeEnd<0||rawTrimmed.slice(schemeEnd+3).includes("@")?false:isPrintableHost(host)}function safeOrigin(scheme,host){return`${scheme}://${host}`}function normalizeBaseUrl(raw){let trimmed=raw.trim(),match=ABSOLUTE_URL.exec(trimmed);if(match===null||match[2]===void 0||match[2].length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let scheme=(match[1]??"").toLowerCase(),host=hostOf(match[2]);if(host.length===0)return configFailure("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let shown=canEchoOrigin(trimmed,host)?`: ${safeOrigin(scheme,host)}`:"";if(scheme!=="https"){if(!(scheme==="http"&&isLoopbackHost(host)))return scheme==="http"?configFailure("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${shown}`):configFailure("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${shown}`)}let value=trimmed.endsWith("/")?trimmed.slice(0,-1):trimmed;/* @__PURE__ */
|
|
5
|
-
return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host=hostname.toLowerCase();return host==="localhost"||host==="127.0.0.1"||host==="[::1]"||host==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
|
|
5
|
+
return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){let host=hostname.toLowerCase();return host==="localhost"||host==="127.0.0.1"||host==="[::1]"||host==="::1"}function readEnv(name){let value=globalThis.process?.env?.[name];return typeof value=="string"&&value.trim().length>0?value.trim():void 0}var DAILY_QUOTA_WIRE_CODE="DAILY_QUOTA_EXCEEDED",THROTTLES=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function foldDailyQuotaWireCode(code,body){if(!THROTTLES.has(code.toUpperCase().replace(/[^A-Z0-9]/g,"")))return code;let b=body,limit=b?.daily_limit??b?.error?.daily_limit;return typeof limit=="number"&&Number.isFinite(limit)?DAILY_QUOTA_WIRE_CODE:code}var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
|
|
6
6
|
/* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
7
7
|
/* @__PURE__ */Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
8
8
|
/* @__PURE__ */Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
@@ -25,6 +25,8 @@ return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){le
|
|
|
25
25
|
/* @__PURE__ */Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
26
26
|
/* @__PURE__ */Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),
|
|
27
27
|
/* @__PURE__ */Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
28
|
+
/* @__PURE__ */Object.freeze({wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
29
|
+
/* @__PURE__ */Object.freeze({wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
28
30
|
/* @__PURE__ */Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
29
31
|
/* @__PURE__ */Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
30
32
|
/* @__PURE__ */Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
@@ -49,6 +51,7 @@ return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){le
|
|
|
49
51
|
/* @__PURE__ */Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
50
52
|
/* @__PURE__ */Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
51
53
|
/* @__PURE__ */Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
54
|
+
/* @__PURE__ */Object.freeze({wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
52
55
|
/* @__PURE__ */Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),
|
|
53
56
|
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),
|
|
54
57
|
/* @__PURE__ */Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),
|
|
@@ -85,13 +88,16 @@ return Object.freeze({ok:true,value:value})}function isLoopbackHost(hostname){le
|
|
|
85
88
|
/* @__PURE__ */Object.freeze({wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
86
89
|
/* @__PURE__ */Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),
|
|
87
90
|
/* @__PURE__ */Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),
|
|
91
|
+
/* @__PURE__ */Object.freeze({wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
88
92
|
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),
|
|
89
93
|
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
90
94
|
/* @__PURE__ */Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),
|
|
91
95
|
/* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
92
96
|
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
93
97
|
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
94
|
-
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"unknown"}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.";function displayFor(code,wireCode){return(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:displayFor(code,opts?.wireCode)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}var REQUEST_ID_HEADER="x-request-id";function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?code:null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var SECRET_KEY_PREFIXES=["sk_partner_","rk_partner_"];function assertServerSecretKey(value,action){if(typeof value!="string"||value.length===0)throw new EverfurConfigError("invalid-argument","partnerSecretKey is required");if(value.startsWith("pk_"))throw new EverfurConfigError("invalid-argument",`partnerSecretKey is a publishable key (pk_...): ${action} needs your secret key, server side only`);if(!SECRET_KEY_PREFIXES.some(prefix=>value.startsWith(prefix)))throw new EverfurConfigError("invalid-argument","partnerSecretKey must be an sk_partner_ secret key or an rk_partner_ restricted key")}var USER_REF_MAX=128;function assertValidUserRef(raw){let length=typeof raw=="string"?[...raw].length:0;if(typeof raw!="string"||length<1||length>USER_REF_MAX)throw new EverfurConfigError("invalid-argument",`user_ref must be 1..${USER_REF_MAX} characters`);if(raw.trim().length===0)throw new EverfurConfigError("invalid-argument","user_ref must not be blank: the server strips surrounding whitespace before validating, so a whitespace-only value arrives empty and is rejected as required.");if(raw!==raw.trim())throw new EverfurConfigError("invalid-argument","user_ref must not have leading or trailing whitespace: the server strips it, so padded and unpadded forms of the same id resolve to ONE user. Pass the exact id you want to key on.");if(raw.includes("@"))throw new EverfurConfigError("invalid-argument","user_ref must not contain '@'");if(!isPrintable(raw))throw new EverfurConfigError("invalid-argument","user_ref must be printable (no control characters)");return raw}function isPrintable(value){return!NON_PRINTABLE.test(value)}var NON_PRINTABLE=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}]|(?!\u0020)[\p{Zs}]/u,USER_REF_INVALID="user_ref_invalid";function foldUserRefInvalid(error){let raw=error.raw,body=typeof raw=="object"&&raw!==null?raw:null,wire=(body!==null&&typeof body.error=="object"&&body.error!==null?body.error.code:void 0)??body?.code;return wire!==USER_REF_INVALID&&error.reasonCode!==USER_REF_INVALID?error:makeEverfurError("validationFailed",{retryable:false,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{},...typeof wire=="string"?{wireCode:wire}:{},reasonCode:USER_REF_INVALID,...error.wireMessage!==void 0?{wireMessage:error.wireMessage}:{},...raw!==void 0?{raw:raw}:{}})}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str(o.ref),name:name,dose:str(o.dose),frequency:str(o.frequency),startDate:str(o.start_date),endDate:str(o.end_date),notes:str(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
|
|
95
|
-
return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(version)&&version>=0?version:0,sex:pick(SEXES,o.sex),spayedNeutered:bool(o.spayed_neutered),birthDate:str(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str(o.food_brand),foodType:str(o.food_type),microchipId:str(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str(row.ref),conditionName:conditionName,diagnosedDate:str(row.diagnosed_date),notes:str(row.notes)})})})}var PET_REF_MAX=128,REQUEST_TIMEOUT_MS=3e4;async function upsertPartnerPet(client,target,profile){return petWrite(client,"PUT",target,profileBody(profile,false))}async function updatePartnerPet(client,target,changes){return petWrite(client,"PATCH",target,profileBody(changes,true))}async function getPartnerPet(client,target){let res=await send(client,"GET",target,void 0);if(!("status"in res))return res;let json=await readJsonSafe(res),requestId=requestIdOf(res);if(!res.ok)return err(errorFromResponse(res.status,withRetryAfter(res,json),requestId));let pet=parsePet(json);return pet?ok(/* @__PURE__ */Object.freeze({...pet,...petHealthFromWire(json)})):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}async function deletePartnerPet(client,target){let res=await send(client,"DELETE",target,void 0);return"status"in res?res.ok?ok(void 0):err(errorFromResponse(res.status,withRetryAfter(res,await readJsonSafe(res)),requestIdOf(res))):res}async function petWrite(client,method,target,body){let res=await send(client,method,target,body);if(!("status"in res))return res;let json=await readJsonSafe(res),requestId=requestIdOf(res);if(!res.ok)return err(errorFromResponse(res.status,withRetryAfter(res,json),requestId));let pet=parsePet(json);return pet?ok(pet):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}async function send(client,method,target,body){assertServerSecretKey(client.partnerSecretKey,"writing pets");let path=memberPetPath(target),fetchImpl=client.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(client.apiBaseUrl)}${path}`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:client.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","x-everfur-partner-secret-key":client.partnerSecretKey};body!==void 0&&(headers["content-type"]="application/json");let controller=new AbortController,timer=setTimeout(()=>controller.abort(),REQUEST_TIMEOUT_MS);try{return await fetchImpl(url,{method:method,headers:headers,...body!==void 0?{body:body}:{},signal:controller.signal})}catch(cause){return err(networkError(cause))}finally{clearTimeout(timer)}}function memberPetPath(target){if(typeof target!="object"||target===null)throw new EverfurConfigError("invalid-argument","target is required");let userRef=assertValidUserRef(target.userRef);assertPathSegment("userRef",userRef);let petRef=target.petRef,length=typeof petRef=="string"?[...petRef].length:0;if(typeof petRef!="string"||length<1||length>PET_REF_MAX)throw new EverfurConfigError("invalid-argument",`petRef must be 1..${PET_REF_MAX} characters`);return assertPathSegment("petRef",petRef),`/partners/members/${encodeURIComponent(userRef)}/pets/${encodeURIComponent(petRef)}`}function assertPathSegment(name,value){if(value.includes("/")||value==="."||value==="..")throw new EverfurConfigError("invalid-argument",`${name} cannot contain '/' or be '.' or '..': it is sent as a URL path segment`)}var PROFILE_FIELDS=[["name","name"],["species","species"],["breed","breed"],["ageYears","age_years"],["weightKg","weight_kg"],["partnerLabelInstructions","partner_label_instructions"]];function profileBody(profile,requireOne){let body=partnerPetProfileBody(profile);if(requireOne&&Object.keys(body).length===0)throw new EverfurConfigError("invalid-argument","updatePartnerPet needs at least one field to change");return JSON.stringify(body)}function partnerPetProfileBody(profile){if(typeof profile!="object"||profile===null||Array.isArray(profile))throw new EverfurConfigError("invalid-argument","the pet profile must be an object");let body={};for(let[key,wire]of PROFILE_FIELDS)profile[key]!==void 0&&(body[wire]=profile[key]);let health=petHealthToWire(profile,profile.species);if("error"in health)throw new EverfurConfigError("invalid-argument",health.error);return Object.assign(body,health.body)}function nullableString(value){return value==null?null:typeof value=="string"?value:void 0}function nullableNumber(value){return value==null?null:typeof value=="number"?value:void 0}function parsePet(json){if(typeof json!="object"||json===null)return null;let obj=json;if(typeof obj.pet_id!="string"||typeof obj.pet_ref!="string"||typeof obj.updated_at!="string")return null;let name=nullableString(obj.name),species=nullableString(obj.species),breed=nullableString(obj.breed),ageYears=nullableNumber(obj.age_years),weightKg=nullableNumber(obj.weight_kg);return name===void 0||species===void 0||breed===void 0||ageYears===void 0||weightKg===void 0?null:/* @__PURE__ */Object.freeze({petId:obj.pet_id,petRef:obj.pet_ref,name:name,species:species,breed:breed,ageYears:ageYears,weightKg:weightKg,updatedAt:obj.updated_at})}async function readJsonSafe(res){try{return await res.json()}catch{return null}}var REQUEST_TIMEOUT_MS2=3e4;async function revokePartnerMemberSessions(client,input){if(assertServerSecretKey(client.partnerSecretKey,"revoking member sessions"),client.partnerSecretKey.startsWith("rk_partner_"))throw new EverfurConfigError("invalid-argument","revoking member sessions needs your unrestricted sk_partner_ secret key; an rk_partner_ restricted key is refused (unrestrictedKeyRequired)");if(typeof input!="object"||input===null)throw new EverfurConfigError("invalid-argument","input is required");let userRef=assertValidUserRef(input.userRef),fetchImpl=client.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(client.apiBaseUrl)}/widget/v1/sessions/revoke`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:client.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","content-type":"application/json","x-everfur-partner-secret-key":client.partnerSecretKey},controller=new AbortController,timer=setTimeout(()=>controller.abort(),REQUEST_TIMEOUT_MS2),res;try{res=await fetchImpl(url,{method:"POST",headers:headers,body:JSON.stringify({user_ref:userRef}),signal:controller.signal})}catch(cause){return err(networkError(cause))}finally{clearTimeout(timer)}let json=await readJsonSafe2(res),requestId=requestIdOf(res);if(!res.ok)return err(foldUserRefInvalid(errorFromResponse(res.status,withRetryAfter(res,json),requestId)));let revocation=parseRevocation(json);return revocation?ok(revocation):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}function parseRevocation(json){if(typeof json!="object"||json===null)return null;let o=json;return o.revoked!==true||typeof o.sessions_valid_after!="number"||!Number.isFinite(o.sessions_valid_after)?null:/* @__PURE__ */Object.freeze({revoked:true,sessionsValidAfter:o.sessions_valid_after})}async function readJsonSafe2(res){try{return await res.json()}catch{return null}}function wireCodeOf(error){let raw=error.raw;if(typeof raw!="object"||raw===null)return null;let code=raw.code;return typeof code=="string"&&code.length>0?code:null}function foldWireReason(error,table){let wire=wireCodeOf(error);if(wire===null)return error;let fold=table[wire];return fold===void 0?error:makeEverfurError(fold.code,{retryable:fold.retryable,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{},wireCode:wire,reasonCode:wire,...error.wireMessage!==void 0?{wireMessage:error.wireMessage}:{},raw:error.raw})}var EMAIL_MAX=254,CONSENT_VERSION_MAX=64,EMAIL_SHAPE=/^[^@\s]+@[^@\s]+\.[^@\s]+$/,REQUEST_TIMEOUT_MS3=3e4,PROFILE_REASONS=/* @__PURE__ */Object.freeze({consent_required:{code:"validationFailed",retryable:false},email_invalid:{code:"validationFailed",retryable:false},consent_invalid:{code:"validationFailed",retryable:false}});async function setPartnerMemberNotificationProfile(client,input){assertServerSecretKey(client.partnerSecretKey,"writing a member notification profile");let path=memberProfilePath(input),body=JSON.stringify({email:input.email,consent:consentBody(input.consent)}),fetchImpl=client.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(client.apiBaseUrl)}${path}`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:client.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","content-type":"application/json","x-everfur-partner-secret-key":client.partnerSecretKey},controller=new AbortController,timer=setTimeout(()=>controller.abort(),REQUEST_TIMEOUT_MS3),res;try{res=await fetchImpl(url,{method:"PUT",headers:headers,body:body,signal:controller.signal})}catch(cause){return err(networkError(cause))}finally{clearTimeout(timer)}let json=await readJsonSafe3(res),requestId=requestIdOf(res);if(!res.ok)return err(foldWireReason(errorFromResponse(res.status,withRetryAfter(res,json),requestId),PROFILE_REASONS));let profile=parseProfile(json);return profile?ok(profile):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}function memberProfilePath(input){if(typeof input!="object"||input===null)throw new EverfurConfigError("invalid-argument","input is required");let userRef=assertValidUserRef(input.userRef);if(userRef.includes("/")||userRef==="."||userRef==="..")throw new EverfurConfigError("invalid-argument","userRef cannot contain '/' or be '.' or '..': it is sent as a URL path segment");let email=input.email;if(typeof email!="string"||email.trim().length<3||email.trim().length>EMAIL_MAX||!EMAIL_SHAPE.test(email.trim()))throw new EverfurConfigError("invalid-argument",`email must be an address of at most ${EMAIL_MAX} characters`);return`/partners/members/${encodeURIComponent(userRef)}/notification-profile`}function consentBody(consent){if(typeof consent!="object"||consent===null)throw new EverfurConfigError("invalid-argument","consent is required: an address is stored only with the stamp of the consent you collected");if(consent.method!=="partner_attested")throw new EverfurConfigError("invalid-argument","consent.method must be 'partner_attested' in this version");let version=consent.version;if(typeof version!="string"||version.length===0||version.length>CONSENT_VERSION_MAX)throw new EverfurConfigError("invalid-argument",`consent.version must be 1..${CONSENT_VERSION_MAX} characters`);let givenAt=consent.givenAt instanceof Date?consent.givenAt.toISOString():consent.givenAt;if(typeof givenAt!="string"||!Number.isFinite(Date.parse(givenAt)))throw new EverfurConfigError("invalid-argument","consent.givenAt must be an ISO 8601 instant or a Date");return{given_at:givenAt,method:"partner_attested",version:version}}function nullableString2(value){return value==null?null:typeof value=="string"?value:void 0}function parseConsent(value){if(value==null)return null;if(typeof value!="object")return;let o=value;if(!(typeof o.given_at!="string"||typeof o.method!="string"||typeof o.version!="string"))/* @__PURE__ */
|
|
96
|
-
return Object.freeze({givenAt:o.given_at,method:o.method,version:o.version})}function parseProfile(json){if(typeof json!="object"||json===null)return null;let o=json;if(typeof o.user_ref!="string"||typeof o.updated_at!="string"||typeof o.push_enabled!="boolean"||typeof o.email_enabled!="boolean"||typeof o.active_devices!="number"||!Number.isFinite(o.active_devices))return null;let emailMasked=nullableString2(o.email),emailVerifiedAt=nullableString2(o.email_verified_at),unsubscribedAt=nullableString2(o.unsubscribed_at),consent=parseConsent(o.consent);return emailMasked===void 0||emailVerifiedAt===void 0||unsubscribedAt===void 0||consent===void 0?null:/* @__PURE__ */Object.freeze({userRef:o.user_ref,emailMasked:emailMasked,consent:consent,emailVerifiedAt:emailVerifiedAt,pushEnabled:o.push_enabled,emailEnabled:o.email_enabled,unsubscribedAt:unsubscribedAt,activeDevices:o.active_devices,updatedAt:o.updated_at})}async function readJsonSafe3(res){try{return await res.json()}catch{return null}}var
|
|
97
|
-
return Object.freeze({sessionToken:obj.session_token,expiresAt:obj.expires_at,capabilities:/* @__PURE__ */Object.freeze(capabilities)})}async function readJsonSafe4(res){try{return await res.json()}catch{return null}}function mintTimeoutSignal(ms){let ctrl=new AbortController,handle=setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>clearTimeout(handle)}}function mergeMintSignals(deadline,caller){if(!caller)return deadline;let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),ctrl.signal}export{assertValidUserRef,canonicalPetSpecies,deletePartnerPet,getPartnerPet,mintPartnerSession,revokePartnerMemberSessions,setPartnerMemberNotificationProfile,updatePartnerPet,upsertPartnerPet};
|
|
98
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",session_revoked:"authExpired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}function fromHttpStatus(status){return status===401?"authExpired":status===403?"accessDenied":status===404?"conversationNotFound":status===409?"idempotencyConflict":status===421?"unknown":status===429?"rateLimited":status===400||status===422?"unknown":status>=500?"internalError":"unknown"}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."}),SESSION_REVOKED_COPY="This session has ended. Please sign in again.",LINKED_ACCOUNT_READ_ONLY="linked_account_read_only";function displayFor(code,wireCode,reasonCode){return code==="conflict"&&reasonCode===LINKED_ACCOUNT_READ_ONLY?ACCESS_DENIED_COPY:(code==="authRejected"||code==="authExpired")&&typeof wireCode=="string"&&wireCode.trim().toLowerCase()==="session_revoked"?SESSION_REVOKED_COPY:userFacingError(code)}function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),linkedReadOnly=code==="conflict"&&opts?.reasonCode===LINKED_ACCOUNT_READ_ONLY,error={code:code,category:categoryFor(code),retryable:opts?.retryable??(linkedReadOnly?false:isRetryableCode(code)),displayMessage:displayFor(code,opts?.wireCode,linkedReadOnly?LINKED_ACCOUNT_READ_ONLY:null)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function withRetryAfter(res,body){if(res.status!==429&&res.status!==503)return body;let seconds=retryAfterSeconds(res.headers.get(RETRY_AFTER_HEADER),Date.now());if(seconds===null)return body;let record=body!==null&&typeof body=="object"&&!Array.isArray(body)?body:null;return record!==null&&namesAWait(record)?body:{...record??{},retry_after_seconds:seconds}}var RETRY_AFTER_HEADER="retry-after";function retryAfterSeconds(value,nowMs){if(value===null)return null;let trimmed=value.trim();if(/^\d+$/.test(trimmed))return Number(trimmed);let at=Date.parse(trimmed);return Number.isFinite(at)?Math.max(0,Math.ceil((at-nowMs)/1e3)):null}function namesAWait(body){return[body,body.error,body.detail].some(scope=>scope!==null&&typeof scope=="object"&&("retry_after_seconds"in scope||"resets_at"in scope))}var REQUEST_ID_HEADER="x-request-id";function errorFromResponse(status,body,requestId){let wireCode=extractWireCode(body),code=wireCode?fromWire(wireCode):fromHttpStatus(status),wireMessage=extractWireMessage(body);return makeEverfurError(code,{httpStatus:status,...extractRetryable(body)?{retryable:true}:{},...requestId?{requestId:requestId}:{},...wireCode?{wireCode:wireCode}:{},...extractReasonCode(body)?{reasonCode:extractReasonCode(body)}:{},...extractRetryAfterSeconds(body)!==null?{retryAfterSeconds:extractRetryAfterSeconds(body)}:{},...wireMessage?{wireMessage:wireMessage}:{},...body!=null?{raw:body}:{}})}function extractRetryAfterSeconds(body){let b=body,value=b?.retry_after_seconds??b?.error?.retry_after_seconds;return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function requestIdOf(res){let value=res.headers.get(REQUEST_ID_HEADER);return typeof value=="string"&&value.length>0?value:null}function getGlobalFetch(){let candidate=globalThis.fetch;if(typeof candidate!="function")throw new EverfurConfigError("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return candidate}function extractReasonCode(body){let b=body,reason=b?.error?.reason_code??b?.reason_code;return typeof reason=="string"&&reason.length>0?reason:null}function extractWireCode(body){let b=body,code=b?.error?.code??b?.code;return typeof code=="string"&&code.length>0?foldDailyQuotaWireCode(code,body):null}function extractWireMessage(body){let b=body,message=b?.error?.message??b?.message;return typeof message=="string"&&message.length>0?message:null}function extractRetryable(body){let b=body;return b?.error?.retryable===true||b?.retryable===true}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var SECRET_KEY_PREFIXES=["sk_partner_","rk_partner_"];function assertServerSecretKey(value,action){if(typeof value!="string"||value.length===0)throw new EverfurConfigError("invalid-argument","partnerSecretKey is required");if(value.startsWith("pk_"))throw new EverfurConfigError("invalid-argument",`partnerSecretKey is a publishable key (pk_...): ${action} needs your secret key, server side only`);if(!SECRET_KEY_PREFIXES.some(prefix=>value.startsWith(prefix)))throw new EverfurConfigError("invalid-argument","partnerSecretKey must be an sk_partner_ secret key or an rk_partner_ restricted key")}var USER_REF_MAX=128;function assertValidUserRef(raw){let length=typeof raw=="string"?[...raw].length:0;if(typeof raw!="string"||length<1||length>USER_REF_MAX)throw new EverfurConfigError("invalid-argument",`user_ref must be 1..${USER_REF_MAX} characters`);if(raw.trim().length===0)throw new EverfurConfigError("invalid-argument","user_ref must not be blank: the server strips surrounding whitespace before validating, so a whitespace-only value arrives empty and is rejected as required.");if(raw!==raw.trim())throw new EverfurConfigError("invalid-argument","user_ref must not have leading or trailing whitespace: the server strips it, so padded and unpadded forms of the same id resolve to ONE user. Pass the exact id you want to key on.");if(raw.includes("@"))throw new EverfurConfigError("invalid-argument","user_ref must not contain '@'");if(!isPrintable(raw))throw new EverfurConfigError("invalid-argument","user_ref must be printable (no control characters)");return raw}function isPrintable(value){return!NON_PRINTABLE.test(value)}var NON_PRINTABLE=/[\p{Cc}\p{Cf}\p{Cs}\p{Co}\p{Cn}\p{Zl}\p{Zp}]|(?!\u0020)[\p{Zs}]/u,USER_REF_INVALID="user_ref_invalid";function foldUserRefInvalid(error){let raw=error.raw,body=typeof raw=="object"&&raw!==null?raw:null,wire=(body!==null&&typeof body.error=="object"&&body.error!==null?body.error.code:void 0)??body?.code;return wire!==USER_REF_INVALID&&error.reasonCode!==USER_REF_INVALID?error:makeEverfurError("validationFailed",{retryable:false,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{},...typeof wire=="string"?{wireCode:wire}:{},reasonCode:USER_REF_INVALID,...error.wireMessage!==void 0?{wireMessage:error.wireMessage}:{},...raw!==void 0?{raw:raw}:{}})}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text(FOOD_MAX),foodType:text(FOOD_MAX),microchipId:text(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text(REF_MAX,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str(o.ref),name:name,dose:str(o.dose),frequency:str(o.frequency),startDate:str(o.start_date),endDate:str(o.end_date),notes:str(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
|
|
99
|
+
return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(version)&&version>=0?version:0,sex:pick(SEXES,o.sex),spayedNeutered:bool(o.spayed_neutered),birthDate:str(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str(o.food_brand),foodType:str(o.food_type),microchipId:str(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str(row.ref),conditionName:conditionName,diagnosedDate:str(row.diagnosed_date),notes:str(row.notes)})})})}var PET_REF_MAX=128,REQUEST_TIMEOUT_MS=3e4;async function upsertPartnerPet(client,target,profile){return petWrite(client,"PUT",target,profileBody(profile,false))}async function updatePartnerPet(client,target,changes){return petWrite(client,"PATCH",target,profileBody(changes,true))}async function getPartnerPet(client,target){let res=await send(client,"GET",target,void 0);if(!("status"in res))return res;let json=await readJsonSafe(res),requestId=requestIdOf(res);if(!res.ok)return err(errorFromResponse(res.status,withRetryAfter(res,json),requestId));let pet=parsePet(json);return pet?ok(/* @__PURE__ */Object.freeze({...pet,...petHealthFromWire(json)})):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}async function deletePartnerPet(client,target){let res=await send(client,"DELETE",target,void 0);return"status"in res?res.ok?ok(void 0):err(errorFromResponse(res.status,withRetryAfter(res,await readJsonSafe(res)),requestIdOf(res))):res}async function petWrite(client,method,target,body){let res=await send(client,method,target,body);if(!("status"in res))return res;let json=await readJsonSafe(res),requestId=requestIdOf(res);if(!res.ok)return err(errorFromResponse(res.status,withRetryAfter(res,json),requestId));let pet=parsePet(json);return pet?ok(pet):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}async function send(client,method,target,body){assertServerSecretKey(client.partnerSecretKey,"writing pets");let path=memberPetPath(target),fetchImpl=client.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(client.apiBaseUrl)}${path}`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:client.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","x-everfur-partner-secret-key":client.partnerSecretKey};body!==void 0&&(headers["content-type"]="application/json");let controller=new AbortController,timer=setTimeout(()=>controller.abort(),REQUEST_TIMEOUT_MS);try{return await fetchImpl(url,{method:method,headers:headers,...body!==void 0?{body:body}:{},signal:controller.signal})}catch(cause){return err(networkError(cause))}finally{clearTimeout(timer)}}function memberPetPath(target){if(typeof target!="object"||target===null)throw new EverfurConfigError("invalid-argument","target is required");let userRef=assertValidUserRef(target.userRef);assertPathSegment("userRef",userRef);let petRef=target.petRef,length=typeof petRef=="string"?[...petRef].length:0;if(typeof petRef!="string"||length<1||length>PET_REF_MAX)throw new EverfurConfigError("invalid-argument",`petRef must be 1..${PET_REF_MAX} characters`);return assertPathSegment("petRef",petRef),`/partners/members/${encodeURIComponent(userRef)}/pets/${encodeURIComponent(petRef)}`}function assertPathSegment(name,value){if(value.includes("/")||value==="."||value==="..")throw new EverfurConfigError("invalid-argument",`${name} cannot contain '/' or be '.' or '..': it is sent as a URL path segment`)}var PROFILE_FIELDS=[["name","name"],["species","species"],["breed","breed"],["ageYears","age_years"],["weightKg","weight_kg"],["partnerLabelInstructions","partner_label_instructions"]];function profileBody(profile,requireOne){let body=partnerPetProfileBody(profile);if(requireOne&&Object.keys(body).length===0)throw new EverfurConfigError("invalid-argument","updatePartnerPet needs at least one field to change");return JSON.stringify(body)}function partnerPetProfileBody(profile){if(typeof profile!="object"||profile===null||Array.isArray(profile))throw new EverfurConfigError("invalid-argument","the pet profile must be an object");let body={};for(let[key,wire]of PROFILE_FIELDS)profile[key]!==void 0&&(body[wire]=profile[key]);let health=petHealthToWire(profile,profile.species);if("error"in health)throw new EverfurConfigError("invalid-argument",health.error);return Object.assign(body,health.body)}function nullableString(value){return value==null?null:typeof value=="string"?value:void 0}function nullableNumber(value){return value==null?null:typeof value=="number"?value:void 0}function parsePet(json){if(typeof json!="object"||json===null)return null;let obj=json;if(typeof obj.pet_id!="string"||typeof obj.pet_ref!="string"||typeof obj.updated_at!="string")return null;let name=nullableString(obj.name),species=nullableString(obj.species),breed=nullableString(obj.breed),ageYears=nullableNumber(obj.age_years),weightKg=nullableNumber(obj.weight_kg);return name===void 0||species===void 0||breed===void 0||ageYears===void 0||weightKg===void 0?null:/* @__PURE__ */Object.freeze({petId:obj.pet_id,petRef:obj.pet_ref,name:name,species:species,breed:breed,ageYears:ageYears,weightKg:weightKg,updatedAt:obj.updated_at})}async function readJsonSafe(res){try{return await res.json()}catch{return null}}var REQUEST_TIMEOUT_MS2=3e4;async function revokePartnerMemberSessions(client,input){if(assertServerSecretKey(client.partnerSecretKey,"revoking member sessions"),client.partnerSecretKey.startsWith("rk_partner_"))throw new EverfurConfigError("invalid-argument","revoking member sessions needs your unrestricted sk_partner_ secret key; an rk_partner_ restricted key is refused (unrestrictedKeyRequired)");if(typeof input!="object"||input===null)throw new EverfurConfigError("invalid-argument","input is required");let userRef=assertValidUserRef(input.userRef),fetchImpl=client.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(client.apiBaseUrl)}/widget/v1/sessions/revoke`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:client.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","content-type":"application/json","x-everfur-partner-secret-key":client.partnerSecretKey},controller=new AbortController,timer=setTimeout(()=>controller.abort(),REQUEST_TIMEOUT_MS2),res;try{res=await fetchImpl(url,{method:"POST",headers:headers,body:JSON.stringify({user_ref:userRef}),signal:controller.signal})}catch(cause){return err(networkError(cause))}finally{clearTimeout(timer)}let json=await readJsonSafe2(res),requestId=requestIdOf(res);if(!res.ok)return err(foldUserRefInvalid(errorFromResponse(res.status,withRetryAfter(res,json),requestId)));let revocation=parseRevocation(json);return revocation?ok(revocation):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}function parseRevocation(json){if(typeof json!="object"||json===null)return null;let o=json;return o.revoked!==true||typeof o.sessions_valid_after!="number"||!Number.isFinite(o.sessions_valid_after)?null:/* @__PURE__ */Object.freeze({revoked:true,sessionsValidAfter:o.sessions_valid_after})}async function readJsonSafe2(res){try{return await res.json()}catch{return null}}function wireCodeOf(error){let raw=error.raw;if(typeof raw!="object"||raw===null)return null;let code=raw.code;return typeof code=="string"&&code.length>0?code:null}function foldWireReason(error,table){let wire=wireCodeOf(error);if(wire===null)return error;let fold=table[wire];return fold===void 0?error:makeEverfurError(fold.code,{retryable:fold.retryable,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{},wireCode:wire,reasonCode:wire,...error.wireMessage!==void 0?{wireMessage:error.wireMessage}:{},raw:error.raw})}function foldWireOrReason(error,table){let folded=foldWireReason(error,table);if(folded!==error||wireCodeOf(error)!==null)return folded;let reason=error.reasonCode;if(typeof reason!="string")return error;let fold=table[reason];return fold===void 0?error:makeEverfurError(fold.code,{retryable:fold.retryable,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{},wireCode:reason,reasonCode:reason,...error.wireMessage!==void 0?{wireMessage:error.wireMessage}:{},raw:error.raw})}var EMAIL_MAX=254,CONSENT_VERSION_MAX=64,EMAIL_SHAPE=/^[^@\s]+@[^@\s]+\.[^@\s]+$/,REQUEST_TIMEOUT_MS3=3e4,PROFILE_REASONS=/* @__PURE__ */Object.freeze({consent_required:{code:"validationFailed",retryable:false},email_invalid:{code:"validationFailed",retryable:false},consent_invalid:{code:"validationFailed",retryable:false}});async function setPartnerMemberNotificationProfile(client,input){assertServerSecretKey(client.partnerSecretKey,"writing a member notification profile");let path=memberProfilePath(input),body=JSON.stringify({email:input.email,consent:consentBody(input.consent)}),fetchImpl=client.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(client.apiBaseUrl)}${path}`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:client.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","content-type":"application/json","x-everfur-partner-secret-key":client.partnerSecretKey},controller=new AbortController,timer=setTimeout(()=>controller.abort(),REQUEST_TIMEOUT_MS3),res;try{res=await fetchImpl(url,{method:"PUT",headers:headers,body:body,signal:controller.signal})}catch(cause){return err(networkError(cause))}finally{clearTimeout(timer)}let json=await readJsonSafe3(res),requestId=requestIdOf(res);if(!res.ok)return err(foldWireReason(errorFromResponse(res.status,withRetryAfter(res,json),requestId),PROFILE_REASONS));let profile=parseProfile(json);return profile?ok(profile):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}function memberProfilePath(input){if(typeof input!="object"||input===null)throw new EverfurConfigError("invalid-argument","input is required");let userRef=assertValidUserRef(input.userRef);if(userRef.includes("/")||userRef==="."||userRef==="..")throw new EverfurConfigError("invalid-argument","userRef cannot contain '/' or be '.' or '..': it is sent as a URL path segment");let email=input.email;if(typeof email!="string"||email.trim().length<3||email.trim().length>EMAIL_MAX||!EMAIL_SHAPE.test(email.trim()))throw new EverfurConfigError("invalid-argument",`email must be an address of at most ${EMAIL_MAX} characters`);return`/partners/members/${encodeURIComponent(userRef)}/notification-profile`}function consentBody(consent){if(typeof consent!="object"||consent===null)throw new EverfurConfigError("invalid-argument","consent is required: an address is stored only with the stamp of the consent you collected");if(consent.method!=="partner_attested")throw new EverfurConfigError("invalid-argument","consent.method must be 'partner_attested' in this version");let version=consent.version;if(typeof version!="string"||version.length===0||version.length>CONSENT_VERSION_MAX)throw new EverfurConfigError("invalid-argument",`consent.version must be 1..${CONSENT_VERSION_MAX} characters`);let givenAt=consent.givenAt instanceof Date?consent.givenAt.toISOString():consent.givenAt;if(typeof givenAt!="string"||!Number.isFinite(Date.parse(givenAt)))throw new EverfurConfigError("invalid-argument","consent.givenAt must be an ISO 8601 instant or a Date");return{given_at:givenAt,method:"partner_attested",version:version}}function nullableString2(value){return value==null?null:typeof value=="string"?value:void 0}function parseConsent(value){if(value==null)return null;if(typeof value!="object")return;let o=value;if(!(typeof o.given_at!="string"||typeof o.method!="string"||typeof o.version!="string"))/* @__PURE__ */
|
|
100
|
+
return Object.freeze({givenAt:o.given_at,method:o.method,version:o.version})}function parseProfile(json){if(typeof json!="object"||json===null)return null;let o=json;if(typeof o.user_ref!="string"||typeof o.updated_at!="string"||typeof o.push_enabled!="boolean"||typeof o.email_enabled!="boolean"||typeof o.active_devices!="number"||!Number.isFinite(o.active_devices))return null;let emailMasked=nullableString2(o.email),emailVerifiedAt=nullableString2(o.email_verified_at),unsubscribedAt=nullableString2(o.unsubscribed_at),consent=parseConsent(o.consent);return emailMasked===void 0||emailVerifiedAt===void 0||unsubscribedAt===void 0||consent===void 0?null:/* @__PURE__ */Object.freeze({userRef:o.user_ref,emailMasked:emailMasked,consent:consent,emailVerifiedAt:emailVerifiedAt,pushEnabled:o.push_enabled,emailEnabled:o.email_enabled,unsubscribedAt:unsubscribedAt,activeDevices:o.active_devices,updatedAt:o.updated_at})}async function readJsonSafe3(res){try{return await res.json()}catch{return null}}var REQUEST_TIMEOUT_MS4=3e4;async function sendServerJson(client,method,path,body,reasons,parse){let fetchImpl=client.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(client.apiBaseUrl)}${path}`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:client.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","content-type":"application/json","x-everfur-partner-secret-key":client.partnerSecretKey},controller=new AbortController,timer=setTimeout(()=>controller.abort(),REQUEST_TIMEOUT_MS4),res;try{res=await fetchImpl(url,{method:method,headers:headers,body:JSON.stringify(body),signal:controller.signal})}catch(cause){return err(networkError(cause))}finally{clearTimeout(timer)}let json=null;try{json=await res.json()}catch{json=null}let requestId=requestIdOf(res);if(!res.ok)return err(foldWireOrReason(errorFromResponse(res.status,withRetryAfter(res,json),requestId),reasons));let value=parse(json);return value===null?err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId)):ok(value)}var TEMPLATE_KEY=/^[a-z][a-z0-9_.]{0,63}$/,VAR_NAME=/^[a-z_]{1,32}$/,VAR_VALUE_MAX=500,VARS_MAX=20,IDEMPOTENCY_KEY=/^[A-Za-z0-9._:-]{1,120}$/,RESERVED_VARS=/* @__PURE__ */new Set(["brand_name","app_link"]),TEXT_REASONS=/* @__PURE__ */Object.freeze({sms_not_live:{code:"accessDenied",retryable:false},not_live:{code:"accessDenied",retryable:false},profile_missing:{code:"accessDenied",retryable:false},profile_suspended:{code:"accessDenied",retryable:false},identity_missing:{code:"accessDenied",retryable:false},identity_ambiguous:{code:"accessDenied",retryable:false},consent_not_partner:{code:"accessDenied",retryable:false},consent_version_mismatch:{code:"accessDenied",retryable:false},channel_opted_out:{code:"accessDenied",retryable:false},destination_not_allowed:{code:"accessDenied",retryable:false},template_not_found:{code:"validationFailed",retryable:false},template_not_approved:{code:"validationFailed",retryable:false},daily_cap:{code:"rateLimited",retryable:false},template_vars_missing:{code:"validationFailed",retryable:false},template_var_unexpected:{code:"validationFailed",retryable:false},template_var_invalid:{code:"validationFailed",retryable:false},template_var_reserved:{code:"validationFailed",retryable:false},member_not_found:{code:"resourceNotFound",retryable:false},idempotency_key_required:{code:"validationFailed",retryable:false},idempotency_key_reused:{code:"conflict",retryable:false}});function sendMemberText(client,input){if(assertServerSecretKey(client.partnerSecretKey,"sending a member text"),typeof input!="object"||input===null)throw new EverfurConfigError("invalid-argument","input is required");let userRef=assertValidUserRef(input.userRef);if(userRef.includes("/")||userRef==="."||userRef==="..")throw new EverfurConfigError("invalid-argument","userRef cannot contain '/' or be '.' or '..': it is sent as a URL path segment");if(typeof input.templateKey!="string"||!TEMPLATE_KEY.test(input.templateKey))throw new EverfurConfigError("invalid-argument","templateKey must start with a letter and be 1 to 64 of a-z, 0-9, _ and .");let vars=checkVars(input.vars??{}),key=input.idempotencyKey;if(typeof key!="string"||!IDEMPOTENCY_KEY.test(key))throw new EverfurConfigError("invalid-argument","idempotencyKey is required: 1 to 120 of A-Z, a-z, 0-9, ., _, : and -");return sendServerJson(client,"POST",`/partners/members/${encodeURIComponent(userRef)}/texts`,{template_key:input.templateKey,vars:vars,idempotency_key:key},TEXT_REASONS,parseReceipt)}function checkVars(vars){if(typeof vars!="object"||vars===null||Array.isArray(vars))throw new EverfurConfigError("invalid-argument","vars must be an object of strings");let entries=Object.entries(vars);if(entries.length>VARS_MAX)throw new EverfurConfigError("invalid-argument",`vars carries at most ${VARS_MAX} values`);let out={};for(let[name,value]of entries){if(!VAR_NAME.test(name))throw new EverfurConfigError("invalid-argument",`vars.${name}: a name is 1 to 32 of a-z and _`);if(RESERVED_VARS.has(name))throw new EverfurConfigError("invalid-argument",`vars.${name} is filled by Everfur from your texting profile`);if(typeof value!="string"||value.length>VAR_VALUE_MAX||value.includes(`\n`))throw new EverfurConfigError("invalid-argument",`vars.${name} must be one line of at most ${VAR_VALUE_MAX} characters`);out[name]=value}return out}function parseReceipt(json){if(json==null)/* @__PURE__ */return Object.freeze({textId:null,status:null,duplicate:null});if(typeof json!="object"||Array.isArray(json))return null;let o=json,id=o.text_id??o.message_id??o.id;/* @__PURE__ */
|
|
101
|
+
return Object.freeze({textId:typeof id=="string"&&id.length>0?id:null,status:typeof o.status=="string"?o.status:null,duplicate:typeof o.duplicate=="boolean"?o.duplicate:null})}var PRODUCTS_MAX=2e3,SKU_MAX=120,TITLE_MAX=200,DESCRIPTION_MAX=600,SHORT_MAX2=60,URL_MAX=1e3,PRICE_MAX=1e6,REASON_TAGS_MAX=20,REASON_TEXT_MAX=120,UNITS_PER_BOX_MAX=1e4,UNIT_LABEL_MAX=30,UNIT_LABEL=/^[A-Za-z][A-Za-z -]*$/,DOSE_BANDS_MAX=10,DOSE_WEIGHT_MAX_KG=200,UNITS_PER_DAY_MAX=50,DISCOUNT_PERCENT_MAX=90,RATING_MAX=5,REVIEW_COUNT_MAX=1e8,REVIEWS_MAX=5,REVIEW_TEXT_MAX=300,REVIEW_BY_MAX=80,INGREDIENTS_MAX=12,INGREDIENT_MAX=60,PARTNER_SKU=/^[A-Za-z0-9._-]+$/,CURRENCY=/^[A-Z]{3}$/,HTTPS=/^https:\/\/\S+$/,REASON_TAG=/^(species|life_stage|size|breed):[a-z0-9_-]{1,40}$/,CLOSED_TAG_VALUES=/* @__PURE__ */Object.freeze({species:["dog","cat"],life_stage:["young","adult","senior"],size:["small","medium","large"]}),CATALOG_REASONS=/* @__PURE__ */Object.freeze({catalog_empty_refused:{code:"conflict",retryable:false},catalog_shrink_refused:{code:"conflict",retryable:false}});function foldCatalogReason(error){let reason=error.reasonCode,fold=typeof reason=="string"?CATALOG_REASONS[reason]:void 0;if(fold===void 0||error.code===fold.code&&error.retryable===fold.retryable)return error;let wire=wireCodeOf(error);return makeEverfurError(fold.code,{retryable:fold.retryable,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{},...wire!==null?{wireCode:wire}:{},reasonCode:reason??null,...error.wireMessage!==void 0?{wireMessage:error.wireMessage}:{},raw:error.raw})}function putCatalog(client,body){return sendServerJson(client,"PUT","/partners/catalog/products",body,CATALOG_REASONS,parseResult).then(result=>result.ok?result:err(foldCatalogReason(result.error)))}function replaceCatalog(client,input){if(assertServerSecretKey(client.partnerSecretKey,"replacing the product catalog"),typeof input!="object"||input===null||!Array.isArray(input.products))throw new EverfurConfigError("invalid-argument","input.products must be an array");if(input.products.length>PRODUCTS_MAX)throw new EverfurConfigError("invalid-argument",`a catalog carries at most ${PRODUCTS_MAX} products`);let confirmEmpty=optionalFlag(input.confirmEmpty,"confirmEmpty"),confirmShrink=optionalFlag(input.confirmShrink,"confirmShrink"),seen=/* @__PURE__ */new Set,products=input.products.map((product,index)=>productBody(product,index,seen,"replace"));return putCatalog(client,{products:products,...confirmEmpty?{confirm_empty:true}:{},...confirmShrink?{confirm_shrink:true}:{}})}function mergeCatalog(client,input){if(assertServerSecretKey(client.partnerSecretKey,"merging into the product catalog"),typeof input!="object"||input===null)throw new EverfurConfigError("invalid-argument","input must be an object");let listed=input.products??[],removing=input.remove??[];if(!Array.isArray(listed))throw new EverfurConfigError("invalid-argument","input.products must be an array");if(!Array.isArray(removing))throw new EverfurConfigError("invalid-argument","input.remove must be an array");if(listed.length===0&&removing.length===0)throw new EverfurConfigError("invalid-argument","a merge needs at least one product or one remove entry");if(listed.length+removing.length>PRODUCTS_MAX)throw new EverfurConfigError("invalid-argument",`a merge names at most ${PRODUCTS_MAX} SKUs in products and remove together`);let seen=/* @__PURE__ */new Set,products=listed.map((product,index)=>productBody(product,index,seen,"merge")),removed=/* @__PURE__ */new Set,remove=removing.map((sku,index)=>{let at=`remove[${index}]`;if(typeof sku!="string"||sku.length===0||sku.length>SKU_MAX||!PARTNER_SKU.test(sku))throw new EverfurConfigError("invalid-argument",`${at} must be a partnerSku of 1 to ${SKU_MAX} of A-Z a-z 0-9 . _ -`);let key=sku.toLowerCase();if(removed.has(key))throw new EverfurConfigError("invalid-argument",`${at} '${sku}' appears twice`);if(seen.has(key))throw new EverfurConfigError("invalid-argument",`${at} '${sku}' is also in products`);return removed.add(key),sku});return putCatalog(client,{mode:"merge",products:products,...remove.length===0?{}:{remove:remove}})}function optionalFlag(value,field){if(value===void 0)return false;if(typeof value!="boolean")throw new EverfurConfigError("invalid-argument",`${field} must be a boolean`);return value}function optionalText(value,field,max){if(value==null)return null;if(typeof value!="string"||value.length===0||value.length>max)throw new EverfurConfigError("invalid-argument",`${field} must be a string of 1 to ${max} characters`);return value}function speciesList(value,field){if(value===void 0)return[];if(!Array.isArray(value)||value.length>2||value.some(entry=>entry!=="dog"&&entry!=="cat"))throw new EverfurConfigError("invalid-argument",`${field} must list at most 'dog' and 'cat'`);return[...value]}function reasonTags(value,field){if(value===void 0)return[];if(!Array.isArray(value)||value.length>REASON_TAGS_MAX)throw new EverfurConfigError("invalid-argument",`${field} must be a list of at most ${REASON_TAGS_MAX} reasons`);return value.map((entry,index)=>{let at=`${field}[${index}]`,o=typeof entry=="object"&&entry!==null?entry:{},tag=o.tag,text2=o.text;if(typeof tag!="string"||!REASON_TAG.test(tag))throw new EverfurConfigError("invalid-argument",`${at}.tag must be species:, life_stage:, size: or breed: and a value`);let[kind="",tagValue=""]=tag.split(":",2),closed=CLOSED_TAG_VALUES[kind];if(closed!==void 0&&!closed.includes(tagValue))throw new EverfurConfigError("invalid-argument",`${at}.tag: ${kind} must be one of ${closed.join(", ")}`);if(typeof text2!="string"||text2.length===0||text2.length>REASON_TEXT_MAX)throw new EverfurConfigError("invalid-argument",`${at}.text must be 1 to ${REASON_TEXT_MAX} characters`);return{tag:tag,text:text2}})}function httpsOrNull(value,field){let text2=optionalText(value,field,URL_MAX+8);if(text2!==null&&(!HTTPS.test(text2)||text2.length-8>URL_MAX))throw new EverfurConfigError("invalid-argument",`${field} must be an https URL`);return text2}function wholeIn(value,field,min,max){if(typeof value!="number"||!Number.isInteger(value)||value<min||value>max)throw new EverfurConfigError("invalid-argument",`${field} must be a whole number from ${min} to ${max}`);return value}function positiveUpTo(value,field,max){if(typeof value!="number"||!Number.isFinite(value)||value<=0||value>max)throw new EverfurConfigError("invalid-argument",`${field} must be a number above 0 and at most ${max}`);return value}function subscriptionBody(value,field){if(typeof value!="object"||value===null)throw new EverfurConfigError("invalid-argument",`${field} must be an object`);let unitsPerBox=wholeIn(value.unitsPerBox,`${field}.unitsPerBox`,1,UNITS_PER_BOX_MAX),unitLabel=value.unitLabel;if(typeof unitLabel!="string"||unitLabel.length>UNIT_LABEL_MAX||!UNIT_LABEL.test(unitLabel))throw new EverfurConfigError("invalid-argument",`${field}.unitLabel must be 1 to ${UNIT_LABEL_MAX} letters, spaces or hyphens, starting with a letter`);let bands=value.doseBands;if(!Array.isArray(bands)||bands.length===0||bands.length>DOSE_BANDS_MAX)throw new EverfurConfigError("invalid-argument",`${field}.doseBands must list 1 to ${DOSE_BANDS_MAX} bands`);let last=0,doseBands=bands.map((band,index)=>{let at=`${field}.doseBands[${index}]`,o=typeof band=="object"&&band!==null?band:{},bound=o.maxWeightKg??null,unitsPerDay=positiveUpTo(o.unitsPerDay,`${at}.unitsPerDay`,UNITS_PER_DAY_MAX);if(bound===null){if(index!==bands.length-1)throw new EverfurConfigError("invalid-argument",`${at}: only the last dose band may leave out maxWeightKg`);return{max_weight_kg:null,units_per_day:unitsPerDay}}let maxWeightKg=positiveUpTo(bound,`${at}.maxWeightKg`,DOSE_WEIGHT_MAX_KG);if(maxWeightKg<=last)throw new EverfurConfigError("invalid-argument",`${at}.maxWeightKg must be above the band before it`);return last=maxWeightKg,{max_weight_kg:maxWeightKg,units_per_day:unitsPerDay}});return{units_per_box:unitsPerBox,unit_label:unitLabel,dose_bands:doseBands,...value.firstBoxDiscountPercent===void 0?{}:{first_box_discount_percent:wholeIn(value.firstBoxDiscountPercent,`${field}.firstBoxDiscountPercent`,0,DISCOUNT_PERCENT_MAX)},...value.oneBoxDiscountPercent===void 0?{}:{one_box_discount_percent:wholeIn(value.oneBoxDiscountPercent,`${field}.oneBoxDiscountPercent`,0,DISCOUNT_PERCENT_MAX)}}}function reviewsList(value,field){if(!Array.isArray(value)||value.length>REVIEWS_MAX)throw new EverfurConfigError("invalid-argument",`${field} must be a list of at most ${REVIEWS_MAX} reviews`);return value.map((entry,index)=>{let at=`${field}[${index}]`,o=typeof entry=="object"&&entry!==null?entry:{},text2=o.text,by=o.by,stars=wholeIn(o.stars,`${at}.stars`,1,5);if(typeof text2!="string"||text2.length===0||text2.length>REVIEW_TEXT_MAX)throw new EverfurConfigError("invalid-argument",`${at}.text must be 1 to ${REVIEW_TEXT_MAX} characters`);if(typeof by!="string"||by.length===0||by.length>REVIEW_BY_MAX)throw new EverfurConfigError("invalid-argument",`${at}.by must be 1 to ${REVIEW_BY_MAX} characters`);return{stars:stars,text:text2,by:by}})}function ingredientsList(value,field){if(!Array.isArray(value)||value.length>INGREDIENTS_MAX)throw new EverfurConfigError("invalid-argument",`${field} must be a list of at most ${INGREDIENTS_MAX} ingredients`);return value.map((entry,index)=>{let text2=typeof entry=="string"?entry.trim():"";if(text2.length===0||text2.length>INGREDIENT_MAX)throw new EverfurConfigError("invalid-argument",`${field}[${index}] must be 1 to ${INGREDIENT_MAX} characters`);return text2})}function productBody(product,index,seen,mode){let at=`products[${index}]`;if(typeof product!="object"||product===null)throw new EverfurConfigError("invalid-argument",`${at} must be an object`);let sku=product.partnerSku;if(typeof sku!="string"||sku.trim().length===0||sku.length>SKU_MAX)throw new EverfurConfigError("invalid-argument",`${at}.partnerSku must be 1 to ${SKU_MAX} characters`);let skuKey=sku.trim().toLowerCase();if(seen.has(skuKey))throw new EverfurConfigError("invalid-argument",`${at}.partnerSku '${sku}' appears twice`);if(seen.add(skuKey),typeof product.title!="string"||product.title.trim().length===0||product.title.length>TITLE_MAX)throw new EverfurConfigError("invalid-argument",`${at}.title must be 1 to ${TITLE_MAX} characters`);let price=product.price??null;if(price!==null&&(typeof price!="number"||!Number.isFinite(price)||price<0||price>PRICE_MAX))throw new EverfurConfigError("invalid-argument",`${at}.price must be a number from 0 to ${PRICE_MAX}`);let currency=product.currency??null;if(currency!==null&&(typeof currency!="string"||!CURRENCY.test(currency)))throw new EverfurConfigError("invalid-argument",`${at}.currency must be an ISO 4217 code such as USD`);let subscription=product.subscription??null;if(subscription!==null&&(price===null||price<=0))throw new EverfurConfigError("invalid-argument",`${at}.subscription needs a price above 0 on the same product`);if(mode==="merge"&&product.price!==void 0&&(price===null||price<=0)&&product.subscription===void 0)throw new EverfurConfigError("invalid-argument",`${at}: a merge that clears a price or sets it to 0 must also send subscription (null to end it)`);let rating=product.rating??null;if(rating!==null&&(typeof rating!="number"||!Number.isFinite(rating)||rating<0||rating>RATING_MAX))throw new EverfurConfigError("invalid-argument",`${at}.rating must be a number from 0 to ${RATING_MAX}`);let reviewCount=product.reviewCount??null;reviewCount!==null&&wholeIn(reviewCount,`${at}.reviewCount`,0,REVIEW_COUNT_MAX);let sent=key=>mode==="replace"||product[key]!==void 0,newer=key=>mode==="replace"?product[key]!==void 0&&product[key]!==null:product[key]!==void 0;return{partner_sku:sku,title:product.title,...sent("description")?{description:optionalText(product.description,`${at}.description`,DESCRIPTION_MAX)}:{},...sent("form")?{form:optionalText(product.form,`${at}.form`,SHORT_MAX2)}:{},...sent("species")?{species:speciesList(product.species,`${at}.species`)}:{},...sent("price")?{price:price}:{},...currency===null?{}:{currency:currency},...sent("url")?{url:httpsOrNull(product.url,`${at}.url`)}:{},...sent("imageUrl")?{image_url:httpsOrNull(product.imageUrl,`${at}.imageUrl`)}:{},...sent("category")?{category:optionalText(product.category,`${at}.category`,SHORT_MAX2)}:{},...sent("reasonTags")?{reason_tags:reasonTags(product.reasonTags,`${at}.reasonTags`)}:{},...sent("sample")?{is_sample:product.sample===true}:{},...newer("subscription")?{subscription:subscription===null?null:subscriptionBody(subscription,`${at}.subscription`)}:{},...newer("rating")?{rating:rating}:{},...newer("reviewCount")?{review_count:reviewCount}:{},...newer("reviews")?{reviews:reviewsList(product.reviews,`${at}.reviews`)}:{},...newer("ingredients")?{ingredients:ingredientsList(product.ingredients,`${at}.ingredients`)}:{}}}function count(value){return typeof value=="number"&&Number.isInteger(value)&&value>=0?value:null}function parseResult(json){if(json==null)/* @__PURE__ */return Object.freeze({active:null,deactivated:null,syncRunId:null,deactivatedSkus:null});if(typeof json!="object"||Array.isArray(json))return null;let o=json,run=o.sync_run_id,skus=o.deactivated_skus;/* @__PURE__ */
|
|
102
|
+
return Object.freeze({active:count(o.upserted??o.active),deactivated:count(o.deactivated),syncRunId:typeof run=="string"&&run.length>0?run:null,deactivatedSkus:Array.isArray(skus)&&skus.every(sku=>typeof sku=="string")?/* @__PURE__ */Object.freeze([...skus]):null})}var TTL_MIN_SECONDS=60,TTL_MAX_SECONDS=3600,MINT_TIMEOUT_MS=3e4;async function mintPartnerSession(params){assertServerSecretKey(params.partnerSecretKey,"minting a session");let partnerUserRef=assertValidUserRef(params.userRef),ttlSeconds=clampTtl(params.ttlSeconds),fetchImpl=params.fetchImpl??getGlobalFetch(),url=`${resolveApiBaseUrl(params.apiBaseUrl)}/widget/v1/sessions`,headers={...buildBaseHeaders({sdkVersion:SDK_VERSION,platform:SDK_PLATFORM,contractVersion:params.contractVersion??DEFAULT_CONTRACT_VERSION}),accept:"application/json","content-type":"application/json","x-everfur-partner-secret-key":params.partnerSecretKey,"x-everfur-partner-key":params.publishableKey},body={user_ref:partnerUserRef};ttlSeconds!==void 0&&(body.ttl_seconds=ttlSeconds);let deadline=mintTimeoutSignal(MINT_TIMEOUT_MS),signal=mergeMintSignals(deadline.signal,params.signal),init={method:"POST",headers:headers,body:JSON.stringify(body),signal:signal},res;try{res=await fetchImpl(url,init)}catch(cause){return err(networkError(cause))}finally{deadline.cancel()}let json=await readJsonSafe4(res),requestId=requestIdOf(res);if(!res.ok)return err(foldUserRefInvalid(errorFromResponse(res.status,withRetryAfter(res,json),requestId)));let mint=parseMint(json);return mint?ok(mint):err(errorFromResponse(502,{error:{code:"INTERNAL_ERROR"}},requestId))}function clampTtl(ttl){if(ttl!=null){if(!Number.isInteger(ttl))throw new EverfurConfigError("invalid-argument","ttl_seconds must be an integer");return Math.min(TTL_MAX_SECONDS,Math.max(TTL_MIN_SECONDS,ttl))}}function parseMint(json){if(typeof json!="object"||json===null)return null;let obj=json;if(typeof obj.session_token!="string"||obj.session_token.length===0||typeof obj.expires_at!="number")return null;let capabilities=Array.isArray(obj.capabilities)?obj.capabilities.filter(c=>typeof c=="string"):[];/* @__PURE__ */
|
|
103
|
+
return Object.freeze({sessionToken:obj.session_token,expiresAt:obj.expires_at,capabilities:/* @__PURE__ */Object.freeze(capabilities)})}async function readJsonSafe4(res){try{return await res.json()}catch{return null}}function mintTimeoutSignal(ms){let ctrl=new AbortController,handle=setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>clearTimeout(handle)}}function mergeMintSignals(deadline,caller){if(!caller)return deadline;let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),ctrl.signal}export{assertValidUserRef,canonicalPetSpecies,deletePartnerPet,getPartnerPet,mergeCatalog,mintPartnerSession,replaceCatalog,revokePartnerMemberSessions,sendMemberText,setPartnerMemberNotificationProfile,updatePartnerPet,upsertPartnerPet};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { ReactNode } from 'react';
|
|
2
|
+
import { P as PetRef } from './ids.d-B2GAAifq.js';
|
|
3
|
+
import { c as RecordForwardItem } from './models.d-BagXhafD.js';
|
|
4
|
+
import { a as RecordsAskHandler } from './recordsAsk.d-C5CGSi3j.js';
|
|
5
|
+
import { U as UseEverfurRecordsState } from './useRecords.d-aQTzQZoV.js';
|
|
6
|
+
|
|
7
|
+
/** What the page hands the sheet: its records state and the page's own flows behind every button. */
|
|
8
|
+
interface EverfurRecordsSheetRenderArgs {
|
|
9
|
+
readonly petRef: PetRef;
|
|
10
|
+
readonly petName: string;
|
|
11
|
+
readonly records: UseEverfurRecordsState;
|
|
12
|
+
/** False when consent gates the record: the sheet then shows only the ways to add records, under `consentControl`. */
|
|
13
|
+
readonly readable: boolean;
|
|
14
|
+
readonly consentControl: ReactNode;
|
|
15
|
+
readonly canRequestFromClinic: boolean;
|
|
16
|
+
readonly onRequest: () => void;
|
|
17
|
+
readonly onUpload: () => void;
|
|
18
|
+
readonly onOpenRecord: () => void;
|
|
19
|
+
readonly onOpenMarker: (markerId: string) => void;
|
|
20
|
+
readonly onOpenScreenings?: (() => void) | undefined;
|
|
21
|
+
readonly renderUpcomingCareAction?: ((item: RecordForwardItem) => ReactNode) | undefined;
|
|
22
|
+
/** The page's `weightUnit` (lb when absent); a sheet built with its own `weightUnit` keeps that. */
|
|
23
|
+
readonly weightUnit?: 'lb' | 'kg' | undefined;
|
|
24
|
+
/** The page's `onOpenPlan`: the top risk line's button. A sheet built with its own `onOpenPlan` keeps that. */
|
|
25
|
+
readonly onOpenPlan?: (() => void) | undefined;
|
|
26
|
+
}
|
|
27
|
+
/** What the page hands the lab screen when a result opens in place. */
|
|
28
|
+
interface EverfurRecordsSheetLabRenderArgs {
|
|
29
|
+
readonly petRef: PetRef;
|
|
30
|
+
readonly markerId: string;
|
|
31
|
+
readonly petName?: string | undefined;
|
|
32
|
+
readonly onAsk?: RecordsAskHandler | undefined;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Raph's v3 records sheet, built by `recordsSheet()` from `@everfur/sdk/web/records-sheet`. Pass it as
|
|
36
|
+
* `EverfurRecordsPage`'s `sheet`. Build it once (module scope or `useMemo`), not on every render.
|
|
37
|
+
*/
|
|
38
|
+
interface EverfurRecordsSheet {
|
|
39
|
+
/** A lab result was opened and the host routes it itself; absent, the page opens the result in place. */
|
|
40
|
+
readonly onOpenMarker?: ((markerId: string) => void) | undefined;
|
|
41
|
+
readonly renderSheet: (args: EverfurRecordsSheetRenderArgs) => ReactNode;
|
|
42
|
+
readonly renderLab: (args: EverfurRecordsSheetLabRenderArgs) => ReactNode;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export type { EverfurRecordsSheet as E, EverfurRecordsSheetLabRenderArgs as a, EverfurRecordsSheetRenderArgs as b };
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { ReactNode } from 'react';
|
|
2
|
+
import { P as PetRef } from './ids.d-B2GAAifq.cjs';
|
|
3
|
+
import { c as RecordForwardItem } from './models.d-BnLm3VAA.cjs';
|
|
4
|
+
import { a as RecordsAskHandler } from './recordsAsk.d-C5CGSi3j.cjs';
|
|
5
|
+
import { U as UseEverfurRecordsState } from './useRecords.d-Cb-36SF5.cjs';
|
|
6
|
+
|
|
7
|
+
/** What the page hands the sheet: its records state and the page's own flows behind every button. */
|
|
8
|
+
interface EverfurRecordsSheetRenderArgs {
|
|
9
|
+
readonly petRef: PetRef;
|
|
10
|
+
readonly petName: string;
|
|
11
|
+
readonly records: UseEverfurRecordsState;
|
|
12
|
+
/** False when consent gates the record: the sheet then shows only the ways to add records, under `consentControl`. */
|
|
13
|
+
readonly readable: boolean;
|
|
14
|
+
readonly consentControl: ReactNode;
|
|
15
|
+
readonly canRequestFromClinic: boolean;
|
|
16
|
+
readonly onRequest: () => void;
|
|
17
|
+
readonly onUpload: () => void;
|
|
18
|
+
readonly onOpenRecord: () => void;
|
|
19
|
+
readonly onOpenMarker: (markerId: string) => void;
|
|
20
|
+
readonly onOpenScreenings?: (() => void) | undefined;
|
|
21
|
+
readonly renderUpcomingCareAction?: ((item: RecordForwardItem) => ReactNode) | undefined;
|
|
22
|
+
/** The page's `weightUnit` (lb when absent); a sheet built with its own `weightUnit` keeps that. */
|
|
23
|
+
readonly weightUnit?: 'lb' | 'kg' | undefined;
|
|
24
|
+
/** The page's `onOpenPlan`: the top risk line's button. A sheet built with its own `onOpenPlan` keeps that. */
|
|
25
|
+
readonly onOpenPlan?: (() => void) | undefined;
|
|
26
|
+
}
|
|
27
|
+
/** What the page hands the lab screen when a result opens in place. */
|
|
28
|
+
interface EverfurRecordsSheetLabRenderArgs {
|
|
29
|
+
readonly petRef: PetRef;
|
|
30
|
+
readonly markerId: string;
|
|
31
|
+
readonly petName?: string | undefined;
|
|
32
|
+
readonly onAsk?: RecordsAskHandler | undefined;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Raph's v3 records sheet, built by `recordsSheet()` from `@everfur/sdk/web/records-sheet`. Pass it as
|
|
36
|
+
* `EverfurRecordsPage`'s `sheet`. Build it once (module scope or `useMemo`), not on every render.
|
|
37
|
+
*/
|
|
38
|
+
interface EverfurRecordsSheet {
|
|
39
|
+
/** A lab result was opened and the host routes it itself; absent, the page opens the result in place. */
|
|
40
|
+
readonly onOpenMarker?: ((markerId: string) => void) | undefined;
|
|
41
|
+
readonly renderSheet: (args: EverfurRecordsSheetRenderArgs) => ReactNode;
|
|
42
|
+
readonly renderLab: (args: EverfurRecordsSheetLabRenderArgs) => ReactNode;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export type { EverfurRecordsSheet as E, EverfurRecordsSheetLabRenderArgs as a, EverfurRecordsSheetRenderArgs as b };
|