@fanfare-io/fanfare-sdk-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +44 -0
  3. package/dist/adapters/google-analytics.d.ts +12 -0
  4. package/dist/adapters/google-analytics.js +1 -0
  5. package/dist/adapters/index.d.ts +9 -0
  6. package/dist/adapters/index.js +1 -0
  7. package/dist/adapters/types.d.ts +9 -0
  8. package/dist/appointments/appointment.module.d.ts +32 -0
  9. package/dist/appointments/appointment.module.js +1 -0
  10. package/dist/appointments/index.d.ts +2 -0
  11. package/dist/appointments/public.d.ts +1 -0
  12. package/dist/appointments/public.js +1 -0
  13. package/dist/appointments/types.d.ts +47 -0
  14. package/dist/auctions/auction.module.d.ts +58 -0
  15. package/dist/auctions/auction.module.js +1 -0
  16. package/dist/auctions/index.d.ts +5 -0
  17. package/dist/auctions/public.d.ts +5 -0
  18. package/dist/auctions/public.js +1 -0
  19. package/dist/auctions/types.d.ts +97 -0
  20. package/dist/auth/auth.module.d.ts +71 -0
  21. package/dist/auth/auth.module.js +1 -0
  22. package/dist/auth/index.d.ts +1 -0
  23. package/dist/auth/index.js +1 -0
  24. package/dist/auth/types.d.ts +112 -0
  25. package/dist/beacon/batching.d.ts +52 -0
  26. package/dist/beacon/batching.js +1 -0
  27. package/dist/beacon/beacon.module.d.ts +58 -0
  28. package/dist/beacon/beacon.module.js +1 -0
  29. package/dist/beacon/enrichment.d.ts +16 -0
  30. package/dist/beacon/enrichment.js +1 -0
  31. package/dist/beacon/index.d.ts +12 -0
  32. package/dist/beacon/public.d.ts +9 -0
  33. package/dist/beacon/public.js +1 -0
  34. package/dist/beacon/types.d.ts +103 -0
  35. package/dist/beacon/validation.d.ts +24 -0
  36. package/dist/beacon/validation.js +1 -0
  37. package/dist/challenges/challenge.module.d.ts +9 -0
  38. package/dist/challenges/challenge.module.js +1 -0
  39. package/dist/challenges/index.d.ts +3 -0
  40. package/dist/challenges/public.d.ts +9 -0
  41. package/dist/challenges/public.js +1 -0
  42. package/dist/challenges/types.d.ts +33 -0
  43. package/dist/config/index.d.ts +44 -0
  44. package/dist/config/index.js +1 -0
  45. package/dist/core/client.d.ts +15 -0
  46. package/dist/core/client.js +2 -0
  47. package/dist/core/errors.d.ts +175 -0
  48. package/dist/core/errors.js +1 -0
  49. package/dist/core/http.d.ts +87 -0
  50. package/dist/core/http.js +1 -0
  51. package/dist/core/logger.d.ts +46 -0
  52. package/dist/core/logger.js +1 -0
  53. package/dist/core/money.d.ts +10 -0
  54. package/dist/core/money.js +1 -0
  55. package/dist/core/parse-response.d.ts +62 -0
  56. package/dist/core/parse-response.js +1 -0
  57. package/dist/core/utils.d.ts +67 -0
  58. package/dist/core/utils.js +1 -0
  59. package/dist/draws/draw.module.d.ts +40 -0
  60. package/dist/draws/draw.module.js +1 -0
  61. package/dist/draws/index.d.ts +5 -0
  62. package/dist/draws/public.d.ts +6 -0
  63. package/dist/draws/public.js +1 -0
  64. package/dist/draws/types.d.ts +90 -0
  65. package/dist/draws/types.js +1 -0
  66. package/dist/errors.d.ts +5 -0
  67. package/dist/errors.js +1 -0
  68. package/dist/events.d.ts +5 -0
  69. package/dist/events.js +1 -0
  70. package/dist/experiences/distribution-monitor.runtime.d.ts +12 -0
  71. package/dist/experiences/distribution-monitor.runtime.js +1 -0
  72. package/dist/experiences/distribution-monitor.types.d.ts +62 -0
  73. package/dist/experiences/experience.module.d.ts +88 -0
  74. package/dist/experiences/experience.module.js +1 -0
  75. package/dist/experiences/index.d.ts +3 -0
  76. package/dist/experiences/index.js +1 -0
  77. package/dist/experiences/journey-contract.fixtures.d.ts +9 -0
  78. package/dist/experiences/journey-view.d.ts +22 -0
  79. package/dist/experiences/journey-view.js +1 -0
  80. package/dist/experiences/journey.d.ts +89 -0
  81. package/dist/experiences/journey.js +1 -0
  82. package/dist/experiences/journey.machine.d.ts +79 -0
  83. package/dist/experiences/journey.machine.js +1 -0
  84. package/dist/experiences/journey.types.d.ts +395 -0
  85. package/dist/experiences/public.d.ts +13 -0
  86. package/dist/experiences/public.js +1 -0
  87. package/dist/experiences/types.d.ts +161 -0
  88. package/dist/handoff/handoff.module.d.ts +184 -0
  89. package/dist/handoff/handoff.module.js +1 -0
  90. package/dist/handoff/index.d.ts +5 -0
  91. package/dist/handoff/index.js +1 -0
  92. package/dist/index.d.ts +11 -0
  93. package/dist/index.js +1 -0
  94. package/dist/internals.d.ts +11 -0
  95. package/dist/internals.js +1 -0
  96. package/dist/queues/index.d.ts +5 -0
  97. package/dist/queues/index.js +1 -0
  98. package/dist/queues/qualitative-bucket.d.ts +12 -0
  99. package/dist/queues/qualitative-bucket.js +1 -0
  100. package/dist/queues/queue.module.d.ts +42 -0
  101. package/dist/queues/queue.module.js +1 -0
  102. package/dist/queues/types.d.ts +112 -0
  103. package/dist/queues/types.js +1 -0
  104. package/dist/security/admission-proof.d.ts +15 -0
  105. package/dist/security/admission-proof.js +1 -0
  106. package/dist/state/capability-token-registry.d.ts +44 -0
  107. package/dist/state/capability-token-registry.js +1 -0
  108. package/dist/state/events.d.ts +342 -0
  109. package/dist/state/events.js +1 -0
  110. package/dist/state/store.d.ts +48 -0
  111. package/dist/state/store.js +1 -0
  112. package/dist/sync/broadcast-transport.d.ts +19 -0
  113. package/dist/sync/broadcast-transport.js +1 -0
  114. package/dist/sync/cross-tab-coordinator.d.ts +44 -0
  115. package/dist/sync/cross-tab-coordinator.js +1 -0
  116. package/dist/sync/index.d.ts +8 -0
  117. package/dist/sync/localstorage-transport.d.ts +32 -0
  118. package/dist/sync/localstorage-transport.js +1 -0
  119. package/dist/sync/protocol-transport.d.ts +51 -0
  120. package/dist/sync/protocol-transport.js +1 -0
  121. package/dist/sync/protocol.d.ts +254 -0
  122. package/dist/sync/protocol.js +1 -0
  123. package/dist/sync/recovery.d.ts +68 -0
  124. package/dist/sync/transport-factory.d.ts +16 -0
  125. package/dist/sync/transport-factory.js +1 -0
  126. package/dist/sync/transport-interface.d.ts +33 -0
  127. package/dist/sync/transport.d.ts +49 -0
  128. package/dist/sync/transport.js +1 -0
  129. package/dist/test-utils/harness-scenarios.d.ts +71 -0
  130. package/dist/test-utils/harness-scenarios.js +1 -0
  131. package/dist/test-utils/index.d.ts +12 -0
  132. package/dist/test-utils/index.js +1 -0
  133. package/dist/test-utils/mock-journey.d.ts +63 -0
  134. package/dist/test-utils/mock-journey.js +1 -0
  135. package/dist/test-utils/mock-sdk-vitest.d.ts +80 -0
  136. package/dist/test-utils/mock-sdk-vitest.js +1 -0
  137. package/dist/test-utils/mock-sdk.d.ts +22 -0
  138. package/dist/test-utils/mock-sdk.js +1 -0
  139. package/dist/test-utils/mock-server.d.ts +105 -0
  140. package/dist/test-utils/mock-server.js +1 -0
  141. package/dist/test-utils/sdk-factory.d.ts +3 -0
  142. package/dist/test-utils/sdk-factory.js +1 -0
  143. package/dist/test-utils/verification-scenarios.d.ts +43 -0
  144. package/dist/test-utils/verification-scenarios.js +1 -0
  145. package/dist/test-utils/verification-state.d.ts +1 -0
  146. package/dist/test-utils/verification-state.js +1 -0
  147. package/dist/theme.d.ts +8 -0
  148. package/dist/theme.js +1 -0
  149. package/dist/timed-releases/index.d.ts +6 -0
  150. package/dist/timed-releases/public.d.ts +6 -0
  151. package/dist/timed-releases/public.js +1 -0
  152. package/dist/timed-releases/timed-release.module.d.ts +31 -0
  153. package/dist/timed-releases/timed-release.module.js +1 -0
  154. package/dist/timed-releases/types.d.ts +70 -0
  155. package/dist/timed-releases/types.js +1 -0
  156. package/dist/types/distribution-type.d.ts +45 -0
  157. package/dist/types/index.d.ts +178 -0
  158. package/dist/utils/fingerprint.module.d.ts +27 -0
  159. package/dist/utils/fingerprint.module.js +1 -0
  160. package/dist/utils/index.d.ts +4 -0
  161. package/dist/version.d.ts +5 -0
  162. package/dist/version.js +1 -0
  163. package/dist/waitlists/index.d.ts +2 -0
  164. package/dist/waitlists/public.d.ts +6 -0
  165. package/dist/waitlists/public.js +1 -0
  166. package/dist/waitlists/types.d.ts +50 -0
  167. package/dist/waitlists/types.js +1 -0
  168. package/dist/waitlists/waitlist.module.d.ts +17 -0
  169. package/dist/waitlists/waitlist.module.js +1 -0
  170. package/package.json +205 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,44 @@
