@farm.js/core 0.1.16 → 0.1.18
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/dist/after.cjs +12 -225
- package/dist/agent-runtime.cjs +83 -2800
- package/dist/agent-runtime.d.mts +3 -3
- package/dist/agent-runtime.d.ts +3 -3
- package/dist/api/client.cjs +17 -4026
- package/dist/api/client.d.mts +3 -3
- package/dist/api/client.d.ts +3 -3
- package/dist/api/client.mjs +3 -3
- package/dist/api/route-manager.cjs +34 -4317
- package/dist/api/route-manager.d.mts +3 -3
- package/dist/api/route-manager.d.ts +3 -3
- package/dist/api/route-manager.mjs +5 -5
- package/dist/api/runtime.cjs +29 -2660
- package/dist/api/runtime.d.mts +3 -3
- package/dist/api/runtime.d.ts +3 -3
- package/dist/api/runtime.mjs +6 -3
- package/dist/{api-client-B-n3pm_Q.d.mts → api-client-Cx54IR5g.d.mts} +2 -2
- package/dist/{api-client-C0_NZEBl.d.ts → api-client-DykpaKcY.d.ts} +2 -2
- package/dist/api.cjs +88 -8361
- package/dist/api.d.mts +5 -5
- package/dist/api.d.ts +5 -5
- package/dist/api.mjs +8 -8
- package/dist/{app-AyjEsCBq.d.ts → app-BHY_10Lm.d.ts} +3 -3
- package/dist/{app-CYPHeOo_.d.mts → app-BMk0do23.d.mts} +3 -3
- package/dist/app-markdown.cjs +39 -280
- package/dist/app-markdown.d.mts +4 -4
- package/dist/app-markdown.d.ts +4 -4
- package/dist/app-markdown.mjs +3 -3
- package/dist/cache.cjs +38 -1526
- package/dist/cache.d.mts +11 -1
- package/dist/cache.d.ts +11 -1
- package/dist/cache.mjs +1 -1
- package/dist/chunk-22GUSVNJ.cjs +351 -0
- package/dist/chunk-2CQ74SP6.cjs +13 -0
- package/dist/chunk-2SJ4RQ6P.cjs +57 -0
- package/dist/chunk-3376ZTRC.cjs +1 -0
- package/dist/{chunk-IL5RWYK7.mjs → chunk-3XG26Z3J.mjs} +1 -1
- package/dist/{chunk-7HDZYYS4.mjs → chunk-4OOBRCJX.mjs} +27 -5
- package/dist/chunk-4PNUXIVU.cjs +472 -0
- package/dist/chunk-4PPEPOZZ.cjs +21 -0
- package/dist/chunk-4ZFL5GFN.cjs +520 -0
- package/dist/{chunk-B76DT5Y6.mjs → chunk-57J3Y7Y3.mjs} +1 -1
- package/dist/chunk-5OVTOKGH.cjs +65 -0
- package/dist/chunk-5QIKR7RR.cjs +224 -0
- package/dist/{chunk-MOQNHLTS.mjs → chunk-5QOEPUYE.mjs} +5 -2
- package/dist/{chunk-HKLRP3BN.mjs → chunk-5SPPCN5J.mjs} +1 -1
- package/dist/chunk-5ZSWG4UX.cjs +127 -0
- package/dist/chunk-62YJ2IEB.cjs +238 -0
- package/dist/chunk-6EODJYCX.cjs +183 -0
- package/dist/chunk-6EXBPJ24.cjs +434 -0
- package/dist/chunk-6QQDAAAZ.cjs +38 -0
- package/dist/chunk-6V4TDWEC.cjs +455 -0
- package/dist/{chunk-LUC2FAGW.mjs → chunk-6VQIKZZO.mjs} +1 -1
- package/dist/chunk-72ADZ6GQ.cjs +19 -0
- package/dist/chunk-75BRBIFP.cjs +172 -0
- package/dist/{chunk-7ZWL7XOU.mjs → chunk-76DG3LF3.mjs} +1 -1
- package/dist/chunk-7W3CPVXS.cjs +24 -0
- package/dist/chunk-A6WIQH5Z.cjs +31 -0
- package/dist/{chunk-EWDK36MM.mjs → chunk-A72YEUZ3.mjs} +1 -1
- package/dist/chunk-AFOD3LYZ.cjs +377 -0
- package/dist/chunk-AMDMVWMI.cjs +39 -0
- package/dist/chunk-AORPIPNB.cjs +552 -0
- package/dist/chunk-ARJWXNQL.cjs +256 -0
- package/dist/{chunk-ZHOIQC6U.mjs → chunk-ATERBVHQ.mjs} +2 -2
- package/dist/chunk-AWRISO2H.cjs +2199 -0
- package/dist/chunk-AYJR42WX.cjs +711 -0
- package/dist/chunk-B4CH33IG.cjs +644 -0
- package/dist/chunk-BIDYX3SL.cjs +91 -0
- package/dist/chunk-BSTRERPP.cjs +40 -0
- package/dist/chunk-BYODCJD6.cjs +663 -0
- package/dist/chunk-C3VRMB6H.cjs +85 -0
- package/dist/chunk-C5GUTBZK.cjs +173 -0
- package/dist/chunk-CIAGU2X4.cjs +337 -0
- package/dist/chunk-CMGMGHUZ.cjs +27 -0
- package/dist/chunk-CXP5U3RW.cjs +54 -0
- package/dist/chunk-D2ULAULS.cjs +166 -0
- package/dist/chunk-D7JTOLFK.cjs +285 -0
- package/dist/chunk-DVM4FKZL.cjs +169 -0
- package/dist/chunk-DYEJQTDN.cjs +49 -0
- package/dist/chunk-E2BMSZ2W.cjs +151 -0
- package/dist/chunk-E3UK5IIB.cjs +593 -0
- package/dist/chunk-EM6SBQKM.cjs +470 -0
- package/dist/{chunk-27JNCYEK.mjs → chunk-EN7WTEAY.mjs} +2 -2
- package/dist/{chunk-IGO2HEV7.mjs → chunk-F6SJAKFJ.mjs} +62 -28
- package/dist/{chunk-GSDIZACQ.mjs → chunk-FG5H2VCJ.mjs} +2 -2
- package/dist/chunk-FJSWYIR7.cjs +482 -0
- package/dist/chunk-FK6GO24V.cjs +54 -0
- package/dist/chunk-FXUUWYAX.cjs +654 -0
- package/dist/chunk-G3HRIVEY.cjs +395 -0
- package/dist/chunk-G643DQCH.cjs +13 -0
- package/dist/chunk-G7HXGLEC.cjs +175 -0
- package/dist/chunk-GDSHDTJ4.cjs +152 -0
- package/dist/chunk-GNEO2XOF.cjs +2040 -0
- package/dist/{chunk-NHHKW2T6.mjs → chunk-GYKJCFTS.mjs} +170 -52
- package/dist/chunk-H6G5INWM.cjs +1094 -0
- package/dist/chunk-HBTUGXHS.cjs +180 -0
- package/dist/chunk-HREOKQWT.cjs +45 -0
- package/dist/chunk-I4J452B7.cjs +435 -0
- package/dist/chunk-I57LW5VZ.cjs +94 -0
- package/dist/chunk-I7PUUDGY.cjs +389 -0
- package/dist/chunk-IAMRBF3Z.cjs +86 -0
- package/dist/chunk-IKNRN4VS.cjs +14214 -0
- package/dist/chunk-IQXFRNY2.cjs +169 -0
- package/dist/chunk-IXTFU4PL.cjs +2355 -0
- package/dist/chunk-J2OP5GG3.cjs +725 -0
- package/dist/chunk-J3LOGE4T.cjs +42 -0
- package/dist/chunk-J7FSKED3.cjs +93 -0
- package/dist/chunk-JDNHKPTD.cjs +22 -0
- package/dist/chunk-JSROZYYO.cjs +164 -0
- package/dist/chunk-K6FNHVDR.cjs +696 -0
- package/dist/chunk-KGZIORNL.cjs +43 -0
- package/dist/{chunk-LZK5CXDW.mjs → chunk-KLSSO6YD.mjs} +2 -2
- package/dist/{chunk-TYVVIQ5M.mjs → chunk-KPNVGRBL.mjs} +32 -25
- package/dist/chunk-KR6CKSXT.cjs +15 -0
- package/dist/chunk-KROWKCUH.cjs +185 -0
- package/dist/chunk-KVFPGF2M.cjs +46 -0
- package/dist/{chunk-KUO3GBPK.mjs → chunk-L6V3P73N.mjs} +1 -1
- package/dist/chunk-LCCBO7PJ.cjs +46 -0
- package/dist/chunk-LIUGYUX3.cjs +22 -0
- package/dist/chunk-LTNGXMQ6.cjs +55 -0
- package/dist/chunk-M2L4MYDQ.cjs +14 -0
- package/dist/chunk-MCJLA63J.cjs +1 -0
- package/dist/chunk-MKB2EGIR.cjs +148 -0
- package/dist/chunk-MQ3H6LT5.cjs +202 -0
- package/dist/chunk-MT763TDW.cjs +43 -0
- package/dist/chunk-MWSK6C4J.cjs +18 -0
- package/dist/chunk-MWWVKDW3.cjs +169 -0
- package/dist/{chunk-KTGFMHET.mjs → chunk-N6UROPT7.mjs} +1 -1
- package/dist/chunk-NO3WWW3N.cjs +192 -0
- package/dist/{chunk-NDD2YVGU.mjs → chunk-NRVGEI5I.mjs} +10 -3
- package/dist/chunk-NV3A5DXM.cjs +862 -0
- package/dist/chunk-NWOD6NIT.cjs +9 -0
- package/dist/chunk-NZKJGRB3.cjs +230 -0
- package/dist/chunk-OAVTUMJP.cjs +1496 -0
- package/dist/chunk-OHY2ZWUG.cjs +25 -0
- package/dist/chunk-OI6CMLWX.cjs +47 -0
- package/dist/chunk-OIEOCXKG.cjs +453 -0
- package/dist/chunk-OWOUTKIJ.cjs +558 -0
- package/dist/chunk-OX6O6WVA.cjs +74 -0
- package/dist/chunk-OXSIH4D6.cjs +476 -0
- package/dist/chunk-OYEUREB6.cjs +35 -0
- package/dist/chunk-PCOTGFSM.cjs +139 -0
- package/dist/chunk-PZYCPSCC.cjs +35 -0
- package/dist/chunk-QBK2AA4U.cjs +445 -0
- package/dist/chunk-QBPXNZGV.cjs +487 -0
- package/dist/{chunk-IXTEENRS.mjs → chunk-QGVJVSNX.mjs} +5 -5
- package/dist/chunk-QNPEUFHQ.cjs +27 -0
- package/dist/chunk-QZRVZSPN.cjs +236 -0
- package/dist/chunk-R5A5KNVX.cjs +20 -0
- package/dist/chunk-R5JIFR6B.cjs +42 -0
- package/dist/chunk-R6AIILII.cjs +193 -0
- package/dist/chunk-RG3ZOTG5.cjs +34 -0
- package/dist/chunk-ROUTX2E5.cjs +390 -0
- package/dist/chunk-RTHIVJ2G.cjs +54 -0
- package/dist/chunk-S3A45T7F.cjs +166 -0
- package/dist/chunk-S3JO3N4H.cjs +17 -0
- package/dist/chunk-SK35NQKK.cjs +27 -0
- package/dist/chunk-SU7MH53P.cjs +180 -0
- package/dist/chunk-SVRTJOUF.cjs +113 -0
- package/dist/chunk-SWN467MP.cjs +18 -0
- package/dist/{chunk-6SCB2MXB.mjs → chunk-SXHV42UQ.mjs} +16 -1
- package/dist/{chunk-OWTIOHON.mjs → chunk-SYGGPS4A.mjs} +2 -2
- package/dist/chunk-SYQ3MOWW.cjs +73 -0
- package/dist/chunk-T5CERMEH.cjs +417 -0
- package/dist/chunk-TFAXUHWX.cjs +206 -0
- package/dist/chunk-TIWHTW3Q.cjs +24 -0
- package/dist/chunk-TKJZFIML.cjs +20 -0
- package/dist/chunk-TKNSDBBN.cjs +193 -0
- package/dist/{chunk-NC333MFA.mjs → chunk-TSWW5BVH.mjs} +7 -4
- package/dist/chunk-TWGMSEHX.cjs +525 -0
- package/dist/chunk-TYQUSXUG.cjs +1357 -0
- package/dist/chunk-U4KT7QP3.cjs +23 -0
- package/dist/{chunk-LK6FGAQR.mjs → chunk-UDBJCUPA.mjs} +7 -4
- package/dist/chunk-UJ2C4ICS.cjs +277 -0
- package/dist/chunk-UN5GHC5V.cjs +10244 -0
- package/dist/chunk-UQZ4AYTH.cjs +168 -0
- package/dist/chunk-US2QVW3E.cjs +36 -0
- package/dist/{chunk-NUD6XBMO.mjs → chunk-UTBVHYS3.mjs} +2 -2
- package/dist/{chunk-76MNRHTS.mjs → chunk-UUYF3CHN.mjs} +2 -2
- package/dist/chunk-VB6UCX3V.cjs +421 -0
- package/dist/chunk-VEKFLAQM.cjs +300 -0
- package/dist/chunk-VQDBNVOO.cjs +14 -0
- package/dist/chunk-W4E7WMXE.cjs +71 -0
- package/dist/{chunk-VVTREAG5.mjs → chunk-WD4YXVLV.mjs} +11 -3
- package/dist/{chunk-UQZPTIML.mjs → chunk-WD5PNSOB.mjs} +2 -2
- package/dist/chunk-WJ3HK3LJ.cjs +1102 -0
- package/dist/chunk-WMAPPDMM.cjs +28 -0
- package/dist/chunk-WMOGFOUJ.cjs +223 -0
- package/dist/chunk-WPYFSQKK.cjs +37 -0
- package/dist/chunk-WZMNW2IW.cjs +1415 -0
- package/dist/chunk-XGC343EY.cjs +443 -0
- package/dist/{chunk-DPZUDPVJ.mjs → chunk-XP777LRD.mjs} +1 -1
- package/dist/chunk-XSKZORAS.cjs +727 -0
- package/dist/chunk-XWAWFQFS.cjs +82 -0
- package/dist/{chunk-KATQ6I56.mjs → chunk-XWAYMDLB.mjs} +1 -1
- package/dist/chunk-Y4YMF2NQ.cjs +460 -0
- package/dist/chunk-Y4YWHNKU.cjs +250 -0
- package/dist/chunk-Y53ZSFN6.cjs +504 -0
- package/dist/chunk-YA6LLTIJ.cjs +411 -0
- package/dist/chunk-YFPGHF5F.cjs +202 -0
- package/dist/chunk-YJRZR7VU.cjs +28 -0
- package/dist/chunk-YTAABQEV.cjs +1 -0
- package/dist/chunk-YX3DBN4M.cjs +18 -0
- package/dist/chunk-YZTASLPQ.cjs +64 -0
- package/dist/chunk-Z5HIWVDP.cjs +2173 -0
- package/dist/{chunk-Q3MDL7TM.mjs → chunk-ZCNJKLA2.mjs} +30 -11
- package/dist/chunk-ZEG3OPIB.cjs +93 -0
- package/dist/chunk-ZMN3H73H.cjs +155 -0
- package/dist/client/lifecycle.cjs +6 -35
- package/dist/{client-plugins-CqVtZi5X.d.ts → client-plugins-C089bQhN.d.ts} +2 -2
- package/dist/{client-plugins-CIPRtSsW.d.mts → client-plugins-JXXmZliS.d.mts} +2 -2
- package/dist/client-plugins.cjs +7 -448
- package/dist/client-plugins.d.mts +3 -3
- package/dist/client-plugins.d.ts +3 -3
- package/dist/client.cjs +171 -9774
- package/dist/client.d.mts +8 -8
- package/dist/client.d.ts +8 -8
- package/dist/client.mjs +6 -6
- package/dist/config.cjs +8 -36
- package/dist/config.d.mts +3 -3
- package/dist/config.d.ts +3 -3
- package/dist/cron.cjs +24 -491
- package/dist/cron.mjs +2 -2
- package/dist/deferred.cjs +26 -475
- package/dist/deployment.cjs +39 -210
- package/dist/devtools-OUIPHVV6.cjs +388 -0
- package/dist/{devtools-IU7LKZOH.mjs → devtools-UFVTMQX5.mjs} +7 -7
- package/dist/devtools-client-4WAPJY5L.cjs +254 -0
- package/dist/devtools-ui-5GBDIGMK.cjs +1296 -0
- package/dist/docs.cjs +46 -5649
- package/dist/docs.mjs +9 -9
- package/dist/{endpoint-kSAxE52R.d.ts → endpoint-1zA994xL.d.ts} +1 -1
- package/dist/{endpoint-Bu3XgeMK.d.mts → endpoint-DAc96i93.d.mts} +1 -1
- package/dist/env-types.cjs +5 -226
- package/dist/env.cjs +23 -306
- package/dist/env.d.mts +5 -3
- package/dist/env.d.ts +5 -3
- package/dist/env.mjs +2 -1
- package/dist/environment/vite.cjs +8 -372
- package/dist/environment.cjs +12 -94
- package/dist/font.cjs +13 -63
- package/dist/headers.cjs +7 -123
- package/dist/i18n/client.cjs +55 -294
- package/dist/i18n/index.cjs +22 -209
- package/dist/i18n/server.cjs +22 -745
- package/dist/image/server.cjs +13 -729
- package/dist/image/sharp.cjs +33 -171
- package/dist/image.cjs +41 -85
- package/dist/index.cjs +1151 -67862
- package/dist/index.d.mts +14 -14
- package/dist/index.d.ts +14 -14
- package/dist/index.mjs +34 -34
- package/dist/instrumentation.cjs +12 -138
- package/dist/integration-orm-55F7CII5.cjs +13 -0
- package/dist/integrations.cjs +55 -4090
- package/dist/integrations.d.mts +3 -3
- package/dist/integrations.d.ts +3 -3
- package/dist/internal/app-markdown-runtime.cjs +27 -224
- package/dist/internal/app-markdown-runtime.d.mts +3 -3
- package/dist/internal/app-markdown-runtime.d.ts +3 -3
- package/dist/internal/app-markdown-runtime.mjs +2 -2
- package/dist/internal/build-runtime.cjs +120 -52038
- package/dist/internal/build-runtime.d.mts +5 -5
- package/dist/internal/build-runtime.d.ts +5 -5
- package/dist/internal/build-runtime.mjs +23 -23
- package/dist/internal/cli-runtime.cjs +67 -13765
- package/dist/internal/cli-runtime.mjs +13 -13
- package/dist/internal/client-error-overlay.cjs +80 -733
- package/dist/internal/client-error-overlay.mjs +1 -1
- package/dist/internal/client-runtime.cjs +81 -913
- package/dist/internal/compression-runtime.cjs +8 -214
- package/dist/internal/compression-runtime.d.mts +3 -3
- package/dist/internal/compression-runtime.d.ts +3 -3
- package/dist/internal/config-runtime.cjs +42 -6535
- package/dist/internal/config-runtime.d.mts +4 -4
- package/dist/internal/config-runtime.d.ts +4 -4
- package/dist/internal/config-runtime.mjs +7 -7
- package/dist/internal/docs-precompiled-runtime.cjs +26 -46
- package/dist/internal/infra-analytics-runtime.cjs +10 -536
- package/dist/internal/isolated-boundary.cjs +14 -414
- package/dist/internal/metadata-image-runtime.cjs +7 -285
- package/dist/internal/product-telemetry-runtime.cjs +42 -97
- package/dist/internal/product-telemetry-runtime.mjs +1 -1
- package/dist/internal/production-node-env.cjs +6 -63
- package/dist/internal/production-runtime.cjs +418 -7073
- package/dist/internal/production-runtime.d.mts +9 -9
- package/dist/internal/production-runtime.d.ts +9 -9
- package/dist/internal/production-runtime.mjs +6 -6
- package/dist/internal/request-cookies.cjs +6 -54
- package/dist/json-ld.cjs +24 -50
- package/dist/layers-E4WPJNY5.cjs +17 -0
- package/dist/manager-G4B2IPYE.cjs +14 -0
- package/dist/markdown.cjs +21 -532
- package/dist/markdown.mjs +1 -1
- package/dist/{metadata-8g__AMPM.d.ts → metadata-BcNJP4fq.d.ts} +1 -1
- package/dist/{metadata-OMX6wFNf.d.mts → metadata-C1Z9vLbb.d.mts} +1 -1
- package/dist/middleware.cjs +36 -2988
- package/dist/middleware.d.mts +5 -5
- package/dist/middleware.d.ts +5 -5
- package/dist/middleware.mjs +4 -4
- package/dist/navigation.cjs +22 -2588
- package/dist/nitro-4I2MYLY2.cjs +652 -0
- package/dist/{nitro-3N4ZXRYM.mjs → nitro-CVZ36JM5.mjs} +4 -4
- package/dist/observability.cjs +22 -614
- package/dist/og.cjs +5 -28
- package/dist/plugin.cjs +106 -37291
- package/dist/plugin.d.mts +3 -3
- package/dist/plugin.d.ts +3 -3
- package/dist/plugin.mjs +19 -19
- package/dist/{production-runtime-W3M0eNDV.d.mts → production-runtime-jcrTlRTb.d.mts} +1 -1
- package/dist/{production-runtime-BJh7o6Cr.d.ts → production-runtime-oKmC0WU-.d.ts} +1 -1
- package/dist/query/client.cjs +113 -449
- package/dist/query/index.cjs +26 -288
- package/dist/query/parsers.cjs +23 -247
- package/dist/query/server.cjs +36 -298
- package/dist/{render-plan-io7pvDNc.d.mts → render-plan-BLIfc4jt.d.mts} +1 -1
- package/dist/{render-plan-Be4ZGTJP.d.ts → render-plan-DOB9cV-h.d.ts} +1 -1
- package/dist/renderer/react/client.cjs +9 -43
- package/dist/renderer/react/server.cjs +40 -103
- package/dist/renderer/react/vite.cjs +7 -29
- package/dist/renderer-client.cjs +126 -4261
- package/dist/renderer-client.d.mts +5 -5
- package/dist/renderer-client.d.ts +5 -5
- package/dist/renderer-client.mjs +3 -3
- package/dist/renderer.cjs +31 -249
- package/dist/{request-DZkHYQ89.d.mts → request-Cr53NRHr.d.mts} +1 -1
- package/dist/{request-G8JhKr4F.d.ts → request-Dt2gNuQD.d.ts} +1 -1
- package/dist/request.cjs +5 -68
- package/dist/request.d.mts +4 -4
- package/dist/request.d.ts +4 -4
- package/dist/{route-C_eLaFTZ.d.mts → route-B0XrsrFk.d.mts} +1 -1
- package/dist/{route-BxNJT447.d.ts → route-DOEpbyWZ.d.ts} +1 -1
- package/dist/{route-rendering-BcLLPJgN.d.ts → route-rendering-CWYd8Mv1.d.ts} +1 -1
- package/dist/{route-rendering-CbAKr1TY.d.mts → route-rendering-CeFBEAoZ.d.mts} +1 -1
- package/dist/router.cjs +11 -474
- package/dist/routes.cjs +42 -2424
- package/dist/routes.d.mts +4 -4
- package/dist/routes.d.ts +4 -4
- package/dist/routes.mjs +2 -2
- package/dist/schema-dev-notice-MXSZMVDG.cjs +56 -0
- package/dist/schema.cjs +6 -33
- package/dist/search-client-G3RICOFU.cjs +13 -0
- package/dist/server-action-security.cjs +25 -541
- package/dist/server-fn-client.cjs +6 -337
- package/dist/server-fn-client.d.mts +3 -3
- package/dist/server-fn-client.d.ts +3 -3
- package/dist/server-fn.cjs +32 -1799
- package/dist/server-fn.d.mts +1 -1
- package/dist/server-fn.d.ts +1 -1
- package/dist/server-fn.mjs +2 -2
- package/dist/server-plugins.cjs +15 -884
- package/dist/server-plugins.d.mts +4 -4
- package/dist/server-plugins.d.ts +4 -4
- package/dist/server-query-client.cjs +15 -1849
- package/dist/server-query-client.d.mts +1 -1
- package/dist/server-query-client.d.ts +1 -1
- package/dist/server-query-client.mjs +4 -4
- package/dist/server-query.cjs +16 -1796
- package/dist/server-query.d.mts +1 -1
- package/dist/server-query.d.ts +1 -1
- package/dist/server-query.mjs +3 -3
- package/dist/server.cjs +296 -44522
- package/dist/server.d.mts +9 -9
- package/dist/server.d.ts +9 -9
- package/dist/server.mjs +22 -22
- package/dist/{spa-router-BcS_4nqm.d.mts → spa-router-CQWiYGxS.d.mts} +2 -2
- package/dist/{spa-router-BzFBUJkn.d.ts → spa-router-Wjiw-8hB.d.ts} +2 -2
- package/dist/storage.cjs +57 -576
- package/dist/testing.cjs +92 -3148
- package/dist/testing.d.mts +3 -3
- package/dist/testing.d.ts +3 -3
- package/dist/testing.mjs +11 -7
- package/dist/theme/client.cjs +13 -108
- package/dist/theme/index.cjs +6 -68
- package/dist/theme/runtime.cjs +13 -78
- package/dist/theme/server.cjs +10 -179
- package/dist/{utils-C4yrAhNc.d.ts → utils-B0XJmG_b.d.ts} +1 -1
- package/dist/{utils-5kQP1mFR.d.mts → utils-uUxF0K0P.d.mts} +1 -1
- package/dist/version.cjs +4 -32
- package/dist/version.mjs +1 -1
- package/dist/vite.cjs +119 -37622
- package/dist/vite.d.mts +3 -3
- package/dist/vite.d.ts +3 -3
- package/dist/vite.mjs +19 -19
- package/dist/workflows.cjs +19 -1040
- package/dist/workflows.mjs +2 -2
- package/package.json +2 -2
- package/dist/{chunk-VO5SCWF5.mjs → chunk-BNGS6KJ6.mjs} +0 -0
- package/dist/{chunk-MUUZJLCI.mjs → chunk-EGJDUF4Q.mjs} +3 -3
- package/dist/{chunk-4L7SZOHZ.mjs → chunk-YHOCRI4H.mjs} +3 -3
package/dist/api/client.cjs
CHANGED
|
@@ -1,4035 +1,26 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
7
|
-
var __export = (target, all) => {
|
|
8
|
-
for (var name in all)
|
|
9
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
-
};
|
|
11
|
-
var __copyProps = (to, from, except, desc) => {
|
|
12
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
-
for (let key of __getOwnPropNames(from))
|
|
14
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
-
}
|
|
17
|
-
return to;
|
|
18
|
-
};
|
|
19
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
20
2
|
|
|
21
|
-
// src/api-client.ts
|
|
22
|
-
var api_client_exports = {};
|
|
23
|
-
__export(api_client_exports, {
|
|
24
|
-
APIClientError: () => APIClientError,
|
|
25
|
-
createAPIClient: () => createAPIClient,
|
|
26
|
-
createApiClients: () => createApiClients,
|
|
27
|
-
createServerAPIClient: () => createServerAPIClient
|
|
28
|
-
});
|
|
29
|
-
module.exports = __toCommonJS(api_client_exports);
|
|
30
3
|
|
|
31
|
-
// src/api/config.ts
|
|
32
|
-
var DEFAULT_FARM_API_BASE_PATH = "/api";
|
|
33
|
-
function getFarmAPIBaseURL() {
|
|
34
|
-
if (typeof __FARM_API_BASE_URL__ !== "undefined" && __FARM_API_BASE_URL__) {
|
|
35
|
-
return __FARM_API_BASE_URL__;
|
|
36
|
-
}
|
|
37
|
-
return DEFAULT_FARM_API_BASE_PATH;
|
|
38
|
-
}
|
|
39
|
-
__name(getFarmAPIBaseURL, "getFarmAPIBaseURL");
|
|
40
|
-
function resolveFarmAPIRequestURL(routePath, baseURL = getFarmAPIBaseURL(), fallbackOrigin = getDefaultOrigin()) {
|
|
41
|
-
const base = new URL(baseURL, fallbackOrigin);
|
|
42
|
-
if (base.pathname === "/") {
|
|
43
|
-
return new URL(routePath, base);
|
|
44
|
-
}
|
|
45
|
-
const route = new URL(routePath, fallbackOrigin);
|
|
46
|
-
const suffix = stripCanonicalAPIBasePath(route.pathname);
|
|
47
|
-
const joinedPath = joinURLPath(base.pathname, suffix);
|
|
48
|
-
base.pathname = joinedPath;
|
|
49
|
-
base.search = route.search;
|
|
50
|
-
base.hash = route.hash;
|
|
51
|
-
return base;
|
|
52
|
-
}
|
|
53
|
-
__name(resolveFarmAPIRequestURL, "resolveFarmAPIRequestURL");
|
|
54
|
-
function stripCanonicalAPIBasePath(pathname) {
|
|
55
|
-
if (pathname === DEFAULT_FARM_API_BASE_PATH) return "";
|
|
56
|
-
if (pathname.startsWith(`${DEFAULT_FARM_API_BASE_PATH}/`)) {
|
|
57
|
-
return pathname.slice(DEFAULT_FARM_API_BASE_PATH.length + 1);
|
|
58
|
-
}
|
|
59
|
-
return pathname.replace(/^\/+/, "");
|
|
60
|
-
}
|
|
61
|
-
__name(stripCanonicalAPIBasePath, "stripCanonicalAPIBasePath");
|
|
62
|
-
function joinURLPath(basePath, suffix) {
|
|
63
|
-
const normalizedBase = basePath === "/" ? "" : basePath.replace(/\/+$/, "");
|
|
64
|
-
const normalizedSuffix = suffix.replace(/^\/+/, "");
|
|
65
|
-
if (!normalizedSuffix) return normalizedBase || "/";
|
|
66
|
-
return `${normalizedBase}/${normalizedSuffix}`;
|
|
67
|
-
}
|
|
68
|
-
__name(joinURLPath, "joinURLPath");
|
|
69
|
-
function getDefaultOrigin() {
|
|
70
|
-
return typeof window !== "undefined" ? window.location.origin : "http://localhost:3000";
|
|
71
|
-
}
|
|
72
|
-
__name(getDefaultOrigin, "getDefaultOrigin");
|
|
73
4
|
|
|
74
|
-
// src/client-headers.ts
|
|
75
|
-
function resolveClientHeaders(source) {
|
|
76
|
-
const value = typeof source === "function" ? source() : source;
|
|
77
|
-
if (value && typeof value.then === "function") {
|
|
78
|
-
return Promise.resolve(value).then((headers) => new Headers(headers));
|
|
79
|
-
}
|
|
80
|
-
return new Headers(value);
|
|
81
|
-
}
|
|
82
|
-
__name(resolveClientHeaders, "resolveClientHeaders");
|
|
83
5
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
controller.abort(timeoutReason);
|
|
100
|
-
}, timeoutMs);
|
|
101
|
-
}
|
|
102
|
-
const combined = signals.length > 1 ? AbortSignal.any(signals) : signals[0];
|
|
103
|
-
let active = 0;
|
|
104
|
-
let closed = false;
|
|
105
|
-
const cleanup = /* @__PURE__ */ __name(() => {
|
|
106
|
-
if (closed && active === 0 && timer !== void 0) {
|
|
107
|
-
clearTimeout(timer);
|
|
108
|
-
timer = void 0;
|
|
109
|
-
}
|
|
110
|
-
}, "cleanup");
|
|
111
|
-
const check = /* @__PURE__ */ __name(() => {
|
|
112
|
-
if (invalid) throw invalid;
|
|
113
|
-
combined?.throwIfAborted();
|
|
114
|
-
}, "check");
|
|
115
|
-
return {
|
|
116
|
-
signal: combined,
|
|
117
|
-
get timedOut() {
|
|
118
|
-
return timeoutReason !== void 0 && combined?.reason === timeoutReason;
|
|
119
|
-
},
|
|
120
|
-
check,
|
|
121
|
-
hold() {
|
|
122
|
-
active++;
|
|
123
|
-
return () => {
|
|
124
|
-
active--;
|
|
125
|
-
cleanup();
|
|
126
|
-
};
|
|
127
|
-
},
|
|
128
|
-
// A race also bounds cooperative local dispatch and custom HTTP implementations.
|
|
129
|
-
// Late completion is consumed, but cannot turn a cancelled result into success.
|
|
130
|
-
async run(work) {
|
|
131
|
-
check();
|
|
132
|
-
active++;
|
|
133
|
-
let abort;
|
|
134
|
-
try {
|
|
135
|
-
if (!combined) return await work();
|
|
136
|
-
return await new Promise((resolve, reject) => {
|
|
137
|
-
abort = /* @__PURE__ */ __name(() => reject(combined.reason), "abort");
|
|
138
|
-
combined.addEventListener("abort", abort, { once: true });
|
|
139
|
-
Promise.resolve().then(() => {
|
|
140
|
-
check();
|
|
141
|
-
return work();
|
|
142
|
-
}).then(resolve, reject);
|
|
143
|
-
});
|
|
144
|
-
} finally {
|
|
145
|
-
if (abort) combined?.removeEventListener("abort", abort);
|
|
146
|
-
active--;
|
|
147
|
-
cleanup();
|
|
148
|
-
}
|
|
149
|
-
},
|
|
150
|
-
async delay(ms) {
|
|
151
|
-
let retryTimer;
|
|
152
|
-
try {
|
|
153
|
-
await this.run(
|
|
154
|
-
() => new Promise((resolve) => {
|
|
155
|
-
retryTimer = setTimeout(resolve, ms);
|
|
156
|
-
})
|
|
157
|
-
);
|
|
158
|
-
} finally {
|
|
159
|
-
if (retryTimer !== void 0) clearTimeout(retryTimer);
|
|
160
|
-
}
|
|
161
|
-
},
|
|
162
|
-
dispose() {
|
|
163
|
-
closed = true;
|
|
164
|
-
cleanup();
|
|
165
|
-
}
|
|
166
|
-
};
|
|
167
|
-
}
|
|
168
|
-
__name(createClientCancellation, "createClientCancellation");
|
|
6
|
+
var _chunkIXTFU4PLcjs = require('../chunk-IXTFU4PL.cjs');
|
|
7
|
+
require('../chunk-LTNGXMQ6.cjs');
|
|
8
|
+
require('../chunk-I7PUUDGY.cjs');
|
|
9
|
+
require('../chunk-J7FSKED3.cjs');
|
|
10
|
+
require('../chunk-72ADZ6GQ.cjs');
|
|
11
|
+
require('../chunk-G7HXGLEC.cjs');
|
|
12
|
+
require('../chunk-ARJWXNQL.cjs');
|
|
13
|
+
require('../chunk-S3A45T7F.cjs');
|
|
14
|
+
require('../chunk-H6G5INWM.cjs');
|
|
15
|
+
require('../chunk-ZEG3OPIB.cjs');
|
|
16
|
+
require('../chunk-LIUGYUX3.cjs');
|
|
17
|
+
require('../chunk-E3UK5IIB.cjs');
|
|
18
|
+
require('../chunk-U4KT7QP3.cjs');
|
|
19
|
+
require('../chunk-NO3WWW3N.cjs');
|
|
20
|
+
require('../chunk-S3JO3N4H.cjs');
|
|
169
21
|
|
|
170
|
-
// src/client-observers.ts
|
|
171
|
-
function notifyClientObserver(observer, args, label = "Client lifecycle") {
|
|
172
|
-
if (!observer) return;
|
|
173
|
-
const report = /* @__PURE__ */ __name((error) => {
|
|
174
|
-
const reportError = globalThis.reportError;
|
|
175
|
-
if (typeof reportError === "function") {
|
|
176
|
-
try {
|
|
177
|
-
reportError.call(globalThis, error);
|
|
178
|
-
return;
|
|
179
|
-
} catch {
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
try {
|
|
183
|
-
console.error(`[Farm.js] ${label} callback failed:`, error);
|
|
184
|
-
} catch {
|
|
185
|
-
}
|
|
186
|
-
}, "report");
|
|
187
|
-
try {
|
|
188
|
-
const result = observer(...args);
|
|
189
|
-
if (result && typeof result.then === "function")
|
|
190
|
-
void Promise.resolve(result).catch(report);
|
|
191
|
-
} catch (error) {
|
|
192
|
-
report(error);
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
__name(notifyClientObserver, "notifyClientObserver");
|
|
196
22
|
|
|
197
|
-
// src/integration-client.ts
|
|
198
|
-
var _IntegrationClientError = class _IntegrationClientError extends Error {
|
|
199
|
-
constructor(message, response, data) {
|
|
200
|
-
super(message);
|
|
201
|
-
this.name = "IntegrationClientError";
|
|
202
|
-
this.status = response.status;
|
|
203
|
-
this.response = response;
|
|
204
|
-
this.data = data;
|
|
205
|
-
}
|
|
206
|
-
};
|
|
207
|
-
__name(_IntegrationClientError, "IntegrationClientError");
|
|
208
|
-
var IntegrationClientError = _IntegrationClientError;
|
|
209
|
-
var INTEGRATION_RUNTIME_REGISTRY_KEY = /* @__PURE__ */ Symbol.for("farm.integrationRuntimeRegistry");
|
|
210
|
-
var CURRENT_REQUEST_RESOLVER_KEY = /* @__PURE__ */ Symbol.for("farm.currentRequestResolver");
|
|
211
|
-
var INTEGRATION_REQUEST_DISPATCHER_KEY = /* @__PURE__ */ Symbol.for("farm.integrationRequestDispatcher");
|
|
212
|
-
function isOperation(value) {
|
|
213
|
-
return !!value && typeof value === "object" && value.kind === "farm-integration-api-operation";
|
|
214
|
-
}
|
|
215
|
-
__name(isOperation, "isOperation");
|
|
216
|
-
function tryResolveSourceAPI(source) {
|
|
217
|
-
if ("kind" in source && source.kind === "farm-integration") {
|
|
218
|
-
if (!source.api) {
|
|
219
|
-
return null;
|
|
220
|
-
}
|
|
221
|
-
return source.api;
|
|
222
|
-
}
|
|
223
|
-
return source;
|
|
224
|
-
}
|
|
225
|
-
__name(tryResolveSourceAPI, "tryResolveSourceAPI");
|
|
226
|
-
function getIntegrationRuntimeRegistry() {
|
|
227
|
-
const globalState2 = globalThis;
|
|
228
|
-
return globalState2[INTEGRATION_RUNTIME_REGISTRY_KEY] || /* @__PURE__ */ new Map();
|
|
229
|
-
}
|
|
230
|
-
__name(getIntegrationRuntimeRegistry, "getIntegrationRuntimeRegistry");
|
|
231
|
-
function getRegisteredIntegrationRuntimeLocal(key) {
|
|
232
|
-
return getIntegrationRuntimeRegistry().get(key);
|
|
233
|
-
}
|
|
234
|
-
__name(getRegisteredIntegrationRuntimeLocal, "getRegisteredIntegrationRuntimeLocal");
|
|
235
|
-
function getRegisteredIntegrationsLocal() {
|
|
236
|
-
return Object.fromEntries(
|
|
237
|
-
Array.from(getIntegrationRuntimeRegistry().entries()).map(([key, runtime3]) => [
|
|
238
|
-
key,
|
|
239
|
-
runtime3.integration
|
|
240
|
-
])
|
|
241
|
-
);
|
|
242
|
-
}
|
|
243
|
-
__name(getRegisteredIntegrationsLocal, "getRegisteredIntegrationsLocal");
|
|
244
|
-
function resolveCurrentRequestLocal() {
|
|
245
|
-
const globalState2 = globalThis;
|
|
246
|
-
return globalState2[CURRENT_REQUEST_RESOLVER_KEY]?.();
|
|
247
|
-
}
|
|
248
|
-
__name(resolveCurrentRequestLocal, "resolveCurrentRequestLocal");
|
|
249
|
-
function resolveIntegrationRequestDispatcherLocal() {
|
|
250
|
-
const globalState2 = globalThis;
|
|
251
|
-
return globalState2[INTEGRATION_REQUEST_DISPATCHER_KEY];
|
|
252
|
-
}
|
|
253
|
-
__name(resolveIntegrationRequestDispatcherLocal, "resolveIntegrationRequestDispatcherLocal");
|
|
254
|
-
var INTEGRATION_DATA_HEADER = "x-farm-integration-data";
|
|
255
|
-
var INTEGRATION_DATA_HEADER_MAX_LENGTH = 16 * 1024;
|
|
256
|
-
var BLOCKED_INTEGRATION_DATA_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
257
|
-
function isIntegrationClientData(value) {
|
|
258
|
-
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
259
|
-
}
|
|
260
|
-
__name(isIntegrationClientData, "isIntegrationClientData");
|
|
261
|
-
function isPlainIntegrationDataObject(value) {
|
|
262
|
-
if (!isIntegrationClientData(value)) {
|
|
263
|
-
return false;
|
|
264
|
-
}
|
|
265
|
-
const prototype = Object.getPrototypeOf(value);
|
|
266
|
-
return prototype === Object.prototype || prototype === null;
|
|
267
|
-
}
|
|
268
|
-
__name(isPlainIntegrationDataObject, "isPlainIntegrationDataObject");
|
|
269
|
-
function sanitizeIntegrationClientDataValue(value) {
|
|
270
|
-
if (Array.isArray(value)) {
|
|
271
|
-
return value.map((item) => sanitizeIntegrationClientDataValue(item));
|
|
272
|
-
}
|
|
273
|
-
if (!isPlainIntegrationDataObject(value)) {
|
|
274
|
-
return value;
|
|
275
|
-
}
|
|
276
|
-
const sanitized = {};
|
|
277
|
-
for (const [key, item] of Object.entries(value)) {
|
|
278
|
-
if (BLOCKED_INTEGRATION_DATA_KEYS.has(key)) {
|
|
279
|
-
continue;
|
|
280
|
-
}
|
|
281
|
-
sanitized[key] = sanitizeIntegrationClientDataValue(item);
|
|
282
|
-
}
|
|
283
|
-
return sanitized;
|
|
284
|
-
}
|
|
285
|
-
__name(sanitizeIntegrationClientDataValue, "sanitizeIntegrationClientDataValue");
|
|
286
|
-
function normalizeIntegrationClientData(value) {
|
|
287
|
-
if (!isIntegrationClientData(value)) {
|
|
288
|
-
return void 0;
|
|
289
|
-
}
|
|
290
|
-
const sanitized = sanitizeIntegrationClientDataValue(value);
|
|
291
|
-
return isIntegrationClientData(sanitized) && Object.keys(sanitized).length > 0 ? sanitized : void 0;
|
|
292
|
-
}
|
|
293
|
-
__name(normalizeIntegrationClientData, "normalizeIntegrationClientData");
|
|
294
|
-
function getIntegrationDataHeaderByteLength(value) {
|
|
295
|
-
return new TextEncoder().encode(value).byteLength;
|
|
296
|
-
}
|
|
297
|
-
__name(getIntegrationDataHeaderByteLength, "getIntegrationDataHeaderByteLength");
|
|
298
|
-
function mergeIntegrationClientData(...values) {
|
|
299
|
-
let merged;
|
|
300
|
-
for (const value of values) {
|
|
301
|
-
const data = normalizeIntegrationClientData(value);
|
|
302
|
-
if (!data) {
|
|
303
|
-
continue;
|
|
304
|
-
}
|
|
305
|
-
merged = {
|
|
306
|
-
...merged,
|
|
307
|
-
...data
|
|
308
|
-
};
|
|
309
|
-
}
|
|
310
|
-
return merged && Object.keys(merged).length > 0 ? merged : void 0;
|
|
311
|
-
}
|
|
312
|
-
__name(mergeIntegrationClientData, "mergeIntegrationClientData");
|
|
313
|
-
function serializeIntegrationClientData(data) {
|
|
314
|
-
const serialized = JSON.stringify(data);
|
|
315
|
-
if (getIntegrationDataHeaderByteLength(serialized) > INTEGRATION_DATA_HEADER_MAX_LENGTH) {
|
|
316
|
-
throw new Error(
|
|
317
|
-
`Integration client data must be smaller than ${INTEGRATION_DATA_HEADER_MAX_LENGTH} bytes when sent over HTTP headers.`
|
|
318
|
-
);
|
|
319
|
-
}
|
|
320
|
-
return serialized;
|
|
321
|
-
}
|
|
322
|
-
__name(serializeIntegrationClientData, "serializeIntegrationClientData");
|
|
323
|
-
function appendIntegrationClientDataHeader(headers, data) {
|
|
324
|
-
if (!data) {
|
|
325
|
-
return;
|
|
326
|
-
}
|
|
327
|
-
headers.set(INTEGRATION_DATA_HEADER, serializeIntegrationClientData(data));
|
|
328
|
-
}
|
|
329
|
-
__name(appendIntegrationClientDataHeader, "appendIntegrationClientDataHeader");
|
|
330
|
-
function resolveAutomaticClientNamespaces() {
|
|
331
|
-
const globalState2 = globalThis;
|
|
332
|
-
const manifest = globalState2.window?.__FARM_INTEGRATION_API_MANIFEST__ || globalState2.__FARM_INTEGRATION_API_MANIFEST__ || {};
|
|
333
|
-
return Object.entries(manifest).map(([key, api]) => [key, api, api]);
|
|
334
|
-
}
|
|
335
|
-
__name(resolveAutomaticClientNamespaces, "resolveAutomaticClientNamespaces");
|
|
336
|
-
function resolveAutomaticServerNamespaces() {
|
|
337
|
-
return Object.entries(getRegisteredIntegrationsLocal()).flatMap(([key, source]) => {
|
|
338
|
-
const api = tryResolveSourceAPI(source);
|
|
339
|
-
return api ? [[key, api, source]] : [];
|
|
340
|
-
});
|
|
341
|
-
}
|
|
342
|
-
__name(resolveAutomaticServerNamespaces, "resolveAutomaticServerNamespaces");
|
|
343
|
-
function appendQuery(url, query) {
|
|
344
|
-
if (!query) {
|
|
345
|
-
return;
|
|
346
|
-
}
|
|
347
|
-
for (const [key, value] of Object.entries(query)) {
|
|
348
|
-
if (value == null) {
|
|
349
|
-
continue;
|
|
350
|
-
}
|
|
351
|
-
if (Array.isArray(value)) {
|
|
352
|
-
for (const item of value) {
|
|
353
|
-
if (item != null) {
|
|
354
|
-
url.searchParams.append(key, String(item));
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
continue;
|
|
358
|
-
}
|
|
359
|
-
url.searchParams.set(key, String(value));
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
__name(appendQuery, "appendQuery");
|
|
363
|
-
function appendHeaders(target, source) {
|
|
364
|
-
if (!source) {
|
|
365
|
-
return;
|
|
366
|
-
}
|
|
367
|
-
const headers = new Headers(source);
|
|
368
|
-
headers.forEach((value, key) => {
|
|
369
|
-
target.set(key, value);
|
|
370
|
-
});
|
|
371
|
-
}
|
|
372
|
-
__name(appendHeaders, "appendHeaders");
|
|
373
|
-
var DEFAULT_FORWARDED_HEADERS = [
|
|
374
|
-
"authorization",
|
|
375
|
-
"cookie",
|
|
376
|
-
"x-client-ip",
|
|
377
|
-
"x-forwarded-for",
|
|
378
|
-
"x-forwarded-host",
|
|
379
|
-
"x-forwarded-proto",
|
|
380
|
-
"x-real-ip"
|
|
381
|
-
];
|
|
382
|
-
function resolveRequestLike(request) {
|
|
383
|
-
if (!request) {
|
|
384
|
-
return void 0;
|
|
385
|
-
}
|
|
386
|
-
if (request instanceof Request) {
|
|
387
|
-
return {
|
|
388
|
-
url: request.url,
|
|
389
|
-
headers: request.headers
|
|
390
|
-
};
|
|
391
|
-
}
|
|
392
|
-
return {
|
|
393
|
-
url: request.url,
|
|
394
|
-
headers: request.headers ? new Headers(request.headers) : void 0
|
|
395
|
-
};
|
|
396
|
-
}
|
|
397
|
-
__name(resolveRequestLike, "resolveRequestLike");
|
|
398
|
-
function resolveServerBaseURL(explicitBaseURL, request) {
|
|
399
|
-
if (explicitBaseURL) {
|
|
400
|
-
return explicitBaseURL;
|
|
401
|
-
}
|
|
402
|
-
if (request?.url) {
|
|
403
|
-
try {
|
|
404
|
-
return new URL(request.url).origin;
|
|
405
|
-
} catch {
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
const headers = request?.headers;
|
|
409
|
-
const host = headers?.get("x-forwarded-host") || headers?.get("host");
|
|
410
|
-
if (host) {
|
|
411
|
-
const proto = headers?.get("x-forwarded-proto") || "http";
|
|
412
|
-
return `${proto}://${host}`;
|
|
413
|
-
}
|
|
414
|
-
return "http://localhost:3000";
|
|
415
|
-
}
|
|
416
|
-
__name(resolveServerBaseURL, "resolveServerBaseURL");
|
|
417
|
-
function resolveForwardHeaders(request, forwardHeaders) {
|
|
418
|
-
if (!request?.headers || forwardHeaders === false) {
|
|
419
|
-
return new Headers();
|
|
420
|
-
}
|
|
421
|
-
const allowed = Array.isArray(forwardHeaders) && forwardHeaders.length > 0 ? new Set(forwardHeaders.map((item) => item.toLowerCase())) : new Set(DEFAULT_FORWARDED_HEADERS);
|
|
422
|
-
const headers = new Headers();
|
|
423
|
-
request.headers.forEach((value, key) => {
|
|
424
|
-
if (allowed.has(key.toLowerCase())) {
|
|
425
|
-
headers.set(key, value);
|
|
426
|
-
}
|
|
427
|
-
});
|
|
428
|
-
return headers;
|
|
429
|
-
}
|
|
430
|
-
__name(resolveForwardHeaders, "resolveForwardHeaders");
|
|
431
|
-
function createBody(format, body, headers) {
|
|
432
|
-
if (body == null || format === "none") {
|
|
433
|
-
return void 0;
|
|
434
|
-
}
|
|
435
|
-
if (format === "form") {
|
|
436
|
-
if (body instanceof FormData || body instanceof URLSearchParams) {
|
|
437
|
-
return body;
|
|
438
|
-
}
|
|
439
|
-
const form = new URLSearchParams();
|
|
440
|
-
for (const [key, value] of Object.entries(body)) {
|
|
441
|
-
if (value == null) {
|
|
442
|
-
continue;
|
|
443
|
-
}
|
|
444
|
-
if (Array.isArray(value)) {
|
|
445
|
-
for (const item of value) {
|
|
446
|
-
if (item != null) {
|
|
447
|
-
form.append(key, String(item));
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
continue;
|
|
451
|
-
}
|
|
452
|
-
form.set(key, String(value));
|
|
453
|
-
}
|
|
454
|
-
headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
|
|
455
|
-
return form;
|
|
456
|
-
}
|
|
457
|
-
headers.set("content-type", "application/json");
|
|
458
|
-
return JSON.stringify(body);
|
|
459
|
-
}
|
|
460
|
-
__name(createBody, "createBody");
|
|
461
|
-
function createOperationBody(operation, body, headers) {
|
|
462
|
-
const requestBody = createBody(operation.bodyFormat, body, headers);
|
|
463
|
-
if (operation.method === "QUERY" && requestBody === void 0 && !headers.has("content-type")) {
|
|
464
|
-
headers.set(
|
|
465
|
-
"content-type",
|
|
466
|
-
operation.bodyFormat === "form" ? "application/x-www-form-urlencoded;charset=UTF-8" : "application/json"
|
|
467
|
-
);
|
|
468
|
-
}
|
|
469
|
-
return requestBody;
|
|
470
|
-
}
|
|
471
|
-
__name(createOperationBody, "createOperationBody");
|
|
472
|
-
async function parseResponseData(response) {
|
|
473
|
-
if (response.status === 204 || response.status === 205) {
|
|
474
|
-
return void 0;
|
|
475
|
-
}
|
|
476
|
-
const contentType = response.headers.get("content-type") || "";
|
|
477
|
-
if (isJSONMediaType(contentType)) {
|
|
478
|
-
return await response.json();
|
|
479
|
-
}
|
|
480
|
-
return await response.text();
|
|
481
|
-
}
|
|
482
|
-
__name(parseResponseData, "parseResponseData");
|
|
483
|
-
function isJSONMediaType(contentType) {
|
|
484
|
-
const mediaType = contentType.split(";", 1)[0].trim().toLowerCase();
|
|
485
|
-
return mediaType === "application/json" || mediaType.endsWith("+json");
|
|
486
|
-
}
|
|
487
|
-
__name(isJSONMediaType, "isJSONMediaType");
|
|
488
|
-
async function safeParseResponseData(response) {
|
|
489
|
-
try {
|
|
490
|
-
return await parseResponseData(response);
|
|
491
|
-
} catch {
|
|
492
|
-
return void 0;
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
__name(safeParseResponseData, "safeParseResponseData");
|
|
496
|
-
function createResponseError(response, errorData) {
|
|
497
|
-
const message = typeof errorData === "string" ? errorData : typeof errorData === "object" && errorData ? String(
|
|
498
|
-
errorData.error || errorData.message || response.statusText
|
|
499
|
-
) : response.statusText || "Integration request failed.";
|
|
500
|
-
return new IntegrationClientError(message, response, errorData);
|
|
501
|
-
}
|
|
502
|
-
__name(createResponseError, "createResponseError");
|
|
503
|
-
function normalizeExecutionError(error) {
|
|
504
|
-
if (error instanceof Error) {
|
|
505
|
-
return error;
|
|
506
|
-
}
|
|
507
|
-
if (typeof error === "string" && error.length > 0) {
|
|
508
|
-
return new Error(error);
|
|
509
|
-
}
|
|
510
|
-
return new Error("Integration request failed.");
|
|
511
|
-
}
|
|
512
|
-
__name(normalizeExecutionError, "normalizeExecutionError");
|
|
513
|
-
async function finalizeOperationResponse(operation, response) {
|
|
514
|
-
if (!response.ok) {
|
|
515
|
-
const errorData = await safeParseResponseData(response);
|
|
516
|
-
return {
|
|
517
|
-
data: null,
|
|
518
|
-
error: createResponseError(response, errorData)
|
|
519
|
-
};
|
|
520
|
-
}
|
|
521
|
-
if (operation.responseFormat === "response") {
|
|
522
|
-
return {
|
|
523
|
-
data: response,
|
|
524
|
-
error: null
|
|
525
|
-
};
|
|
526
|
-
}
|
|
527
|
-
return {
|
|
528
|
-
data: await parseResponseData(response),
|
|
529
|
-
error: null
|
|
530
|
-
};
|
|
531
|
-
}
|
|
532
|
-
__name(finalizeOperationResponse, "finalizeOperationResponse");
|
|
533
|
-
var integrationRequestCounter = 0;
|
|
534
|
-
var noIntegrationObservers = {
|
|
535
|
-
response(_response) {
|
|
536
|
-
},
|
|
537
|
-
finish(result) {
|
|
538
|
-
return result;
|
|
539
|
-
}
|
|
540
|
-
};
|
|
541
|
-
function createIntegrationObservers(operation, options, requestOptions) {
|
|
542
|
-
if (!options.onRequest && !options.onResponse && !options.onError && !requestOptions?.onRequest && !requestOptions?.onResponse && !requestOptions?.onError) {
|
|
543
|
-
return noIntegrationObservers;
|
|
544
|
-
}
|
|
545
|
-
const requestEvent = {
|
|
546
|
-
requestId: `integration-${Date.now()}-${++integrationRequestCounter}`,
|
|
547
|
-
method: operation.method,
|
|
548
|
-
path: operation.path ?? "",
|
|
549
|
-
attempt: 0,
|
|
550
|
-
timestamp: Date.now()
|
|
551
|
-
};
|
|
552
|
-
let response;
|
|
553
|
-
notifyClientObserver(options.onRequest, [requestEvent]);
|
|
554
|
-
notifyClientObserver(requestOptions?.onRequest, [requestEvent]);
|
|
555
|
-
return {
|
|
556
|
-
response(value) {
|
|
557
|
-
response = value;
|
|
558
|
-
},
|
|
559
|
-
finish(result) {
|
|
560
|
-
const data = result.error ? void 0 : result.data;
|
|
561
|
-
const event = {
|
|
562
|
-
...requestEvent,
|
|
563
|
-
timestamp: Date.now(),
|
|
564
|
-
response,
|
|
565
|
-
data,
|
|
566
|
-
error: result.error ?? void 0,
|
|
567
|
-
ok: !result.error,
|
|
568
|
-
status: response?.status
|
|
569
|
-
};
|
|
570
|
-
notifyClientObserver(options.onResponse, [data, result.error, event]);
|
|
571
|
-
notifyClientObserver(requestOptions?.onResponse, [data, result.error, event]);
|
|
572
|
-
if (result.error) {
|
|
573
|
-
notifyClientObserver(options.onError, [result.error]);
|
|
574
|
-
notifyClientObserver(requestOptions?.onError, [result.error]);
|
|
575
|
-
}
|
|
576
|
-
return result;
|
|
577
|
-
}
|
|
578
|
-
};
|
|
579
|
-
}
|
|
580
|
-
__name(createIntegrationObservers, "createIntegrationObservers");
|
|
581
|
-
async function executeClientOperation(operation, input, options, requestOptions) {
|
|
582
|
-
const cancellation = createClientCancellation(
|
|
583
|
-
requestOptions?.signal,
|
|
584
|
-
requestOptions?.timeoutMs ?? options.timeoutMs
|
|
585
|
-
);
|
|
586
|
-
const observers = createIntegrationObservers(operation, options, requestOptions);
|
|
587
|
-
try {
|
|
588
|
-
const result = await cancellation.run(async () => {
|
|
589
|
-
if (!operation.path) {
|
|
590
|
-
return {
|
|
591
|
-
data: null,
|
|
592
|
-
error: new Error(
|
|
593
|
-
"Integration API operation path is missing. Pass a path to api.get/post/... or wrap pathless methods with api.route(path, { ... })."
|
|
594
|
-
)
|
|
595
|
-
};
|
|
596
|
-
}
|
|
597
|
-
const baseURL = options.baseURL || (typeof window !== "undefined" ? window.location.origin : "http://localhost:3000");
|
|
598
|
-
const url = resolveFarmAPIRequestURL(operation.path, baseURL);
|
|
599
|
-
appendQuery(url, input.query);
|
|
600
|
-
const resolved = resolveClientHeaders(options.headers);
|
|
601
|
-
const headers = resolved instanceof Headers ? resolved : await resolved;
|
|
602
|
-
cancellation.check();
|
|
603
|
-
appendHeaders(headers, operation.headers);
|
|
604
|
-
appendHeaders(headers, requestOptions?.headers);
|
|
605
|
-
headers.set("x-farm-integration-client", "1");
|
|
606
|
-
if (operation.responseFormat !== "response") {
|
|
607
|
-
headers.set("accept", "application/json");
|
|
608
|
-
}
|
|
609
|
-
appendIntegrationClientDataHeader(
|
|
610
|
-
headers,
|
|
611
|
-
mergeIntegrationClientData(options.data, requestOptions?.data)
|
|
612
|
-
);
|
|
613
|
-
const body = createOperationBody(operation, input.body, headers);
|
|
614
|
-
const response = await (options.fetch ?? fetch)(url.toString(), {
|
|
615
|
-
method: operation.method,
|
|
616
|
-
headers,
|
|
617
|
-
body,
|
|
618
|
-
credentials: requestOptions?.credentials ?? operation.credentials ?? options.credentials ?? "include",
|
|
619
|
-
signal: cancellation.signal
|
|
620
|
-
});
|
|
621
|
-
cancellation.check();
|
|
622
|
-
observers.response(response);
|
|
623
|
-
if (!response.ok) {
|
|
624
|
-
const errorData = await safeParseResponseData(response);
|
|
625
|
-
return {
|
|
626
|
-
data: null,
|
|
627
|
-
error: createResponseError(response, errorData)
|
|
628
|
-
};
|
|
629
|
-
}
|
|
630
|
-
if (operation.responseFormat === "response") {
|
|
631
|
-
return {
|
|
632
|
-
data: response,
|
|
633
|
-
error: null
|
|
634
|
-
};
|
|
635
|
-
}
|
|
636
|
-
return {
|
|
637
|
-
data: await parseResponseData(response),
|
|
638
|
-
error: null
|
|
639
|
-
};
|
|
640
|
-
});
|
|
641
|
-
return observers.finish(result);
|
|
642
|
-
} catch (error) {
|
|
643
|
-
return observers.finish({
|
|
644
|
-
data: null,
|
|
645
|
-
error: normalizeExecutionError(error)
|
|
646
|
-
});
|
|
647
|
-
} finally {
|
|
648
|
-
cancellation.dispose();
|
|
649
|
-
}
|
|
650
|
-
}
|
|
651
|
-
__name(executeClientOperation, "executeClientOperation");
|
|
652
|
-
async function executeServerOperation(operation, input, options, requestOptions, integrationKey, source) {
|
|
653
|
-
const currentRequest = requestOptions?.request instanceof Request ? requestOptions.request : options.request instanceof Request ? options.request : resolveCurrentRequestLocal();
|
|
654
|
-
const cancellation = createClientCancellation(
|
|
655
|
-
requestOptions?.signal,
|
|
656
|
-
requestOptions?.timeoutMs ?? options.timeoutMs,
|
|
657
|
-
currentRequest?.signal
|
|
658
|
-
);
|
|
659
|
-
const observers = createIntegrationObservers(operation, options, requestOptions);
|
|
660
|
-
try {
|
|
661
|
-
const result = await cancellation.run(async () => {
|
|
662
|
-
if (!operation.path) {
|
|
663
|
-
return {
|
|
664
|
-
data: null,
|
|
665
|
-
error: new Error(
|
|
666
|
-
"Integration API operation path is missing. Pass a path to api.get/post/... or wrap pathless methods with api.route(path, { ... })."
|
|
667
|
-
)
|
|
668
|
-
};
|
|
669
|
-
}
|
|
670
|
-
const serverRequestOptions = requestOptions && ("request" in requestOptions || "baseURL" in requestOptions || "forwardHeaders" in requestOptions) ? requestOptions : void 0;
|
|
671
|
-
const request = resolveRequestLike(
|
|
672
|
-
serverRequestOptions?.request ?? options.request ?? currentRequest
|
|
673
|
-
);
|
|
674
|
-
const baseURL = resolveServerBaseURL(
|
|
675
|
-
serverRequestOptions?.baseURL ?? options.baseURL,
|
|
676
|
-
request
|
|
677
|
-
);
|
|
678
|
-
const origin = resolveServerBaseURL(void 0, request);
|
|
679
|
-
const url = new URL(operation.path, new URL(baseURL, origin));
|
|
680
|
-
appendQuery(url, input.query);
|
|
681
|
-
const headers = new Headers();
|
|
682
|
-
appendHeaders(
|
|
683
|
-
headers,
|
|
684
|
-
resolveForwardHeaders(
|
|
685
|
-
request,
|
|
686
|
-
serverRequestOptions?.forwardHeaders ?? options.forwardHeaders
|
|
687
|
-
)
|
|
688
|
-
);
|
|
689
|
-
const resolved = resolveClientHeaders(options.headers);
|
|
690
|
-
appendHeaders(headers, resolved instanceof Headers ? resolved : await resolved);
|
|
691
|
-
cancellation.check();
|
|
692
|
-
appendHeaders(headers, operation.headers);
|
|
693
|
-
appendHeaders(headers, requestOptions?.headers);
|
|
694
|
-
headers.set("x-farm-integration-client", "1");
|
|
695
|
-
if (operation.responseFormat !== "response") {
|
|
696
|
-
headers.set("accept", "application/json");
|
|
697
|
-
}
|
|
698
|
-
const data = mergeIntegrationClientData(options.data, requestOptions?.data);
|
|
699
|
-
if (integrationKey) {
|
|
700
|
-
const runtime3 = "kind" in (source || {}) && source.kind === "farm-integration" ? getRegisteredIntegrationRuntimeLocal(integrationKey) || {
|
|
701
|
-
integration: source,
|
|
702
|
-
config: {},
|
|
703
|
-
isDev: process.env.NODE_ENV !== "production",
|
|
704
|
-
isProd: process.env.NODE_ENV === "production"
|
|
705
|
-
} : getRegisteredIntegrationRuntimeLocal(integrationKey);
|
|
706
|
-
if (runtime3) {
|
|
707
|
-
const dispatchIntegrationRequest = resolveIntegrationRequestDispatcherLocal();
|
|
708
|
-
const body2 = createOperationBody(operation, input.body, headers);
|
|
709
|
-
const directResponse = dispatchIntegrationRequest ? await dispatchIntegrationRequest(
|
|
710
|
-
runtime3,
|
|
711
|
-
new Request(url.toString(), {
|
|
712
|
-
method: operation.method,
|
|
713
|
-
headers,
|
|
714
|
-
body: body2,
|
|
715
|
-
signal: cancellation.signal
|
|
716
|
-
}),
|
|
717
|
-
{
|
|
718
|
-
currentRequest,
|
|
719
|
-
data,
|
|
720
|
-
internal: true
|
|
721
|
-
}
|
|
722
|
-
) : null;
|
|
723
|
-
cancellation.check();
|
|
724
|
-
if (directResponse) {
|
|
725
|
-
observers.response(directResponse);
|
|
726
|
-
return await finalizeOperationResponse(operation, directResponse);
|
|
727
|
-
}
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
appendIntegrationClientDataHeader(headers, data);
|
|
731
|
-
const body = createOperationBody(operation, input.body, headers);
|
|
732
|
-
const httpURL = resolveFarmAPIRequestURL(operation.path, baseURL, origin);
|
|
733
|
-
appendQuery(httpURL, input.query);
|
|
734
|
-
const response = await (options.fetch ?? fetch)(httpURL.toString(), {
|
|
735
|
-
method: operation.method,
|
|
736
|
-
headers,
|
|
737
|
-
body,
|
|
738
|
-
credentials: requestOptions?.credentials ?? operation.credentials ?? options.credentials ?? "include",
|
|
739
|
-
signal: cancellation.signal
|
|
740
|
-
});
|
|
741
|
-
cancellation.check();
|
|
742
|
-
observers.response(response);
|
|
743
|
-
return await finalizeOperationResponse(operation, response);
|
|
744
|
-
});
|
|
745
|
-
return observers.finish(result);
|
|
746
|
-
} catch (error) {
|
|
747
|
-
return observers.finish({
|
|
748
|
-
data: null,
|
|
749
|
-
error: normalizeExecutionError(error)
|
|
750
|
-
});
|
|
751
|
-
} finally {
|
|
752
|
-
cancellation.dispose();
|
|
753
|
-
}
|
|
754
|
-
}
|
|
755
|
-
__name(executeServerOperation, "executeServerOperation");
|
|
756
|
-
function createAutomaticIntegrationAliases(isServer, options = {}) {
|
|
757
|
-
const cache = isServer ? /* @__PURE__ */ new Map() : null;
|
|
758
|
-
const integrationNamespaces = new Proxy(
|
|
759
|
-
{},
|
|
760
|
-
{
|
|
761
|
-
get(_target, property) {
|
|
762
|
-
if (typeof property !== "string") {
|
|
763
|
-
return void 0;
|
|
764
|
-
}
|
|
765
|
-
if (property === "integrations") {
|
|
766
|
-
return integrationNamespaces;
|
|
767
|
-
}
|
|
768
|
-
if (cache?.has(property)) {
|
|
769
|
-
return cache.get(property);
|
|
770
|
-
}
|
|
771
|
-
const namespaces = isServer ? resolveAutomaticServerNamespaces() : resolveAutomaticClientNamespaces();
|
|
772
|
-
const match = namespaces.find(([key]) => key === property);
|
|
773
|
-
if (!match) {
|
|
774
|
-
return void 0;
|
|
775
|
-
}
|
|
776
|
-
const namespace = isServer ? createServerNamespaceProxy(
|
|
777
|
-
match[0],
|
|
778
|
-
match[2],
|
|
779
|
-
match[1],
|
|
780
|
-
options
|
|
781
|
-
) : createNamespaceProxy(match[1], options);
|
|
782
|
-
cache?.set(property, namespace);
|
|
783
|
-
return namespace;
|
|
784
|
-
}
|
|
785
|
-
}
|
|
786
|
-
);
|
|
787
|
-
Object.defineProperty(integrationNamespaces, "integrations", {
|
|
788
|
-
value: integrationNamespaces,
|
|
789
|
-
enumerable: false,
|
|
790
|
-
configurable: false,
|
|
791
|
-
writable: false
|
|
792
|
-
});
|
|
793
|
-
return integrationNamespaces;
|
|
794
|
-
}
|
|
795
|
-
__name(createAutomaticIntegrationAliases, "createAutomaticIntegrationAliases");
|
|
796
|
-
function integrationsClient(options = {}) {
|
|
797
|
-
return createAutomaticIntegrationAliases(
|
|
798
|
-
false,
|
|
799
|
-
options
|
|
800
|
-
);
|
|
801
|
-
}
|
|
802
|
-
__name(integrationsClient, "integrationsClient");
|
|
803
|
-
function integrationsServer(options = {}) {
|
|
804
|
-
return createAutomaticIntegrationAliases(true, {
|
|
805
|
-
...options,
|
|
806
|
-
isServer: true
|
|
807
|
-
});
|
|
808
|
-
}
|
|
809
|
-
__name(integrationsServer, "integrationsServer");
|
|
810
|
-
function resolveSingleNamespaceOperation(api) {
|
|
811
|
-
const entries = Object.entries(api);
|
|
812
|
-
if (entries.length !== 1) {
|
|
813
|
-
return null;
|
|
814
|
-
}
|
|
815
|
-
const [, value] = entries[0];
|
|
816
|
-
return isOperation(value) ? value : null;
|
|
817
|
-
}
|
|
818
|
-
__name(resolveSingleNamespaceOperation, "resolveSingleNamespaceOperation");
|
|
819
|
-
function createClientOperationCaller(operation, property, options) {
|
|
820
|
-
if (operation.isServer === true) {
|
|
821
|
-
return async () => {
|
|
822
|
-
throw new Error(
|
|
823
|
-
`Integration method "${property}" is registered with isServer: true and is only available from a server integration client.`
|
|
824
|
-
);
|
|
825
|
-
};
|
|
826
|
-
}
|
|
827
|
-
return async (input = {}, requestOptions) => {
|
|
828
|
-
if (typeof window === "undefined") {
|
|
829
|
-
throw new Error(
|
|
830
|
-
"Client integration API cannot be called on the server. Pass { isServer: true } to createIntegrationClient(...) during server rendering, or provide { isServer: true, request } outside it."
|
|
831
|
-
);
|
|
832
|
-
}
|
|
833
|
-
return executeClientOperation(operation, input, options, requestOptions);
|
|
834
|
-
};
|
|
835
|
-
}
|
|
836
|
-
__name(createClientOperationCaller, "createClientOperationCaller");
|
|
837
|
-
function createServerOperationCaller(operation, options, integrationKey, source) {
|
|
838
|
-
return async (input = {}, requestOptions) => {
|
|
839
|
-
if (typeof window !== "undefined") {
|
|
840
|
-
throw new Error(
|
|
841
|
-
"Server integration API cannot be called in the browser. Remove { isServer: true } and create a client integration API instead."
|
|
842
|
-
);
|
|
843
|
-
}
|
|
844
|
-
return executeServerOperation(
|
|
845
|
-
operation,
|
|
846
|
-
input,
|
|
847
|
-
options,
|
|
848
|
-
requestOptions,
|
|
849
|
-
integrationKey,
|
|
850
|
-
source
|
|
851
|
-
);
|
|
852
|
-
};
|
|
853
|
-
}
|
|
854
|
-
__name(createServerOperationCaller, "createServerOperationCaller");
|
|
855
|
-
function createNamespaceProxy(api, options) {
|
|
856
|
-
const cache = /* @__PURE__ */ new Map();
|
|
857
|
-
const directOperation = resolveSingleNamespaceOperation(api);
|
|
858
|
-
const target = directOperation ? createClientOperationCaller(directOperation, directOperation.method.toLowerCase(), options) : {};
|
|
859
|
-
return new Proxy(target, {
|
|
860
|
-
get(targetObject, property, receiver) {
|
|
861
|
-
if (typeof property !== "string") {
|
|
862
|
-
return Reflect.get(targetObject, property, receiver);
|
|
863
|
-
}
|
|
864
|
-
if (cache.has(property)) {
|
|
865
|
-
return cache.get(property);
|
|
866
|
-
}
|
|
867
|
-
const value = api[property];
|
|
868
|
-
if (!value) {
|
|
869
|
-
return Reflect.get(targetObject, property, receiver);
|
|
870
|
-
}
|
|
871
|
-
if (isOperation(value)) {
|
|
872
|
-
const caller = createClientOperationCaller(value, property, options);
|
|
873
|
-
cache.set(property, caller);
|
|
874
|
-
return caller;
|
|
875
|
-
}
|
|
876
|
-
const namespace = createNamespaceProxy(value, options);
|
|
877
|
-
cache.set(property, namespace);
|
|
878
|
-
return namespace;
|
|
879
|
-
}
|
|
880
|
-
});
|
|
881
|
-
}
|
|
882
|
-
__name(createNamespaceProxy, "createNamespaceProxy");
|
|
883
|
-
function createServerNamespaceProxy(integrationKey, source, api, options) {
|
|
884
|
-
const cache = /* @__PURE__ */ new Map();
|
|
885
|
-
const directOperation = resolveSingleNamespaceOperation(api);
|
|
886
|
-
const target = directOperation ? createServerOperationCaller(directOperation, options, integrationKey, source) : {};
|
|
887
|
-
return new Proxy(target, {
|
|
888
|
-
get(targetObject, property, receiver) {
|
|
889
|
-
if (typeof property !== "string") {
|
|
890
|
-
return Reflect.get(targetObject, property, receiver);
|
|
891
|
-
}
|
|
892
|
-
if (cache.has(property)) {
|
|
893
|
-
return cache.get(property);
|
|
894
|
-
}
|
|
895
|
-
const value = api[property];
|
|
896
|
-
if (!value) {
|
|
897
|
-
return Reflect.get(targetObject, property, receiver);
|
|
898
|
-
}
|
|
899
|
-
if (isOperation(value)) {
|
|
900
|
-
const caller = createServerOperationCaller(value, options, integrationKey, source);
|
|
901
|
-
cache.set(property, caller);
|
|
902
|
-
return caller;
|
|
903
|
-
}
|
|
904
|
-
const namespace = createServerNamespaceProxy(
|
|
905
|
-
integrationKey,
|
|
906
|
-
source,
|
|
907
|
-
value,
|
|
908
|
-
options
|
|
909
|
-
);
|
|
910
|
-
cache.set(property, namespace);
|
|
911
|
-
return namespace;
|
|
912
|
-
}
|
|
913
|
-
});
|
|
914
|
-
}
|
|
915
|
-
__name(createServerNamespaceProxy, "createServerNamespaceProxy");
|
|
916
23
|
|
|
917
|
-
// src/tracing.ts
|
|
918
|
-
var import_api = require("@opentelemetry/api");
|
|
919
|
-
var FARM_TRACER_NAME = "@farm.js/core";
|
|
920
|
-
var ALL_SPAN_KINDS = [
|
|
921
|
-
"request",
|
|
922
|
-
"render",
|
|
923
|
-
"middleware",
|
|
924
|
-
"api",
|
|
925
|
-
"integration",
|
|
926
|
-
"storage",
|
|
927
|
-
"ppr",
|
|
928
|
-
"build",
|
|
929
|
-
"plugin"
|
|
930
|
-
];
|
|
931
|
-
var DEFAULT_IGNORED_PATHS = [
|
|
932
|
-
"/@vite/",
|
|
933
|
-
"/@fs/",
|
|
934
|
-
"/@id/",
|
|
935
|
-
"/@react-refresh",
|
|
936
|
-
"/node_modules/",
|
|
937
|
-
"/__vite",
|
|
938
|
-
"/.well-known/appspecific/"
|
|
939
|
-
];
|
|
940
|
-
var FARM_REQUEST_METHOD_CONTEXT_KEY = (0, import_api.createContextKey)("@farm.js/core/request-method");
|
|
941
|
-
var TRACING_RUNTIME = /* @__PURE__ */ Symbol.for("@farm.js/core/tracing-runtime/v1");
|
|
942
|
-
var runtime = globalThis;
|
|
943
|
-
var tracingState = runtime[TRACING_RUNTIME] ?? (runtime[TRACING_RUNTIME] = normalizeFarmTracingConfig(false));
|
|
944
|
-
function normalizeFarmTracingConfig(config) {
|
|
945
|
-
if (!config) {
|
|
946
|
-
return {
|
|
947
|
-
enabled: false,
|
|
948
|
-
spans: new Set(ALL_SPAN_KINDS),
|
|
949
|
-
recordEvents: true,
|
|
950
|
-
attributes: {},
|
|
951
|
-
ignorePaths: DEFAULT_IGNORED_PATHS
|
|
952
|
-
};
|
|
953
|
-
}
|
|
954
|
-
if (config === true) {
|
|
955
|
-
return {
|
|
956
|
-
enabled: true,
|
|
957
|
-
spans: new Set(ALL_SPAN_KINDS),
|
|
958
|
-
recordEvents: true,
|
|
959
|
-
attributes: {},
|
|
960
|
-
ignorePaths: DEFAULT_IGNORED_PATHS
|
|
961
|
-
};
|
|
962
|
-
}
|
|
963
|
-
return {
|
|
964
|
-
enabled: config.enabled ?? true,
|
|
965
|
-
spans: new Set(config.spans ?? ALL_SPAN_KINDS),
|
|
966
|
-
recordEvents: config.recordEvents ?? true,
|
|
967
|
-
attributes: { ...config.attributes },
|
|
968
|
-
ignorePaths: [...DEFAULT_IGNORED_PATHS, ...config.ignorePaths ?? []]
|
|
969
|
-
};
|
|
970
|
-
}
|
|
971
|
-
__name(normalizeFarmTracingConfig, "normalizeFarmTracingConfig");
|
|
972
|
-
function recordFarmEventTrace(event) {
|
|
973
|
-
if (!tracingState.enabled) return void 0;
|
|
974
|
-
const activeContext = import_api.context.active();
|
|
975
|
-
const activeSpan = import_api.trace.getSpan(activeContext);
|
|
976
|
-
const traceContext = getSpanTraceContext(activeSpan);
|
|
977
|
-
if (activeSpan && traceContext) {
|
|
978
|
-
if (event.type === "route.matched") {
|
|
979
|
-
const method = activeContext.getValue(FARM_REQUEST_METHOD_CONTEXT_KEY) ?? "HTTP";
|
|
980
|
-
activeSpan.updateName(`${method} ${event.route}`);
|
|
981
|
-
activeSpan.setAttribute("http.route", event.route);
|
|
982
|
-
activeSpan.setAttribute("farm.route", event.route);
|
|
983
|
-
}
|
|
984
|
-
if (tracingState.recordEvents) {
|
|
985
|
-
activeSpan.addEvent(event.type, toEventAttributes(event), event.timestamp);
|
|
986
|
-
}
|
|
987
|
-
const error = event.type === "request.error" ? void 0 : getEventError(event);
|
|
988
|
-
if (error !== void 0) {
|
|
989
|
-
if (event.type === "render.error") {
|
|
990
|
-
recordSpanException(activeSpan, error);
|
|
991
|
-
} else {
|
|
992
|
-
recordSpanError(activeSpan, error);
|
|
993
|
-
}
|
|
994
|
-
}
|
|
995
|
-
}
|
|
996
|
-
const completedTraceContext = recordCompletedEventSpan(event, activeContext);
|
|
997
|
-
return traceContext ?? completedTraceContext;
|
|
998
|
-
}
|
|
999
|
-
__name(recordFarmEventTrace, "recordFarmEventTrace");
|
|
1000
|
-
function recordCompletedEventSpan(event, parentContext) {
|
|
1001
|
-
const descriptor = getCompletedSpanDescriptor(event);
|
|
1002
|
-
if (!descriptor || !tracingState.spans.has(descriptor.kind)) return void 0;
|
|
1003
|
-
const tracer = import_api.trace.getTracer(FARM_TRACER_NAME);
|
|
1004
|
-
const span = tracer.startSpan(
|
|
1005
|
-
descriptor.name,
|
|
1006
|
-
{
|
|
1007
|
-
kind: import_api.SpanKind.INTERNAL,
|
|
1008
|
-
startTime: event.timestamp - descriptor.durationMs,
|
|
1009
|
-
attributes: {
|
|
1010
|
-
...tracingState.attributes,
|
|
1011
|
-
...toEventAttributes(event),
|
|
1012
|
-
"farm.event.type": event.type
|
|
1013
|
-
}
|
|
1014
|
-
},
|
|
1015
|
-
parentContext
|
|
1016
|
-
);
|
|
1017
|
-
const status = "status" in event && typeof event.status === "number" ? event.status : void 0;
|
|
1018
|
-
if (status !== void 0) setResponseStatus(span, status);
|
|
1019
|
-
const error = getEventError(event);
|
|
1020
|
-
if (error !== void 0) recordSpanError(span, error);
|
|
1021
|
-
const traceContext = getSpanTraceContext(span);
|
|
1022
|
-
span.end(event.timestamp);
|
|
1023
|
-
return traceContext;
|
|
1024
|
-
}
|
|
1025
|
-
__name(recordCompletedEventSpan, "recordCompletedEventSpan");
|
|
1026
|
-
function getCompletedSpanDescriptor(event) {
|
|
1027
|
-
if (!("durationMs" in event) || typeof event.durationMs !== "number") return void 0;
|
|
1028
|
-
switch (event.type) {
|
|
1029
|
-
case "render.complete":
|
|
1030
|
-
return { kind: "render", name: `farm.render ${event.route}`, durationMs: event.durationMs };
|
|
1031
|
-
case "render.stream.shellReady":
|
|
1032
|
-
return {
|
|
1033
|
-
kind: "render",
|
|
1034
|
-
name: `farm.render.shell ${event.route}`,
|
|
1035
|
-
durationMs: event.durationMs
|
|
1036
|
-
};
|
|
1037
|
-
case "render.stream.complete":
|
|
1038
|
-
return {
|
|
1039
|
-
kind: "render",
|
|
1040
|
-
name: `farm.render.stream ${event.route}`,
|
|
1041
|
-
durationMs: event.durationMs
|
|
1042
|
-
};
|
|
1043
|
-
case "middleware.complete":
|
|
1044
|
-
return {
|
|
1045
|
-
kind: "middleware",
|
|
1046
|
-
name: `farm.middleware ${event.name ?? event.route ?? "anonymous"}`,
|
|
1047
|
-
durationMs: event.durationMs
|
|
1048
|
-
};
|
|
1049
|
-
case "api.request.complete":
|
|
1050
|
-
case "api.error":
|
|
1051
|
-
return {
|
|
1052
|
-
kind: "api",
|
|
1053
|
-
name: `farm.api ${event.method} ${event.route}`,
|
|
1054
|
-
durationMs: event.durationMs
|
|
1055
|
-
};
|
|
1056
|
-
case "integration.api.call.complete":
|
|
1057
|
-
return {
|
|
1058
|
-
kind: "integration",
|
|
1059
|
-
name: `farm.integration ${event.integration}.${event.operation}`,
|
|
1060
|
-
durationMs: event.durationMs
|
|
1061
|
-
};
|
|
1062
|
-
case "storage.query.complete":
|
|
1063
|
-
return {
|
|
1064
|
-
kind: "storage",
|
|
1065
|
-
name: `farm.storage ${event.operation}`,
|
|
1066
|
-
durationMs: event.durationMs
|
|
1067
|
-
};
|
|
1068
|
-
case "ppr.refresh.complete":
|
|
1069
|
-
return {
|
|
1070
|
-
kind: "ppr",
|
|
1071
|
-
name: `farm.ppr.refresh ${event.route}`,
|
|
1072
|
-
durationMs: event.durationMs
|
|
1073
|
-
};
|
|
1074
|
-
case "build.complete":
|
|
1075
|
-
return {
|
|
1076
|
-
kind: "build",
|
|
1077
|
-
name: `farm.build${event.target ? ` ${event.target}` : ""}`,
|
|
1078
|
-
durationMs: event.durationMs
|
|
1079
|
-
};
|
|
1080
|
-
case "plugin.hook.complete":
|
|
1081
|
-
return {
|
|
1082
|
-
kind: "plugin",
|
|
1083
|
-
name: `farm.plugin ${event.plugin}.${event.hook}`,
|
|
1084
|
-
durationMs: event.durationMs
|
|
1085
|
-
};
|
|
1086
|
-
default:
|
|
1087
|
-
return void 0;
|
|
1088
|
-
}
|
|
1089
|
-
}
|
|
1090
|
-
__name(getCompletedSpanDescriptor, "getCompletedSpanDescriptor");
|
|
1091
|
-
function hashFarmCacheKey(value) {
|
|
1092
|
-
let hash = 2166136261;
|
|
1093
|
-
for (let index = 0; index < value.length; index++) {
|
|
1094
|
-
hash ^= value.charCodeAt(index);
|
|
1095
|
-
hash = Math.imul(hash, 16777619);
|
|
1096
|
-
}
|
|
1097
|
-
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
1098
|
-
}
|
|
1099
|
-
__name(hashFarmCacheKey, "hashFarmCacheKey");
|
|
1100
|
-
function toEventAttributes(event) {
|
|
1101
|
-
const attributes = {};
|
|
1102
|
-
const redactKey = typeof event.type === "string" && event.type.startsWith("cache.");
|
|
1103
|
-
for (const [key, value] of Object.entries(event)) {
|
|
1104
|
-
if (key === "timestamp" || key === "level" || key === "error" || key === "traceId" || key === "spanId" || key === "traceSampled" || value === void 0) {
|
|
1105
|
-
continue;
|
|
1106
|
-
}
|
|
1107
|
-
if (redactKey && key === "key" && typeof value === "string") {
|
|
1108
|
-
attributes["farm.key_hash"] = hashFarmCacheKey(value);
|
|
1109
|
-
continue;
|
|
1110
|
-
}
|
|
1111
|
-
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
1112
|
-
attributes[`farm.${key}`] = value;
|
|
1113
|
-
} else if (Array.isArray(value)) {
|
|
1114
|
-
if (value.every((entry) => typeof entry === "string")) {
|
|
1115
|
-
attributes[`farm.${key}`] = value;
|
|
1116
|
-
} else if (value.every((entry) => typeof entry === "number")) {
|
|
1117
|
-
attributes[`farm.${key}`] = value;
|
|
1118
|
-
} else if (value.every((entry) => typeof entry === "boolean")) {
|
|
1119
|
-
attributes[`farm.${key}`] = value;
|
|
1120
|
-
}
|
|
1121
|
-
}
|
|
1122
|
-
}
|
|
1123
|
-
return attributes;
|
|
1124
|
-
}
|
|
1125
|
-
__name(toEventAttributes, "toEventAttributes");
|
|
1126
|
-
function getEventError(event) {
|
|
1127
|
-
return "error" in event ? event.error : void 0;
|
|
1128
|
-
}
|
|
1129
|
-
__name(getEventError, "getEventError");
|
|
1130
|
-
function recordSpanException(span, error) {
|
|
1131
|
-
const normalized = error instanceof Error ? error : new Error(String(error));
|
|
1132
|
-
span.recordException(normalized);
|
|
1133
|
-
return normalized;
|
|
1134
|
-
}
|
|
1135
|
-
__name(recordSpanException, "recordSpanException");
|
|
1136
|
-
function recordSpanError(span, error) {
|
|
1137
|
-
const normalized = recordSpanException(span, error);
|
|
1138
|
-
span.setStatus({ code: import_api.SpanStatusCode.ERROR, message: normalized.message });
|
|
1139
|
-
}
|
|
1140
|
-
__name(recordSpanError, "recordSpanError");
|
|
1141
|
-
function setResponseStatus(span, status) {
|
|
1142
|
-
span.setAttribute("http.response.status_code", status);
|
|
1143
|
-
if (status >= 500) {
|
|
1144
|
-
span.setStatus({ code: import_api.SpanStatusCode.ERROR });
|
|
1145
|
-
}
|
|
1146
|
-
}
|
|
1147
|
-
__name(setResponseStatus, "setResponseStatus");
|
|
1148
|
-
function getSpanTraceContext(span) {
|
|
1149
|
-
if (!span) return void 0;
|
|
1150
|
-
const spanContext = span.spanContext();
|
|
1151
|
-
if (!(0, import_api.isSpanContextValid)(spanContext)) return void 0;
|
|
1152
|
-
return {
|
|
1153
|
-
traceId: spanContext.traceId,
|
|
1154
|
-
spanId: spanContext.spanId,
|
|
1155
|
-
traceSampled: (spanContext.traceFlags & 1) === 1
|
|
1156
|
-
};
|
|
1157
|
-
}
|
|
1158
|
-
__name(getSpanTraceContext, "getSpanTraceContext");
|
|
1159
24
|
|
|
1160
|
-
// src/observability.ts
|
|
1161
|
-
var OBSERVABILITY_RUNTIME = /* @__PURE__ */ Symbol.for("@farm.js/core/observability-runtime/v1");
|
|
1162
|
-
var runtime2 = globalThis;
|
|
1163
|
-
var shared = runtime2[OBSERVABILITY_RUNTIME] ?? (runtime2[OBSERVABILITY_RUNTIME] = {
|
|
1164
|
-
handlers: /* @__PURE__ */ new Set(),
|
|
1165
|
-
unfilteredHandlers: /* @__PURE__ */ new Set(),
|
|
1166
|
-
config: { logs: false, handlers: [], tracing: normalizeFarmTracingConfig(false) }
|
|
1167
|
-
});
|
|
1168
|
-
var runtimeHandlers = shared.handlers;
|
|
1169
|
-
var unfilteredRuntimeHandlers = shared.unfilteredHandlers;
|
|
1170
|
-
var observabilityState = shared.config;
|
|
1171
|
-
function emitFarmEvent(input) {
|
|
1172
|
-
const event = {
|
|
1173
|
-
timestamp: Date.now(),
|
|
1174
|
-
level: inferFarmEventLevel(input.type),
|
|
1175
|
-
...input
|
|
1176
|
-
};
|
|
1177
|
-
const traceContext = recordFarmEventTrace(event);
|
|
1178
|
-
if (traceContext) {
|
|
1179
|
-
event.traceId = traceContext.traceId;
|
|
1180
|
-
event.spanId = traceContext.spanId;
|
|
1181
|
-
event.traceSampled = traceContext.traceSampled;
|
|
1182
|
-
}
|
|
1183
|
-
notifyFarmEventHandlers(event, unfilteredRuntimeHandlers);
|
|
1184
|
-
if (!shouldEmitFarmEvent(event)) return event;
|
|
1185
|
-
if (observabilityState.logs) {
|
|
1186
|
-
logFarmEvent(event);
|
|
1187
|
-
}
|
|
1188
|
-
notifyFarmEventHandlers(event, [...observabilityState.handlers, ...runtimeHandlers]);
|
|
1189
|
-
return event;
|
|
1190
|
-
}
|
|
1191
|
-
__name(emitFarmEvent, "emitFarmEvent");
|
|
1192
|
-
function notifyFarmEventHandlers(event, handlers) {
|
|
1193
|
-
for (const handler of handlers) {
|
|
1194
|
-
try {
|
|
1195
|
-
Promise.resolve(handler(event)).catch((error) => {
|
|
1196
|
-
console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
|
|
1197
|
-
});
|
|
1198
|
-
} catch (error) {
|
|
1199
|
-
console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
|
|
1200
|
-
}
|
|
1201
|
-
}
|
|
1202
|
-
}
|
|
1203
|
-
__name(notifyFarmEventHandlers, "notifyFarmEventHandlers");
|
|
1204
|
-
function shouldEmitFarmEvent(event) {
|
|
1205
|
-
if (!observabilityState.logs && observabilityState.handlers.length === 0 && runtimeHandlers.size === 0) {
|
|
1206
|
-
return false;
|
|
1207
|
-
}
|
|
1208
|
-
if (observabilityState.events && !observabilityState.events.has(event.type)) {
|
|
1209
|
-
return false;
|
|
1210
|
-
}
|
|
1211
|
-
return true;
|
|
1212
|
-
}
|
|
1213
|
-
__name(shouldEmitFarmEvent, "shouldEmitFarmEvent");
|
|
1214
|
-
function inferFarmEventLevel(type) {
|
|
1215
|
-
if (type === "error" || type.endsWith(".error") || type.endsWith(".failed")) {
|
|
1216
|
-
return "error";
|
|
1217
|
-
}
|
|
1218
|
-
if (type.endsWith(".bypass") || type.endsWith(".invalidated") || type.endsWith(".stale") || type.endsWith(".notFound")) {
|
|
1219
|
-
return "warn";
|
|
1220
|
-
}
|
|
1221
|
-
if (type.endsWith(".hit") || type.endsWith(".miss") || type.endsWith(".start") || type.endsWith(".shellReady")) {
|
|
1222
|
-
return "debug";
|
|
1223
|
-
}
|
|
1224
|
-
return "info";
|
|
1225
|
-
}
|
|
1226
|
-
__name(inferFarmEventLevel, "inferFarmEventLevel");
|
|
1227
|
-
function logFarmEvent(event) {
|
|
1228
|
-
const message = `[farm:${event.level}] ${event.type}${formatFarmEventDetails(event)}`;
|
|
1229
|
-
switch (event.level) {
|
|
1230
|
-
case "error":
|
|
1231
|
-
console.error(message);
|
|
1232
|
-
break;
|
|
1233
|
-
case "warn":
|
|
1234
|
-
console.warn(message);
|
|
1235
|
-
break;
|
|
1236
|
-
default:
|
|
1237
|
-
console.log(message);
|
|
1238
|
-
break;
|
|
1239
|
-
}
|
|
1240
|
-
}
|
|
1241
|
-
__name(logFarmEvent, "logFarmEvent");
|
|
1242
|
-
function formatFarmEventDetails(event) {
|
|
1243
|
-
const details = [];
|
|
1244
|
-
const record = event;
|
|
1245
|
-
for (const key of [
|
|
1246
|
-
"route",
|
|
1247
|
-
"pathname",
|
|
1248
|
-
"method",
|
|
1249
|
-
"status",
|
|
1250
|
-
"key",
|
|
1251
|
-
"tag",
|
|
1252
|
-
"path",
|
|
1253
|
-
"reason",
|
|
1254
|
-
"durationMs",
|
|
1255
|
-
"integration",
|
|
1256
|
-
"server",
|
|
1257
|
-
"tool",
|
|
1258
|
-
"outcome",
|
|
1259
|
-
"operation",
|
|
1260
|
-
"plugin",
|
|
1261
|
-
"hook",
|
|
1262
|
-
"target",
|
|
1263
|
-
"count"
|
|
1264
|
-
]) {
|
|
1265
|
-
const value = record[key];
|
|
1266
|
-
if (value !== void 0) {
|
|
1267
|
-
details.push(`${key}=${formatDetailValue(value)}`);
|
|
1268
|
-
}
|
|
1269
|
-
}
|
|
1270
|
-
return details.length > 0 ? ` ${details.join(" ")}` : "";
|
|
1271
|
-
}
|
|
1272
|
-
__name(formatFarmEventDetails, "formatFarmEventDetails");
|
|
1273
|
-
function formatDetailValue(value) {
|
|
1274
|
-
if (typeof value === "string") {
|
|
1275
|
-
return value;
|
|
1276
|
-
}
|
|
1277
|
-
if (typeof value === "number" || typeof value === "boolean") {
|
|
1278
|
-
return String(value);
|
|
1279
|
-
}
|
|
1280
|
-
try {
|
|
1281
|
-
return JSON.stringify(value);
|
|
1282
|
-
} catch {
|
|
1283
|
-
return String(value);
|
|
1284
|
-
}
|
|
1285
|
-
}
|
|
1286
|
-
__name(formatDetailValue, "formatDetailValue");
|
|
1287
|
-
function formatError(error) {
|
|
1288
|
-
return error instanceof Error ? error.message : String(error);
|
|
1289
|
-
}
|
|
1290
|
-
__name(formatError, "formatError");
|
|
1291
25
|
|
|
1292
|
-
|
|
1293
|
-
var FARM_CACHE_INVALIDATION_HEADER = "x-farm-cache-invalidations";
|
|
1294
|
-
var FARM_CACHE_INVALIDATION_STATE = /* @__PURE__ */ Symbol.for("farm.cacheInvalidationState");
|
|
1295
|
-
var globalState = globalThis;
|
|
1296
|
-
function getFarmCacheInvalidationState() {
|
|
1297
|
-
return globalState[FARM_CACHE_INVALIDATION_STATE] ?? (globalState[FARM_CACHE_INVALIDATION_STATE] = {
|
|
1298
|
-
listeners: /* @__PURE__ */ new Set(),
|
|
1299
|
-
taskListeners: /* @__PURE__ */ new Set()
|
|
1300
|
-
});
|
|
1301
|
-
}
|
|
1302
|
-
__name(getFarmCacheInvalidationState, "getFarmCacheInvalidationState");
|
|
1303
|
-
function warnFarmCacheListenerError(scope, error) {
|
|
1304
|
-
const detail = error instanceof Error ? error.stack ?? error.message : String(error);
|
|
1305
|
-
console.warn(`[farm:cache] ${scope} listener failed: ${detail}`);
|
|
1306
|
-
}
|
|
1307
|
-
__name(warnFarmCacheListenerError, "warnFarmCacheListenerError");
|
|
1308
|
-
function notifyFarmCacheInvalidation(key, source = "local") {
|
|
1309
|
-
if (typeof key !== "string" || key.length === 0) return;
|
|
1310
|
-
for (const listener of getFarmCacheInvalidationState().listeners) {
|
|
1311
|
-
try {
|
|
1312
|
-
listener(key, source);
|
|
1313
|
-
} catch (error) {
|
|
1314
|
-
warnFarmCacheListenerError("invalidation", error);
|
|
1315
|
-
}
|
|
1316
|
-
}
|
|
1317
|
-
}
|
|
1318
|
-
__name(notifyFarmCacheInvalidation, "notifyFarmCacheInvalidation");
|
|
1319
|
-
function applyFarmCacheInvalidations(keys, source = "local") {
|
|
1320
|
-
if (!Array.isArray(keys)) return;
|
|
1321
|
-
for (const key of keys) {
|
|
1322
|
-
if (typeof key === "string") {
|
|
1323
|
-
notifyFarmCacheInvalidation(key, source);
|
|
1324
|
-
}
|
|
1325
|
-
}
|
|
1326
|
-
}
|
|
1327
|
-
__name(applyFarmCacheInvalidations, "applyFarmCacheInvalidations");
|
|
1328
|
-
function decodeFarmCacheInvalidations(value) {
|
|
1329
|
-
if (!value) return [];
|
|
1330
|
-
try {
|
|
1331
|
-
const parsed = JSON.parse(decodeURIComponent(value));
|
|
1332
|
-
return Array.isArray(parsed) ? Array.from(
|
|
1333
|
-
new Set(parsed.filter((key) => typeof key === "string" && key.length > 0))
|
|
1334
|
-
) : [];
|
|
1335
|
-
} catch {
|
|
1336
|
-
return [];
|
|
1337
|
-
}
|
|
1338
|
-
}
|
|
1339
|
-
__name(decodeFarmCacheInvalidations, "decodeFarmCacheInvalidations");
|
|
1340
|
-
function subscribeFarmCacheInvalidation(listener) {
|
|
1341
|
-
const state = getFarmCacheInvalidationState();
|
|
1342
|
-
state.listeners.add(listener);
|
|
1343
|
-
return () => state.listeners.delete(listener);
|
|
1344
|
-
}
|
|
1345
|
-
__name(subscribeFarmCacheInvalidation, "subscribeFarmCacheInvalidation");
|
|
1346
|
-
|
|
1347
|
-
// src/cache-invalidation-stream.ts
|
|
1348
|
-
var MAX_BUFFERED_BYTES = 64 * 1024;
|
|
1349
|
-
var textEncoder = new TextEncoder();
|
|
1350
|
-
|
|
1351
|
-
// src/cache.ts
|
|
1352
|
-
var _FarmDataCache = class _FarmDataCache {
|
|
1353
|
-
constructor(config = {}) {
|
|
1354
|
-
this.entries = /* @__PURE__ */ new Map();
|
|
1355
|
-
this.inflight = /* @__PURE__ */ new Map();
|
|
1356
|
-
this.invalidatedTagVersions = /* @__PURE__ */ new Map();
|
|
1357
|
-
this.activeGenerations = /* @__PURE__ */ new Set();
|
|
1358
|
-
this.version = 0;
|
|
1359
|
-
this.generation = 0;
|
|
1360
|
-
this.namespace = "farm";
|
|
1361
|
-
this.local = true;
|
|
1362
|
-
this.maxEntries = 1024;
|
|
1363
|
-
this.lease = {
|
|
1364
|
-
enabled: true,
|
|
1365
|
-
ttlMs: 1e4,
|
|
1366
|
-
waitTimeoutMs: 1e4,
|
|
1367
|
-
pollIntervalMs: 25
|
|
1368
|
-
};
|
|
1369
|
-
this.configure(config);
|
|
1370
|
-
}
|
|
1371
|
-
configure(config = {}) {
|
|
1372
|
-
this.generation++;
|
|
1373
|
-
this.entries.clear();
|
|
1374
|
-
this.inflight.clear();
|
|
1375
|
-
this.invalidatedTagVersions.clear();
|
|
1376
|
-
this.activeGenerations.clear();
|
|
1377
|
-
this.version = 0;
|
|
1378
|
-
this.adapter = config.adapter;
|
|
1379
|
-
this.namespace = normalizeCacheNamespace(config.namespace || "farm");
|
|
1380
|
-
this.local = !config.adapter;
|
|
1381
|
-
this.maxEntries = normalizePositiveInteger(config.maxEntries, 1024, "cache.maxEntries");
|
|
1382
|
-
this.lease = config.lease === false ? { ...this.lease, enabled: false } : {
|
|
1383
|
-
enabled: true,
|
|
1384
|
-
ttlMs: normalizePositiveDuration(config.lease?.ttlMs, 1e4, "cache.lease.ttlMs"),
|
|
1385
|
-
waitTimeoutMs: normalizePositiveDuration(
|
|
1386
|
-
config.lease?.waitTimeoutMs,
|
|
1387
|
-
1e4,
|
|
1388
|
-
"cache.lease.waitTimeoutMs"
|
|
1389
|
-
),
|
|
1390
|
-
pollIntervalMs: normalizePositiveDuration(
|
|
1391
|
-
config.lease?.pollIntervalMs,
|
|
1392
|
-
25,
|
|
1393
|
-
"cache.lease.pollIntervalMs"
|
|
1394
|
-
)
|
|
1395
|
-
};
|
|
1396
|
-
}
|
|
1397
|
-
get adapterName() {
|
|
1398
|
-
return this.adapter?.name || (this.adapter ? "custom" : "memory");
|
|
1399
|
-
}
|
|
1400
|
-
get hasAdapter() {
|
|
1401
|
-
return this.adapter !== void 0;
|
|
1402
|
-
}
|
|
1403
|
-
get size() {
|
|
1404
|
-
return this.entries.size;
|
|
1405
|
-
}
|
|
1406
|
-
get(key, options = {}) {
|
|
1407
|
-
return this.getEntry(key, options)?.value;
|
|
1408
|
-
}
|
|
1409
|
-
getEntry(key, options = {}) {
|
|
1410
|
-
const entry = this.entries.get(key);
|
|
1411
|
-
if (!entry) {
|
|
1412
|
-
emitFarmEvent({ type: "cache.miss", key });
|
|
1413
|
-
return void 0;
|
|
1414
|
-
}
|
|
1415
|
-
const stale = this.isStale(entry, options.now);
|
|
1416
|
-
if (stale) {
|
|
1417
|
-
emitFarmEvent({
|
|
1418
|
-
type: "cache.stale",
|
|
1419
|
-
key,
|
|
1420
|
-
tags: Array.from(entry.tags),
|
|
1421
|
-
revalidate: entry.revalidate
|
|
1422
|
-
});
|
|
1423
|
-
}
|
|
1424
|
-
if (!options.allowStale && stale) {
|
|
1425
|
-
emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
|
|
1426
|
-
return void 0;
|
|
1427
|
-
}
|
|
1428
|
-
this.touchEntry(key, entry);
|
|
1429
|
-
emitFarmEvent({
|
|
1430
|
-
type: "cache.hit",
|
|
1431
|
-
key,
|
|
1432
|
-
tags: Array.from(entry.tags),
|
|
1433
|
-
revalidate: entry.revalidate,
|
|
1434
|
-
stale
|
|
1435
|
-
});
|
|
1436
|
-
return this.toPublicEntry(entry);
|
|
1437
|
-
}
|
|
1438
|
-
async getEntryAsync(key, options = {}) {
|
|
1439
|
-
if (this.local) {
|
|
1440
|
-
const localEntry = this.getEntry(key, options);
|
|
1441
|
-
if (localEntry) return localEntry;
|
|
1442
|
-
}
|
|
1443
|
-
if (!this.adapter) {
|
|
1444
|
-
return this.local ? void 0 : this.getEntry(key, options);
|
|
1445
|
-
}
|
|
1446
|
-
const generation = this.generation;
|
|
1447
|
-
const adapter = this.adapter;
|
|
1448
|
-
const namespace = this.namespace;
|
|
1449
|
-
const entry = await adapter.get(`${namespace}:entry:${key}`);
|
|
1450
|
-
if (generation !== this.generation) return void 0;
|
|
1451
|
-
if (!entry) {
|
|
1452
|
-
emitFarmEvent({ type: "cache.miss", key });
|
|
1453
|
-
return void 0;
|
|
1454
|
-
}
|
|
1455
|
-
assertFarmCacheEntry(entry, key);
|
|
1456
|
-
const stale = await this.isAdapterEntryStale(entry, options.now, adapter, namespace);
|
|
1457
|
-
if (generation !== this.generation) return void 0;
|
|
1458
|
-
if (stale) {
|
|
1459
|
-
emitFarmEvent({
|
|
1460
|
-
type: "cache.stale",
|
|
1461
|
-
key,
|
|
1462
|
-
tags: [...entry.tags],
|
|
1463
|
-
revalidate: entry.revalidate
|
|
1464
|
-
});
|
|
1465
|
-
if (!options.allowStale) {
|
|
1466
|
-
emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
|
|
1467
|
-
return void 0;
|
|
1468
|
-
}
|
|
1469
|
-
}
|
|
1470
|
-
emitFarmEvent({
|
|
1471
|
-
type: "cache.hit",
|
|
1472
|
-
key,
|
|
1473
|
-
tags: [...entry.tags],
|
|
1474
|
-
revalidate: entry.revalidate,
|
|
1475
|
-
stale
|
|
1476
|
-
});
|
|
1477
|
-
if (this.local && !stale) {
|
|
1478
|
-
this.hydrateLocalEntry(entry);
|
|
1479
|
-
}
|
|
1480
|
-
return { ...entry, key };
|
|
1481
|
-
}
|
|
1482
|
-
set(key, value, options = {}) {
|
|
1483
|
-
const revalidate = normalizeRevalidate(options.revalidate);
|
|
1484
|
-
const tags = /* @__PURE__ */ new Set();
|
|
1485
|
-
for (const tag of options.tags ?? []) {
|
|
1486
|
-
tags.add(normalizeCacheTag(tag));
|
|
1487
|
-
}
|
|
1488
|
-
for (const routePath of options.paths ?? []) {
|
|
1489
|
-
tags.add(createPathCacheTag(routePath));
|
|
1490
|
-
}
|
|
1491
|
-
const entry = {
|
|
1492
|
-
key,
|
|
1493
|
-
value,
|
|
1494
|
-
tags,
|
|
1495
|
-
tagVersions: void 0,
|
|
1496
|
-
createdAt: options.createdAt ?? Date.now(),
|
|
1497
|
-
createdVersion: ++this.version,
|
|
1498
|
-
revalidate
|
|
1499
|
-
};
|
|
1500
|
-
this.storeLocalEntry(entry);
|
|
1501
|
-
emitFarmEvent({
|
|
1502
|
-
type: "cache.set",
|
|
1503
|
-
key,
|
|
1504
|
-
tags: Array.from(tags),
|
|
1505
|
-
revalidate: entry.revalidate
|
|
1506
|
-
});
|
|
1507
|
-
return this.toPublicEntry(entry);
|
|
1508
|
-
}
|
|
1509
|
-
async setAsync(key, value, options = {}, tagVersions) {
|
|
1510
|
-
return this.writeAsync(key, value, options, tagVersions);
|
|
1511
|
-
}
|
|
1512
|
-
async writeAsync(key, value, options, tagVersions, createdVersion) {
|
|
1513
|
-
const revalidate = normalizeRevalidate(options.revalidate);
|
|
1514
|
-
const tags = normalizeCacheOptionsTags(options);
|
|
1515
|
-
const capturedVersions = tagVersions ?? await this.getAdapterTagVersions(Array.from(tags.values()));
|
|
1516
|
-
const entry = {
|
|
1517
|
-
key,
|
|
1518
|
-
value,
|
|
1519
|
-
tags: Array.from(tags),
|
|
1520
|
-
tagVersions: capturedVersions,
|
|
1521
|
-
createdAt: options.createdAt ?? Date.now(),
|
|
1522
|
-
createdVersion: createdVersion ?? ++this.version,
|
|
1523
|
-
revalidate
|
|
1524
|
-
};
|
|
1525
|
-
if (this.local) {
|
|
1526
|
-
this.hydrateLocalEntry(entry);
|
|
1527
|
-
}
|
|
1528
|
-
if (this.adapter) {
|
|
1529
|
-
await this.adapter.set(this.createAdapterKey(key), entry);
|
|
1530
|
-
}
|
|
1531
|
-
emitFarmEvent({
|
|
1532
|
-
type: "cache.set",
|
|
1533
|
-
key,
|
|
1534
|
-
tags: [...entry.tags],
|
|
1535
|
-
revalidate: entry.revalidate
|
|
1536
|
-
});
|
|
1537
|
-
return entry;
|
|
1538
|
-
}
|
|
1539
|
-
delete(key) {
|
|
1540
|
-
const deleted = this.entries.delete(key);
|
|
1541
|
-
if (deleted) this.pruneInvalidatedTagVersions();
|
|
1542
|
-
emitFarmEvent({ type: "cache.delete", key, deleted });
|
|
1543
|
-
return deleted;
|
|
1544
|
-
}
|
|
1545
|
-
async deleteAsync(key) {
|
|
1546
|
-
const deleted = this.entries.delete(key);
|
|
1547
|
-
if (deleted) this.pruneInvalidatedTagVersions();
|
|
1548
|
-
if (this.adapter) {
|
|
1549
|
-
await this.adapter.delete(this.createAdapterKey(key));
|
|
1550
|
-
}
|
|
1551
|
-
emitFarmEvent({ type: "cache.delete", key, deleted: this.adapter ? true : deleted });
|
|
1552
|
-
return this.adapter ? true : deleted;
|
|
1553
|
-
}
|
|
1554
|
-
clear() {
|
|
1555
|
-
const count = this.entries.size;
|
|
1556
|
-
this.generation++;
|
|
1557
|
-
this.entries.clear();
|
|
1558
|
-
this.inflight.clear();
|
|
1559
|
-
this.invalidatedTagVersions.clear();
|
|
1560
|
-
this.activeGenerations.clear();
|
|
1561
|
-
this.version = 0;
|
|
1562
|
-
emitFarmEvent({ type: "cache.clear", count });
|
|
1563
|
-
}
|
|
1564
|
-
async clearAsync() {
|
|
1565
|
-
this.clear();
|
|
1566
|
-
await this.adapter?.clear?.();
|
|
1567
|
-
}
|
|
1568
|
-
isStale(entry, now = Date.now()) {
|
|
1569
|
-
if (typeof entry.revalidate === "number" && entry.revalidate >= 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
|
|
1570
|
-
return true;
|
|
1571
|
-
}
|
|
1572
|
-
for (const tag of entry.tags) {
|
|
1573
|
-
const invalidatedVersion = this.invalidatedTagVersions.get(normalizeCacheTag(tag));
|
|
1574
|
-
if (typeof invalidatedVersion === "number" && typeof entry.createdVersion === "number" && invalidatedVersion > entry.createdVersion) {
|
|
1575
|
-
return true;
|
|
1576
|
-
}
|
|
1577
|
-
}
|
|
1578
|
-
return false;
|
|
1579
|
-
}
|
|
1580
|
-
async isStaleAsync(entry, now = Date.now()) {
|
|
1581
|
-
if (this.adapter) {
|
|
1582
|
-
return this.isAdapterEntryStale(entry, now);
|
|
1583
|
-
}
|
|
1584
|
-
return this.isStale(entry, now);
|
|
1585
|
-
}
|
|
1586
|
-
revalidateTag(tag, options = {}) {
|
|
1587
|
-
const normalized = normalizeCacheTag(tag);
|
|
1588
|
-
const count = this.invalidateTag(normalized);
|
|
1589
|
-
emitFarmEvent(
|
|
1590
|
-
options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
|
|
1591
|
-
);
|
|
1592
|
-
return count;
|
|
1593
|
-
}
|
|
1594
|
-
async revalidateTagAsync(tag, options = {}) {
|
|
1595
|
-
const normalized = normalizeCacheTag(tag);
|
|
1596
|
-
const count = this.invalidateTag(normalized);
|
|
1597
|
-
await this.adapter?.invalidateTags?.([this.createAdapterTag(normalized)]);
|
|
1598
|
-
emitFarmEvent(
|
|
1599
|
-
options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
|
|
1600
|
-
);
|
|
1601
|
-
return count;
|
|
1602
|
-
}
|
|
1603
|
-
revalidatePath(routePath) {
|
|
1604
|
-
const normalizedPath = normalizeRevalidatePath(routePath);
|
|
1605
|
-
const pathTag = createPathCacheTag(normalizedPath);
|
|
1606
|
-
const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
|
|
1607
|
-
const count = this.invalidateTag(pathTag);
|
|
1608
|
-
emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
|
|
1609
|
-
if (pprCount > 0) {
|
|
1610
|
-
emitFarmEvent({
|
|
1611
|
-
type: "ppr.shell.invalidated",
|
|
1612
|
-
route: normalizedPath,
|
|
1613
|
-
reason: "revalidatePath",
|
|
1614
|
-
count: pprCount
|
|
1615
|
-
});
|
|
1616
|
-
}
|
|
1617
|
-
return count;
|
|
1618
|
-
}
|
|
1619
|
-
async revalidatePathAsync(routePath) {
|
|
1620
|
-
const normalizedPath = normalizeRevalidatePath(routePath);
|
|
1621
|
-
const pathTag = createPathCacheTag(normalizedPath);
|
|
1622
|
-
const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
|
|
1623
|
-
const count = this.invalidateTag(pathTag);
|
|
1624
|
-
await this.adapter?.invalidateTags?.([this.createAdapterTag(pathTag)]);
|
|
1625
|
-
emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
|
|
1626
|
-
if (pprCount > 0) {
|
|
1627
|
-
emitFarmEvent({
|
|
1628
|
-
type: "ppr.shell.invalidated",
|
|
1629
|
-
route: normalizedPath,
|
|
1630
|
-
reason: "revalidatePath",
|
|
1631
|
-
count: pprCount
|
|
1632
|
-
});
|
|
1633
|
-
}
|
|
1634
|
-
return count;
|
|
1635
|
-
}
|
|
1636
|
-
async getOrSet(key, producer, options = {}) {
|
|
1637
|
-
normalizeRevalidate(options.revalidate);
|
|
1638
|
-
const cached = await this.getEntryAsync(key);
|
|
1639
|
-
if (cached) {
|
|
1640
|
-
return cached.value;
|
|
1641
|
-
}
|
|
1642
|
-
const inflight = this.inflight.get(key);
|
|
1643
|
-
if (inflight) {
|
|
1644
|
-
emitFarmEvent({ type: "cache.dedupe", key });
|
|
1645
|
-
return inflight;
|
|
1646
|
-
}
|
|
1647
|
-
const tags = Array.from(normalizeCacheOptionsTags(options));
|
|
1648
|
-
const generation = this.generation;
|
|
1649
|
-
const promise = this.fillCacheEntry(key, producer, options, tags, generation).catch((error) => {
|
|
1650
|
-
emitFarmEvent({ type: "cache.error", key, operation: "set", error });
|
|
1651
|
-
throw error;
|
|
1652
|
-
}).finally(() => {
|
|
1653
|
-
if (this.inflight.get(key) === promise) {
|
|
1654
|
-
this.inflight.delete(key);
|
|
1655
|
-
}
|
|
1656
|
-
});
|
|
1657
|
-
this.inflight.set(key, promise);
|
|
1658
|
-
return promise;
|
|
1659
|
-
}
|
|
1660
|
-
async fillCacheEntry(key, producer, options, tags, generation) {
|
|
1661
|
-
const adapter = this.adapter;
|
|
1662
|
-
const namespace = this.namespace;
|
|
1663
|
-
const lease = { ...this.lease };
|
|
1664
|
-
const leaseKey = `${namespace}:lease:${key}`;
|
|
1665
|
-
let leaseToken;
|
|
1666
|
-
if (adapter?.acquireLease && adapter.releaseLease && lease.enabled) {
|
|
1667
|
-
leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);
|
|
1668
|
-
if (!leaseToken) {
|
|
1669
|
-
const shared2 = await this.waitForAdapterEntry(
|
|
1670
|
-
key,
|
|
1671
|
-
adapter,
|
|
1672
|
-
namespace,
|
|
1673
|
-
lease,
|
|
1674
|
-
generation
|
|
1675
|
-
);
|
|
1676
|
-
if (shared2) {
|
|
1677
|
-
emitFarmEvent({ type: "cache.dedupe", key });
|
|
1678
|
-
return shared2.value;
|
|
1679
|
-
}
|
|
1680
|
-
if (generation === this.generation) {
|
|
1681
|
-
leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);
|
|
1682
|
-
}
|
|
1683
|
-
}
|
|
1684
|
-
}
|
|
1685
|
-
const initialCreatedVersion = this.version;
|
|
1686
|
-
const activeGeneration = {
|
|
1687
|
-
tags: new Set(tags),
|
|
1688
|
-
createdVersion: initialCreatedVersion
|
|
1689
|
-
};
|
|
1690
|
-
this.activeGenerations.add(activeGeneration);
|
|
1691
|
-
try {
|
|
1692
|
-
const initialTagVersions = await this.getAdapterTagVersions(tags, adapter, namespace);
|
|
1693
|
-
const value = await producer();
|
|
1694
|
-
if (generation === this.generation) {
|
|
1695
|
-
await this.writeAsync(key, value, options, initialTagVersions, initialCreatedVersion);
|
|
1696
|
-
}
|
|
1697
|
-
return value;
|
|
1698
|
-
} finally {
|
|
1699
|
-
this.activeGenerations.delete(activeGeneration);
|
|
1700
|
-
this.pruneInvalidatedTagVersions();
|
|
1701
|
-
if (leaseToken && adapter?.releaseLease) {
|
|
1702
|
-
try {
|
|
1703
|
-
await adapter.releaseLease(leaseKey, leaseToken);
|
|
1704
|
-
} catch (error) {
|
|
1705
|
-
emitFarmEvent({ type: "cache.error", key, operation: "set", error });
|
|
1706
|
-
}
|
|
1707
|
-
}
|
|
1708
|
-
}
|
|
1709
|
-
}
|
|
1710
|
-
async waitForAdapterEntry(key, adapter, namespace, lease, generation) {
|
|
1711
|
-
const deadline = Date.now() + lease.waitTimeoutMs;
|
|
1712
|
-
while (Date.now() < deadline) {
|
|
1713
|
-
await delay(lease.pollIntervalMs);
|
|
1714
|
-
if (generation !== this.generation) return void 0;
|
|
1715
|
-
const entry = await adapter.get(`${namespace}:entry:${key}`);
|
|
1716
|
-
if (generation !== this.generation) return void 0;
|
|
1717
|
-
if (!entry) {
|
|
1718
|
-
emitFarmEvent({ type: "cache.miss", key });
|
|
1719
|
-
continue;
|
|
1720
|
-
}
|
|
1721
|
-
assertFarmCacheEntry(entry, key);
|
|
1722
|
-
const stale = await this.isAdapterEntryStale(entry, Date.now(), adapter, namespace);
|
|
1723
|
-
if (generation !== this.generation) return void 0;
|
|
1724
|
-
if (stale) {
|
|
1725
|
-
emitFarmEvent({
|
|
1726
|
-
type: "cache.stale",
|
|
1727
|
-
key,
|
|
1728
|
-
tags: [...entry.tags],
|
|
1729
|
-
revalidate: entry.revalidate
|
|
1730
|
-
});
|
|
1731
|
-
emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
|
|
1732
|
-
} else {
|
|
1733
|
-
emitFarmEvent({
|
|
1734
|
-
type: "cache.hit",
|
|
1735
|
-
key,
|
|
1736
|
-
tags: [...entry.tags],
|
|
1737
|
-
revalidate: entry.revalidate,
|
|
1738
|
-
stale: false
|
|
1739
|
-
});
|
|
1740
|
-
return { ...entry, key };
|
|
1741
|
-
}
|
|
1742
|
-
}
|
|
1743
|
-
return void 0;
|
|
1744
|
-
}
|
|
1745
|
-
countEntriesForTag(tag) {
|
|
1746
|
-
let count = 0;
|
|
1747
|
-
for (const entry of this.entries.values()) {
|
|
1748
|
-
if (entry.tags.has(tag)) {
|
|
1749
|
-
count++;
|
|
1750
|
-
}
|
|
1751
|
-
}
|
|
1752
|
-
return count;
|
|
1753
|
-
}
|
|
1754
|
-
countEntriesForTags(tags) {
|
|
1755
|
-
let count = 0;
|
|
1756
|
-
for (const entry of this.entries.values()) {
|
|
1757
|
-
if (tags.every((tag) => entry.tags.has(tag))) {
|
|
1758
|
-
count++;
|
|
1759
|
-
}
|
|
1760
|
-
}
|
|
1761
|
-
return count;
|
|
1762
|
-
}
|
|
1763
|
-
invalidateTag(normalizedTag) {
|
|
1764
|
-
const count = this.countEntriesForTag(normalizedTag);
|
|
1765
|
-
this.invalidatedTagVersions.delete(normalizedTag);
|
|
1766
|
-
this.invalidatedTagVersions.set(normalizedTag, ++this.version);
|
|
1767
|
-
this.pruneInvalidatedTagVersions();
|
|
1768
|
-
return count;
|
|
1769
|
-
}
|
|
1770
|
-
toPublicEntry(entry) {
|
|
1771
|
-
return {
|
|
1772
|
-
key: entry.key,
|
|
1773
|
-
value: entry.value,
|
|
1774
|
-
tags: Array.from(entry.tags),
|
|
1775
|
-
tagVersions: entry.tagVersions,
|
|
1776
|
-
createdAt: entry.createdAt,
|
|
1777
|
-
createdVersion: entry.createdVersion,
|
|
1778
|
-
revalidate: entry.revalidate
|
|
1779
|
-
};
|
|
1780
|
-
}
|
|
1781
|
-
hydrateLocalEntry(entry) {
|
|
1782
|
-
this.storeLocalEntry({
|
|
1783
|
-
key: entry.key,
|
|
1784
|
-
value: entry.value,
|
|
1785
|
-
tags: new Set(entry.tags.map(normalizeCacheTag)),
|
|
1786
|
-
tagVersions: entry.tagVersions,
|
|
1787
|
-
createdAt: entry.createdAt,
|
|
1788
|
-
createdVersion: entry.createdVersion ?? ++this.version,
|
|
1789
|
-
revalidate: normalizeRevalidate(entry.revalidate)
|
|
1790
|
-
});
|
|
1791
|
-
}
|
|
1792
|
-
touchEntry(key, entry) {
|
|
1793
|
-
this.entries.delete(key);
|
|
1794
|
-
this.entries.set(key, entry);
|
|
1795
|
-
}
|
|
1796
|
-
storeLocalEntry(entry) {
|
|
1797
|
-
this.entries.delete(entry.key);
|
|
1798
|
-
this.entries.set(entry.key, entry);
|
|
1799
|
-
while (this.entries.size > this.maxEntries) {
|
|
1800
|
-
const oldestKey = this.entries.keys().next().value;
|
|
1801
|
-
if (oldestKey === void 0) break;
|
|
1802
|
-
this.entries.delete(oldestKey);
|
|
1803
|
-
}
|
|
1804
|
-
this.pruneInvalidatedTagVersions();
|
|
1805
|
-
}
|
|
1806
|
-
pruneInvalidatedTagVersions() {
|
|
1807
|
-
tags: for (const [tag, invalidatedVersion] of this.invalidatedTagVersions) {
|
|
1808
|
-
for (const entry of this.entries.values()) {
|
|
1809
|
-
if (entry.tags.has(tag) && entry.createdVersion < invalidatedVersion) continue tags;
|
|
1810
|
-
}
|
|
1811
|
-
for (const generation of this.activeGenerations) {
|
|
1812
|
-
if (generation.tags.has(tag) && generation.createdVersion < invalidatedVersion)
|
|
1813
|
-
continue tags;
|
|
1814
|
-
}
|
|
1815
|
-
this.invalidatedTagVersions.delete(tag);
|
|
1816
|
-
}
|
|
1817
|
-
}
|
|
1818
|
-
createAdapterKey(key) {
|
|
1819
|
-
return `${this.namespace}:entry:${key}`;
|
|
1820
|
-
}
|
|
1821
|
-
createAdapterTag(tag) {
|
|
1822
|
-
return `${this.namespace}:tag:${tag}`;
|
|
1823
|
-
}
|
|
1824
|
-
async getAdapterTagVersions(tags, adapter = this.adapter, namespace = this.namespace) {
|
|
1825
|
-
if (!adapter?.getTagVersions || tags.length === 0) return {};
|
|
1826
|
-
const normalized = tags.map(normalizeCacheTag);
|
|
1827
|
-
const physicalTags = normalized.map((tag) => `${namespace}:tag:${tag}`);
|
|
1828
|
-
const versions = await adapter.getTagVersions(physicalTags);
|
|
1829
|
-
return Object.fromEntries(
|
|
1830
|
-
normalized.map((tag, index) => [
|
|
1831
|
-
tag,
|
|
1832
|
-
normalizeAdapterVersion(versions[physicalTags[index]])
|
|
1833
|
-
])
|
|
1834
|
-
);
|
|
1835
|
-
}
|
|
1836
|
-
async isAdapterEntryStale(entry, now = Date.now(), adapter = this.adapter, namespace = this.namespace) {
|
|
1837
|
-
if (typeof entry.revalidate === "number" && entry.revalidate >= 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
|
|
1838
|
-
return true;
|
|
1839
|
-
}
|
|
1840
|
-
const currentVersions = await this.getAdapterTagVersions(entry.tags, adapter, namespace);
|
|
1841
|
-
for (const tag of entry.tags) {
|
|
1842
|
-
if (normalizeAdapterVersion(currentVersions[tag]) > normalizeAdapterVersion(entry.tagVersions?.[tag])) {
|
|
1843
|
-
return true;
|
|
1844
|
-
}
|
|
1845
|
-
}
|
|
1846
|
-
return false;
|
|
1847
|
-
}
|
|
1848
|
-
};
|
|
1849
|
-
__name(_FarmDataCache, "FarmDataCache");
|
|
1850
|
-
var FarmDataCache = _FarmDataCache;
|
|
1851
|
-
var FARM_DATA_CACHE_SYMBOL = /* @__PURE__ */ Symbol.for("farm.dataCache");
|
|
1852
|
-
var farmDataCacheGlobal = globalThis;
|
|
1853
|
-
var sharedFarmDataCache = farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] ?? (farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] = new FarmDataCache());
|
|
1854
|
-
function createPathCacheTag(routePath) {
|
|
1855
|
-
return `path:${normalizeRevalidatePath(routePath)}`;
|
|
1856
|
-
}
|
|
1857
|
-
__name(createPathCacheTag, "createPathCacheTag");
|
|
1858
|
-
function createRouteDataCacheKey(key) {
|
|
1859
|
-
return createFarmCacheKey(Array.isArray(key) ? key : [key]);
|
|
1860
|
-
}
|
|
1861
|
-
__name(createRouteDataCacheKey, "createRouteDataCacheKey");
|
|
1862
|
-
function normalizeRevalidatePath(routePath) {
|
|
1863
|
-
if (typeof routePath !== "string") {
|
|
1864
|
-
throw new TypeError("revalidatePath expects a path string.");
|
|
1865
|
-
}
|
|
1866
|
-
let normalized = routePath.trim();
|
|
1867
|
-
if (!normalized) {
|
|
1868
|
-
throw new Error("revalidatePath expects a non-empty path.");
|
|
1869
|
-
}
|
|
1870
|
-
try {
|
|
1871
|
-
if (/^https?:\/\//i.test(normalized)) {
|
|
1872
|
-
normalized = new URL(normalized).pathname;
|
|
1873
|
-
}
|
|
1874
|
-
} catch {
|
|
1875
|
-
}
|
|
1876
|
-
normalized = normalized.split(/[?#]/, 1)[0] ?? normalized;
|
|
1877
|
-
normalized = normalized.startsWith("/") ? normalized : `/${normalized}`;
|
|
1878
|
-
normalized = normalized.replace(/\/{2,}/g, "/");
|
|
1879
|
-
normalized = new URL(normalized, "http://farm.invalid").pathname;
|
|
1880
|
-
if (normalized.length > 1) {
|
|
1881
|
-
normalized = normalized.replace(/\/+$/, "");
|
|
1882
|
-
}
|
|
1883
|
-
return normalized || "/";
|
|
1884
|
-
}
|
|
1885
|
-
__name(normalizeRevalidatePath, "normalizeRevalidatePath");
|
|
1886
|
-
function createFarmCacheKey(parts) {
|
|
1887
|
-
return stableSerialize(parts);
|
|
1888
|
-
}
|
|
1889
|
-
__name(createFarmCacheKey, "createFarmCacheKey");
|
|
1890
|
-
function normalizeRevalidate(revalidate) {
|
|
1891
|
-
if (revalidate === false || revalidate === void 0) {
|
|
1892
|
-
return revalidate;
|
|
1893
|
-
}
|
|
1894
|
-
if (!Number.isFinite(revalidate) || revalidate < 0) {
|
|
1895
|
-
throw new TypeError("Cache revalidate must be false or a finite, non-negative number.");
|
|
1896
|
-
}
|
|
1897
|
-
return revalidate;
|
|
1898
|
-
}
|
|
1899
|
-
__name(normalizeRevalidate, "normalizeRevalidate");
|
|
1900
|
-
function normalizeCacheTag(tag) {
|
|
1901
|
-
if (typeof tag !== "string") {
|
|
1902
|
-
throw new TypeError("Cache tags must be strings.");
|
|
1903
|
-
}
|
|
1904
|
-
const normalized = tag.trim();
|
|
1905
|
-
if (!normalized) {
|
|
1906
|
-
throw new Error("Cache tags cannot be empty.");
|
|
1907
|
-
}
|
|
1908
|
-
return normalized;
|
|
1909
|
-
}
|
|
1910
|
-
__name(normalizeCacheTag, "normalizeCacheTag");
|
|
1911
|
-
function normalizeCacheNamespace(namespace) {
|
|
1912
|
-
if (typeof namespace !== "string") {
|
|
1913
|
-
throw new TypeError("Cache namespace must be a string.");
|
|
1914
|
-
}
|
|
1915
|
-
const normalized = namespace.trim().replace(/:+$/g, "");
|
|
1916
|
-
if (!normalized) {
|
|
1917
|
-
throw new Error("Cache namespace cannot be empty.");
|
|
1918
|
-
}
|
|
1919
|
-
return normalized;
|
|
1920
|
-
}
|
|
1921
|
-
__name(normalizeCacheNamespace, "normalizeCacheNamespace");
|
|
1922
|
-
function normalizeAdapterVersion(value) {
|
|
1923
|
-
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
|
|
1924
|
-
}
|
|
1925
|
-
__name(normalizeAdapterVersion, "normalizeAdapterVersion");
|
|
1926
|
-
function normalizePositiveDuration(value, fallback, name) {
|
|
1927
|
-
if (value === void 0) return fallback;
|
|
1928
|
-
if (!Number.isFinite(value) || value <= 0) {
|
|
1929
|
-
throw new TypeError(`${name} must be a positive number of milliseconds.`);
|
|
1930
|
-
}
|
|
1931
|
-
return Math.floor(value);
|
|
1932
|
-
}
|
|
1933
|
-
__name(normalizePositiveDuration, "normalizePositiveDuration");
|
|
1934
|
-
function normalizePositiveInteger(value, fallback, name) {
|
|
1935
|
-
if (value === void 0) return fallback;
|
|
1936
|
-
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
1937
|
-
throw new TypeError(`${name} must be a positive integer.`);
|
|
1938
|
-
}
|
|
1939
|
-
return value;
|
|
1940
|
-
}
|
|
1941
|
-
__name(normalizePositiveInteger, "normalizePositiveInteger");
|
|
1942
|
-
function delay(ms) {
|
|
1943
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1944
|
-
}
|
|
1945
|
-
__name(delay, "delay");
|
|
1946
|
-
function normalizeCacheOptionsTags(options) {
|
|
1947
|
-
const tags = /* @__PURE__ */ new Set();
|
|
1948
|
-
for (const tag of options.tags ?? []) {
|
|
1949
|
-
tags.add(normalizeCacheTag(tag));
|
|
1950
|
-
}
|
|
1951
|
-
for (const routePath of options.paths ?? []) {
|
|
1952
|
-
tags.add(createPathCacheTag(routePath));
|
|
1953
|
-
}
|
|
1954
|
-
return tags;
|
|
1955
|
-
}
|
|
1956
|
-
__name(normalizeCacheOptionsTags, "normalizeCacheOptionsTags");
|
|
1957
|
-
function assertFarmCacheEntry(entry, expectedKey) {
|
|
1958
|
-
if (!entry || typeof entry !== "object" || entry.key !== expectedKey || !Array.isArray(entry.tags) || typeof entry.createdAt !== "number") {
|
|
1959
|
-
throw new TypeError(
|
|
1960
|
-
`Cache adapter returned an invalid entry for ${JSON.stringify(expectedKey)}.`
|
|
1961
|
-
);
|
|
1962
|
-
}
|
|
1963
|
-
}
|
|
1964
|
-
__name(assertFarmCacheEntry, "assertFarmCacheEntry");
|
|
1965
|
-
function getFunctionCacheIdentity(fn) {
|
|
1966
|
-
const name = fn.name || "anonymous";
|
|
1967
|
-
return `${name}:${hashFunctionSource(String(fn))}`;
|
|
1968
|
-
}
|
|
1969
|
-
__name(getFunctionCacheIdentity, "getFunctionCacheIdentity");
|
|
1970
|
-
function hashFunctionSource(source) {
|
|
1971
|
-
let hash = 2166136261;
|
|
1972
|
-
for (let index = 0; index < source.length; index++) {
|
|
1973
|
-
hash ^= source.charCodeAt(index);
|
|
1974
|
-
hash = Math.imul(hash, 16777619);
|
|
1975
|
-
}
|
|
1976
|
-
return (hash >>> 0).toString(36);
|
|
1977
|
-
}
|
|
1978
|
-
__name(hashFunctionSource, "hashFunctionSource");
|
|
1979
|
-
function compareCodepoint(a, b) {
|
|
1980
|
-
return a < b ? -1 : a > b ? 1 : 0;
|
|
1981
|
-
}
|
|
1982
|
-
__name(compareCodepoint, "compareCodepoint");
|
|
1983
|
-
function serializeBinaryBytes(bytes) {
|
|
1984
|
-
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
1985
|
-
}
|
|
1986
|
-
__name(serializeBinaryBytes, "serializeBinaryBytes");
|
|
1987
|
-
function serializeCanonicalStringEntries(entries, seen) {
|
|
1988
|
-
const valuesByKey = /* @__PURE__ */ new Map();
|
|
1989
|
-
for (const [key, item] of entries) {
|
|
1990
|
-
const values = valuesByKey.get(key);
|
|
1991
|
-
if (values) values.push(item);
|
|
1992
|
-
else valuesByKey.set(key, [item]);
|
|
1993
|
-
}
|
|
1994
|
-
return Array.from(valuesByKey.keys()).sort(compareCodepoint).flatMap(
|
|
1995
|
-
(key) => valuesByKey.get(key).map((item) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`)
|
|
1996
|
-
).join(",");
|
|
1997
|
-
}
|
|
1998
|
-
__name(serializeCanonicalStringEntries, "serializeCanonicalStringEntries");
|
|
1999
|
-
function isPlainCacheKeyObject(value) {
|
|
2000
|
-
const prototype = Object.getPrototypeOf(value);
|
|
2001
|
-
if (prototype === null) return true;
|
|
2002
|
-
const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
|
|
2003
|
-
return Object.getPrototypeOf(prototype) === null && typeof constructor === "function" && constructor.name === "Object";
|
|
2004
|
-
}
|
|
2005
|
-
__name(isPlainCacheKeyObject, "isPlainCacheKeyObject");
|
|
2006
|
-
function getCacheKeyValueType(value) {
|
|
2007
|
-
const prototype = Object.getPrototypeOf(value);
|
|
2008
|
-
const constructor = prototype ? Object.getOwnPropertyDescriptor(prototype, "constructor")?.value : void 0;
|
|
2009
|
-
if (typeof constructor === "function" && constructor.name) {
|
|
2010
|
-
return constructor.name;
|
|
2011
|
-
}
|
|
2012
|
-
return Object.prototype.toString.call(value).slice(8, -1) || "object";
|
|
2013
|
-
}
|
|
2014
|
-
__name(getCacheKeyValueType, "getCacheKeyValueType");
|
|
2015
|
-
function stableSerialize(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
2016
|
-
if (value === null) return "null";
|
|
2017
|
-
if (value === void 0) return "undefined";
|
|
2018
|
-
const valueType = typeof value;
|
|
2019
|
-
if (valueType === "string") return JSON.stringify(value);
|
|
2020
|
-
if (valueType === "number" || valueType === "boolean" || valueType === "bigint") {
|
|
2021
|
-
return `${valueType}:${String(value)}`;
|
|
2022
|
-
}
|
|
2023
|
-
if (valueType === "symbol") {
|
|
2024
|
-
return `symbol:${String(value)}`;
|
|
2025
|
-
}
|
|
2026
|
-
if (valueType === "function") {
|
|
2027
|
-
return `function:${getFunctionCacheIdentity(value)}`;
|
|
2028
|
-
}
|
|
2029
|
-
if (value instanceof Date) {
|
|
2030
|
-
return Number.isNaN(value.getTime()) ? "date:invalid" : `date:${value.toISOString()}`;
|
|
2031
|
-
}
|
|
2032
|
-
if (value instanceof URL) {
|
|
2033
|
-
return `url:${value.toString()}`;
|
|
2034
|
-
}
|
|
2035
|
-
if (value instanceof RegExp) {
|
|
2036
|
-
return `regexp:${value.toString()}`;
|
|
2037
|
-
}
|
|
2038
|
-
if (value instanceof ArrayBuffer) {
|
|
2039
|
-
return `arraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;
|
|
2040
|
-
}
|
|
2041
|
-
if (typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer) {
|
|
2042
|
-
return `sharedarraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;
|
|
2043
|
-
}
|
|
2044
|
-
if (ArrayBuffer.isView(value)) {
|
|
2045
|
-
const viewType = Object.prototype.toString.call(value).slice(8, -1);
|
|
2046
|
-
const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
2047
|
-
return `binary:${viewType}:${serializeBinaryBytes(bytes)}`;
|
|
2048
|
-
}
|
|
2049
|
-
if (value && typeof value === "object") {
|
|
2050
|
-
if (seen.has(value)) {
|
|
2051
|
-
return "[Circular]";
|
|
2052
|
-
}
|
|
2053
|
-
seen.add(value);
|
|
2054
|
-
if (Array.isArray(value)) {
|
|
2055
|
-
const items = [];
|
|
2056
|
-
for (let index = 0; index < value.length; index++) {
|
|
2057
|
-
items.push(
|
|
2058
|
-
Object.prototype.hasOwnProperty.call(value, index) ? stableSerialize(value[index], seen) : "[Hole]"
|
|
2059
|
-
);
|
|
2060
|
-
}
|
|
2061
|
-
seen.delete(value);
|
|
2062
|
-
return `[${items.join(",")}]`;
|
|
2063
|
-
}
|
|
2064
|
-
if (value instanceof Set) {
|
|
2065
|
-
const items = Array.from(value, (item) => stableSerialize(item, seen)).sort(compareCodepoint);
|
|
2066
|
-
seen.delete(value);
|
|
2067
|
-
return `set:[${items.join(",")}]`;
|
|
2068
|
-
}
|
|
2069
|
-
if (value instanceof Map) {
|
|
2070
|
-
const items = Array.from(
|
|
2071
|
-
value,
|
|
2072
|
-
([key, item]) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`
|
|
2073
|
-
).sort(compareCodepoint);
|
|
2074
|
-
seen.delete(value);
|
|
2075
|
-
return `map:[${items.join(",")}]`;
|
|
2076
|
-
}
|
|
2077
|
-
if (value instanceof URLSearchParams) {
|
|
2078
|
-
const serialized2 = serializeCanonicalStringEntries(value, seen);
|
|
2079
|
-
seen.delete(value);
|
|
2080
|
-
return `urlsearchparams:[${serialized2}]`;
|
|
2081
|
-
}
|
|
2082
|
-
if (value instanceof Headers) {
|
|
2083
|
-
const serialized2 = serializeCanonicalStringEntries(value, seen);
|
|
2084
|
-
seen.delete(value);
|
|
2085
|
-
return `headers:[${serialized2}]`;
|
|
2086
|
-
}
|
|
2087
|
-
if (!isPlainCacheKeyObject(value)) {
|
|
2088
|
-
throw new TypeError(
|
|
2089
|
-
`Cache keys do not support ${getCacheKeyValueType(value)} values. Convert the value to an explicit stable string or structured key before caching.`
|
|
2090
|
-
);
|
|
2091
|
-
}
|
|
2092
|
-
const entries = Object.entries(value).sort(
|
|
2093
|
-
([a], [b]) => compareCodepoint(a, b)
|
|
2094
|
-
);
|
|
2095
|
-
const serialized = entries.map(([key, item]) => `${JSON.stringify(key)}:${stableSerialize(item, seen)}`).join(",");
|
|
2096
|
-
seen.delete(value);
|
|
2097
|
-
return `{${serialized}}`;
|
|
2098
|
-
}
|
|
2099
|
-
return String(value);
|
|
2100
|
-
}
|
|
2101
|
-
__name(stableSerialize, "stableSerialize");
|
|
2102
|
-
|
|
2103
|
-
// src/client-cache.ts
|
|
2104
|
-
var invalidationTrackers = /* @__PURE__ */ new WeakMap();
|
|
2105
|
-
var cacheFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((unsubscribe) => unsubscribe()) : void 0;
|
|
2106
|
-
var DEFAULT_GC_SWEEP_INTERVAL_MS = 3e4;
|
|
2107
|
-
var _FarmClientDataCache = class _FarmClientDataCache {
|
|
2108
|
-
constructor(options = {}) {
|
|
2109
|
-
this.entries = /* @__PURE__ */ new Map();
|
|
2110
|
-
this.aliases = /* @__PURE__ */ new Map();
|
|
2111
|
-
this.aliasesByTarget = /* @__PURE__ */ new Map();
|
|
2112
|
-
this.invalidatedAt = /* @__PURE__ */ new Map();
|
|
2113
|
-
this.listeners = /* @__PURE__ */ new Map();
|
|
2114
|
-
this.inflight = /* @__PURE__ */ new Map();
|
|
2115
|
-
this.pendingMetadataSweeps = /* @__PURE__ */ new Set();
|
|
2116
|
-
this.gcSweepIntervalMs = options.gcSweepIntervalMs ?? DEFAULT_GC_SWEEP_INTERVAL_MS;
|
|
2117
|
-
if (options.subscribeToInvalidation !== false) {
|
|
2118
|
-
if (typeof WeakRef === "function") {
|
|
2119
|
-
const reference = new WeakRef(this);
|
|
2120
|
-
const unsubscribe = _FarmClientDataCache.subscribeWeakCache(reference);
|
|
2121
|
-
cacheFinalizer?.register(this, unsubscribe, reference);
|
|
2122
|
-
this.unsubscribeInvalidation = unsubscribe;
|
|
2123
|
-
} else {
|
|
2124
|
-
this.unsubscribeInvalidation = subscribeFarmCacheInvalidation(
|
|
2125
|
-
(key) => this.applyInvalidation(key, Date.now(), false)
|
|
2126
|
-
);
|
|
2127
|
-
}
|
|
2128
|
-
}
|
|
2129
|
-
}
|
|
2130
|
-
// This closure must only capture a weak reference, never the cache itself.
|
|
2131
|
-
static subscribeWeakCache(reference) {
|
|
2132
|
-
const unsubscribe = subscribeFarmCacheInvalidation((key) => {
|
|
2133
|
-
const cache = reference.deref();
|
|
2134
|
-
if (cache) cache.applyInvalidation(key, Date.now(), false);
|
|
2135
|
-
else dispose();
|
|
2136
|
-
});
|
|
2137
|
-
function dispose() {
|
|
2138
|
-
unsubscribe();
|
|
2139
|
-
cacheFinalizer?.unregister(reference);
|
|
2140
|
-
}
|
|
2141
|
-
__name(dispose, "dispose");
|
|
2142
|
-
return dispose;
|
|
2143
|
-
}
|
|
2144
|
-
get size() {
|
|
2145
|
-
return this.entries.size;
|
|
2146
|
-
}
|
|
2147
|
-
/** @internal Attach or detach the persistence engine's observation sink. */
|
|
2148
|
-
attachPersistence(sink) {
|
|
2149
|
-
this.persistence = sink;
|
|
2150
|
-
}
|
|
2151
|
-
resolveKey(key) {
|
|
2152
|
-
let resolved = key;
|
|
2153
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2154
|
-
while (this.aliases.has(resolved) && !seen.has(resolved)) {
|
|
2155
|
-
seen.add(resolved);
|
|
2156
|
-
resolved = this.aliases.get(resolved);
|
|
2157
|
-
}
|
|
2158
|
-
return resolved;
|
|
2159
|
-
}
|
|
2160
|
-
get(key, now = Date.now()) {
|
|
2161
|
-
const resolved = this.resolveKey(key);
|
|
2162
|
-
const entry = this.entries.get(resolved);
|
|
2163
|
-
if (!entry) return void 0;
|
|
2164
|
-
if (entry.gcAt !== void 0 && now >= entry.gcAt) {
|
|
2165
|
-
if (entry.fetching) return void 0;
|
|
2166
|
-
this.entries.delete(resolved);
|
|
2167
|
-
this.persistence?.onDelete(resolved);
|
|
2168
|
-
this.sweepEntryMetadata(/* @__PURE__ */ new Set([resolved]));
|
|
2169
|
-
this.emit(resolved);
|
|
2170
|
-
return void 0;
|
|
2171
|
-
}
|
|
2172
|
-
return entry;
|
|
2173
|
-
}
|
|
2174
|
-
set(key, entry) {
|
|
2175
|
-
const resolved = this.resolveKey(key);
|
|
2176
|
-
const invalidatedAt = this.invalidatedAt.get(resolved);
|
|
2177
|
-
const nextEntry = invalidatedAt !== void 0 && invalidatedAt > entry.updatedAt ? { ...entry, staleAt: 0, invalidatedAt } : { ...entry, invalidatedAt: void 0 };
|
|
2178
|
-
if (invalidatedAt === void 0 || entry.updatedAt >= invalidatedAt) {
|
|
2179
|
-
this.invalidatedAt.delete(resolved);
|
|
2180
|
-
}
|
|
2181
|
-
this.entries.set(resolved, nextEntry);
|
|
2182
|
-
this.pendingMetadataSweeps.delete(resolved);
|
|
2183
|
-
if (nextEntry.gcAt !== void 0) this.scheduleGcSweep();
|
|
2184
|
-
this.persistence?.onSet(resolved, nextEntry);
|
|
2185
|
-
this.emit(resolved);
|
|
2186
|
-
return this;
|
|
2187
|
-
}
|
|
2188
|
-
delete(key) {
|
|
2189
|
-
const resolved = this.resolveKey(key);
|
|
2190
|
-
const deleted = this.entries.delete(resolved);
|
|
2191
|
-
this.inflight.delete(resolved);
|
|
2192
|
-
if (deleted) this.persistence?.onDelete(resolved);
|
|
2193
|
-
if (deleted || this.pendingMetadataSweeps.has(resolved)) {
|
|
2194
|
-
this.sweepEntryMetadata(/* @__PURE__ */ new Set([resolved]));
|
|
2195
|
-
}
|
|
2196
|
-
this.emit(resolved);
|
|
2197
|
-
return deleted;
|
|
2198
|
-
}
|
|
2199
|
-
clear() {
|
|
2200
|
-
const keys = /* @__PURE__ */ new Set([...this.entries.keys(), ...this.listeners.keys()]);
|
|
2201
|
-
this.entries.clear();
|
|
2202
|
-
this.aliases.clear();
|
|
2203
|
-
this.aliasesByTarget.clear();
|
|
2204
|
-
this.invalidatedAt.clear();
|
|
2205
|
-
this.inflight.clear();
|
|
2206
|
-
this.pendingMetadataSweeps.clear();
|
|
2207
|
-
this.persistence?.onClear();
|
|
2208
|
-
for (const key of keys) this.emit(key);
|
|
2209
|
-
}
|
|
2210
|
-
dispose() {
|
|
2211
|
-
this.unsubscribeInvalidation?.();
|
|
2212
|
-
this.unsubscribeInvalidation = void 0;
|
|
2213
|
-
if (this.gcTimer !== void 0) {
|
|
2214
|
-
clearTimeout(this.gcTimer);
|
|
2215
|
-
this.gcTimer = void 0;
|
|
2216
|
-
}
|
|
2217
|
-
this.clear();
|
|
2218
|
-
}
|
|
2219
|
-
isStale(key, now = Date.now()) {
|
|
2220
|
-
const entry = this.get(key, now);
|
|
2221
|
-
return !entry || entry.invalidatedAt !== void 0 || now >= entry.staleAt;
|
|
2222
|
-
}
|
|
2223
|
-
invalidate(key, now = Date.now()) {
|
|
2224
|
-
this.applyInvalidation(key, now, true);
|
|
2225
|
-
}
|
|
2226
|
-
applyInvalidation(key, now, retainUnowned) {
|
|
2227
|
-
const resolved = this.resolveKey(key);
|
|
2228
|
-
for (const keys of invalidationTrackers.get(this) ?? []) keys.add(resolved);
|
|
2229
|
-
const entry = this.entries.get(resolved);
|
|
2230
|
-
const alreadyRetained = this.invalidatedAt.has(resolved);
|
|
2231
|
-
if (retainUnowned || entry || alreadyRetained || this.hasMetadataOwner(resolved)) {
|
|
2232
|
-
this.invalidatedAt.set(resolved, now);
|
|
2233
|
-
if (!entry && !retainUnowned && !alreadyRetained) this.pendingMetadataSweeps.add(resolved);
|
|
2234
|
-
}
|
|
2235
|
-
if (entry) {
|
|
2236
|
-
this.entries.set(resolved, {
|
|
2237
|
-
...entry,
|
|
2238
|
-
staleAt: 0,
|
|
2239
|
-
invalidatedAt: now
|
|
2240
|
-
});
|
|
2241
|
-
}
|
|
2242
|
-
this.emit(resolved, "invalidate");
|
|
2243
|
-
}
|
|
2244
|
-
hasMetadataOwner(key) {
|
|
2245
|
-
const related = /* @__PURE__ */ new Set([key]);
|
|
2246
|
-
for (const target of related) {
|
|
2247
|
-
if (this.listeners.has(target) || this.inflight.has(target)) return true;
|
|
2248
|
-
for (const alias of this.aliasesByTarget.get(target) ?? []) related.add(alias);
|
|
2249
|
-
}
|
|
2250
|
-
return false;
|
|
2251
|
-
}
|
|
2252
|
-
alias(alias, key) {
|
|
2253
|
-
const resolved = this.resolveKey(key);
|
|
2254
|
-
if (alias === resolved) return;
|
|
2255
|
-
const aliasEntry = this.entries.get(alias);
|
|
2256
|
-
const aliasInvalidatedAt = this.invalidatedAt.get(alias) ?? aliasEntry?.invalidatedAt;
|
|
2257
|
-
const resolvedInvalidatedAt = this.invalidatedAt.get(resolved);
|
|
2258
|
-
if (aliasEntry && !this.entries.has(resolved)) {
|
|
2259
|
-
this.entries.set(resolved, aliasEntry);
|
|
2260
|
-
this.persistence?.onSet(resolved, aliasEntry);
|
|
2261
|
-
}
|
|
2262
|
-
if (this.entries.delete(alias)) this.persistence?.onDelete(alias);
|
|
2263
|
-
this.invalidatedAt.delete(alias);
|
|
2264
|
-
const invalidatedAt = [aliasInvalidatedAt, resolvedInvalidatedAt].reduce(
|
|
2265
|
-
(latest, value) => value === void 0 ? latest : latest === void 0 ? value : Math.max(latest, value),
|
|
2266
|
-
void 0
|
|
2267
|
-
);
|
|
2268
|
-
const resolvedEntry = this.entries.get(resolved);
|
|
2269
|
-
if (invalidatedAt !== void 0 && (!resolvedEntry || invalidatedAt > resolvedEntry.updatedAt)) {
|
|
2270
|
-
this.invalidatedAt.set(resolved, invalidatedAt);
|
|
2271
|
-
if (resolvedEntry) {
|
|
2272
|
-
this.entries.set(resolved, {
|
|
2273
|
-
...resolvedEntry,
|
|
2274
|
-
staleAt: 0,
|
|
2275
|
-
invalidatedAt
|
|
2276
|
-
});
|
|
2277
|
-
}
|
|
2278
|
-
} else if (invalidatedAt !== void 0) {
|
|
2279
|
-
this.invalidatedAt.delete(resolved);
|
|
2280
|
-
if (resolvedEntry?.invalidatedAt !== void 0) {
|
|
2281
|
-
this.entries.set(resolved, { ...resolvedEntry, invalidatedAt: void 0 });
|
|
2282
|
-
}
|
|
2283
|
-
}
|
|
2284
|
-
const aliasInflight = this.inflight.get(alias);
|
|
2285
|
-
if (aliasInflight && !this.inflight.has(resolved)) {
|
|
2286
|
-
this.inflight.set(resolved, aliasInflight);
|
|
2287
|
-
}
|
|
2288
|
-
this.inflight.delete(alias);
|
|
2289
|
-
if (this.pendingMetadataSweeps.delete(alias) && !this.entries.has(resolved)) {
|
|
2290
|
-
this.pendingMetadataSweeps.add(resolved);
|
|
2291
|
-
}
|
|
2292
|
-
const previousTarget = this.aliases.get(alias);
|
|
2293
|
-
if (previousTarget !== resolved) {
|
|
2294
|
-
const previousResolved = previousTarget !== void 0 && this.pendingMetadataSweeps.size > 0 ? this.resolveKey(alias) : void 0;
|
|
2295
|
-
this.removeAlias(alias);
|
|
2296
|
-
this.aliases.set(alias, resolved);
|
|
2297
|
-
let aliases = this.aliasesByTarget.get(resolved);
|
|
2298
|
-
if (!aliases) this.aliasesByTarget.set(resolved, aliases = /* @__PURE__ */ new Set());
|
|
2299
|
-
aliases.add(alias);
|
|
2300
|
-
if (previousResolved !== void 0) this.sweepPendingEntryMetadata(previousResolved);
|
|
2301
|
-
}
|
|
2302
|
-
this.emit(alias);
|
|
2303
|
-
this.emit(resolved, this.invalidatedAt.has(resolved) ? "invalidate" : void 0);
|
|
2304
|
-
}
|
|
2305
|
-
subscribe(key, listener) {
|
|
2306
|
-
let listeners = this.listeners.get(key);
|
|
2307
|
-
if (!listeners) {
|
|
2308
|
-
listeners = /* @__PURE__ */ new Set();
|
|
2309
|
-
this.listeners.set(key, listeners);
|
|
2310
|
-
}
|
|
2311
|
-
listeners.add(listener);
|
|
2312
|
-
return () => {
|
|
2313
|
-
listeners.delete(listener);
|
|
2314
|
-
if (listeners.size === 0 && this.listeners.get(key) === listeners) {
|
|
2315
|
-
this.listeners.delete(key);
|
|
2316
|
-
this.sweepPendingEntryMetadata(key);
|
|
2317
|
-
}
|
|
2318
|
-
};
|
|
2319
|
-
}
|
|
2320
|
-
getInflight(key) {
|
|
2321
|
-
return this.inflight.get(this.resolveKey(key));
|
|
2322
|
-
}
|
|
2323
|
-
setInflight(key, promise) {
|
|
2324
|
-
this.inflight.set(this.resolveKey(key), promise);
|
|
2325
|
-
}
|
|
2326
|
-
deleteInflight(key) {
|
|
2327
|
-
const resolved = this.resolveKey(key);
|
|
2328
|
-
if (this.inflight.delete(resolved)) this.sweepPendingEntryMetadata(resolved);
|
|
2329
|
-
}
|
|
2330
|
-
scheduleGcSweep() {
|
|
2331
|
-
if (this.gcSweepIntervalMs === false || this.gcTimer !== void 0) return;
|
|
2332
|
-
const timer = setTimeout(() => {
|
|
2333
|
-
this.gcTimer = void 0;
|
|
2334
|
-
this.sweepExpiredEntries();
|
|
2335
|
-
}, this.gcSweepIntervalMs);
|
|
2336
|
-
timer.unref?.();
|
|
2337
|
-
this.gcTimer = timer;
|
|
2338
|
-
}
|
|
2339
|
-
sweepExpiredEntries(now = Date.now()) {
|
|
2340
|
-
const watched = /* @__PURE__ */ new Set();
|
|
2341
|
-
for (const key of this.listeners.keys()) watched.add(this.resolveKey(key));
|
|
2342
|
-
let remaining = false;
|
|
2343
|
-
const swept = /* @__PURE__ */ new Set();
|
|
2344
|
-
for (const [key, entry] of this.entries) {
|
|
2345
|
-
if (entry.gcAt === void 0) continue;
|
|
2346
|
-
if (now < entry.gcAt || entry.fetching || this.inflight.has(key) || watched.has(key)) {
|
|
2347
|
-
remaining = true;
|
|
2348
|
-
continue;
|
|
2349
|
-
}
|
|
2350
|
-
this.entries.delete(key);
|
|
2351
|
-
this.persistence?.onDelete(key);
|
|
2352
|
-
swept.add(key);
|
|
2353
|
-
}
|
|
2354
|
-
if (swept.size > 0) this.sweepEntryMetadata(swept);
|
|
2355
|
-
if (remaining) this.scheduleGcSweep();
|
|
2356
|
-
}
|
|
2357
|
-
/**
|
|
2358
|
-
* Entry eviction alone leaves the per-key metadata behind. `invalidatedAt`
|
|
2359
|
-
* marks and provisional aliases are created per query invocation, so with
|
|
2360
|
-
* dynamic keys they accumulate for the lifetime of the page even though the
|
|
2361
|
-
* entries they describe are long gone.
|
|
2362
|
-
*/
|
|
2363
|
-
sweepEntryMetadata(swept) {
|
|
2364
|
-
const protectedKeys = /* @__PURE__ */ new Set();
|
|
2365
|
-
for (const key of swept) if (this.hasMetadataOwner(key)) protectedKeys.add(key);
|
|
2366
|
-
for (const key of swept) {
|
|
2367
|
-
if (this.entries.has(key)) {
|
|
2368
|
-
this.pendingMetadataSweeps.delete(key);
|
|
2369
|
-
} else if (protectedKeys.has(key)) {
|
|
2370
|
-
this.pendingMetadataSweeps.add(key);
|
|
2371
|
-
} else {
|
|
2372
|
-
this.pendingMetadataSweeps.delete(key);
|
|
2373
|
-
this.invalidatedAt.delete(key);
|
|
2374
|
-
}
|
|
2375
|
-
}
|
|
2376
|
-
const related = /* @__PURE__ */ new Set();
|
|
2377
|
-
const targets = new Set(swept);
|
|
2378
|
-
for (const target of targets) {
|
|
2379
|
-
for (const alias of this.aliasesByTarget.get(target) ?? []) {
|
|
2380
|
-
related.add(alias);
|
|
2381
|
-
targets.add(alias);
|
|
2382
|
-
}
|
|
2383
|
-
}
|
|
2384
|
-
const removable = [];
|
|
2385
|
-
for (const alias of related) {
|
|
2386
|
-
if (this.entries.has(alias) || this.listeners.has(alias) || this.inflight.has(alias))
|
|
2387
|
-
continue;
|
|
2388
|
-
const resolved = this.resolveKey(alias);
|
|
2389
|
-
if (!swept.has(resolved)) continue;
|
|
2390
|
-
if (this.entries.has(resolved) || protectedKeys.has(resolved)) continue;
|
|
2391
|
-
removable.push(alias);
|
|
2392
|
-
}
|
|
2393
|
-
for (const alias of removable) {
|
|
2394
|
-
this.removeAlias(alias);
|
|
2395
|
-
this.invalidatedAt.delete(alias);
|
|
2396
|
-
}
|
|
2397
|
-
}
|
|
2398
|
-
removeAlias(alias) {
|
|
2399
|
-
const target = this.aliases.get(alias);
|
|
2400
|
-
if (target === void 0) return;
|
|
2401
|
-
this.aliases.delete(alias);
|
|
2402
|
-
const aliases = this.aliasesByTarget.get(target);
|
|
2403
|
-
aliases?.delete(alias);
|
|
2404
|
-
if (aliases?.size === 0) this.aliasesByTarget.delete(target);
|
|
2405
|
-
}
|
|
2406
|
-
sweepPendingEntryMetadata(key) {
|
|
2407
|
-
if (this.pendingMetadataSweeps.size === 0) return;
|
|
2408
|
-
if (key !== void 0) {
|
|
2409
|
-
const resolved = this.resolveKey(key);
|
|
2410
|
-
if (this.pendingMetadataSweeps.has(resolved)) {
|
|
2411
|
-
this.sweepEntryMetadata(/* @__PURE__ */ new Set([resolved]));
|
|
2412
|
-
}
|
|
2413
|
-
return;
|
|
2414
|
-
}
|
|
2415
|
-
this.sweepEntryMetadata(new Set(this.pendingMetadataSweeps));
|
|
2416
|
-
}
|
|
2417
|
-
emit(key, event) {
|
|
2418
|
-
this.notifyListeners(key, event);
|
|
2419
|
-
if (this.listeners.size === 0) return;
|
|
2420
|
-
for (const [alias, target] of this.aliases) {
|
|
2421
|
-
if (!this.listeners.has(alias)) continue;
|
|
2422
|
-
if (this.resolveKey(target) === key) {
|
|
2423
|
-
this.notifyListeners(alias, event);
|
|
2424
|
-
}
|
|
2425
|
-
}
|
|
2426
|
-
}
|
|
2427
|
-
notifyListeners(key, event) {
|
|
2428
|
-
for (const listener of this.listeners.get(key) ?? []) {
|
|
2429
|
-
try {
|
|
2430
|
-
listener(event);
|
|
2431
|
-
} catch (error) {
|
|
2432
|
-
const detail = error instanceof Error ? error.stack ?? error.message : String(error);
|
|
2433
|
-
console.warn(`[farm:client-cache] cache listener failed: ${detail}`);
|
|
2434
|
-
}
|
|
2435
|
-
}
|
|
2436
|
-
}
|
|
2437
|
-
};
|
|
2438
|
-
__name(_FarmClientDataCache, "FarmClientDataCache");
|
|
2439
|
-
var FarmClientDataCache = _FarmClientDataCache;
|
|
2440
|
-
var FARM_CLIENT_DATA_CACHE = /* @__PURE__ */ Symbol.for("farm.clientDataCache");
|
|
2441
|
-
var clientCacheGlobal = globalThis;
|
|
2442
|
-
var sharedFarmClientDataCache = clientCacheGlobal[FARM_CLIENT_DATA_CACHE] ?? (clientCacheGlobal[FARM_CLIENT_DATA_CACHE] = new FarmClientDataCache());
|
|
2443
|
-
function getFarmClientDataCache() {
|
|
2444
|
-
return sharedFarmClientDataCache;
|
|
2445
|
-
}
|
|
2446
|
-
__name(getFarmClientDataCache, "getFarmClientDataCache");
|
|
2447
|
-
function normalizeFarmClientCacheKey(key) {
|
|
2448
|
-
return typeof key === "string" ? key : createRouteDataCacheKey(key);
|
|
2449
|
-
}
|
|
2450
|
-
__name(normalizeFarmClientCacheKey, "normalizeFarmClientCacheKey");
|
|
2451
|
-
|
|
2452
|
-
// src/routing/specificity.ts
|
|
2453
|
-
var SEGMENT_RANK = {
|
|
2454
|
-
static: 4,
|
|
2455
|
-
dynamic: 3,
|
|
2456
|
-
"catch-all": 1,
|
|
2457
|
-
"optional-catch-all": 0
|
|
2458
|
-
};
|
|
2459
|
-
var ROUTE_END_RANK = 2;
|
|
2460
|
-
function compareRouteSpecificity(left, right) {
|
|
2461
|
-
const length = Math.max(left.length, right.length);
|
|
2462
|
-
for (let index = 0; index < length; index++) {
|
|
2463
|
-
const leftRank = index < left.length ? SEGMENT_RANK[left[index]] : ROUTE_END_RANK;
|
|
2464
|
-
const rightRank = index < right.length ? SEGMENT_RANK[right[index]] : ROUTE_END_RANK;
|
|
2465
|
-
if (leftRank !== rightRank) return rightRank - leftRank;
|
|
2466
|
-
}
|
|
2467
|
-
return 0;
|
|
2468
|
-
}
|
|
2469
|
-
__name(compareRouteSpecificity, "compareRouteSpecificity");
|
|
2470
|
-
|
|
2471
|
-
// src/api/route-pattern.ts
|
|
2472
|
-
var compiledEntries = /* @__PURE__ */ new WeakMap();
|
|
2473
|
-
function matchAPIRoute(routes, pathname) {
|
|
2474
|
-
const exactRoute = routes.get(pathname);
|
|
2475
|
-
if (exactRoute) return { route: exactRoute, params: {} };
|
|
2476
|
-
const normalizedPathname = normalizePathname(pathname);
|
|
2477
|
-
if (normalizedPathname !== pathname) {
|
|
2478
|
-
const normalizedRoute = routes.get(normalizedPathname);
|
|
2479
|
-
if (normalizedRoute) return { route: normalizedRoute, params: {} };
|
|
2480
|
-
}
|
|
2481
|
-
const pathnameSegments = getPathSegments(normalizedPathname).map(decodePathSegment);
|
|
2482
|
-
let bestMatch = null;
|
|
2483
|
-
let bestSpecificity = null;
|
|
2484
|
-
for (const route of routes.values()) {
|
|
2485
|
-
const routePath = route.path;
|
|
2486
|
-
let entry = compiledEntries.get(route);
|
|
2487
|
-
if (!entry || entry.path !== routePath) {
|
|
2488
|
-
entry = compileRouteEntry(routePath);
|
|
2489
|
-
compiledEntries.set(route, entry);
|
|
2490
|
-
}
|
|
2491
|
-
const params = matchRouteEntry(entry, pathnameSegments);
|
|
2492
|
-
if (!params) continue;
|
|
2493
|
-
if (bestSpecificity === null || compareRouteSpecificity(entry.specificity, bestSpecificity) < 0) {
|
|
2494
|
-
bestMatch = { route, params };
|
|
2495
|
-
bestSpecificity = entry.specificity;
|
|
2496
|
-
}
|
|
2497
|
-
}
|
|
2498
|
-
return bestMatch;
|
|
2499
|
-
}
|
|
2500
|
-
__name(matchAPIRoute, "matchAPIRoute");
|
|
2501
|
-
function compileRouteEntry(path) {
|
|
2502
|
-
const segments = getPathSegments(path).map((segment) => {
|
|
2503
|
-
const dynamic = parseDynamicSegment(segment);
|
|
2504
|
-
return dynamic ? { dynamic } : { value: decodePathSegment(segment) };
|
|
2505
|
-
});
|
|
2506
|
-
return {
|
|
2507
|
-
path,
|
|
2508
|
-
segments,
|
|
2509
|
-
specificity: segments.map((segment) => {
|
|
2510
|
-
const dynamic = segment.dynamic;
|
|
2511
|
-
if (!dynamic) return "static";
|
|
2512
|
-
if (!dynamic.catchAll) return "dynamic";
|
|
2513
|
-
return dynamic.optional ? "optional-catch-all" : "catch-all";
|
|
2514
|
-
})
|
|
2515
|
-
};
|
|
2516
|
-
}
|
|
2517
|
-
__name(compileRouteEntry, "compileRouteEntry");
|
|
2518
|
-
function matchRouteEntry(entry, pathnameSegments) {
|
|
2519
|
-
const params = {};
|
|
2520
|
-
let pathIndex = 0;
|
|
2521
|
-
for (const routeSegment of entry.segments) {
|
|
2522
|
-
const dynamicSegment = routeSegment.dynamic;
|
|
2523
|
-
if (dynamicSegment?.catchAll) {
|
|
2524
|
-
const remainingSegments = pathnameSegments.slice(pathIndex);
|
|
2525
|
-
if (remainingSegments.length === 0 && !dynamicSegment.optional) {
|
|
2526
|
-
return null;
|
|
2527
|
-
}
|
|
2528
|
-
if (remainingSegments.length > 0) {
|
|
2529
|
-
params[dynamicSegment.name] = remainingSegments;
|
|
2530
|
-
}
|
|
2531
|
-
pathIndex = pathnameSegments.length;
|
|
2532
|
-
continue;
|
|
2533
|
-
}
|
|
2534
|
-
const pathnameSegment = pathnameSegments[pathIndex];
|
|
2535
|
-
if (pathnameSegment === void 0) {
|
|
2536
|
-
return null;
|
|
2537
|
-
}
|
|
2538
|
-
if (dynamicSegment) {
|
|
2539
|
-
params[dynamicSegment.name] = pathnameSegment;
|
|
2540
|
-
pathIndex++;
|
|
2541
|
-
continue;
|
|
2542
|
-
}
|
|
2543
|
-
if (routeSegment.value !== pathnameSegment) {
|
|
2544
|
-
return null;
|
|
2545
|
-
}
|
|
2546
|
-
pathIndex++;
|
|
2547
|
-
}
|
|
2548
|
-
return pathIndex === pathnameSegments.length ? params : null;
|
|
2549
|
-
}
|
|
2550
|
-
__name(matchRouteEntry, "matchRouteEntry");
|
|
2551
|
-
function getPathSegments(pathname) {
|
|
2552
|
-
return normalizePathname(pathname).split("/").filter((segment) => segment.length > 0);
|
|
2553
|
-
}
|
|
2554
|
-
__name(getPathSegments, "getPathSegments");
|
|
2555
|
-
function normalizePathname(pathname) {
|
|
2556
|
-
if (pathname.length > 1 && pathname.endsWith("/")) {
|
|
2557
|
-
return pathname.replace(/\/+$/, "");
|
|
2558
|
-
}
|
|
2559
|
-
return pathname;
|
|
2560
|
-
}
|
|
2561
|
-
__name(normalizePathname, "normalizePathname");
|
|
2562
|
-
function parseDynamicSegment(segment) {
|
|
2563
|
-
const optionalCatchAll = segment.match(/^\[\[\.\.\.(.+)\]\]$/);
|
|
2564
|
-
if (optionalCatchAll?.[1]) {
|
|
2565
|
-
return { name: optionalCatchAll[1], catchAll: true, optional: true };
|
|
2566
|
-
}
|
|
2567
|
-
const catchAll = segment.match(/^\[\.\.\.(.+)\]$/);
|
|
2568
|
-
if (catchAll?.[1]) {
|
|
2569
|
-
return { name: catchAll[1], catchAll: true, optional: false };
|
|
2570
|
-
}
|
|
2571
|
-
const dynamic = segment.match(/^\[(.+)\]$/);
|
|
2572
|
-
if (dynamic?.[1]) {
|
|
2573
|
-
return { name: dynamic[1], catchAll: false, optional: false };
|
|
2574
|
-
}
|
|
2575
|
-
return null;
|
|
2576
|
-
}
|
|
2577
|
-
__name(parseDynamicSegment, "parseDynamicSegment");
|
|
2578
|
-
function decodePathSegment(segment) {
|
|
2579
|
-
try {
|
|
2580
|
-
return decodeURIComponent(segment);
|
|
2581
|
-
} catch {
|
|
2582
|
-
return segment;
|
|
2583
|
-
}
|
|
2584
|
-
}
|
|
2585
|
-
__name(decodePathSegment, "decodePathSegment");
|
|
2586
|
-
|
|
2587
|
-
// src/api/client-routes.ts
|
|
2588
|
-
var _ClientRouteManifest = class _ClientRouteManifest {
|
|
2589
|
-
constructor(routes) {
|
|
2590
|
-
this.candidates = /* @__PURE__ */ new Map();
|
|
2591
|
-
this.nextSegments = /* @__PURE__ */ new Map();
|
|
2592
|
-
this.routes = new Map(
|
|
2593
|
-
routes.map((route) => [
|
|
2594
|
-
route.path.replace(/\/$/, ""),
|
|
2595
|
-
{
|
|
2596
|
-
path: route.path.replace(/\/$/, ""),
|
|
2597
|
-
methods: [...route.methods]
|
|
2598
|
-
}
|
|
2599
|
-
])
|
|
2600
|
-
);
|
|
2601
|
-
const addCandidate = /* @__PURE__ */ __name((path, route) => {
|
|
2602
|
-
let candidates = this.candidates.get(path);
|
|
2603
|
-
if (!candidates) this.candidates.set(path, candidates = []);
|
|
2604
|
-
candidates.push(route);
|
|
2605
|
-
}, "addCandidate");
|
|
2606
|
-
for (const route of this.routes.values()) {
|
|
2607
|
-
addCandidate(route.path, route);
|
|
2608
|
-
const segments = route.path.split("/");
|
|
2609
|
-
let parent = "";
|
|
2610
|
-
for (let i = 0; i < segments.length; i++) {
|
|
2611
|
-
const segment = segments[i];
|
|
2612
|
-
if (i > 0 && parseDynamicSegment(segment)) {
|
|
2613
|
-
let next = this.nextSegments.get(parent);
|
|
2614
|
-
if (!next) this.nextSegments.set(parent, next = /* @__PURE__ */ new Set());
|
|
2615
|
-
next.add(segment);
|
|
2616
|
-
if (i === segments.length - 1) addCandidate(parent, route);
|
|
2617
|
-
}
|
|
2618
|
-
parent = i === 0 ? segment : `${parent}/${segment}`;
|
|
2619
|
-
}
|
|
2620
|
-
}
|
|
2621
|
-
}
|
|
2622
|
-
bind(path, input) {
|
|
2623
|
-
const params = readParams(input);
|
|
2624
|
-
const normalized = path.replace(/\/$/, "");
|
|
2625
|
-
const candidates = new Set(
|
|
2626
|
-
[...this.nextSegments.get(normalized) ?? []].filter((segment2) => {
|
|
2627
|
-
const dynamic2 = parseDynamicSegment(segment2);
|
|
2628
|
-
return dynamic2 && Object.keys(params).every((key) => key === dynamic2.name) && (Object.prototype.hasOwnProperty.call(params, dynamic2.name) || dynamic2.optional);
|
|
2629
|
-
})
|
|
2630
|
-
);
|
|
2631
|
-
if (candidates.size !== 1)
|
|
2632
|
-
throw new TypeError(
|
|
2633
|
-
`Cannot bind route params at ${path}: supply exactly the next dynamic segment's parameter.`
|
|
2634
|
-
);
|
|
2635
|
-
const segment = [...candidates][0];
|
|
2636
|
-
const dynamic = parseDynamicSegment(segment);
|
|
2637
|
-
encodeParameter(dynamic, params[dynamic.name]);
|
|
2638
|
-
return {
|
|
2639
|
-
segment,
|
|
2640
|
-
params: Object.freeze(
|
|
2641
|
-
Object.fromEntries(
|
|
2642
|
-
Object.entries(params).map(([key, value]) => [
|
|
2643
|
-
key,
|
|
2644
|
-
Array.isArray(value) ? Object.freeze([...value]) : value
|
|
2645
|
-
])
|
|
2646
|
-
)
|
|
2647
|
-
)
|
|
2648
|
-
};
|
|
2649
|
-
}
|
|
2650
|
-
resolve(path, method, bound, input) {
|
|
2651
|
-
const normalized = path.replace(/\/$/, "");
|
|
2652
|
-
const supplied = readParams(input?.params);
|
|
2653
|
-
const candidates = (this.candidates.get(normalized) ?? []).filter((route2) => {
|
|
2654
|
-
if (route2.path === normalized) return true;
|
|
2655
|
-
if (!route2.path.startsWith(`${normalized}/`)) return false;
|
|
2656
|
-
const tail = route2.path.slice(normalized.length + 1);
|
|
2657
|
-
return !tail.includes("/") && Boolean(parseDynamicSegment(tail)) && input?.params !== void 0;
|
|
2658
|
-
});
|
|
2659
|
-
const selected = candidates.filter((route2) => {
|
|
2660
|
-
const unbound = route2.path.split("/").map(parseDynamicSegment).filter((part) => part && !Object.prototype.hasOwnProperty.call(bound, part.name));
|
|
2661
|
-
return Object.keys(supplied).every((key) => unbound.some((part) => part.name === key)) && unbound.every(
|
|
2662
|
-
(part) => part.optional || Object.prototype.hasOwnProperty.call(supplied, part.name)
|
|
2663
|
-
);
|
|
2664
|
-
});
|
|
2665
|
-
if (selected.length !== 1)
|
|
2666
|
-
throw new TypeError(
|
|
2667
|
-
`Cannot resolve ${method} ${normalized}: missing, unexpected, or ambiguous route params.`
|
|
2668
|
-
);
|
|
2669
|
-
const route = selected[0];
|
|
2670
|
-
if (!route.methods.includes(method) && !(method === "HEAD" && route.methods.includes("GET"))) {
|
|
2671
|
-
throw new TypeError(`${method} is not registered for ${route.path}.`);
|
|
2672
|
-
}
|
|
2673
|
-
const params = { ...bound, ...supplied };
|
|
2674
|
-
const resolved = route.path.split("/").map((segment) => {
|
|
2675
|
-
const dynamic = parseDynamicSegment(segment);
|
|
2676
|
-
return dynamic ? encodeParameter(dynamic, params[dynamic.name]) : segment;
|
|
2677
|
-
}).filter(Boolean).join("/");
|
|
2678
|
-
const pathname = `/${resolved}`;
|
|
2679
|
-
const winner = matchAPIRoute(this.routes, pathname);
|
|
2680
|
-
if (winner?.route.path !== route.path) {
|
|
2681
|
-
throw new TypeError(
|
|
2682
|
-
`Route ${route.path} resolves to ${pathname}, which is shadowed by ${winner?.route.path ?? "another route"}.`
|
|
2683
|
-
);
|
|
2684
|
-
}
|
|
2685
|
-
return pathname;
|
|
2686
|
-
}
|
|
2687
|
-
};
|
|
2688
|
-
__name(_ClientRouteManifest, "ClientRouteManifest");
|
|
2689
|
-
var ClientRouteManifest = _ClientRouteManifest;
|
|
2690
|
-
function readParams(input) {
|
|
2691
|
-
if (input === void 0) return {};
|
|
2692
|
-
if (!input || typeof input !== "object" || Array.isArray(input) || ![Object.prototype, null].includes(Object.getPrototypeOf(input))) {
|
|
2693
|
-
throw new TypeError("Route params must be a plain object.");
|
|
2694
|
-
}
|
|
2695
|
-
for (const key of Object.keys(input)) {
|
|
2696
|
-
if (["__proto__", "constructor", "prototype"].includes(key))
|
|
2697
|
-
throw new TypeError(`Unsafe route parameter ${key}.`);
|
|
2698
|
-
}
|
|
2699
|
-
return input;
|
|
2700
|
-
}
|
|
2701
|
-
__name(readParams, "readParams");
|
|
2702
|
-
function encodeParameter(parameter, value) {
|
|
2703
|
-
if (parameter.optional && value === void 0) return "";
|
|
2704
|
-
const parts = parameter.catchAll ? value : [value];
|
|
2705
|
-
if (!Array.isArray(parts) || !parts.length && !parameter.optional) {
|
|
2706
|
-
throw new TypeError(
|
|
2707
|
-
`Route parameter ${parameter.name} must be ${parameter.catchAll ? "a non-empty array of strings" : "a string"}.`
|
|
2708
|
-
);
|
|
2709
|
-
}
|
|
2710
|
-
return Array.from(parts, (part) => {
|
|
2711
|
-
if (typeof part !== "string" || !part || part === "." || part === ".." || Array.from(part).some(
|
|
2712
|
-
(character) => character.charCodeAt(0) <= 31 || character.charCodeAt(0) >= 127 && character.charCodeAt(0) <= 159
|
|
2713
|
-
)) {
|
|
2714
|
-
throw new TypeError(`Invalid value for route parameter ${parameter.name}.`);
|
|
2715
|
-
}
|
|
2716
|
-
return encodeURIComponent(part);
|
|
2717
|
-
}).join("/");
|
|
2718
|
-
}
|
|
2719
|
-
__name(encodeParameter, "encodeParameter");
|
|
2720
|
-
|
|
2721
|
-
// src/server/request-bridge.ts
|
|
2722
|
-
var CURRENT_REQUEST_RESOLVER_KEY2 = /* @__PURE__ */ Symbol.for("farm.currentRequestResolver");
|
|
2723
|
-
function getGlobalState() {
|
|
2724
|
-
return globalThis;
|
|
2725
|
-
}
|
|
2726
|
-
__name(getGlobalState, "getGlobalState");
|
|
2727
|
-
function _resolveCurrentRequest() {
|
|
2728
|
-
return getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY2]?.();
|
|
2729
|
-
}
|
|
2730
|
-
__name(_resolveCurrentRequest, "_resolveCurrentRequest");
|
|
2731
|
-
|
|
2732
|
-
// src/client-retry.ts
|
|
2733
|
-
var MAX_TIMER_DELAY = 2147483647;
|
|
2734
|
-
function resolveClientRetryCount(value) {
|
|
2735
|
-
const count = value ?? 0;
|
|
2736
|
-
if (!Number.isSafeInteger(count) || count < 0) {
|
|
2737
|
-
throw new RangeError("retry.count must be a non-negative safe integer");
|
|
2738
|
-
}
|
|
2739
|
-
return count;
|
|
2740
|
-
}
|
|
2741
|
-
__name(resolveClientRetryCount, "resolveClientRetryCount");
|
|
2742
|
-
function resolveClientRetryDelay(value) {
|
|
2743
|
-
const delay2 = value ?? 0;
|
|
2744
|
-
if (!Number.isFinite(delay2) || delay2 < 0 || delay2 > MAX_TIMER_DELAY) {
|
|
2745
|
-
throw new RangeError(`retry.delay must be between 0 and ${MAX_TIMER_DELAY} milliseconds`);
|
|
2746
|
-
}
|
|
2747
|
-
return delay2;
|
|
2748
|
-
}
|
|
2749
|
-
__name(resolveClientRetryDelay, "resolveClientRetryDelay");
|
|
2750
|
-
|
|
2751
|
-
// src/api/server-client-bridge.ts
|
|
2752
|
-
var API_RUNTIME_RESOLVER = /* @__PURE__ */ Symbol.for("farm.apiRequestRuntimeResolver");
|
|
2753
|
-
function resolveAPIRequestRuntime() {
|
|
2754
|
-
return globalThis[API_RUNTIME_RESOLVER]?.();
|
|
2755
|
-
}
|
|
2756
|
-
__name(resolveAPIRequestRuntime, "resolveAPIRequestRuntime");
|
|
2757
|
-
|
|
2758
|
-
// src/api/transport.ts
|
|
2759
|
-
function isJSONStreamResponse(response) {
|
|
2760
|
-
const contentType = response.headers?.get?.("content-type")?.toLowerCase() ?? "";
|
|
2761
|
-
return contentType.includes("application/x-ndjson") || contentType.includes("application/ndjson");
|
|
2762
|
-
}
|
|
2763
|
-
__name(isJSONStreamResponse, "isJSONStreamResponse");
|
|
2764
|
-
function readJSONStream(response) {
|
|
2765
|
-
if (!response.body) {
|
|
2766
|
-
throw new TypeError("Cannot read a JSON stream response without a body");
|
|
2767
|
-
}
|
|
2768
|
-
const reader = response.body.getReader();
|
|
2769
|
-
const decoder = new TextDecoder();
|
|
2770
|
-
let buffer = "";
|
|
2771
|
-
let completed = false;
|
|
2772
|
-
let cancelled = false;
|
|
2773
|
-
let claimed = false;
|
|
2774
|
-
let released = false;
|
|
2775
|
-
const releaseReader = /* @__PURE__ */ __name(() => {
|
|
2776
|
-
if (released) return;
|
|
2777
|
-
released = true;
|
|
2778
|
-
reader.releaseLock();
|
|
2779
|
-
}, "releaseReader");
|
|
2780
|
-
const parseLine = /* @__PURE__ */ __name(async (line) => {
|
|
2781
|
-
try {
|
|
2782
|
-
return JSON.parse(line);
|
|
2783
|
-
} catch (error) {
|
|
2784
|
-
completed = true;
|
|
2785
|
-
buffer = "";
|
|
2786
|
-
void reader.cancel(error).catch(() => {
|
|
2787
|
-
});
|
|
2788
|
-
releaseReader();
|
|
2789
|
-
throw error;
|
|
2790
|
-
}
|
|
2791
|
-
}, "parseLine");
|
|
2792
|
-
const readNext = /* @__PURE__ */ __name(async () => {
|
|
2793
|
-
while (true) {
|
|
2794
|
-
if (cancelled) return { done: true, value: void 0 };
|
|
2795
|
-
const lineEnd = buffer.indexOf("\n");
|
|
2796
|
-
if (lineEnd >= 0) {
|
|
2797
|
-
const line = buffer.slice(0, lineEnd).trim();
|
|
2798
|
-
buffer = buffer.slice(lineEnd + 1);
|
|
2799
|
-
if (!line) continue;
|
|
2800
|
-
return { done: false, value: await parseLine(line) };
|
|
2801
|
-
}
|
|
2802
|
-
if (completed) {
|
|
2803
|
-
const line = buffer.trim();
|
|
2804
|
-
buffer = "";
|
|
2805
|
-
if (!line) {
|
|
2806
|
-
releaseReader();
|
|
2807
|
-
return { done: true, value: void 0 };
|
|
2808
|
-
}
|
|
2809
|
-
return { done: false, value: await parseLine(line) };
|
|
2810
|
-
}
|
|
2811
|
-
let chunk;
|
|
2812
|
-
try {
|
|
2813
|
-
chunk = await reader.read();
|
|
2814
|
-
} catch (error) {
|
|
2815
|
-
if (cancelled) return { done: true, value: void 0 };
|
|
2816
|
-
completed = true;
|
|
2817
|
-
buffer = "";
|
|
2818
|
-
releaseReader();
|
|
2819
|
-
throw error;
|
|
2820
|
-
}
|
|
2821
|
-
if (cancelled) return { done: true, value: void 0 };
|
|
2822
|
-
completed = chunk.done;
|
|
2823
|
-
buffer += decoder.decode(chunk.value, { stream: !chunk.done });
|
|
2824
|
-
}
|
|
2825
|
-
}, "readNext");
|
|
2826
|
-
let readQueue = Promise.resolve();
|
|
2827
|
-
const iterator = {
|
|
2828
|
-
next() {
|
|
2829
|
-
const result = readQueue.then(readNext);
|
|
2830
|
-
readQueue = result.then(
|
|
2831
|
-
() => {
|
|
2832
|
-
},
|
|
2833
|
-
() => {
|
|
2834
|
-
}
|
|
2835
|
-
);
|
|
2836
|
-
return result;
|
|
2837
|
-
},
|
|
2838
|
-
async return() {
|
|
2839
|
-
cancelled = true;
|
|
2840
|
-
completed = true;
|
|
2841
|
-
buffer = "";
|
|
2842
|
-
if (!released) {
|
|
2843
|
-
try {
|
|
2844
|
-
await reader.cancel();
|
|
2845
|
-
} finally {
|
|
2846
|
-
releaseReader();
|
|
2847
|
-
}
|
|
2848
|
-
}
|
|
2849
|
-
return { done: true, value: void 0 };
|
|
2850
|
-
}
|
|
2851
|
-
};
|
|
2852
|
-
return {
|
|
2853
|
-
response,
|
|
2854
|
-
async cancel(reason) {
|
|
2855
|
-
cancelled = true;
|
|
2856
|
-
completed = true;
|
|
2857
|
-
buffer = "";
|
|
2858
|
-
if (!released) {
|
|
2859
|
-
try {
|
|
2860
|
-
await reader.cancel(reason);
|
|
2861
|
-
} finally {
|
|
2862
|
-
releaseReader();
|
|
2863
|
-
}
|
|
2864
|
-
}
|
|
2865
|
-
},
|
|
2866
|
-
[Symbol.asyncIterator]() {
|
|
2867
|
-
if (claimed) {
|
|
2868
|
-
throw new TypeError("Farm API streams can only be consumed once");
|
|
2869
|
-
}
|
|
2870
|
-
claimed = true;
|
|
2871
|
-
return iterator;
|
|
2872
|
-
}
|
|
2873
|
-
};
|
|
2874
|
-
}
|
|
2875
|
-
__name(readJSONStream, "readJSONStream");
|
|
2876
|
-
function isFarmAPIStream(value) {
|
|
2877
|
-
return typeof value === "object" && value !== null && "response" in value && typeof value.cancel === "function" && typeof value[Symbol.asyncIterator] === "function";
|
|
2878
|
-
}
|
|
2879
|
-
__name(isFarmAPIStream, "isFarmAPIStream");
|
|
2880
|
-
|
|
2881
|
-
// src/api/client.ts
|
|
2882
|
-
var FARM_API_ROUTE_REF_SYMBOL = /* @__PURE__ */ Symbol.for("farm.api.route-ref");
|
|
2883
|
-
var FARM_API_ROUTE_META_SYMBOL = /* @__PURE__ */ Symbol.for("farm.api.route-meta");
|
|
2884
|
-
var _APIClientError = class _APIClientError extends Error {
|
|
2885
|
-
constructor(code, data, options) {
|
|
2886
|
-
super(options.message);
|
|
2887
|
-
this.name = "APIClientError";
|
|
2888
|
-
this.code = code;
|
|
2889
|
-
this.data = data;
|
|
2890
|
-
this.status = options.status;
|
|
2891
|
-
this.response = options.response;
|
|
2892
|
-
}
|
|
2893
|
-
};
|
|
2894
|
-
__name(_APIClientError, "APIClientError");
|
|
2895
|
-
var APIClientError = _APIClientError;
|
|
2896
|
-
var FARM_IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE", "QUERY"]);
|
|
2897
|
-
var FARM_RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 425, 429]);
|
|
2898
|
-
function isFarmRetryableFailure(context2) {
|
|
2899
|
-
if (!FARM_IDEMPOTENT_METHODS.has(context2.method)) return false;
|
|
2900
|
-
if (context2.status === void 0) return true;
|
|
2901
|
-
return context2.status >= 500 || FARM_RETRYABLE_STATUSES.has(context2.status);
|
|
2902
|
-
}
|
|
2903
|
-
__name(isFarmRetryableFailure, "isFarmRetryableFailure");
|
|
2904
|
-
function createApiClients(options = {}) {
|
|
2905
|
-
const localScopes = /* @__PURE__ */ new WeakMap();
|
|
2906
|
-
const routeMeta = /* @__PURE__ */ new WeakMap();
|
|
2907
|
-
const api = createNestedProxy(
|
|
2908
|
-
[],
|
|
2909
|
-
async (path, method, input, clientOptions) => {
|
|
2910
|
-
if (typeof window !== "undefined") {
|
|
2911
|
-
throw new Error(
|
|
2912
|
-
"api is server-only. Use apiClient from createApiClients() in the browser."
|
|
2913
|
-
);
|
|
2914
|
-
}
|
|
2915
|
-
const currentRequest = _resolveCurrentRequest();
|
|
2916
|
-
const runtime3 = resolveAPIRequestRuntime();
|
|
2917
|
-
if (!currentRequest || !runtime3) {
|
|
2918
|
-
throw new Error(
|
|
2919
|
-
"api requires an active Farm server request. Call it from a server page, query, action, or API handler; use apiClient with an absolute baseURL for standalone HTTP calls."
|
|
2920
|
-
);
|
|
2921
|
-
}
|
|
2922
|
-
let localClients = localScopes.get(runtime3);
|
|
2923
|
-
if (!localClients) {
|
|
2924
|
-
localClients = /* @__PURE__ */ new WeakMap();
|
|
2925
|
-
localScopes.set(runtime3, localClients);
|
|
2926
|
-
}
|
|
2927
|
-
let local = localClients.get(currentRequest);
|
|
2928
|
-
if (!local) {
|
|
2929
|
-
const origin = new URL(currentRequest.url).origin;
|
|
2930
|
-
const headers = new Headers();
|
|
2931
|
-
for (const name of ["cookie", "authorization", "accept-language"]) {
|
|
2932
|
-
const value = currentRequest.headers.get(name);
|
|
2933
|
-
if (value !== null) headers.set(name, value);
|
|
2934
|
-
}
|
|
2935
|
-
local = createAPIClientRuntime(
|
|
2936
|
-
{
|
|
2937
|
-
...options,
|
|
2938
|
-
integrations: false,
|
|
2939
|
-
baseURL: new URL(runtime3.basePath, origin).toString()
|
|
2940
|
-
},
|
|
2941
|
-
{
|
|
2942
|
-
headers,
|
|
2943
|
-
signal: currentRequest.signal,
|
|
2944
|
-
cache: new FarmClientDataCache({ subscribeToInvalidation: false }),
|
|
2945
|
-
routeMeta,
|
|
2946
|
-
fetch: /* @__PURE__ */ __name((url, init) => {
|
|
2947
|
-
if (new URL(url).origin !== origin) {
|
|
2948
|
-
throw new Error(
|
|
2949
|
-
"api can only dispatch to this Farm app. Use apiClient for HTTP calls."
|
|
2950
|
-
);
|
|
2951
|
-
}
|
|
2952
|
-
currentRequest.signal.throwIfAborted();
|
|
2953
|
-
return runtime3.dispatch(new Request(url, init));
|
|
2954
|
-
}, "fetch")
|
|
2955
|
-
}
|
|
2956
|
-
);
|
|
2957
|
-
localClients.set(currentRequest, local);
|
|
2958
|
-
}
|
|
2959
|
-
return local.request(path, method, input, clientOptions);
|
|
2960
|
-
},
|
|
2961
|
-
routeMeta,
|
|
2962
|
-
"/api",
|
|
2963
|
-
true,
|
|
2964
|
-
options.integrations === false ? void 0 : {
|
|
2965
|
-
integrations: integrationsServer({
|
|
2966
|
-
baseURL: options.baseURL,
|
|
2967
|
-
headers: options.headers,
|
|
2968
|
-
credentials: options.credentials,
|
|
2969
|
-
timeoutMs: options.timeoutMs,
|
|
2970
|
-
fetch: options.fetch,
|
|
2971
|
-
onRequest: options.onRequest,
|
|
2972
|
-
onResponse: options.onResponse,
|
|
2973
|
-
onError: options.onError,
|
|
2974
|
-
...options.integrations
|
|
2975
|
-
})
|
|
2976
|
-
},
|
|
2977
|
-
options.routes ? new ClientRouteManifest(options.routes) : void 0
|
|
2978
|
-
);
|
|
2979
|
-
return {
|
|
2980
|
-
api,
|
|
2981
|
-
apiClient: createAPIClient(options)
|
|
2982
|
-
};
|
|
2983
|
-
}
|
|
2984
|
-
__name(createApiClients, "createApiClients");
|
|
2985
|
-
function createAPIClient(options = {}) {
|
|
2986
|
-
return createAPIClientRuntime(options).client;
|
|
2987
|
-
}
|
|
2988
|
-
__name(createAPIClient, "createAPIClient");
|
|
2989
|
-
function createAPIClientRuntime(options = {}, transport) {
|
|
2990
|
-
options ?? (options = {});
|
|
2991
|
-
const baseURL = options.baseURL || getFarmAPIBaseURL();
|
|
2992
|
-
const httpFetch = options.fetch;
|
|
2993
|
-
const integrationOptions = options.integrations === false ? false : {
|
|
2994
|
-
baseURL: options.baseURL,
|
|
2995
|
-
headers: options.headers,
|
|
2996
|
-
credentials: options.credentials,
|
|
2997
|
-
timeoutMs: options.timeoutMs,
|
|
2998
|
-
fetch: httpFetch,
|
|
2999
|
-
onRequest: options.onRequest,
|
|
3000
|
-
onResponse: options.onResponse,
|
|
3001
|
-
onError: options.onError,
|
|
3002
|
-
...typeof options.integrations === "object" ? options.integrations : {}
|
|
3003
|
-
};
|
|
3004
|
-
const rootAliases = integrationOptions === false ? void 0 : {
|
|
3005
|
-
integrations: integrationsClient(integrationOptions)
|
|
3006
|
-
};
|
|
3007
|
-
const sharedCacheState = transport?.cache ?? getFarmClientDataCache();
|
|
3008
|
-
const localCaches = transport ? /* @__PURE__ */ new Set([sharedCacheState]) : void 0;
|
|
3009
|
-
const sharedInflightState = /* @__PURE__ */ new Map();
|
|
3010
|
-
let scopedRequestState;
|
|
3011
|
-
const routeMeta = transport?.routeMeta ?? /* @__PURE__ */ new WeakMap();
|
|
3012
|
-
let requestCounter = 0;
|
|
3013
|
-
const fetchClient = /* @__PURE__ */ __name(async (path, requestOptions, defaultHeaders, cancellation) => {
|
|
3014
|
-
const url = resolveFarmAPIRequestURL(path, baseURL);
|
|
3015
|
-
const method = String(requestOptions.method || "GET").toUpperCase();
|
|
3016
|
-
if (requestOptions.query) {
|
|
3017
|
-
appendAPIQuery(url.searchParams, requestOptions.query);
|
|
3018
|
-
}
|
|
3019
|
-
const headers = new Headers(defaultHeaders);
|
|
3020
|
-
new Headers(requestOptions.headers).forEach((value, key) => headers.set(key, value));
|
|
3021
|
-
const fetchOptions = {
|
|
3022
|
-
method,
|
|
3023
|
-
headers,
|
|
3024
|
-
credentials: options.credentials,
|
|
3025
|
-
signal: cancellation.signal
|
|
3026
|
-
};
|
|
3027
|
-
if (method === "QUERY" && !headers.has("content-type")) {
|
|
3028
|
-
headers.set("content-type", "application/json");
|
|
3029
|
-
}
|
|
3030
|
-
if (requestOptions.body !== void 0) {
|
|
3031
|
-
if (isFormData(requestOptions.body)) {
|
|
3032
|
-
headers.delete("content-type");
|
|
3033
|
-
fetchOptions.body = requestOptions.body;
|
|
3034
|
-
} else {
|
|
3035
|
-
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
|
3036
|
-
fetchOptions.body = JSON.stringify(requestOptions.body);
|
|
3037
|
-
}
|
|
3038
|
-
}
|
|
3039
|
-
cancellation.check();
|
|
3040
|
-
const response = await (transport?.fetch ?? httpFetch ?? fetch)(url.toString(), fetchOptions);
|
|
3041
|
-
cancellation.check();
|
|
3042
|
-
const invalidations = decodeFarmCacheInvalidations(
|
|
3043
|
-
response.headers?.get?.(FARM_CACHE_INVALIDATION_HEADER)
|
|
3044
|
-
);
|
|
3045
|
-
if (transport) {
|
|
3046
|
-
for (const cache of localCaches) {
|
|
3047
|
-
for (const key of invalidations) cache.invalidate(key);
|
|
3048
|
-
}
|
|
3049
|
-
} else {
|
|
3050
|
-
applyFarmCacheInvalidations(invalidations);
|
|
3051
|
-
}
|
|
3052
|
-
let data;
|
|
3053
|
-
try {
|
|
3054
|
-
data = await readAPIResponseData(response, method);
|
|
3055
|
-
cancellation.check();
|
|
3056
|
-
} catch (decodeError) {
|
|
3057
|
-
if (!(decodeError instanceof APIResponseDecodeError)) throw decodeError;
|
|
3058
|
-
if (response.ok) throw decodeError.cause;
|
|
3059
|
-
return { response, data: void 0, decodeError: decodeError.cause };
|
|
3060
|
-
}
|
|
3061
|
-
return { response, data };
|
|
3062
|
-
}, "fetchClient");
|
|
3063
|
-
const request = /* @__PURE__ */ __name(async (path, method, input = {}, clientOptions) => {
|
|
3064
|
-
const maxRetries = resolveClientRetryCount(clientOptions?.retry?.count);
|
|
3065
|
-
if (typeof clientOptions?.retry?.delay !== "function") {
|
|
3066
|
-
resolveClientRetryDelay(clientOptions?.retry?.delay);
|
|
3067
|
-
}
|
|
3068
|
-
const cancellation = createClientCancellation(
|
|
3069
|
-
clientOptions?.signal,
|
|
3070
|
-
clientOptions?.timeoutMs ?? options.timeoutMs,
|
|
3071
|
-
transport?.signal
|
|
3072
|
-
);
|
|
3073
|
-
const normalizeCallError = /* @__PURE__ */ __name((error) => {
|
|
3074
|
-
if (!cancellation.signal?.aborted) return normalizeError(error);
|
|
3075
|
-
const normalized = new APIClientError(
|
|
3076
|
-
cancellation.timedOut ? "timeout" : "aborted",
|
|
3077
|
-
void 0,
|
|
3078
|
-
{
|
|
3079
|
-
status: 0,
|
|
3080
|
-
message: cancellation.timedOut ? "Client request timed out" : "Client request aborted"
|
|
3081
|
-
}
|
|
3082
|
-
);
|
|
3083
|
-
normalized.cause = cancellation.signal.reason;
|
|
3084
|
-
return normalized;
|
|
3085
|
-
}, "normalizeCallError");
|
|
3086
|
-
try {
|
|
3087
|
-
const methodUpper = method.toUpperCase();
|
|
3088
|
-
const requestId = `${Date.now()}-${++requestCounter}`;
|
|
3089
|
-
const defaultHeaders = new Headers(transport?.headers);
|
|
3090
|
-
let requestContextError;
|
|
3091
|
-
try {
|
|
3092
|
-
cancellation.check();
|
|
3093
|
-
const resolved = resolveClientHeaders(options.headers);
|
|
3094
|
-
const headers = resolved instanceof Headers ? resolved : await cancellation.run(() => resolved);
|
|
3095
|
-
cancellation.check();
|
|
3096
|
-
headers.forEach((value, name) => defaultHeaders.set(name, value));
|
|
3097
|
-
} catch (error) {
|
|
3098
|
-
requestContextError = normalizeCallError(error);
|
|
3099
|
-
}
|
|
3100
|
-
const cacheOptions = clientOptions?.cache ? {
|
|
3101
|
-
...options.cacheDefaults,
|
|
3102
|
-
...clientOptions.cache
|
|
3103
|
-
} : void 0;
|
|
3104
|
-
const configuredCacheKey = clientOptions?.key ?? cacheOptions?.key;
|
|
3105
|
-
const cacheKey = normalizeFarmClientCacheKey(
|
|
3106
|
-
configuredCacheKey ?? buildCacheKey(methodUpper, path, input, baseURL, defaultHeaders)
|
|
3107
|
-
);
|
|
3108
|
-
const now = Date.now();
|
|
3109
|
-
const emitStatus = /* @__PURE__ */ __name((phase, payload) => {
|
|
3110
|
-
notifyClientObserver(
|
|
3111
|
-
clientOptions?.onStatus,
|
|
3112
|
-
[
|
|
3113
|
-
{
|
|
3114
|
-
phase,
|
|
3115
|
-
requestId,
|
|
3116
|
-
method: methodUpper,
|
|
3117
|
-
key: cacheKey,
|
|
3118
|
-
input,
|
|
3119
|
-
timestamp: Date.now(),
|
|
3120
|
-
...payload
|
|
3121
|
-
}
|
|
3122
|
-
],
|
|
3123
|
-
"API client onStatus"
|
|
3124
|
-
);
|
|
3125
|
-
}, "emitStatus");
|
|
3126
|
-
const policy = cacheOptions?.policy ?? (cacheOptions ? "cache-first" : "network-only");
|
|
3127
|
-
const staleTime = cacheOptions?.staleTime ?? 0;
|
|
3128
|
-
const hasReliableDefaultCacheKey = methodUpper !== "QUERY" || !isFormData(input?.body) || configuredCacheKey !== void 0;
|
|
3129
|
-
const isCacheEnabled = Boolean(cacheOptions) && (methodUpper === "GET" || methodUpper === "QUERY") && hasReliableDefaultCacheKey;
|
|
3130
|
-
const needsCacheState = isCacheEnabled || Boolean(clientOptions?.optimistic?.update?.length) || Boolean(clientOptions?.invalidate);
|
|
3131
|
-
let requestCacheContext = void 0;
|
|
3132
|
-
if (needsCacheState && !requestContextError) {
|
|
3133
|
-
try {
|
|
3134
|
-
requestCacheContext = getRequestCacheContext(
|
|
3135
|
-
{ headers: defaultHeaders, credentials: options.credentials },
|
|
3136
|
-
input,
|
|
3137
|
-
// Custom transports can inject an identity outside visible headers.
|
|
3138
|
-
// Never share their cached data with other client instances.
|
|
3139
|
-
httpFetch ? "client" : cacheOptions?.scope
|
|
3140
|
-
);
|
|
3141
|
-
} catch (error) {
|
|
3142
|
-
requestContextError = normalizeError(error);
|
|
3143
|
-
}
|
|
3144
|
-
}
|
|
3145
|
-
let cacheState = sharedCacheState;
|
|
3146
|
-
let inflightState = sharedInflightState;
|
|
3147
|
-
let requestScopedState;
|
|
3148
|
-
if (requestCacheContext !== void 0) {
|
|
3149
|
-
if (scopedRequestState && scopedRequestState.context !== requestCacheContext) {
|
|
3150
|
-
scopedRequestState.retired = true;
|
|
3151
|
-
if (scopedRequestState.inflight.size === 0) scopedRequestState.cache.dispose();
|
|
3152
|
-
scopedRequestState = void 0;
|
|
3153
|
-
}
|
|
3154
|
-
scopedRequestState ?? (scopedRequestState = {
|
|
3155
|
-
context: requestCacheContext,
|
|
3156
|
-
cache: new FarmClientDataCache({ subscribeToInvalidation: !transport }),
|
|
3157
|
-
inflight: /* @__PURE__ */ new Map(),
|
|
3158
|
-
retired: false
|
|
3159
|
-
});
|
|
3160
|
-
requestScopedState = scopedRequestState;
|
|
3161
|
-
cacheState = requestScopedState.cache;
|
|
3162
|
-
localCaches?.add(cacheState);
|
|
3163
|
-
inflightState = requestScopedState.inflight;
|
|
3164
|
-
}
|
|
3165
|
-
const optimisticState = getOptimisticState(cacheState);
|
|
3166
|
-
const entry = getValidCacheEntry(cacheState, cacheKey, now);
|
|
3167
|
-
const isStale = entry ? isEntryStale(entry, now) : true;
|
|
3168
|
-
const applyOptimisticUpdates = /* @__PURE__ */ __name(() => {
|
|
3169
|
-
if (!clientOptions?.optimistic?.update?.length) return [];
|
|
3170
|
-
const snapshots = /* @__PURE__ */ new Map();
|
|
3171
|
-
for (const update of clientOptions.optimistic.update) {
|
|
3172
|
-
const [target, targetInput, updater] = update.length === 2 ? [update[0], void 0, update[1]] : [update[0], update[1], update[2]];
|
|
3173
|
-
const targetKey = resolveTargetKey(
|
|
3174
|
-
routeMeta,
|
|
3175
|
-
target,
|
|
3176
|
-
targetInput,
|
|
3177
|
-
baseURL,
|
|
3178
|
-
defaultHeaders,
|
|
3179
|
-
transport ? baseURL : void 0
|
|
3180
|
-
);
|
|
3181
|
-
if (!targetKey) continue;
|
|
3182
|
-
const targetEntry = getValidCacheEntry(cacheState, targetKey, now);
|
|
3183
|
-
const currentEntry = cacheState.get(targetKey);
|
|
3184
|
-
let stack = optimisticState.get(targetKey);
|
|
3185
|
-
if (stack && !reconcileOptimisticInvalidation(cacheState, targetKey, stack)) {
|
|
3186
|
-
stack = void 0;
|
|
3187
|
-
}
|
|
3188
|
-
if (!stack) {
|
|
3189
|
-
stack = {
|
|
3190
|
-
entry: targetEntry ? { ...targetEntry } : void 0,
|
|
3191
|
-
layers: [],
|
|
3192
|
-
renderedEntry: currentEntry
|
|
3193
|
-
};
|
|
3194
|
-
optimisticState.set(targetKey, stack);
|
|
3195
|
-
}
|
|
3196
|
-
let snapshot = snapshots.get(targetKey);
|
|
3197
|
-
if (!snapshot) {
|
|
3198
|
-
const previousEntry = stack.layers.length === 0 ? stack.entry : stack.renderedEntry;
|
|
3199
|
-
const layer = {
|
|
3200
|
-
updaters: [],
|
|
3201
|
-
updatedAt: now,
|
|
3202
|
-
staleAt: targetEntry?.staleAt ?? now + (cacheOptions?.staleTime ?? options.cacheDefaults?.staleTime ?? 0),
|
|
3203
|
-
gcAt: targetEntry?.gcAt ?? getGcAt(now, cacheOptions?.gcTime ?? options.cacheDefaults?.gcTime)
|
|
3204
|
-
};
|
|
3205
|
-
stack.layers.push(layer);
|
|
3206
|
-
snapshot = {
|
|
3207
|
-
key: targetKey,
|
|
3208
|
-
stack,
|
|
3209
|
-
layer
|
|
3210
|
-
};
|
|
3211
|
-
snapshots.set(targetKey, snapshot);
|
|
3212
|
-
snapshot.layer.updaters.push(updater);
|
|
3213
|
-
const nextEntry2 = applyOptimisticLayer(previousEntry, {
|
|
3214
|
-
...snapshot.layer,
|
|
3215
|
-
updaters: [updater]
|
|
3216
|
-
});
|
|
3217
|
-
storeOptimisticEntry(cacheState, targetKey, stack, nextEntry2);
|
|
3218
|
-
continue;
|
|
3219
|
-
}
|
|
3220
|
-
snapshot.layer.updaters.push(updater);
|
|
3221
|
-
const nextEntry = applyOptimisticLayer(stack.renderedEntry, {
|
|
3222
|
-
...snapshot.layer,
|
|
3223
|
-
updaters: [updater]
|
|
3224
|
-
});
|
|
3225
|
-
storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);
|
|
3226
|
-
}
|
|
3227
|
-
return Array.from(snapshots.values());
|
|
3228
|
-
}, "applyOptimisticUpdates");
|
|
3229
|
-
const rollbackOptimisticUpdates = /* @__PURE__ */ __name((snapshots) => {
|
|
3230
|
-
if (!clientOptions?.optimistic?.rollbackOnError) return;
|
|
3231
|
-
settleOptimisticUpdates(cacheState, optimisticState, snapshots, "rollback");
|
|
3232
|
-
}, "rollbackOptimisticUpdates");
|
|
3233
|
-
const invalidateUncommittedOptimisticUpdates = /* @__PURE__ */ __name((snapshots) => {
|
|
3234
|
-
if (clientOptions?.optimistic?.rollbackOnError) return;
|
|
3235
|
-
for (const key of settleOptimisticUpdates(
|
|
3236
|
-
cacheState,
|
|
3237
|
-
optimisticState,
|
|
3238
|
-
snapshots,
|
|
3239
|
-
"invalidate"
|
|
3240
|
-
)) {
|
|
3241
|
-
emitStatus("invalidated", { key });
|
|
3242
|
-
}
|
|
3243
|
-
}, "invalidateUncommittedOptimisticUpdates");
|
|
3244
|
-
const executeNetwork = /* @__PURE__ */ __name(async (opts) => {
|
|
3245
|
-
const release = cancellation.hold();
|
|
3246
|
-
let unsubscribeInvalidation;
|
|
3247
|
-
let readOwners;
|
|
3248
|
-
let readOwner;
|
|
3249
|
-
const resolvedCacheKey = cacheState.resolveKey(cacheKey);
|
|
3250
|
-
try {
|
|
3251
|
-
const dedupeMs = cacheOptions?.dedupeMs ?? 0;
|
|
3252
|
-
const inflight = inflightState.get(cacheKey);
|
|
3253
|
-
const allowDedupe = isCacheEnabled && dedupeMs > 0 && !cancellation.signal && !requestContextError;
|
|
3254
|
-
if (allowDedupe && inflight && !inflight.cancellable && now - inflight.startedAt < dedupeMs) {
|
|
3255
|
-
emitStatus("pending", { isBackground: opts?.isBackground, data: entry?.data });
|
|
3256
|
-
const result2 = await inflight.promise;
|
|
3257
|
-
if (result2.error) {
|
|
3258
|
-
emitStatus("error", { error: result2.error, isBackground: opts?.isBackground });
|
|
3259
|
-
notifyClientObserver(options.onError, [result2.error]);
|
|
3260
|
-
if (opts?.callCallbacks !== false) {
|
|
3261
|
-
notifyClientObserver(clientOptions?.onError, [result2.error], "API client onError");
|
|
3262
|
-
}
|
|
3263
|
-
} else {
|
|
3264
|
-
emitStatus("success", { data: result2.data, isBackground: opts?.isBackground });
|
|
3265
|
-
if (opts?.callCallbacks !== false) {
|
|
3266
|
-
notifyClientObserver(
|
|
3267
|
-
clientOptions?.onSuccess,
|
|
3268
|
-
[result2.data],
|
|
3269
|
-
"API client onSuccess"
|
|
3270
|
-
);
|
|
3271
|
-
}
|
|
3272
|
-
}
|
|
3273
|
-
return result2;
|
|
3274
|
-
}
|
|
3275
|
-
let invalidatedDuringRequest = false;
|
|
3276
|
-
if (isCacheEnabled) {
|
|
3277
|
-
readOwners = getCacheReadOwners(cacheState);
|
|
3278
|
-
readOwner = {};
|
|
3279
|
-
readOwners.set(resolvedCacheKey, readOwner);
|
|
3280
|
-
unsubscribeInvalidation = cacheState.subscribe(cacheKey, (event) => {
|
|
3281
|
-
if (event === "invalidate") invalidatedDuringRequest = true;
|
|
3282
|
-
});
|
|
3283
|
-
}
|
|
3284
|
-
emitStatus(opts?.isBackground ? "revalidating" : "pending", {
|
|
3285
|
-
isBackground: opts?.isBackground
|
|
3286
|
-
});
|
|
3287
|
-
const promise = (async () => {
|
|
3288
|
-
const shouldRetryFailure = clientOptions?.retry?.shouldRetry ?? isFarmRetryableFailure;
|
|
3289
|
-
let attempt = 0;
|
|
3290
|
-
while (true) {
|
|
3291
|
-
if (options.onRequest || clientOptions?.onRequest) {
|
|
3292
|
-
const requestEvent = {
|
|
3293
|
-
requestId,
|
|
3294
|
-
method: methodUpper,
|
|
3295
|
-
key: cacheKey,
|
|
3296
|
-
path,
|
|
3297
|
-
input,
|
|
3298
|
-
attempt,
|
|
3299
|
-
timestamp: Date.now()
|
|
3300
|
-
};
|
|
3301
|
-
notifyClientObserver(options.onRequest, [requestEvent]);
|
|
3302
|
-
notifyClientObserver(
|
|
3303
|
-
clientOptions?.onRequest,
|
|
3304
|
-
[requestEvent],
|
|
3305
|
-
"API client onRequest"
|
|
3306
|
-
);
|
|
3307
|
-
}
|
|
3308
|
-
try {
|
|
3309
|
-
if (requestContextError) throw requestContextError;
|
|
3310
|
-
const { response, data, decodeError } = await cancellation.run(
|
|
3311
|
-
() => fetchClient(
|
|
3312
|
-
path,
|
|
3313
|
-
{
|
|
3314
|
-
...input,
|
|
3315
|
-
method: methodUpper
|
|
3316
|
-
},
|
|
3317
|
-
defaultHeaders,
|
|
3318
|
-
cancellation
|
|
3319
|
-
)
|
|
3320
|
-
);
|
|
3321
|
-
const error = response.ok ? null : createResponseError2(response, data, decodeError);
|
|
3322
|
-
const responseEvent = {
|
|
3323
|
-
requestId,
|
|
3324
|
-
method: methodUpper,
|
|
3325
|
-
key: cacheKey,
|
|
3326
|
-
path,
|
|
3327
|
-
input,
|
|
3328
|
-
attempt,
|
|
3329
|
-
timestamp: Date.now(),
|
|
3330
|
-
response,
|
|
3331
|
-
data: response.ok ? data : void 0,
|
|
3332
|
-
error: error ?? void 0,
|
|
3333
|
-
ok: response.ok,
|
|
3334
|
-
status: response.status
|
|
3335
|
-
};
|
|
3336
|
-
notifyClientObserver(options.onResponse, [
|
|
3337
|
-
response.ok ? data : void 0,
|
|
3338
|
-
error,
|
|
3339
|
-
responseEvent
|
|
3340
|
-
]);
|
|
3341
|
-
notifyResponseObserver(
|
|
3342
|
-
clientOptions?.onResponse,
|
|
3343
|
-
response.ok ? data : void 0,
|
|
3344
|
-
error,
|
|
3345
|
-
responseEvent
|
|
3346
|
-
);
|
|
3347
|
-
if (!error) {
|
|
3348
|
-
return { data, error: null, key: cacheKey };
|
|
3349
|
-
}
|
|
3350
|
-
if (attempt >= maxRetries || !shouldRetryFailure({
|
|
3351
|
-
attempt,
|
|
3352
|
-
method: methodUpper,
|
|
3353
|
-
status: response.status,
|
|
3354
|
-
error
|
|
3355
|
-
})) {
|
|
3356
|
-
return { data: void 0, error, key: cacheKey };
|
|
3357
|
-
}
|
|
3358
|
-
} catch (err) {
|
|
3359
|
-
const error = normalizeCallError(err);
|
|
3360
|
-
const responseEvent = {
|
|
3361
|
-
requestId,
|
|
3362
|
-
method: methodUpper,
|
|
3363
|
-
key: cacheKey,
|
|
3364
|
-
path,
|
|
3365
|
-
input,
|
|
3366
|
-
attempt,
|
|
3367
|
-
timestamp: Date.now(),
|
|
3368
|
-
error,
|
|
3369
|
-
ok: false
|
|
3370
|
-
};
|
|
3371
|
-
notifyClientObserver(options.onResponse, [void 0, error, responseEvent]);
|
|
3372
|
-
notifyResponseObserver(clientOptions?.onResponse, void 0, error, responseEvent);
|
|
3373
|
-
if (attempt >= maxRetries || requestContextError || cancellation.signal?.aborted || !shouldRetryFailure({ attempt, method: methodUpper, error })) {
|
|
3374
|
-
return { data: void 0, error, key: cacheKey };
|
|
3375
|
-
}
|
|
3376
|
-
}
|
|
3377
|
-
attempt += 1;
|
|
3378
|
-
const delay2 = resolveClientRetryDelay(
|
|
3379
|
-
typeof clientOptions?.retry?.delay === "function" ? clientOptions.retry.delay(attempt) : clientOptions?.retry?.delay
|
|
3380
|
-
);
|
|
3381
|
-
if (delay2 > 0) {
|
|
3382
|
-
try {
|
|
3383
|
-
await cancellation.delay(delay2);
|
|
3384
|
-
} catch (error) {
|
|
3385
|
-
return { data: void 0, error: normalizeCallError(error), key: cacheKey };
|
|
3386
|
-
}
|
|
3387
|
-
}
|
|
3388
|
-
}
|
|
3389
|
-
})();
|
|
3390
|
-
const inflightEntry = {
|
|
3391
|
-
promise,
|
|
3392
|
-
startedAt: now,
|
|
3393
|
-
cancellable: !!cancellation.signal || !!requestContextError
|
|
3394
|
-
};
|
|
3395
|
-
inflightState.set(cacheKey, inflightEntry);
|
|
3396
|
-
try {
|
|
3397
|
-
const result2 = await promise;
|
|
3398
|
-
if (inflightState.get(cacheKey) === inflightEntry && readOwners?.get(resolvedCacheKey) === readOwner && !invalidatedDuringRequest && !result2.error && isCacheEnabled && !isFarmAPIStream(result2.data)) {
|
|
3399
|
-
const updatedAt = Date.now();
|
|
3400
|
-
const cached = {
|
|
3401
|
-
data: result2.data,
|
|
3402
|
-
updatedAt,
|
|
3403
|
-
staleAt: updatedAt + staleTime,
|
|
3404
|
-
gcAt: getGcAt(updatedAt, cacheOptions?.gcTime),
|
|
3405
|
-
invalidatedAt: void 0,
|
|
3406
|
-
persist: cacheOptions?.persist === true ? true : void 0,
|
|
3407
|
-
[API_CACHE_REFETCH]: createCacheRefetch(
|
|
3408
|
-
request,
|
|
3409
|
-
path,
|
|
3410
|
-
method,
|
|
3411
|
-
input,
|
|
3412
|
-
cacheKey,
|
|
3413
|
-
cacheOptions,
|
|
3414
|
-
clientOptions,
|
|
3415
|
-
options.onError
|
|
3416
|
-
)
|
|
3417
|
-
};
|
|
3418
|
-
cacheState.set(cacheKey, cached);
|
|
3419
|
-
}
|
|
3420
|
-
if (result2.error) {
|
|
3421
|
-
emitStatus("error", { error: result2.error, isBackground: opts?.isBackground });
|
|
3422
|
-
notifyClientObserver(options.onError, [result2.error]);
|
|
3423
|
-
if (opts?.callCallbacks !== false) {
|
|
3424
|
-
notifyClientObserver(clientOptions?.onError, [result2.error], "API client onError");
|
|
3425
|
-
}
|
|
3426
|
-
} else {
|
|
3427
|
-
emitStatus("success", { data: result2.data, isBackground: opts?.isBackground });
|
|
3428
|
-
if (opts?.callCallbacks !== false) {
|
|
3429
|
-
notifyClientObserver(
|
|
3430
|
-
clientOptions?.onSuccess,
|
|
3431
|
-
[result2.data],
|
|
3432
|
-
"API client onSuccess"
|
|
3433
|
-
);
|
|
3434
|
-
}
|
|
3435
|
-
}
|
|
3436
|
-
return result2;
|
|
3437
|
-
} finally {
|
|
3438
|
-
if (inflightState.get(cacheKey) === inflightEntry) {
|
|
3439
|
-
inflightState.delete(cacheKey);
|
|
3440
|
-
}
|
|
3441
|
-
if (requestContextError && requestScopedState) {
|
|
3442
|
-
requestScopedState.retired = true;
|
|
3443
|
-
if (scopedRequestState === requestScopedState) scopedRequestState = void 0;
|
|
3444
|
-
}
|
|
3445
|
-
if (requestScopedState?.retired && requestScopedState.inflight.size === 0) {
|
|
3446
|
-
requestScopedState.cache.dispose();
|
|
3447
|
-
}
|
|
3448
|
-
}
|
|
3449
|
-
} finally {
|
|
3450
|
-
if (readOwner && readOwners?.get(resolvedCacheKey) === readOwner) {
|
|
3451
|
-
readOwners.delete(resolvedCacheKey);
|
|
3452
|
-
}
|
|
3453
|
-
unsubscribeInvalidation?.();
|
|
3454
|
-
release();
|
|
3455
|
-
}
|
|
3456
|
-
}, "executeNetwork");
|
|
3457
|
-
const invalidateTargets = /* @__PURE__ */ __name(async () => {
|
|
3458
|
-
if (!clientOptions?.invalidate) return;
|
|
3459
|
-
const invalidateOptions = Array.isArray(clientOptions.invalidate) ? { targets: clientOptions.invalidate, refetch: false } : {
|
|
3460
|
-
targets: clientOptions.invalidate.targets,
|
|
3461
|
-
refetch: clientOptions.invalidate.refetch ?? false
|
|
3462
|
-
};
|
|
3463
|
-
const refetches = /* @__PURE__ */ new Set();
|
|
3464
|
-
for (const target of invalidateOptions.targets) {
|
|
3465
|
-
const targetKey = resolveTargetKey(
|
|
3466
|
-
routeMeta,
|
|
3467
|
-
target,
|
|
3468
|
-
void 0,
|
|
3469
|
-
baseURL,
|
|
3470
|
-
defaultHeaders,
|
|
3471
|
-
transport ? baseURL : void 0
|
|
3472
|
-
);
|
|
3473
|
-
if (!targetKey) continue;
|
|
3474
|
-
const existing = cacheState.get(targetKey);
|
|
3475
|
-
const invalidatedAt = Date.now();
|
|
3476
|
-
cacheState.invalidate(targetKey, invalidatedAt);
|
|
3477
|
-
if (existing) {
|
|
3478
|
-
const stack = optimisticState.get(targetKey);
|
|
3479
|
-
if (stack?.renderedEntry === existing) {
|
|
3480
|
-
stack.invalidatedAt = invalidatedAt;
|
|
3481
|
-
stack.renderedEntry = cacheState.get(targetKey);
|
|
3482
|
-
}
|
|
3483
|
-
}
|
|
3484
|
-
emitStatus("invalidated", { key: targetKey });
|
|
3485
|
-
const refetch = existing?.[API_CACHE_REFETCH];
|
|
3486
|
-
if (invalidateOptions.refetch && refetch) {
|
|
3487
|
-
refetches.add(refetch);
|
|
3488
|
-
}
|
|
3489
|
-
}
|
|
3490
|
-
for (const refetch of refetches) refetch();
|
|
3491
|
-
}, "invalidateTargets");
|
|
3492
|
-
const optimisticSnapshots = requestContextError ? [] : applyOptimisticUpdates();
|
|
3493
|
-
if (isCacheEnabled && !requestContextError && !cancellation.signal?.aborted) {
|
|
3494
|
-
if (entry && !isStale && policy !== "network-only") {
|
|
3495
|
-
emitStatus("success", { data: entry.data });
|
|
3496
|
-
notifyClientObserver(clientOptions?.onSuccess, [entry.data], "API client onSuccess");
|
|
3497
|
-
notifyClientObserver(
|
|
3498
|
-
clientOptions?.onSettled,
|
|
3499
|
-
[entry.data, null],
|
|
3500
|
-
"API client onSettled"
|
|
3501
|
-
);
|
|
3502
|
-
return { data: entry.data, error: null, key: cacheKey };
|
|
3503
|
-
}
|
|
3504
|
-
if (entry && isStale && policy === "stale-while-revalidate") {
|
|
3505
|
-
emitStatus("success", { data: entry.data });
|
|
3506
|
-
notifyClientObserver(clientOptions?.onSuccess, [entry.data], "API client onSuccess");
|
|
3507
|
-
notifyClientObserver(
|
|
3508
|
-
clientOptions?.onSettled,
|
|
3509
|
-
[entry.data, null],
|
|
3510
|
-
"API client onSettled"
|
|
3511
|
-
);
|
|
3512
|
-
void executeNetwork({ isBackground: true, callCallbacks: false });
|
|
3513
|
-
return { data: entry.data, error: null, key: cacheKey };
|
|
3514
|
-
}
|
|
3515
|
-
}
|
|
3516
|
-
const result = await executeNetwork();
|
|
3517
|
-
if (result.error) {
|
|
3518
|
-
if (cancellation.signal?.aborted) {
|
|
3519
|
-
settleOptimisticUpdates(cacheState, optimisticState, optimisticSnapshots, "rollback");
|
|
3520
|
-
} else {
|
|
3521
|
-
rollbackOptimisticUpdates(optimisticSnapshots);
|
|
3522
|
-
invalidateUncommittedOptimisticUpdates(optimisticSnapshots);
|
|
3523
|
-
}
|
|
3524
|
-
} else {
|
|
3525
|
-
settleOptimisticUpdates(cacheState, optimisticState, optimisticSnapshots, "commit");
|
|
3526
|
-
await invalidateTargets();
|
|
3527
|
-
}
|
|
3528
|
-
notifyClientObserver(
|
|
3529
|
-
clientOptions?.onSettled,
|
|
3530
|
-
[result.data, result.error],
|
|
3531
|
-
"API client onSettled"
|
|
3532
|
-
);
|
|
3533
|
-
return result;
|
|
3534
|
-
} finally {
|
|
3535
|
-
cancellation.dispose();
|
|
3536
|
-
}
|
|
3537
|
-
}, "request");
|
|
3538
|
-
const client = createNestedProxy(
|
|
3539
|
-
[],
|
|
3540
|
-
request,
|
|
3541
|
-
routeMeta,
|
|
3542
|
-
baseURL,
|
|
3543
|
-
isSameOriginAPIBaseURL(baseURL),
|
|
3544
|
-
rootAliases,
|
|
3545
|
-
options.routes ? new ClientRouteManifest(options.routes) : void 0
|
|
3546
|
-
);
|
|
3547
|
-
return { client, request };
|
|
3548
|
-
}
|
|
3549
|
-
__name(createAPIClientRuntime, "createAPIClientRuntime");
|
|
3550
|
-
async function readAPIResponseData(response, method) {
|
|
3551
|
-
if (method === "HEAD" || response.status === 204 || response.status === 205 || response.status === 304) {
|
|
3552
|
-
return void 0;
|
|
3553
|
-
}
|
|
3554
|
-
if (!response.headers?.get && typeof response.json === "function") {
|
|
3555
|
-
return readResponseJSON(response);
|
|
3556
|
-
}
|
|
3557
|
-
if (response.body === null) return void 0;
|
|
3558
|
-
if (isJSONStreamResponse(response)) {
|
|
3559
|
-
return readJSONStream(response);
|
|
3560
|
-
}
|
|
3561
|
-
const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
|
|
3562
|
-
if (typeof response.arrayBuffer === "function") {
|
|
3563
|
-
const data = await response.arrayBuffer();
|
|
3564
|
-
if (data.byteLength === 0) return void 0;
|
|
3565
|
-
if (!contentType || contentType === "application/json" || contentType.endsWith("+json")) {
|
|
3566
|
-
return parseResponseJSON(new TextDecoder().decode(data));
|
|
3567
|
-
}
|
|
3568
|
-
if (contentType.startsWith("text/") || contentType === "application/xml" || contentType === "application/xhtml+xml" || contentType === "application/graphql") {
|
|
3569
|
-
return new TextDecoder().decode(data);
|
|
3570
|
-
}
|
|
3571
|
-
return data;
|
|
3572
|
-
}
|
|
3573
|
-
if ((!contentType || contentType === "application/json" || contentType.endsWith("+json")) && typeof response.json === "function") {
|
|
3574
|
-
return readResponseJSON(response);
|
|
3575
|
-
}
|
|
3576
|
-
if ((contentType?.startsWith("text/") || contentType === "application/xml" || contentType === "application/xhtml+xml" || contentType === "application/graphql") && typeof response.text === "function") {
|
|
3577
|
-
return response.text();
|
|
3578
|
-
}
|
|
3579
|
-
if (typeof response.json === "function") {
|
|
3580
|
-
return readResponseJSON(response);
|
|
3581
|
-
}
|
|
3582
|
-
return void 0;
|
|
3583
|
-
}
|
|
3584
|
-
__name(readAPIResponseData, "readAPIResponseData");
|
|
3585
|
-
var _APIResponseDecodeError = class _APIResponseDecodeError extends Error {
|
|
3586
|
-
constructor(cause) {
|
|
3587
|
-
super(cause instanceof Error ? cause.message : "Failed to decode JSON response");
|
|
3588
|
-
this.name = "APIResponseDecodeError";
|
|
3589
|
-
this.cause = cause;
|
|
3590
|
-
}
|
|
3591
|
-
};
|
|
3592
|
-
__name(_APIResponseDecodeError, "APIResponseDecodeError");
|
|
3593
|
-
var APIResponseDecodeError = _APIResponseDecodeError;
|
|
3594
|
-
function parseResponseJSON(value) {
|
|
3595
|
-
try {
|
|
3596
|
-
return JSON.parse(value);
|
|
3597
|
-
} catch (error) {
|
|
3598
|
-
throw new APIResponseDecodeError(error);
|
|
3599
|
-
}
|
|
3600
|
-
}
|
|
3601
|
-
__name(parseResponseJSON, "parseResponseJSON");
|
|
3602
|
-
async function readResponseJSON(response) {
|
|
3603
|
-
try {
|
|
3604
|
-
return await response.json();
|
|
3605
|
-
} catch (error) {
|
|
3606
|
-
if (error instanceof SyntaxError) throw new APIResponseDecodeError(error);
|
|
3607
|
-
throw error;
|
|
3608
|
-
}
|
|
3609
|
-
}
|
|
3610
|
-
__name(readResponseJSON, "readResponseJSON");
|
|
3611
|
-
function createNestedProxy(path, client, routeMeta, baseURL, sameOrigin, rootAliases, manifest, bound = {}) {
|
|
3612
|
-
const target = /* @__PURE__ */ __name(() => {
|
|
3613
|
-
}, "target");
|
|
3614
|
-
const proxy = new Proxy(target, {
|
|
3615
|
-
// When accessing a property (api.hello)
|
|
3616
|
-
get(_target, prop) {
|
|
3617
|
-
if (prop === "then") return void 0;
|
|
3618
|
-
if (prop === "$params") {
|
|
3619
|
-
return (params) => {
|
|
3620
|
-
if (!manifest)
|
|
3621
|
-
throw new TypeError(
|
|
3622
|
-
"$params requires createAPIClient({ routes: apiRoutes }) from the generated API manifest."
|
|
3623
|
-
);
|
|
3624
|
-
const scope = manifest.bind(buildProxyRoutePath(path), params);
|
|
3625
|
-
return createNestedProxy(
|
|
3626
|
-
[...path, scope.segment],
|
|
3627
|
-
client,
|
|
3628
|
-
routeMeta,
|
|
3629
|
-
baseURL,
|
|
3630
|
-
sameOrigin,
|
|
3631
|
-
rootAliases,
|
|
3632
|
-
manifest,
|
|
3633
|
-
Object.freeze({ ...bound, ...scope.params })
|
|
3634
|
-
);
|
|
3635
|
-
};
|
|
3636
|
-
}
|
|
3637
|
-
if (prop === FARM_API_ROUTE_REF_SYMBOL) {
|
|
3638
|
-
return path.length > 0;
|
|
3639
|
-
}
|
|
3640
|
-
if (prop === FARM_API_ROUTE_META_SYMBOL) {
|
|
3641
|
-
let metadata;
|
|
3642
|
-
try {
|
|
3643
|
-
metadata = resolveRouteMeta({ path, baseURL, manifest, bound });
|
|
3644
|
-
} catch {
|
|
3645
|
-
return null;
|
|
3646
|
-
}
|
|
3647
|
-
const requestURL = resolveFarmAPIRequestURL(metadata.routePath, baseURL);
|
|
3648
|
-
return Object.freeze({
|
|
3649
|
-
path: `${requestURL.pathname}${requestURL.search}${requestURL.hash}`,
|
|
3650
|
-
method: metadata.method,
|
|
3651
|
-
baseURL: requestURL.origin,
|
|
3652
|
-
sameOrigin
|
|
3653
|
-
});
|
|
3654
|
-
}
|
|
3655
|
-
if (path.length === 0 && typeof prop === "string" && rootAliases && Object.prototype.hasOwnProperty.call(rootAliases, prop)) {
|
|
3656
|
-
return rootAliases[prop];
|
|
3657
|
-
}
|
|
3658
|
-
if (typeof prop !== "string") {
|
|
3659
|
-
return Reflect.get(_target, prop);
|
|
3660
|
-
}
|
|
3661
|
-
return createNestedProxy(
|
|
3662
|
-
[...path, prop],
|
|
3663
|
-
client,
|
|
3664
|
-
routeMeta,
|
|
3665
|
-
baseURL,
|
|
3666
|
-
sameOrigin,
|
|
3667
|
-
rootAliases,
|
|
3668
|
-
manifest,
|
|
3669
|
-
bound
|
|
3670
|
-
);
|
|
3671
|
-
},
|
|
3672
|
-
// When calling as a function
|
|
3673
|
-
apply(_target, _thisArg, args) {
|
|
3674
|
-
const lastPart = path[path.length - 1];
|
|
3675
|
-
const httpMethods = ["get", "head", "query", "post", "put", "delete", "patch", "options"];
|
|
3676
|
-
if (httpMethods.includes(lastPart)) {
|
|
3677
|
-
const routePath = buildProxyRoutePath(path.slice(0, -1));
|
|
3678
|
-
const method = lastPart.toUpperCase();
|
|
3679
|
-
const [options, clientOptions] = args;
|
|
3680
|
-
const resolved = manifest ? manifest.resolve(routePath, method, bound, options) : routePath;
|
|
3681
|
-
if (!manifest && options?.params)
|
|
3682
|
-
throw new TypeError("Dynamic params require the generated routes manifest.");
|
|
3683
|
-
return client(resolved, method, options, clientOptions);
|
|
3684
|
-
} else {
|
|
3685
|
-
const routePath = buildProxyRoutePath(path);
|
|
3686
|
-
const [options, clientOptions] = args;
|
|
3687
|
-
const method = options?.method || "GET";
|
|
3688
|
-
const resolved = manifest ? manifest.resolve(routePath, method, bound, options) : routePath;
|
|
3689
|
-
return client(resolved, method, options, clientOptions);
|
|
3690
|
-
}
|
|
3691
|
-
}
|
|
3692
|
-
});
|
|
3693
|
-
routeMeta.set(proxy, { path: [...path], baseURL, manifest, bound });
|
|
3694
|
-
return proxy;
|
|
3695
|
-
}
|
|
3696
|
-
__name(createNestedProxy, "createNestedProxy");
|
|
3697
|
-
function buildProxyRoutePath(path) {
|
|
3698
|
-
return "/api/" + path.join("/").replace(/^\/+/, "");
|
|
3699
|
-
}
|
|
3700
|
-
__name(buildProxyRoutePath, "buildProxyRoutePath");
|
|
3701
|
-
function createServerAPIClient(endpoints, options = {}) {
|
|
3702
|
-
if (options.integrations === false || Object.prototype.hasOwnProperty.call(endpoints, "integrations")) {
|
|
3703
|
-
return endpoints;
|
|
3704
|
-
}
|
|
3705
|
-
Object.defineProperty(endpoints, "integrations", {
|
|
3706
|
-
get() {
|
|
3707
|
-
return integrationsServer(
|
|
3708
|
-
typeof options.integrations === "object" ? options.integrations : {}
|
|
3709
|
-
);
|
|
3710
|
-
},
|
|
3711
|
-
enumerable: false,
|
|
3712
|
-
configurable: true
|
|
3713
|
-
});
|
|
3714
|
-
return endpoints;
|
|
3715
|
-
}
|
|
3716
|
-
__name(createServerAPIClient, "createServerAPIClient");
|
|
3717
|
-
var API_CACHE_REFETCH = /* @__PURE__ */ Symbol.for("farm.api.cache-refetch");
|
|
3718
|
-
function createCacheRefetch(request, path, method, input, key, cache, options, onError) {
|
|
3719
|
-
const readOptions = {
|
|
3720
|
-
cache: { ...cache, key, policy: "network-only", dedupeMs: 0 },
|
|
3721
|
-
retry: options?.retry,
|
|
3722
|
-
timeoutMs: options?.timeoutMs
|
|
3723
|
-
};
|
|
3724
|
-
return () => {
|
|
3725
|
-
void request(path, method, input, readOptions).catch((error) => {
|
|
3726
|
-
notifyClientObserver(onError, [normalizeError(error)]);
|
|
3727
|
-
});
|
|
3728
|
-
};
|
|
3729
|
-
}
|
|
3730
|
-
__name(createCacheRefetch, "createCacheRefetch");
|
|
3731
|
-
var optimisticStates = /* @__PURE__ */ new WeakMap();
|
|
3732
|
-
var cacheReadOwners = /* @__PURE__ */ new WeakMap();
|
|
3733
|
-
function getCacheReadOwners(cache) {
|
|
3734
|
-
let owners = cacheReadOwners.get(cache);
|
|
3735
|
-
if (!owners) {
|
|
3736
|
-
owners = /* @__PURE__ */ new Map();
|
|
3737
|
-
cacheReadOwners.set(cache, owners);
|
|
3738
|
-
}
|
|
3739
|
-
return owners;
|
|
3740
|
-
}
|
|
3741
|
-
__name(getCacheReadOwners, "getCacheReadOwners");
|
|
3742
|
-
function getOptimisticState(cache) {
|
|
3743
|
-
let state = optimisticStates.get(cache);
|
|
3744
|
-
if (!state) {
|
|
3745
|
-
state = /* @__PURE__ */ new Map();
|
|
3746
|
-
optimisticStates.set(cache, state);
|
|
3747
|
-
}
|
|
3748
|
-
return state;
|
|
3749
|
-
}
|
|
3750
|
-
__name(getOptimisticState, "getOptimisticState");
|
|
3751
|
-
function applyOptimisticLayer(entry, layer) {
|
|
3752
|
-
let data = entry?.data;
|
|
3753
|
-
for (const updater of layer.updaters) data = updater(data);
|
|
3754
|
-
return {
|
|
3755
|
-
data,
|
|
3756
|
-
updatedAt: layer.updatedAt,
|
|
3757
|
-
staleAt: entry?.staleAt ?? layer.staleAt,
|
|
3758
|
-
gcAt: entry?.gcAt ?? layer.gcAt,
|
|
3759
|
-
invalidatedAt: entry?.invalidatedAt,
|
|
3760
|
-
[API_CACHE_REFETCH]: entry?.[API_CACHE_REFETCH]
|
|
3761
|
-
};
|
|
3762
|
-
}
|
|
3763
|
-
__name(applyOptimisticLayer, "applyOptimisticLayer");
|
|
3764
|
-
function storeOptimisticEntry(cacheState, key, stack, entry) {
|
|
3765
|
-
if (!entry) {
|
|
3766
|
-
cacheState.delete(key);
|
|
3767
|
-
stack.renderedEntry = void 0;
|
|
3768
|
-
return;
|
|
3769
|
-
}
|
|
3770
|
-
cacheState.set(key, entry);
|
|
3771
|
-
if (stack.invalidatedAt !== void 0) {
|
|
3772
|
-
cacheState.invalidate(key, stack.invalidatedAt);
|
|
3773
|
-
}
|
|
3774
|
-
stack.renderedEntry = cacheState.get(key);
|
|
3775
|
-
}
|
|
3776
|
-
__name(storeOptimisticEntry, "storeOptimisticEntry");
|
|
3777
|
-
function reconcileOptimisticInvalidation(cacheState, key, stack) {
|
|
3778
|
-
const current = cacheState.get(key);
|
|
3779
|
-
const rendered = stack.renderedEntry;
|
|
3780
|
-
if (current === rendered) return true;
|
|
3781
|
-
if (!current || !rendered || current.data !== rendered.data || current.updatedAt !== rendered.updatedAt || current.gcAt !== rendered.gcAt || current.status !== rendered.status || current.error !== rendered.error || current.fetching !== rendered.fetching || current.staleAt !== 0 || current.invalidatedAt === void 0) {
|
|
3782
|
-
return false;
|
|
3783
|
-
}
|
|
3784
|
-
stack.invalidatedAt = current.invalidatedAt;
|
|
3785
|
-
stack.renderedEntry = current;
|
|
3786
|
-
return true;
|
|
3787
|
-
}
|
|
3788
|
-
__name(reconcileOptimisticInvalidation, "reconcileOptimisticInvalidation");
|
|
3789
|
-
function renderOptimisticStack(cacheState, key, stack) {
|
|
3790
|
-
let entry = stack.entry ? { ...stack.entry } : void 0;
|
|
3791
|
-
for (const layer of stack.layers) entry = applyOptimisticLayer(entry, layer);
|
|
3792
|
-
storeOptimisticEntry(cacheState, key, stack, entry);
|
|
3793
|
-
}
|
|
3794
|
-
__name(renderOptimisticStack, "renderOptimisticStack");
|
|
3795
|
-
function settleOptimisticUpdates(cacheState, optimisticState, snapshots, outcome) {
|
|
3796
|
-
const settledKeys = [];
|
|
3797
|
-
for (const snapshot of snapshots) {
|
|
3798
|
-
const stack = optimisticState.get(snapshot.key);
|
|
3799
|
-
if (stack !== snapshot.stack) continue;
|
|
3800
|
-
if (!reconcileOptimisticInvalidation(cacheState, snapshot.key, stack)) {
|
|
3801
|
-
optimisticState.delete(snapshot.key);
|
|
3802
|
-
continue;
|
|
3803
|
-
}
|
|
3804
|
-
if (outcome === "rollback") {
|
|
3805
|
-
stack.layers = stack.layers.filter((layer) => layer !== snapshot.layer);
|
|
3806
|
-
} else {
|
|
3807
|
-
snapshot.layer.committed = true;
|
|
3808
|
-
if (outcome === "invalidate") stack.invalidatedAt = Date.now();
|
|
3809
|
-
}
|
|
3810
|
-
while (stack.layers[0]?.committed) {
|
|
3811
|
-
stack.entry = applyOptimisticLayer(stack.entry, stack.layers.shift());
|
|
3812
|
-
}
|
|
3813
|
-
renderOptimisticStack(cacheState, snapshot.key, stack);
|
|
3814
|
-
if (stack.layers.length === 0) optimisticState.delete(snapshot.key);
|
|
3815
|
-
settledKeys.push(snapshot.key);
|
|
3816
|
-
}
|
|
3817
|
-
return settledKeys;
|
|
3818
|
-
}
|
|
3819
|
-
__name(settleOptimisticUpdates, "settleOptimisticUpdates");
|
|
3820
|
-
function buildCacheKey(method, path, input, baseURL, defaultHeaders) {
|
|
3821
|
-
const keyInput = input && typeof input === "object" ? {
|
|
3822
|
-
query: input.query,
|
|
3823
|
-
body: input.body,
|
|
3824
|
-
...method === "QUERY" ? {
|
|
3825
|
-
contentType: getHeader(input.headers, "content-type") ?? getHeader(defaultHeaders, "content-type") ?? "application/json",
|
|
3826
|
-
contentEncoding: getHeader(input.headers, "content-encoding") ?? getHeader(defaultHeaders, "content-encoding")
|
|
3827
|
-
} : {}
|
|
3828
|
-
} : input;
|
|
3829
|
-
const url = resolveFarmAPIRequestURL(path, baseURL);
|
|
3830
|
-
return `${method}:${url.origin}${url.pathname}:${stableStringify(keyInput ?? {})}`;
|
|
3831
|
-
}
|
|
3832
|
-
__name(buildCacheKey, "buildCacheKey");
|
|
3833
|
-
function isSameOriginAPIBaseURL(baseURL) {
|
|
3834
|
-
if (typeof window === "undefined") return baseURL.startsWith("/");
|
|
3835
|
-
return resolveFarmAPIRequestURL("/api", baseURL).origin === window.location.origin;
|
|
3836
|
-
}
|
|
3837
|
-
__name(isSameOriginAPIBaseURL, "isSameOriginAPIBaseURL");
|
|
3838
|
-
function stableStringify(value) {
|
|
3839
|
-
if (value === null || value === void 0) return String(value);
|
|
3840
|
-
if (value instanceof Date) return value.toISOString();
|
|
3841
|
-
if (typeof value === "bigint") return `bigint:${value.toString()}`;
|
|
3842
|
-
if (typeof value !== "object") return JSON.stringify(value);
|
|
3843
|
-
if (Array.isArray(value)) {
|
|
3844
|
-
return `[${value.map((item) => stableStringify(item)).join(",")}]`;
|
|
3845
|
-
}
|
|
3846
|
-
if (value instanceof URLSearchParams) {
|
|
3847
|
-
return `urlsearchparams:${stableStringify(Array.from(value.entries()))}`;
|
|
3848
|
-
}
|
|
3849
|
-
const keys = Object.keys(value).sort();
|
|
3850
|
-
const entries = keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`);
|
|
3851
|
-
return `{${entries.join(",")}}`;
|
|
3852
|
-
}
|
|
3853
|
-
__name(stableStringify, "stableStringify");
|
|
3854
|
-
function getHeader(headers, name) {
|
|
3855
|
-
if (!headers || typeof headers !== "object") return void 0;
|
|
3856
|
-
if (typeof Headers !== "undefined" && headers instanceof Headers) {
|
|
3857
|
-
return headers.get(name) ?? void 0;
|
|
3858
|
-
}
|
|
3859
|
-
const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name);
|
|
3860
|
-
return entry?.[1] === void 0 ? void 0 : String(entry[1]);
|
|
3861
|
-
}
|
|
3862
|
-
__name(getHeader, "getHeader");
|
|
3863
|
-
function getRequestCacheContext(options, input, scope) {
|
|
3864
|
-
const credentials = options.credentials ?? "same-origin";
|
|
3865
|
-
const headers = new Headers(options.headers);
|
|
3866
|
-
const requestHeaders = input && typeof input === "object" && "headers" in input ? input.headers : void 0;
|
|
3867
|
-
if (requestHeaders) {
|
|
3868
|
-
new Headers(requestHeaders).forEach((value, key) => headers.set(key, value));
|
|
3869
|
-
}
|
|
3870
|
-
const carriesBrowserIdentity = credentials !== "omit" || [...headers].length > 0;
|
|
3871
|
-
if (scope !== "client" && !carriesBrowserIdentity) return void 0;
|
|
3872
|
-
return stableStringify({
|
|
3873
|
-
credentials,
|
|
3874
|
-
headers: [...headers].sort(([left], [right]) => left.localeCompare(right))
|
|
3875
|
-
});
|
|
3876
|
-
}
|
|
3877
|
-
__name(getRequestCacheContext, "getRequestCacheContext");
|
|
3878
|
-
function getGcAt(now, gcTime) {
|
|
3879
|
-
if (gcTime === void 0) return void 0;
|
|
3880
|
-
if (!Number.isFinite(gcTime) || gcTime <= 0) return now;
|
|
3881
|
-
return now + gcTime;
|
|
3882
|
-
}
|
|
3883
|
-
__name(getGcAt, "getGcAt");
|
|
3884
|
-
function getValidCacheEntry(cacheState, key, now) {
|
|
3885
|
-
const entry = cacheState.get(key);
|
|
3886
|
-
if (!entry) return void 0;
|
|
3887
|
-
if (entry.gcAt !== void 0 && now >= entry.gcAt) {
|
|
3888
|
-
cacheState.delete(key);
|
|
3889
|
-
return void 0;
|
|
3890
|
-
}
|
|
3891
|
-
return entry;
|
|
3892
|
-
}
|
|
3893
|
-
__name(getValidCacheEntry, "getValidCacheEntry");
|
|
3894
|
-
function isEntryStale(entry, now) {
|
|
3895
|
-
if (entry.invalidatedAt !== void 0) return true;
|
|
3896
|
-
return now >= entry.staleAt;
|
|
3897
|
-
}
|
|
3898
|
-
__name(isEntryStale, "isEntryStale");
|
|
3899
|
-
function resolveTargetKey(routeMeta, target, input, baseURL = "http://localhost:3000", defaultHeaders, localBaseURL) {
|
|
3900
|
-
if (!target) return null;
|
|
3901
|
-
if (typeof target === "string") return target;
|
|
3902
|
-
if (typeof target === "function") {
|
|
3903
|
-
const meta = routeMeta.get(target);
|
|
3904
|
-
if (!meta) return null;
|
|
3905
|
-
const { method, routePath } = resolveRouteMeta(meta, input);
|
|
3906
|
-
return buildCacheKey(
|
|
3907
|
-
method,
|
|
3908
|
-
routePath,
|
|
3909
|
-
input ?? {},
|
|
3910
|
-
localBaseURL ?? meta.baseURL,
|
|
3911
|
-
defaultHeaders
|
|
3912
|
-
);
|
|
3913
|
-
}
|
|
3914
|
-
if (Array.isArray(target)) {
|
|
3915
|
-
const [route, routeInput] = target;
|
|
3916
|
-
if (typeof route === "function") {
|
|
3917
|
-
return resolveTargetKey(routeMeta, route, routeInput, baseURL, defaultHeaders, localBaseURL);
|
|
3918
|
-
}
|
|
3919
|
-
return normalizeFarmClientCacheKey(target);
|
|
3920
|
-
}
|
|
3921
|
-
if ("key" in target) return normalizeFarmClientCacheKey(target.key);
|
|
3922
|
-
if ("path" in target) {
|
|
3923
|
-
const method = target.method ?? "GET";
|
|
3924
|
-
return buildCacheKey(method, target.path, target.input ?? {}, baseURL, defaultHeaders);
|
|
3925
|
-
}
|
|
3926
|
-
return null;
|
|
3927
|
-
}
|
|
3928
|
-
__name(resolveTargetKey, "resolveTargetKey");
|
|
3929
|
-
function resolveRouteMeta(meta, input) {
|
|
3930
|
-
const httpMethods = ["get", "head", "query", "post", "put", "delete", "patch", "options"];
|
|
3931
|
-
const lastPart = meta.path[meta.path.length - 1];
|
|
3932
|
-
if (lastPart && httpMethods.includes(lastPart)) {
|
|
3933
|
-
return {
|
|
3934
|
-
routePath: meta.manifest ? meta.manifest.resolve(
|
|
3935
|
-
buildProxyRoutePath(meta.path.slice(0, -1)),
|
|
3936
|
-
lastPart.toUpperCase(),
|
|
3937
|
-
meta.bound ?? {},
|
|
3938
|
-
input
|
|
3939
|
-
) : buildProxyRoutePath(meta.path.slice(0, -1)),
|
|
3940
|
-
method: lastPart.toUpperCase()
|
|
3941
|
-
};
|
|
3942
|
-
}
|
|
3943
|
-
return {
|
|
3944
|
-
routePath: meta.manifest ? meta.manifest.resolve(buildProxyRoutePath(meta.path), "GET", meta.bound ?? {}, input) : buildProxyRoutePath(meta.path),
|
|
3945
|
-
method: "GET"
|
|
3946
|
-
};
|
|
3947
|
-
}
|
|
3948
|
-
__name(resolveRouteMeta, "resolveRouteMeta");
|
|
3949
|
-
function normalizeError(error) {
|
|
3950
|
-
if (error instanceof APIClientError) return error;
|
|
3951
|
-
const normalized = new APIClientError("network_error", void 0, {
|
|
3952
|
-
status: 0,
|
|
3953
|
-
message: error instanceof Error ? error.message : typeof error === "string" ? error : "Network request failed"
|
|
3954
|
-
});
|
|
3955
|
-
normalized.cause = error;
|
|
3956
|
-
return normalized;
|
|
3957
|
-
}
|
|
3958
|
-
__name(normalizeError, "normalizeError");
|
|
3959
|
-
function notifyResponseObserver(observer, data, error, event) {
|
|
3960
|
-
notifyClientObserver(observer, [data, error, event], "API client onResponse");
|
|
3961
|
-
}
|
|
3962
|
-
__name(notifyResponseObserver, "notifyResponseObserver");
|
|
3963
|
-
function isFormData(value) {
|
|
3964
|
-
return typeof value === "object" && value !== null && (typeof FormData !== "undefined" && value instanceof FormData || Object.prototype.toString.call(value) === "[object FormData]" && typeof value.entries === "function");
|
|
3965
|
-
}
|
|
3966
|
-
__name(isFormData, "isFormData");
|
|
3967
|
-
function appendAPIQuery(searchParams, query) {
|
|
3968
|
-
if (query instanceof URLSearchParams) {
|
|
3969
|
-
const keys = new Set(query.keys());
|
|
3970
|
-
for (const key of keys) searchParams.delete(key);
|
|
3971
|
-
query.forEach((value, key) => searchParams.append(key, value));
|
|
3972
|
-
return;
|
|
3973
|
-
}
|
|
3974
|
-
if (!query || typeof query !== "object" || Array.isArray(query)) {
|
|
3975
|
-
throw new TypeError("API query input must be an object or URLSearchParams.");
|
|
3976
|
-
}
|
|
3977
|
-
for (const [key, value] of Object.entries(query)) {
|
|
3978
|
-
if (value === void 0 || value === null) continue;
|
|
3979
|
-
searchParams.delete(key);
|
|
3980
|
-
const values = Array.isArray(value) ? value : [value];
|
|
3981
|
-
for (const item of values) {
|
|
3982
|
-
if (item === void 0 || item === null) continue;
|
|
3983
|
-
if (!isAPIQueryPrimitive(item)) {
|
|
3984
|
-
throw new TypeError(
|
|
3985
|
-
`API query parameter "${key}" must be a string, number, boolean, bigint, or an array of those values.`
|
|
3986
|
-
);
|
|
3987
|
-
}
|
|
3988
|
-
searchParams.append(key, String(item));
|
|
3989
|
-
}
|
|
3990
|
-
}
|
|
3991
|
-
}
|
|
3992
|
-
__name(appendAPIQuery, "appendAPIQuery");
|
|
3993
|
-
function isAPIQueryPrimitive(value) {
|
|
3994
|
-
return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint";
|
|
3995
|
-
}
|
|
3996
|
-
__name(isAPIQueryPrimitive, "isAPIQueryPrimitive");
|
|
3997
|
-
function createResponseError2(response, data, cause) {
|
|
3998
|
-
const expected = readEndpointErrorEnvelope(data);
|
|
3999
|
-
if (expected) {
|
|
4000
|
-
return new APIClientError(expected.code, expected.data, {
|
|
4001
|
-
status: response.status,
|
|
4002
|
-
message: expected.message,
|
|
4003
|
-
response
|
|
4004
|
-
});
|
|
4005
|
-
}
|
|
4006
|
-
const error = new APIClientError("http_error", data, {
|
|
4007
|
-
status: response.status,
|
|
4008
|
-
message: `HTTP ${response.status}: ${response.statusText}`,
|
|
4009
|
-
response
|
|
4010
|
-
});
|
|
4011
|
-
if (cause !== void 0) error.cause = cause;
|
|
4012
|
-
return error;
|
|
4013
|
-
}
|
|
4014
|
-
__name(createResponseError2, "createResponseError");
|
|
4015
|
-
function readEndpointErrorEnvelope(data) {
|
|
4016
|
-
if (!data || typeof data !== "object") return null;
|
|
4017
|
-
const error = data.error;
|
|
4018
|
-
if (!error || typeof error !== "object") return null;
|
|
4019
|
-
const code = error.code;
|
|
4020
|
-
const message = error.message;
|
|
4021
|
-
if (typeof code !== "string" || typeof message !== "string") return null;
|
|
4022
|
-
return {
|
|
4023
|
-
code,
|
|
4024
|
-
message,
|
|
4025
|
-
data: error.data
|
|
4026
|
-
};
|
|
4027
|
-
}
|
|
4028
|
-
__name(readEndpointErrorEnvelope, "readEndpointErrorEnvelope");
|
|
4029
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
4030
|
-
0 && (module.exports = {
|
|
4031
|
-
APIClientError,
|
|
4032
|
-
createAPIClient,
|
|
4033
|
-
createApiClients,
|
|
4034
|
-
createServerAPIClient
|
|
4035
|
-
});
|
|
26
|
+
exports.APIClientError = _chunkIXTFU4PLcjs.APIClientError; exports.createAPIClient = _chunkIXTFU4PLcjs.createAPIClient; exports.createApiClients = _chunkIXTFU4PLcjs.createApiClients; exports.createServerAPIClient = _chunkIXTFU4PLcjs.createServerAPIClient;
|