1
+ # @fanfare-io/fanfare-sdk-core
2
+
3
+ Framework-agnostic browser SDK for [Fanfare](https://www.fanfare.io) controlled-access experiences: queues, draws, auctions, timed releases, waitlists, and appointments.
4
+
5
+ The core concept is a **journey**: one consumer's progress through one Fanfare experience. Your application reads the current `JourneyView` and offers only the actions present in that view. The [React](https://www.npmjs.com/package/@fanfare-io/fanfare-sdk-react) and [Solid / web component](https://www.npmjs.com/package/@fanfare-io/fanfare-sdk-solid) adapters build on this package; use core directly when you want to own the UI.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @fanfare-io/fanfare-sdk-core
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import initFanfare from "@fanfare-io/fanfare-sdk-core";
17
+
18
+ const sdk = await initFanfare({
19
+ organizationId: "org_123",
20
+ publishableKey: "pk_live_123",
21
+ });
22
+
23
+ const journey = sdk.journeys.get("exp_123");
24
+
25
+ journey.view$.listen((view) => {
26
+ if (view.journeyStage === "ready") {
27
+ // offer view.start()
28
+ }
29
+ });
30
+ ```
31
+
32
+ The published artifact is self-contained: installable, runnable, and typecheckable using only public package dependencies.
33
+
34
+ ## Documentation
35
+
36
+ - [Core SDK quickstart](https://docs.fanfare.io/sdk/core/quickstart)
37
+ - [Journey state model](https://docs.fanfare.io/sdk/core/journey-state)
38
+ - [SDK overview](https://docs.fanfare.io/sdk/overview)
39
+ - [Website](https://www.fanfare.io)
40
+ - [Source & issues](https://github.com/fanfare-io/fanfare-sdk)
41
+
42
+ ## License
43
+
44
+ [Apache-2.0](./LICENSE)
@@ -0,0 +1,12 @@
1
+ import { SDKEventKey } from '../state/events';
2
+ import { CDPAdapter } from './types';
3
+ declare global {
4
+ interface Window {
5
+ gtag?: (...args: unknown[]) => void;
6
+ }
7
+ }
8
+ export interface GAAdapterOptions {
9
+ measurementId?: string;
10
+ events?: SDKEventKey[];
11
+ }
12
+ export declare function createGAAdapter(options?: GAAdapterOptions): CDPAdapter;
@@ -0,0 +1 @@
1
+ const e={"experience:entered":"fanfare_experience_entered","experience:left":"fanfare_experience_left","experience:distribution-entered":"fanfare_distribution_entered","queue:entered":"fanfare_queue_entered","queue:granted":"fanfare_queue_granted","queue:left":"fanfare_queue_left","queue:expired":"fanfare_queue_expired","draw:entered":"fanfare_draw_entered","draw:won":"fanfare_draw_won","draw:lost":"fanfare_draw_lost","auction:entered":"fanfare_auction_entered","auction:bid-placed":"fanfare_auction_bid_placed","auction:outbid":"fanfare_auction_outbid","auction:won":"fanfare_auction_won","auction:lost":"fanfare_auction_lost","waitlist:entered":"fanfare_waitlist_entered","waitlist:left":"fanfare_waitlist_left","timed_release:entered":"fanfare_timed_release_entered","timed_release:completed":"fanfare_timed_release_completed","auth:authenticated":"fanfare_auth_authenticated"},t=Object.keys(e),i={"experience:entered":e=>({experience_id:String(e.experienceId??"")}),"experience:left":e=>({experience_id:String(e.experienceId??"")}),"experience:distribution-entered":e=>({distribution_type:String(e.distributionType??""),distribution_id:String(e.distributionId??"")}),"queue:entered":e=>({queue_id:String(e.queueId??""),position:Number(e.position??0),...null!=e.estimatedWaitTime?{estimated_wait_time:Number(e.estimatedWaitTime)}:{}}),"queue:granted":e=>({queue_id:String(e.queueId??"")}),"queue:left":e=>({queue_id:String(e.queueId??""),...e.reason?{reason:String(e.reason)}:{}}),"queue:expired":e=>({queue_id:String(e.queueId??"")}),"draw:entered":e=>({draw_id:String(e.drawId??""),...e.entryNumber?{entry_number:String(e.entryNumber)}:{}}),"draw:won":e=>({draw_id:String(e.drawId??"")}),"draw:lost":e=>({draw_id:String(e.drawId??"")}),"auction:entered":e=>({auction_id:String(e.auctionId??"")}),"auction:bid-placed":e=>({auction_id:String(e.auctionId??""),amount:String(e.amount??""),status:String(e.status??"")}),"auction:outbid":e=>({auction_id:String(e.auctionId??""),your_bid:String(e.yourBid??""),highest_bid:String(e.highestBid??"")}),"auction:won":e=>({auction_id:String(e.auctionId??""),winning_bid:String(e.winningBid??"")}),"auction:lost":e=>({auction_id:String(e.auctionId??""),highest_bid:String(e.highestBid??"")}),"waitlist:entered":e=>({waitlist_id:String(e.waitlistId??""),sequence_id:String(e.sequenceId??"")}),"waitlist:left":e=>({waitlist_id:String(e.waitlistId??"")}),"timed_release:entered":e=>({timed_release_id:String(e.timedReleaseId??"")}),"timed_release:completed":e=>({timed_release_id:String(e.timedReleaseId??"")}),"auth:authenticated":e=>({is_new:Boolean(e.isNew)})};function n(n){const r=[];return{id:"google-analytics",init(a,d){if(r.length>0)throw new Error("GA adapter already initialized. Create a new adapter instance per SDK via createGAAdapter().");const u=[...new Set(d?.events??n?.events??t)];for(const t of u){const d=e[t];if(!d)continue;const u=a.on(t,e=>{if("undefined"==typeof window||"function"!=typeof window.gtag)return;const r=i[t],a={fanfare_event:t,...r?r(e):{},...n?.measurementId?{send_to:n.measurementId}:{}};window.gtag("event",d,a)});r.push(u)}},destroy(){for(const e of r)e();r.length=0}}}export{n as createGAAdapter};
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Experimental CDP adapter surface backing `sdk.use(adapter, config)`: the
3
+ * `CDPAdapter` contract for custom analytics adapters plus the bundled GA4
4
+ * adapter. Not yet a stability-guaranteed public API — shapes may change
5
+ * without a major bump (see docs/PUBLIC_SURFACE.md).
6
+ */
7
+ export { createGAAdapter } from './google-analytics';
8
+ export type { GAAdapterOptions } from './google-analytics';
9
+ export type { CDPAdapter, CDPAdapterConfig } from './types';
@@ -0,0 +1 @@
1
+ import{createGAAdapter as o}from"./google-analytics.js";export{o as createGAAdapter};
@@ -0,0 +1,9 @@
1
+ import { EventBus, SDKEventKey } from '../state/events';
2
+ export interface CDPAdapterConfig {
3
+ events?: SDKEventKey[];
4
+ }
5
+ export interface CDPAdapter {
6
+ readonly id: string;
7
+ init(eventBus: EventBus, config?: CDPAdapterConfig): void;
8
+ destroy(): void;
9
+ }
@@ -0,0 +1,32 @@
1
+ import { HttpClient } from '../core/http';
2
+ import { MonitorUpdate } from '../experiences/distribution-monitor.types';
3
+ import { AppointmentDetails } from '../experiences/types';
4
+ import { AppointmentBooking, AppointmentModule, AppointmentSlot } from './types';
5
+ export declare class AppointmentManagementModule implements AppointmentModule {
6
+ private readonly http;
7
+ private readonly logger;
8
+ private readonly monitorRuntime;
9
+ private readonly pollingIntervals;
10
+ private readonly monitorGenerations;
11
+ private readonly pollingIntervalMs;
12
+ private destroyed;
13
+ constructor(http: HttpClient, opts?: {
14
+ pollingIntervalMs?: number;
15
+ });
16
+ get(appointmentId: string): Promise<AppointmentDetails>;
17
+ getSlots(appointmentId: string, range: {
18
+ startDate: string;
19
+ endDate: string;
20
+ timezone?: string;
21
+ }): Promise<AppointmentSlot[]>;
22
+ getMe(appointmentId: string): Promise<AppointmentBooking | null>;
23
+ book(appointmentId: string, slotId: string, locationId?: string): Promise<AppointmentBooking>;
24
+ cancel(appointmentId: string, slotId: string, locationId?: string, reason?: string): Promise<void>;
25
+ reschedule(appointmentId: string, newSlotId: string, newLocationId?: string): Promise<AppointmentBooking>;
26
+ startMonitoring(id: string, context?: Record<string, unknown>, onUpdate?: (update: MonitorUpdate) => void): void;
27
+ stopMonitoring(id: string): void;
28
+ isMonitoring(id: string): boolean;
29
+ bumpMonitorGeneration(id: string): void;
30
+ destroy(): void;
31
+ private stopPolling;
32
+ }
@@ -0,0 +1 @@
1
+ import*as t from"valibot";import{isFanfareError as o,createError as n}from"../core/errors.js";import{getLogger as i}from"../core/logger.js";import{parseResponse as e}from"../core/parse-response.js";import{DistributionMonitorRuntime as r}from"../experiences/distribution-monitor.runtime.js";function s(t,o,n){const i=e(t,o,{endpoint:n},{throwOnFailure:!0});if(!i.ok)throw i.error;return i.value}const a=t.object({id:t.string(),startTime:t.string(),endTime:t.string(),locationId:t.nullish(t.string()),locationName:t.nullish(t.string()),timezone:t.nullish(t.string()),capacity:t.number(),available:t.number()}),l=t.object({slots:t.array(a)}),d=t.object({id:t.string(),type:t.literal("appointment"),openAt:t.nullish(t.string()),closeAt:t.nullish(t.string()),slotDurationMinutes:t.nullish(t.number()),timeZone:t.nullish(t.string()),locationId:t.nullish(t.string()),totalSlots:t.nullish(t.number()),availableSlots:t.nullish(t.number())}),m=t.picklist(["booked","checked_in","completed"]),c=t.object({bookingId:t.string(),appointmentId:t.string(),consumerId:t.string(),slotId:t.string(),locationId:t.nullish(t.string()),locationName:t.nullish(t.string()),startTime:t.string(),endTime:t.string(),confirmationCode:t.string(),status:m,createdAt:t.string()}),p=t.object({booking:t.nullish(t.object({bookingId:t.string(),appointmentId:t.string(),consumerId:t.string(),slotId:t.string(),locationId:t.nullish(t.string()),locationName:t.nullish(t.string()),joinUrl:t.nullish(t.string()),startTime:t.string(),endTime:t.string(),confirmationCode:t.nullish(t.string()),status:m}))}),g=t.object({bookingId:t.string(),previousSlotId:t.string(),newSlotId:t.string(),confirmationCode:t.string(),status:m});function h(t){return{id:t.id,startTime:t.startTime,endTime:t.endTime,locationId:t.locationId??void 0,locationName:t.locationName??void 0,timezone:t.timezone??void 0,capacity:t.capacity,available:t.available}}class u{constructor(t,o){this.logger=i(),this.monitorRuntime=new r,this.pollingIntervals=/* @__PURE__ */new Map,this.monitorGenerations=/* @__PURE__ */new Map,this.destroyed=!1,this.http=t,this.pollingIntervalMs=o?.pollingIntervalMs??3e4}async get(t){try{const o=await this.http.get(`/appointments/${t}`),n=s(d,o,`/appointments/${t}`);return{id:n.id,type:"appointment",openAt:n.openAt??void 0,closeAt:n.closeAt??void 0,slotDurationMinutes:n.slotDurationMinutes??void 0,bookingWindowOpenAt:n.openAt??void 0,bookingWindowCloseAt:n.closeAt??void 0,timezone:n.timeZone??void 0,locationId:n.locationId??void 0,totalSlots:n.totalSlots??void 0,availableSlots:n.availableSlots??void 0}}catch(i){if(this.logger.error("Failed to get appointment",{appointmentId:t,error:i}),o(i))throw i;throw n.networkError("Failed to get appointment",{error:i})}}async getSlots(t,i){try{const o=new URLSearchParams({startDate:i.startDate,endDate:i.endDate});i.timezone&&o.set("timezone",i.timezone);const n=await this.http.get(`/appointments/${t}/slots?${o.toString()}`);return s(l,n,`/appointments/${t}/slots`).slots.map(h)}catch(e){if(this.logger.error("Failed to get appointment slots",{appointmentId:t,error:e}),o(e))throw e;throw n.networkError("Failed to get appointment slots",{error:e})}}async getMe(t){try{const o=await this.http.get(`/appointments/${t}/me`),n=s(p,o,`/appointments/${t}/me`);return n.booking?function(t){return{bookingId:t.bookingId,appointmentId:t.appointmentId,slotId:t.slotId,locationId:t.locationId??void 0,locationName:t.locationName??void 0,joinUrl:t.joinUrl??void 0,startTime:t.startTime,endTime:t.endTime,confirmationCode:t.confirmationCode??void 0,consumerStatus:t.status}}(n.booking):null}catch(i){if(this.logger.error("Failed to get current booking",{appointmentId:t,error:i}),o(i))throw i;throw n.networkError("Failed to get current booking",{error:i})}}async book(t,i,e){try{const o=await this.http.post(`/appointments/${t}/book`,{slotId:i,locationId:e??null});return function(t){return{bookingId:t.bookingId,appointmentId:t.appointmentId,slotId:t.slotId,locationId:t.locationId??void 0,locationName:t.locationName??void 0,startTime:t.startTime,endTime:t.endTime,confirmationCode:t.confirmationCode,consumerStatus:t.status}}(s(c,o,`/appointments/${t}/book`))}catch(r){if(this.logger.error("Failed to book appointment",{appointmentId:t,slotId:i,locationId:e,error:r}),o(r))throw r;throw n.networkError("Failed to book appointment",{error:r})}}async cancel(t,i,e,r){try{await this.http.post(`/appointments/${t}/cancel`,{slotId:i,locationId:e??null,reason:r??null})}catch(s){if(this.logger.error("Failed to cancel appointment",{appointmentId:t,slotId:i,locationId:e,error:s}),o(s))throw s;throw n.networkError("Failed to cancel appointment",{error:s})}}async reschedule(t,i,e){try{const o=await this.http.post(`/appointments/${t}/reschedule`,{newSlotId:i,newLocationId:e??null}),n=s(g,o,`/appointments/${t}/reschedule`),r=await this.getMe(t);return r?{...r,confirmationCode:n.confirmationCode}:{bookingId:n.bookingId,appointmentId:t,slotId:n.newSlotId,locationId:e,startTime:"",endTime:"",confirmationCode:n.confirmationCode,consumerStatus:n.status}}catch(r){if(this.logger.error("Failed to reschedule appointment",{appointmentId:t,newSlotId:i,newLocationId:e,error:r}),o(r))throw r;throw n.networkError("Failed to reschedule appointment",{error:r})}}startMonitoring(t,o,n){if(this.destroyed)return;this.monitorRuntime.start(t,o,n),this.stopPolling(t);const i=(this.monitorGenerations.get(t)??0)+1;this.monitorGenerations.set(t,i);const e=async()=>{if(!this.destroyed&&this.monitorGenerations.get(t)===i)try{const o=await this.getMe(t);if(this.destroyed||this.monitorGenerations.get(t)!==i)return;const n=this.monitorRuntime.getDisplayAtom(t);if(!n)return;if(o){const t=Math.max(0,Date.parse(o.startTime)-Date.now());n.set({type:"appointment",booking:{slotId:o.slotId,locationId:o.locationId,locationName:o.locationName,joinUrl:o.joinUrl,startTime:o.startTime,endTime:o.endTime,confirmationCode:o.confirmationCode,consumerStatus:o.consumerStatus},msUntilStart:t})}else n.set({type:"appointment"})}catch(o){this.logger.error("Appointment polling tick failed",{id:t,error:o})}};e();const r=setInterval(()=>{e()},this.pollingIntervalMs);this.pollingIntervals.set(t,r)}stopMonitoring(t){this.stopPolling(t),this.monitorRuntime.stop(t),this.monitorGenerations.set(t,(this.monitorGenerations.get(t)??0)+1)}isMonitoring(t){return this.monitorRuntime.has(t)||this.pollingIntervals.has(t)}bumpMonitorGeneration(t){this.monitorGenerations.set(t,(this.monitorGenerations.get(t)??0)+1)}destroy(){this.destroyed=!0,this.monitorGenerations.clear();for(const t of Array.from(this.pollingIntervals.keys()))this.stopPolling(t);this.monitorRuntime.clear()}stopPolling(t){const o=this.pollingIntervals.get(t);void 0!==o&&(clearInterval(o),this.pollingIntervals.delete(t))}}export{u as AppointmentManagementModule};
@@ -0,0 +1,2 @@
1
+ export { AppointmentManagementModule } from './appointment.module';
2
+ export type { AppointmentBooking, AppointmentModule, AppointmentSlot } from './types';
@@ -0,0 +1 @@
1
+ export type { AppointmentBooking, AppointmentModule, AppointmentSlot } from './types';
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,47 @@
1
+ import { MonitorUpdate } from '../experiences/distribution-monitor.types';
2
+ export interface AppointmentSlot {
3
+ id: string;
4
+ startTime: string;
5
+ endTime: string;
6
+ locationId?: string;
7
+ locationName?: string;
8
+ timezone?: string;
9
+ capacity: number;
10
+ available: number;
11
+ }
12
+ export interface AppointmentBooking {
13
+ bookingId: string;
14
+ appointmentId: string;
15
+ slotId: string;
16
+ locationId?: string;
17
+ locationName?: string;
18
+ /** Join URL for online appointments. Absent for in-person bookings. */
19
+ joinUrl?: string;
20
+ startTime: string;
21
+ endTime: string;
22
+ confirmationCode?: string;
23
+ consumerStatus: "booked" | "checked_in" | "completed";
24
+ }
25
+ export interface AppointmentModule {
26
+ get(appointmentId: string): Promise<import('../experiences/types').AppointmentDetails>;
27
+ getSlots(appointmentId: string, range: {
28
+ startDate: string;
29
+ endDate: string;
30
+ timezone?: string;
31
+ }): Promise<AppointmentSlot[]>;
32
+ getMe(appointmentId: string): Promise<AppointmentBooking | null>;
33
+ book(appointmentId: string, slotId: string, locationId?: string): Promise<AppointmentBooking>;
34
+ cancel(appointmentId: string, slotId: string, locationId?: string, reason?: string): Promise<void>;
35
+ reschedule(appointmentId: string, newSlotId: string, newLocationId?: string): Promise<AppointmentBooking>;
36
+ startMonitoring(id: string, context?: Record<string, unknown>, onUpdate?: (update: MonitorUpdate) => void): void;
37
+ stopMonitoring(id: string): void;
38
+ isMonitoring(id: string): boolean;
39
+ /**
40
+ * Bump the monitor generation for `id` so any in-flight polling tick fails
41
+ * its post-await guard. Used by the journey after non-poll writes
42
+ * (book, reschedule) to prevent a concurrent tick from overwriting the
43
+ * fresh data with stale.
44
+ */
45
+ bumpMonitorGeneration(id: string): void;
46
+ destroy(): void;
47
+ }
@@ -0,0 +1,58 @@
1
+ import { HttpClient, RequestOptions } from '../core/http';
2
+ import { MonitorUpdate } from '../experiences/distribution-monitor.types';
3
+ import { AuctionDetails, AuctionModule, AuctionStatus, AutoRebidConfig, Bid, BidResult } from './types';
4
+ export declare class AuctionManagementModule implements AuctionModule {
5
+ private readonly http;
6
+ private readonly logger;
7
+ private readonly events;
8
+ private readonly trackedParticipations;
9
+ private readonly inFlightRequests;
10
+ private readonly pollingIntervals;
11
+ private readonly lastStatusCache;
12
+ private readonly autoRebidConfigs;
13
+ private readonly monitorRuntime;
14
+ private readonly bidHistoryCache;
15
+ private readonly auctionDetailsCache;
16
+ private readonly monitorGenerations;
17
+ private readonly operationGenerations;
18
+ private readonly diagnosticEmissionIds;
19
+ private readonly BID_HISTORY_CACHE_TTL;
20
+ private readonly AUCTION_DETAILS_CACHE_TTL;
21
+ private destroyed;
22
+ private lifecycleGeneration;
23
+ private get store();
24
+ constructor(http: HttpClient);
25
+ private computeMinNextBid;
26
+ private getAuctionDetailsCached;
27
+ private getTrackedParticipation;
28
+ private getAuctionCloseAt;
29
+ private buildDisplayState;
30
+ private emitTransitionEvents;
31
+ private applyTransition;
32
+ private checkOutbidConditions;
33
+ private buildBidTransition;
34
+ private buildStatusTransition;
35
+ private buildMissingTransition;
36
+ get(auctionId: string): Promise<AuctionDetails>;
37
+ bid(auctionId: string, amount: string, options?: RequestOptions): Promise<BidResult>;
38
+ enter(auctionId: string, metadata?: Record<string, unknown>, options?: RequestOptions): Promise<void>;
39
+ leave(auctionId: string, options?: RequestOptions): Promise<void>;
40
+ status(auctionId: string): Promise<AuctionStatus>;
41
+ private doStatus;
42
+ getBidHistory(auctionId: string): Promise<Bid[]>;
43
+ private startWatching;
44
+ private stopWatching;
45
+ private stopAllWatching;
46
+ private bumpMonitorGeneration;
47
+ private getOperationGeneration;
48
+ private bumpOperationGeneration;
49
+ private canApplyAsyncResult;
50
+ enableAutoRebid(auctionId: string, maxBid: string, increment: string): void;
51
+ disableAutoRebid(auctionId: string): void;
52
+ getAutoRebidConfig(auctionId: string): AutoRebidConfig | undefined;
53
+ private handleAutoRebid;
54
+ startMonitoring(id: string, context?: Record<string, unknown>, onUpdate?: (update: MonitorUpdate) => void): void;
55
+ stopMonitoring(id: string): void;
56
+ isMonitoring(id: string): boolean;
57
+ destroy(): void;
58
+ }
@@ -0,0 +1 @@
1
+ import{AuctionBidderStateResponseSchema as t,AuctionHighestBidResponseSchema as i,AuctionBidHistoryResponseSchema as e}from"@fanfare-io/fanfare-sdk-contracts/auction";import{createError as n}from"../core/errors.js";import{getLogger as a}from"../core/logger.js";import{isMoneyString as s,addMoney as o,isMoneyGreaterThan as r,normalizeMoney as d,isMoneyLessThanOrEqualTo as u,subtractMoney as c}from"../core/money.js";import{parseResponse as h}from"../core/parse-response.js";import{DistributionMonitorRuntime as l}from"../experiences/distribution-monitor.runtime.js";import{getEventBus as g}from"../state/events.js";import{getSDKStore as p}from"../state/store.js";class m{constructor(t){this.logger=a(),this.events=g(),this.trackedParticipations=/* @__PURE__ */new Map,this.inFlightRequests=/* @__PURE__ */new Map,this.pollingIntervals=/* @__PURE__ */new Map,this.lastStatusCache=/* @__PURE__ */new Map,this.autoRebidConfigs=/* @__PURE__ */new Map,this.monitorRuntime=new l,this.bidHistoryCache=/* @__PURE__ */new Map,this.auctionDetailsCache=/* @__PURE__ */new Map,this.monitorGenerations=/* @__PURE__ */new Map,this.operationGenerations=/* @__PURE__ */new Map,this.diagnosticEmissionIds=/* @__PURE__ */new Set,this.BID_HISTORY_CACHE_TTL=5e3,this.AUCTION_DETAILS_CACHE_TTL=3e4,this.destroyed=!1,this.lifecycleGeneration=0,this.http=t}get store(){return p()}computeMinNextBid(t,i){if(i&&s(t)&&s(i))return o(t,i)}async getAuctionDetailsCached(t){const i=this.auctionDetailsCache.get(t);if(i&&Date.now()-i.fetchedAt<this.AUCTION_DETAILS_CACHE_TTL)return i.details;const e=await this.http.get(`/auctions/${t}`);return this.auctionDetailsCache.set(t,{details:e,fetchedAt:Date.now()}),e}getTrackedParticipation(t){return this.trackedParticipations.get(t)}getAuctionCloseAt(t){return t.closeAt??t.settleAt}buildDisplayState(t,{status:i,highestBid:e,currentBid:n,bidCount:a}){return{highestBid:e,currentBid:n,bidCount:a,closeAt:this.getAuctionCloseAt(t),status:i,currencyCode:t.currencyCode,minNextBid:e?this.computeMinNextBid(e,t.minBidIncrement):void 0,bidIncrement:t.minBidIncrement??void 0}}emitTransitionEvents(t){for(const i of t)this.events.emit(i.type,i.payload)}applyTransition(t,i){i.trackedParticipation?this.trackedParticipations.set(t,i.trackedParticipation):this.trackedParticipations.delete(t);const e=this.monitorRuntime.getDisplayAtom(t);e&&i.displayState&&e.set({type:"auction",...i.displayState}),this.emitTransitionEvents(i.events),i.diagnosticError&&!this.diagnosticEmissionIds.has(t)?(this.diagnosticEmissionIds.add(t),this.logger.error("Auction monitoring diagnostic",{auctionId:t,error:i.diagnosticError}),this.events.emit("auction:error",{auctionId:t,error:i.diagnosticError})):i.diagnosticError||this.diagnosticEmissionIds.delete(t),i.monitorUpdate&&this.monitorRuntime.notify(t,i.monitorUpdate),i.stopWatching&&this.stopWatching(t),i.autoRebidStatus&&this.handleAutoRebid(t,i.autoRebidStatus)}checkOutbidConditions(t,i,e){if("winning"===t.status&&"outbid"===i.status)return!0;if(e?.currentBid&&i.highestBid){const n=e.currentBid,a=i.highestBid,o=t.highestBid||"0";if(s(n)&&s(a)&&s(o))return r(a,o)&&r(a,n)&&"winning"!==i.status}return"outbid"!==t.status&&"outbid"===i.status}buildBidTransition(t,i,e,n,a){const s="winning"===i.status?"winning":"outbid"===i.status?"outbid":"bidding";return{trackedParticipation:{auctionId:t,enteredAt:a?.enteredAt??/* @__PURE__ */(new Date).toISOString(),status:s,currentBid:e,highestBid:i.highestBid,bidCount:i.bidCount,lastBidAt:/* @__PURE__ */(new Date).toISOString(),metadata:a?.metadata,fingerprint:a?.fingerprint},displayState:this.buildDisplayState(n,{status:i.status,highestBid:i.highestBid,currentBid:e,bidCount:i.bidCount}),events:[{type:"auction:bid-placed",payload:{auctionId:t,amount:e,status:i.status}},..."winning"===i.status?[{type:"auction:winning",payload:{auctionId:t,amount:e,highestBid:i.highestBid}}]:[],..."outbid"===i.status?[{type:"auction:outbid",payload:{auctionId:t,yourBid:e,highestBid:i.highestBid}}]:[]],monitorUpdate:null,stopWatching:!1,autoRebidStatus:null}}buildStatusTransition(t,i,e,{previousParticipation:n,previousStatus:a}){const s=i.currentBid??n?.currentBid,o=i.bidCount??n?.bidCount;if(i.timeRemaining<=0){const a="winning"===i.status;return a&&!i.admissionGrant?{trackedParticipation:{auctionId:t,enteredAt:n?.enteredAt??/* @__PURE__ */(new Date).toISOString(),status:"winning",currentBid:s,highestBid:i.highestBid,bidCount:o,metadata:n?.metadata,fingerprint:n?.fingerprint},displayState:this.buildDisplayState(e,{status:"winning",highestBid:i.highestBid,currentBid:s,bidCount:o}),events:[],monitorUpdate:null,stopWatching:!1,autoRebidStatus:null,diagnosticError:new Error("Auction resolved to terminal winning without admissionGrant")}:{trackedParticipation:null,displayState:this.buildDisplayState(e,{status:a?"won":"lost",highestBid:i.highestBid,currentBid:s,bidCount:o}),events:a?[{type:"auction:won",payload:{auctionId:t,winningBid:s??""}}]:[{type:"auction:lost",payload:{auctionId:t,highestBid:i.highestBid}}],monitorUpdate:a&&i.admissionGrant?{type:"granted",token:i.admissionGrant}:a?null:{type:"ended",outcome:{type:"lost"}},stopWatching:!0,autoRebidStatus:null}}const r={auctionId:t,enteredAt:n?.enteredAt??/* @__PURE__ */(new Date).toISOString(),status:i.status,currentBid:s,highestBid:i.highestBid,bidCount:o,metadata:n?.metadata,fingerprint:n?.fingerprint},d=[];let u=null;return a&&(this.checkOutbidConditions(a,i,n)&&(d.push({type:"auction:outbid",payload:{auctionId:t,yourBid:a.currentBid||n?.currentBid||"",highestBid:i.highestBid}}),u=i),"winning"!==a.status&&"winning"===i.status&&d.push({type:"auction:winning",payload:{auctionId:t,amount:s||"",highestBid:i.highestBid}}),a.highestBid!==i.highestBid&&"winning"!==i.status&&d.push({type:"auction:bid-updated",payload:{auctionId:t,highestBid:i.highestBid,bidCount:i.bidCount||0}})),{trackedParticipation:r,displayState:this.buildDisplayState(e,{status:i.status,highestBid:i.highestBid,currentBid:s,bidCount:o}),events:d,monitorUpdate:null,stopWatching:!1,autoRebidStatus:u}}buildMissingTransition(){return{trackedParticipation:null,displayState:{status:"lost"},events:[],monitorUpdate:{type:"ended",outcome:{type:"closed",reason:"not_participating"}},stopWatching:!0,autoRebidStatus:null}}async get(t){try{return await this.getAuctionDetailsCached(t)}catch(i){throw this.logger.error("Failed to get auction",{auctionId:t,error:i}),i}}async bid(e,a,o){try{const r=this.lifecycleGeneration;if(!s(a))throw n.validationError("Invalid bid amount format. Must be a numeric string (e.g., '100.00')");if(!this.store.session)throw n.unauthorized("Not authenticated. Call auth.guest() or auth.login() first");let u=this.bumpOperationGeneration(e),c=this.getTrackedParticipation(e);c||(this.logger.warn("Attempting to bid without entering auction first",{auctionId:e}),await this.enter(e,void 0,o),c=this.getTrackedParticipation(e),u=this.bumpOperationGeneration(e)),this.logger.info("Placing bid",{auctionId:e,amount:a});const l=`/auctions/${e}/bid`,g=`/auctions/${e}/highest-bid`,[p,m,b]=await Promise.all([this.http.post(l,{amount:a},o),this.http.get(g),this.getAuctionDetailsCached(e)]),y=h(t,p,{endpoint:l},{throwOnFailure:!0});if(!y.ok)throw y.error;const I=h(i,m,{endpoint:g},{throwOnFailure:!0});if(!I.ok)throw I.error;const f=y.value,B=I.value,w=d(B.amount),v={status:"WINNING"===f.status||"WON"===f.status?"winning":"OUTBID"===f.status||"BIDDING"===f.status||"LOST"===f.status?"outbid":"accepted",amount:a,highestBid:w,bidCount:f.bidCount??(c?.bidCount||0)+1};return this.canApplyAsyncResult(e,r,void 0,u)?(this.applyTransition(e,this.buildBidTransition(e,v,a,b,c)),v):v}catch(r){throw this.logger.error("Failed to place bid",{auctionId:e,amount:a,error:r}),this.events.emit("auction:error",{auctionId:e,error:r}),r}}async enter(t,i,e){try{const s=this.lifecycleGeneration,o=this.store.session;if(!o)throw n.unauthorized("Not authenticated. Call auth.guest() or auth.login() first");const r=this.bumpOperationGeneration(t);this.logger.info("Entering auction",{auctionId:t});try{await this.http.post(`/auctions/${t}/enter`,{metadata:i},e)}catch(a){if(404!==a?.status)throw a}if(!this.canApplyAsyncResult(t,s,void 0,r))return;this.trackedParticipations.set(t,{auctionId:t,enteredAt:/* @__PURE__ */(new Date).toISOString(),status:"watching",metadata:i,fingerprint:o.deviceFingerprint}),this.emitTransitionEvents([{type:"auction:entered",payload:{auctionId:t}}])}catch(a){throw this.logger.error("Failed to enter auction",{auctionId:t,error:a}),this.events.emit("auction:error",{auctionId:t,error:a}),a}}async leave(t,i){try{const e=this.lifecycleGeneration,n=this.bumpOperationGeneration(t);this.logger.info("Leaving auction",{auctionId:t}),this.stopMonitoring(t);try{await this.http.post(`/auctions/${t}/leave`,void 0,i)}catch{this.logger.debug("Leave endpoint not available",{auctionId:t})}if(!this.canApplyAsyncResult(t,e,void 0,n))return;this.trackedParticipations.delete(t),this.emitTransitionEvents([{type:"auction:left",payload:{auctionId:t}}])}catch(e){throw this.logger.error("Failed to leave auction",{auctionId:t,error:e}),this.events.emit("auction:error",{auctionId:t,error:e}),e}}async status(t){const i=this.inFlightRequests.get(t);if(i)return this.logger.debug("Returning existing in-flight request",{auctionId:t}),i;const e=this.lifecycleGeneration,n=this.bumpOperationGeneration(t),a=this.doStatus(t,e,void 0,n).finally(()=>{this.inFlightRequests.delete(t)});return this.inFlightRequests.set(t,a),a}async doStatus(e,n,a,s){try{const o=`/auctions/${e}/status`,r=`/auctions/${e}/highest-bid`,[u,c,l]=await Promise.all([this.http.get(o),this.http.get(r),this.getAuctionDetailsCached(e)]),g=h(t,u,{endpoint:o},{throwOnFailure:!0});if(!g.ok)throw g.error;const p=h(i,c,{endpoint:r},{throwOnFailure:!0});if(!p.ok)throw p.error;const m=g.value,b=p.value,y=this.getAuctionCloseAt(l),I=y?new Date(y).getTime():Number.NaN,f=d(b.amount),B=this.getTrackedParticipation(e),w=m.lastBidAmount??m.winningBidAmount;let v="watching";"WINNING"===m.status||"WON"===m.status?v="winning":"OUTBID"!==m.status&&"LOST"!==m.status&&"BIDDING"!==m.status||(v="outbid");const A={auctionId:e,status:v,currentBid:B?.currentBid??(w?d(w):void 0),highestBid:f,timeRemaining:Number.isFinite(I)?Math.max(0,I-Date.now()):0,bidCount:m.bidCount,admissionGrant:m.admissionGrant};if(!this.canApplyAsyncResult(e,n,a,s))return A;const C=this.buildStatusTransition(e,A,l,{previousParticipation:B,previousStatus:this.lastStatusCache.get(e)});return this.applyTransition(e,C),C.stopWatching?this.lastStatusCache.delete(e):this.lastStatusCache.set(e,A),this.events.emit("auction:status-updated",{auctionId:e,status:A}),A}catch(o){if(o&&"object"==typeof o&&"status"in o&&404===o.status){const t={auctionId:e,status:"watching",highestBid:"0.00",timeRemaining:0};if(!this.canApplyAsyncResult(e,n,a,s))return t;const i=this.buildMissingTransition();return this.applyTransition(e,i),this.lastStatusCache.delete(e),this.events.emit("auction:status-updated",{auctionId:e,status:t}),t}if(!this.canApplyAsyncResult(e,n,a,s))return this.lastStatusCache.get(e)??{auctionId:e,status:"watching",highestBid:"0.00",timeRemaining:0};throw this.logger.error("Failed to get auction status",{auctionId:e,error:o}),this.events.emit("auction:error",{auctionId:e,error:o}),o}}async getBidHistory(t){try{const i=this.bidHistoryCache.get(t);if(i&&Date.now()-i.fetchedAt<this.BID_HISTORY_CACHE_TTL)return this.logger.debug("Returning cached bid history",{auctionId:t}),i.bids;this.logger.info("Fetching bid history",{auctionId:t});const n=`/auctions/${t}/bids/history`,a=await this.http.get(n),s=h(e,a,{endpoint:n},{throwOnFailure:!0});if(!s.ok)throw s.error;const o=s.value.map(t=>({amount:d(t.amount),timestamp:t.timestamp,isWinning:t.isHighest,isYours:!0}));return this.bidHistoryCache.set(t,{bids:o,fetchedAt:Date.now()}),this.events.emit("auction:history-fetched",{auctionId:t,bidCount:o.length}),o}catch(i){throw this.logger.error("Failed to get bid history",{auctionId:t,error:i}),this.events.emit("auction:error",{auctionId:t,error:i}),i}}startWatching(t,i=5e3){this.stopWatching(t);const e=this.bumpMonitorGeneration(t);this.logger.info("Starting auction status polling",{auctionId:t,intervalMs:i});const n=this.getOperationGeneration(t);this.doStatus(t,this.lifecycleGeneration,e,n).catch(i=>{this.canApplyAsyncResult(t,this.lifecycleGeneration,e,n)&&this.logger.error("Initial status check failed",{auctionId:t,error:i})});const a=setInterval(()=>{const i=this.getOperationGeneration(t);this.doStatus(t,this.lifecycleGeneration,e,i).catch(n=>{this.canApplyAsyncResult(t,this.lifecycleGeneration,e,i)&&this.logger.error("Polling failed",{auctionId:t,error:n})})},i);this.pollingIntervals.set(t,a),this.events.emit("auction:watching-started",{auctionId:t,intervalMs:i})}stopWatching(t){this.bumpMonitorGeneration(t);const i=this.pollingIntervals.get(t);i&&(clearInterval(i),this.pollingIntervals.delete(t),this.lastStatusCache.delete(t),this.logger.info("Stopped watching auction",{auctionId:t}),this.events.emit("auction:watching-stopped",{auctionId:t}))}stopAllWatching(){for(const t of Array.from(this.pollingIntervals.keys()))this.stopWatching(t)}bumpMonitorGeneration(t){const i=(this.monitorGenerations.get(t)??0)+1;return this.monitorGenerations.set(t,i),i}getOperationGeneration(t){return this.operationGenerations.get(t)??0}bumpOperationGeneration(t){const i=this.getOperationGeneration(t)+1;return this.operationGenerations.set(t,i),i}canApplyAsyncResult(t,i,e,n){return!this.destroyed&&this.lifecycleGeneration===i&&((void 0===e||this.monitorGenerations.get(t)===e)&&(void 0===n||this.getOperationGeneration(t)===n))}enableAutoRebid(t,i,e){if(!s(i)||!s(e))throw n.validationError("Invalid monetary format. Must be numeric strings (e.g., '100.00')");if(u(i,"0")||u(e,"0"))throw n.validationError("Max bid and increment must be positive");if(r(e,i))throw n.validationError("Increment cannot be greater than max bid");const a=this.getTrackedParticipation(t);if(!a)throw n.validationError("Must enter auction before enabling auto-rebid");const o=d(a.currentBid),h=c(i,o);this.autoRebidConfigs.set(t,{enabled:!0,maxBid:i,increment:e,remainingBudget:h,rebidCount:0}),this.logger.info("Auto-rebid enabled",{auctionId:t,maxBid:i,increment:e,remainingBudget:h}),this.events.emit("auction:auto-rebid-enabled",{auctionId:t,maxBid:i,increment:e})}disableAutoRebid(t){const i=this.autoRebidConfigs.get(t);i&&(i.enabled=!1,this.logger.info("Auto-rebid disabled",{auctionId:t}),this.events.emit("auction:auto-rebid-disabled",{auctionId:t,finalRebidCount:i.rebidCount||0}))}getAutoRebidConfig(t){return this.autoRebidConfigs.get(t)}async handleAutoRebid(t,i){const e=this.autoRebidConfigs.get(t);if(e&&e.enabled)try{if(!s(i.highestBid)||!s(e.maxBid)||!s(e.increment))return void this.logger.error("Invalid auto-rebid amounts",{auctionId:t,config:e});const n=o(i.highestBid,e.increment);if(r(n,e.maxBid))return this.logger.info("Auto-rebid would exceed max bid, disabling",{auctionId:t,wouldBid:n,maxBid:e.maxBid}),this.disableAutoRebid(t),void this.events.emit("auction:auto-rebid-max-reached",{auctionId:t,maxBid:e.maxBid,wouldNeedToBid:n});this.logger.info("Placing auto-rebid",{auctionId:t,amount:n});const a=await this.bid(t,n);e.lastRebidAt=/* @__PURE__ */(new Date).toISOString(),e.rebidCount=(e.rebidCount||0)+1,e.remainingBudget=c(e.maxBid,n),this.events.emit("auction:auto-rebid-placed",{auctionId:t,amount:n,remainingBudget:e.remainingBudget,status:a.status})}catch(n){this.logger.error("Auto-rebid failed",{auctionId:t,error:n}),this.events.emit("auction:auto-rebid-failed",{auctionId:t,error:n})}}startMonitoring(t,i,e){this.monitorRuntime.start(t,i,e),this.trackedParticipations.has(t)||this.trackedParticipations.set(t,{auctionId:t,enteredAt:/* @__PURE__ */(new Date).toISOString(),status:"watching"}),this.startWatching(t)}stopMonitoring(t){this.stopWatching(t),this.monitorRuntime.stop(t)}isMonitoring(t){return this.monitorRuntime.has(t)||this.pollingIntervals.has(t)}destroy(){this.destroyed=!0,this.lifecycleGeneration+=1,this.stopAllWatching(),this.inFlightRequests.clear(),this.lastStatusCache.clear(),this.diagnosticEmissionIds.clear(),this.trackedParticipations.clear(),this.monitorGenerations.clear(),this.operationGenerations.clear(),this.bidHistoryCache.clear(),this.auctionDetailsCache.clear(),this.autoRebidConfigs.clear(),this.monitorRuntime.clear()}}export{m as AuctionManagementModule};
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Auction module exports
3
+ */
4
+ export { AuctionManagementModule } from './auction.module';
5
+ export type { AuctionDetails, AuctionModule, AuctionParticipation, AuctionStatus, AutoRebidConfig, Bid, BidResult, } from './types';
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Public auction surface. The runtime `AuctionManagementModule`/`AuctionModule`/`AuctionParticipation`
3
+ * symbols from `./types` are internal and not exported here.
4
+ */
5
+ export type { AuctionDetails, AuctionStatus, AutoRebidConfig, Bid, BidResult } from './types';
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,97 @@
1
+ import { RequestOptions } from '../core/http';
2
+ /**
3
+ * Auction participation stored in state
4
+ */
5
+ export interface AuctionParticipation {
6
+ auctionId: string;
7
+ enteredAt: string;
8
+ status: "watching" | "bidding" | "winning" | "outbid";
9
+ currentBid?: string;
10
+ highestBid?: string;
11
+ bidCount?: number;
12
+ lastBidAt?: string;
13
+ metadata?: Record<string, unknown>;
14
+ fingerprint?: string;
15
+ }
16
+ /**
17
+ * Bid details
18
+ */
19
+ export interface Bid {
20
+ id?: string;
21
+ amount: string;
22
+ timestamp: string;
23
+ isWinning: boolean;
24
+ bidderAlias?: string;
25
+ isYours?: boolean;
26
+ }
27
+ /**
28
+ * Result of placing a bid
29
+ */
30
+ export interface BidResult {
31
+ status: "winning" | "outbid" | "accepted";
32
+ amount: string;
33
+ highestBid: string;
34
+ bidCount: number;
35
+ position?: number;
36
+ }
37
+ /**
38
+ * Auction status from API
39
+ */
40
+ export interface AuctionStatus {
41
+ auctionId: string;
42
+ status: "winning" | "outbid" | "watching";
43
+ currentBid?: string;
44
+ highestBid: string;
45
+ timeRemaining: number;
46
+ bidCount?: number;
47
+ position?: number;
48
+ admissionGrant?: string;
49
+ }
50
+ /**
51
+ * Auction details from API
52
+ */
53
+ export interface AuctionDetails {
54
+ id: string;
55
+ /** ISO timestamp when bidding opens (if scheduled). */
56
+ openAt?: string | null;
57
+ /** ISO timestamp when bidding closes (if scheduled). */
58
+ closeAt?: string | null;
59
+ /** ISO timestamp when auction is settled. */
60
+ settleAt: string;
61
+ /** Organization-level currency code (ISO 4217). */
62
+ currencyCode: string;
63
+ /** Reserve price (monetary string), if configured. */
64
+ reservePrice?: string | null;
65
+ /** Minimum bid increment (monetary string), if configured. */
66
+ minBidIncrement?: string | null;
67
+ /** Auto-extend duration (seconds), if configured. */
68
+ autoExtendSeconds?: number | null;
69
+ /** Timezone identifier (e.g. "America/New_York"). */
70
+ timeZone: string;
71
+ }
72
+ /**
73
+ * Auto-rebid configuration
74
+ */
75
+ export interface AutoRebidConfig {
76
+ enabled: boolean;
77
+ maxBid: string;
78
+ increment: string;
79
+ remainingBudget?: string;
80
+ lastRebidAt?: string;
81
+ rebidCount?: number;
82
+ }
83
+ /**
84
+ * Auction module interface
85
+ */
86
+ export interface AuctionModule {
87
+ get(auctionId: string): Promise<AuctionDetails>;
88
+ bid(auctionId: string, amount: string, options?: RequestOptions): Promise<BidResult>;
89
+ enter(auctionId: string, metadata?: Record<string, unknown>, options?: RequestOptions): Promise<void>;
90
+ leave(auctionId: string, options?: RequestOptions): Promise<void>;
91
+ status(auctionId: string): Promise<AuctionStatus>;
92
+ getBidHistory(auctionId: string): Promise<Bid[]>;
93
+ enableAutoRebid(auctionId: string, maxBid: string, increment: string): void;
94
+ disableAutoRebid(auctionId: string): void;
95
+ getAutoRebidConfig(auctionId: string): AutoRebidConfig | undefined;
96
+ destroy(): void;
97
+ }