@warp-drive/core 5.8.0-alpha.9 → 5.8.0-beta.1

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 (258) hide show
  1. package/README.md +22 -38
  2. package/declarations/configure.d.ts +1 -1
  3. package/declarations/graph/-private/-edge-definition.d.ts +12 -2
  4. package/declarations/index.d.ts +14 -9
  5. package/declarations/reactive/-private/default-mode.d.ts +1 -1
  6. package/declarations/reactive/-private/fields/extension.d.ts +1 -1
  7. package/declarations/reactive/-private/fields/managed-array.d.ts +2 -2
  8. package/declarations/reactive/-private/fields/managed-object.d.ts +1 -1
  9. package/declarations/reactive/-private/record.d.ts +10 -1
  10. package/declarations/reactive/-private.d.ts +1 -0
  11. package/declarations/reactive.d.ts +11 -7
  12. package/declarations/request/-private/types.d.ts +1 -1
  13. package/declarations/signals/-leaked.d.ts +2 -0
  14. package/declarations/signals/-private.d.ts +6 -0
  15. package/declarations/{store/-private/new-core-tmp → signals}/promise-state.d.ts +1 -1
  16. package/declarations/{store/-private/new-core-tmp → signals}/request-state.d.ts +6 -6
  17. package/declarations/{store/-private/new-core-tmp → signals}/request-subscription.d.ts +4 -4
  18. package/declarations/store/-private/cache-handler/types.d.ts +2 -16
  19. package/declarations/store/-private/caches/instance-cache.d.ts +1 -1
  20. package/declarations/store/-private/managers/cache-manager.d.ts +1 -14
  21. package/declarations/store/-private/managers/notification-manager.d.ts +1 -1
  22. package/declarations/store/-private/record-arrays/legacy-many-array.d.ts +1 -1
  23. package/declarations/store/-private/record-arrays/resource-array.d.ts +1 -1
  24. package/declarations/store/-private/store-service.d.ts +2 -2
  25. package/declarations/store/-private.d.ts +0 -6
  26. package/declarations/store/deprecated/-private.d.ts +2 -2
  27. package/declarations/store/deprecated/store.d.ts +1 -1
  28. package/declarations/store.d.ts +1 -0
  29. package/declarations/types/cache.d.ts +2 -2
  30. package/declarations/types/record.d.ts +132 -0
  31. package/declarations/types/request.d.ts +22 -8
  32. package/declarations/types/schema/fields.d.ts +26 -13
  33. package/declarations/types/schema/schema-service.d.ts +4 -4
  34. package/declarations/types/spec/document.d.ts +34 -0
  35. package/dist/configure-DPUFCemT.js +1940 -0
  36. package/dist/configure.js +2 -1
  37. package/dist/{request-oqoLC9rz.js → future-BKkJJkj7.js} +1 -48
  38. package/dist/graph/-private.js +15 -5
  39. package/dist/{index-B1cSRj-N.js → index-CQP2NSqg.js} +63 -1812
  40. package/dist/index.js +5 -5
  41. package/dist/reactive/-private.js +1 -1
  42. package/dist/reactive.js +4 -129
  43. package/dist/request.js +49 -1
  44. package/dist/signals/-leaked.js +1 -0
  45. package/dist/store/-private.js +1 -2
  46. package/dist/symbols-3C1OkYtZ.js +39 -0
  47. package/dist/types/-private.js +1 -1
  48. package/dist/types/record.js +127 -0
  49. package/dist/types/request.js +11 -7
  50. package/dist/unpkg/dev/-leaked-Co0EI6Go.js +1939 -0
  51. package/dist/unpkg/dev/build-config/babel-macros.js +1 -0
  52. package/dist/unpkg/dev/build-config/canary-features.js +1 -0
  53. package/dist/unpkg/dev/build-config/debugging.js +1 -0
  54. package/dist/unpkg/dev/build-config/deprecations.js +1 -0
  55. package/dist/unpkg/dev/build-config/env.js +1 -0
  56. package/dist/unpkg/dev/build-config/macros.js +1 -0
  57. package/dist/unpkg/dev/build-config.js +1 -0
  58. package/dist/unpkg/dev/configure.js +1 -0
  59. package/dist/unpkg/dev/future-DFfOzSoe.js +672 -0
  60. package/dist/unpkg/dev/graph/-private.js +3132 -0
  61. package/dist/unpkg/dev/index-BzcBOnw9.js +9392 -0
  62. package/dist/unpkg/dev/index.js +6 -0
  63. package/dist/unpkg/dev/reactive/-private.js +1 -0
  64. package/dist/unpkg/dev/reactive.js +3 -0
  65. package/dist/unpkg/dev/request.js +49 -0
  66. package/dist/unpkg/dev/runtime-E1M51_-O.js +135 -0
  67. package/dist/unpkg/dev/signals/-leaked.js +1 -0
  68. package/dist/unpkg/dev/store/-private.js +55 -0
  69. package/dist/unpkg/dev/store.js +558 -0
  70. package/dist/unpkg/dev/types/-private.js +69 -0
  71. package/dist/unpkg/dev/types/cache/aliases.js +0 -0
  72. package/dist/unpkg/dev/types/cache/change.js +0 -0
  73. package/dist/unpkg/dev/types/cache/mutations.js +0 -0
  74. package/dist/unpkg/dev/types/cache/operations.js +0 -0
  75. package/dist/unpkg/dev/types/cache/relationship.js +0 -0
  76. package/dist/unpkg/dev/types/cache.js +0 -0
  77. package/dist/unpkg/dev/types/graph.js +0 -0
  78. package/dist/unpkg/dev/types/identifier.js +61 -0
  79. package/dist/unpkg/dev/types/json/raw.js +0 -0
  80. package/dist/unpkg/dev/types/params.js +0 -0
  81. package/dist/unpkg/dev/types/record.js +191 -0
  82. package/dist/unpkg/dev/types/request.js +77 -0
  83. package/dist/unpkg/dev/types/runtime.js +34 -0
  84. package/dist/unpkg/dev/types/schema/concepts.js +0 -0
  85. package/dist/unpkg/dev/types/schema/fields.js +505 -0
  86. package/dist/unpkg/dev/types/schema/fields.type-test.js +0 -0
  87. package/dist/unpkg/dev/types/schema/schema-service.js +0 -0
  88. package/dist/unpkg/dev/types/spec/document.js +0 -0
  89. package/dist/unpkg/dev/types/spec/error.js +0 -0
  90. package/dist/unpkg/dev/types/spec/json-api-raw.js +0 -0
  91. package/dist/unpkg/dev/types/symbols.js +84 -0
  92. package/dist/unpkg/dev/types/utils.js +0 -0
  93. package/dist/unpkg/dev/types.js +0 -0
  94. package/dist/unpkg/dev/utils/string.js +91 -0
  95. package/dist/unpkg/dev-deprecated/-leaked-DjMeRqdU.js +1939 -0
  96. package/dist/unpkg/dev-deprecated/-private-3C1OkYtZ.js +39 -0
  97. package/dist/unpkg/dev-deprecated/build-config/babel-macros.js +1 -0
  98. package/dist/unpkg/dev-deprecated/build-config/canary-features.js +1 -0
  99. package/dist/unpkg/dev-deprecated/build-config/debugging.js +1 -0
  100. package/dist/unpkg/dev-deprecated/build-config/deprecations.js +1 -0
  101. package/dist/unpkg/dev-deprecated/build-config/env.js +1 -0
  102. package/dist/unpkg/dev-deprecated/build-config/macros.js +1 -0
  103. package/dist/unpkg/dev-deprecated/build-config.js +1 -0
  104. package/dist/unpkg/dev-deprecated/configure.js +1 -0
  105. package/dist/unpkg/dev-deprecated/future-DFfOzSoe.js +672 -0
  106. package/dist/unpkg/dev-deprecated/graph/-private.js +3327 -0
  107. package/dist/unpkg/dev-deprecated/index-6TnTv-WG.js +10007 -0
  108. package/dist/unpkg/dev-deprecated/index.js +5 -0
  109. package/dist/unpkg/dev-deprecated/reactive/-private.js +1 -0
  110. package/dist/unpkg/dev-deprecated/reactive.js +3 -0
  111. package/dist/unpkg/dev-deprecated/request.js +49 -0
  112. package/dist/unpkg/dev-deprecated/runtime-DAu5b0IR.js +135 -0
  113. package/dist/unpkg/dev-deprecated/signals/-leaked.js +1 -0
  114. package/dist/unpkg/dev-deprecated/store/-private.js +1 -0
  115. package/dist/unpkg/dev-deprecated/store.js +558 -0
  116. package/dist/unpkg/dev-deprecated/types/-private.js +69 -0
  117. package/dist/unpkg/dev-deprecated/types/cache/aliases.js +0 -0
  118. package/dist/unpkg/dev-deprecated/types/cache/change.js +0 -0
  119. package/dist/unpkg/dev-deprecated/types/cache/mutations.js +0 -0
  120. package/dist/unpkg/dev-deprecated/types/cache/operations.js +0 -0
  121. package/dist/unpkg/dev-deprecated/types/cache/relationship.js +0 -0
  122. package/dist/unpkg/dev-deprecated/types/cache.js +0 -0
  123. package/dist/unpkg/dev-deprecated/types/graph.js +0 -0
  124. package/dist/unpkg/dev-deprecated/types/identifier.js +61 -0
  125. package/dist/unpkg/dev-deprecated/types/json/raw.js +0 -0
  126. package/dist/unpkg/dev-deprecated/types/params.js +0 -0
  127. package/dist/unpkg/dev-deprecated/types/record.js +191 -0
  128. package/dist/unpkg/dev-deprecated/types/request.js +77 -0
  129. package/dist/unpkg/dev-deprecated/types/runtime.js +34 -0
  130. package/dist/unpkg/dev-deprecated/types/schema/concepts.js +0 -0
  131. package/dist/unpkg/dev-deprecated/types/schema/fields.js +505 -0
  132. package/dist/unpkg/dev-deprecated/types/schema/fields.type-test.js +0 -0
  133. package/dist/unpkg/dev-deprecated/types/schema/schema-service.js +0 -0
  134. package/dist/unpkg/dev-deprecated/types/spec/document.js +0 -0
  135. package/dist/unpkg/dev-deprecated/types/spec/error.js +0 -0
  136. package/dist/unpkg/dev-deprecated/types/spec/json-api-raw.js +0 -0
  137. package/dist/unpkg/dev-deprecated/types/symbols.js +84 -0
  138. package/dist/unpkg/dev-deprecated/types/utils.js +0 -0
  139. package/dist/unpkg/dev-deprecated/types.js +0 -0
  140. package/dist/unpkg/dev-deprecated/utils/string.js +91 -0
  141. package/dist/unpkg/prod/-leaked-DUONXQDB.js +1676 -0
  142. package/dist/unpkg/prod/-private-sql1_mdx.js +39 -0
  143. package/dist/unpkg/prod/build-config/babel-macros.js +1 -0
  144. package/dist/unpkg/prod/build-config/canary-features.js +1 -0
  145. package/dist/unpkg/prod/build-config/debugging.js +1 -0
  146. package/dist/unpkg/prod/build-config/deprecations.js +1 -0
  147. package/dist/unpkg/prod/build-config/env.js +1 -0
  148. package/dist/unpkg/prod/build-config/macros.js +1 -0
  149. package/dist/unpkg/prod/build-config.js +1 -0
  150. package/dist/unpkg/prod/configure.js +2 -0
  151. package/dist/unpkg/prod/graph/-private.js +2235 -0
  152. package/dist/unpkg/prod/handler-EU_8ncB2.js +1619 -0
  153. package/dist/unpkg/prod/index.js +483 -0
  154. package/dist/unpkg/prod/promise-cache-DIT8Ypjq.js +19 -0
  155. package/dist/unpkg/prod/reactive/-private.js +1 -0
  156. package/dist/unpkg/prod/reactive.js +30 -0
  157. package/dist/unpkg/prod/request-BrJSCG6r.js +421 -0
  158. package/dist/unpkg/prod/request.js +2 -0
  159. package/dist/unpkg/prod/schema-BSkHyoWz.js +5219 -0
  160. package/dist/unpkg/prod/signals/-leaked.js +1 -0
  161. package/dist/unpkg/prod/store/-private.js +126 -0
  162. package/dist/unpkg/prod/store.js +437 -0
  163. package/dist/unpkg/prod/types/-private.js +49 -0
  164. package/dist/unpkg/prod/types/cache/aliases.js +0 -0
  165. package/dist/unpkg/prod/types/cache/change.js +0 -0
  166. package/dist/unpkg/prod/types/cache/mutations.js +0 -0
  167. package/dist/unpkg/prod/types/cache/operations.js +0 -0
  168. package/dist/unpkg/prod/types/cache/relationship.js +0 -0
  169. package/dist/unpkg/prod/types/cache.js +0 -0
  170. package/dist/unpkg/prod/types/graph.js +0 -0
  171. package/dist/unpkg/prod/types/identifier.js +61 -0
  172. package/dist/unpkg/prod/types/json/raw.js +0 -0
  173. package/dist/unpkg/prod/types/params.js +0 -0
  174. package/dist/unpkg/prod/types/record.js +191 -0
  175. package/dist/unpkg/prod/types/request.js +77 -0
  176. package/dist/unpkg/prod/types/runtime.js +34 -0
  177. package/dist/unpkg/prod/types/schema/concepts.js +0 -0
  178. package/dist/unpkg/prod/types/schema/fields.js +505 -0
  179. package/dist/unpkg/prod/types/schema/fields.type-test.js +0 -0
  180. package/dist/unpkg/prod/types/schema/schema-service.js +0 -0
  181. package/dist/unpkg/prod/types/spec/document.js +0 -0
  182. package/dist/unpkg/prod/types/spec/error.js +0 -0
  183. package/dist/unpkg/prod/types/spec/json-api-raw.js +0 -0
  184. package/dist/unpkg/prod/types/symbols.js +84 -0
  185. package/dist/unpkg/prod/types/utils.js +0 -0
  186. package/dist/unpkg/prod/types.js +0 -0
  187. package/dist/unpkg/prod/utils/string.js +72 -0
  188. package/dist/unpkg/prod-deprecated/-leaked-DRNv9VIX.js +1676 -0
  189. package/dist/unpkg/prod-deprecated/-private-3C1OkYtZ.js +39 -0
  190. package/dist/unpkg/prod-deprecated/build-config/babel-macros.js +1 -0
  191. package/dist/unpkg/prod-deprecated/build-config/canary-features.js +1 -0
  192. package/dist/unpkg/prod-deprecated/build-config/debugging.js +1 -0
  193. package/dist/unpkg/prod-deprecated/build-config/deprecations.js +1 -0
  194. package/dist/unpkg/prod-deprecated/build-config/env.js +1 -0
  195. package/dist/unpkg/prod-deprecated/build-config/macros.js +1 -0
  196. package/dist/unpkg/prod-deprecated/build-config.js +1 -0
  197. package/dist/unpkg/prod-deprecated/configure.js +2 -0
  198. package/dist/unpkg/prod-deprecated/graph/-private.js +2408 -0
  199. package/dist/unpkg/prod-deprecated/handler-CCIu4sQ3.js +334 -0
  200. package/dist/unpkg/prod-deprecated/hooks-Dv4Np0MY.js +26 -0
  201. package/dist/unpkg/prod-deprecated/index.js +483 -0
  202. package/dist/unpkg/prod-deprecated/promise-cache-DIT8Ypjq.js +19 -0
  203. package/dist/unpkg/prod-deprecated/reactive/-private.js +1 -0
  204. package/dist/unpkg/prod-deprecated/reactive.js +5 -0
  205. package/dist/unpkg/prod-deprecated/request-BrJSCG6r.js +421 -0
  206. package/dist/unpkg/prod-deprecated/request.js +2 -0
  207. package/dist/unpkg/prod-deprecated/schema-CJcjHv0E.js +6939 -0
  208. package/dist/unpkg/prod-deprecated/signals/-leaked.js +1 -0
  209. package/dist/unpkg/prod-deprecated/store/-private.js +88 -0
  210. package/dist/unpkg/prod-deprecated/store.js +437 -0
  211. package/dist/unpkg/prod-deprecated/types/-private.js +49 -0
  212. package/dist/unpkg/prod-deprecated/types/cache/aliases.js +0 -0
  213. package/dist/unpkg/prod-deprecated/types/cache/change.js +0 -0
  214. package/dist/unpkg/prod-deprecated/types/cache/mutations.js +0 -0
  215. package/dist/unpkg/prod-deprecated/types/cache/operations.js +0 -0
  216. package/dist/unpkg/prod-deprecated/types/cache/relationship.js +0 -0
  217. package/dist/unpkg/prod-deprecated/types/cache.js +0 -0
  218. package/dist/unpkg/prod-deprecated/types/graph.js +0 -0
  219. package/dist/unpkg/prod-deprecated/types/identifier.js +61 -0
  220. package/dist/unpkg/prod-deprecated/types/json/raw.js +0 -0
  221. package/dist/unpkg/prod-deprecated/types/params.js +0 -0
  222. package/dist/unpkg/prod-deprecated/types/record.js +191 -0
  223. package/dist/unpkg/prod-deprecated/types/request.js +77 -0
  224. package/dist/unpkg/prod-deprecated/types/runtime.js +34 -0
  225. package/dist/unpkg/prod-deprecated/types/schema/concepts.js +0 -0
  226. package/dist/unpkg/prod-deprecated/types/schema/fields.js +505 -0
  227. package/dist/unpkg/prod-deprecated/types/schema/fields.type-test.js +0 -0
  228. package/dist/unpkg/prod-deprecated/types/schema/schema-service.js +0 -0
  229. package/dist/unpkg/prod-deprecated/types/spec/document.js +0 -0
  230. package/dist/unpkg/prod-deprecated/types/spec/error.js +0 -0
  231. package/dist/unpkg/prod-deprecated/types/spec/json-api-raw.js +0 -0
  232. package/dist/unpkg/prod-deprecated/types/symbols.js +84 -0
  233. package/dist/unpkg/prod-deprecated/types/utils.js +0 -0
  234. package/dist/unpkg/prod-deprecated/types.js +0 -0
  235. package/dist/unpkg/prod-deprecated/utils/string.js +72 -0
  236. package/logos/README.md +2 -2
  237. package/logos/logo-yellow-slab.svg +1 -0
  238. package/logos/word-mark-black.svg +1 -0
  239. package/logos/word-mark-white.svg +1 -0
  240. package/package.json +11 -3
  241. package/declarations/store/-private/new-core-tmp/expensive-subscription.d.ts +0 -24
  242. package/dist/configure-C3x8YXzL.js +0 -181
  243. package/logos/NCC-1701-a-blue.svg +0 -4
  244. package/logos/NCC-1701-a-gold.svg +0 -4
  245. package/logos/NCC-1701-a-gold_100.svg +0 -1
  246. package/logos/NCC-1701-a-gold_base-64.txt +0 -1
  247. package/logos/NCC-1701-a.svg +0 -4
  248. package/logos/docs-badge.svg +0 -2
  249. package/logos/ember-data-logo-dark.svg +0 -12
  250. package/logos/ember-data-logo-light.svg +0 -12
  251. package/logos/social1.png +0 -0
  252. package/logos/social2.png +0 -0
  253. package/logos/warp-drive-logo-dark.svg +0 -4
  254. package/logos/warp-drive-logo-gold.svg +0 -4
  255. /package/declarations/{store/-private/new-core-tmp → signals}/reactivity/configure.d.ts +0 -0
  256. /package/declarations/{store/-private/new-core-tmp → signals}/reactivity/internal.d.ts +0 -0
  257. /package/declarations/{store/-private/new-core-tmp → signals}/reactivity/signal.d.ts +0 -0
  258. /package/dist/{symbols-sql1_mdx.js → unpkg/dev/-private-sql1_mdx.js} +0 -0
@@ -0,0 +1,1939 @@
1
+ import { getOrSetGlobal, peekTransient, setTransient } from './types/-private.js';
2
+ import './types/request.js';
3
+ import { g as getPromiseResult, s as setPromiseResult } from "./future-DFfOzSoe.js";
4
+
5
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
6
+
7
+ const ARRAY_SIGNAL = getOrSetGlobal('#[]', Symbol('#[]'));
8
+ const OBJECT_SIGNAL = getOrSetGlobal('#{}', Symbol('#{}'));
9
+
10
+ /**
11
+ * Requirements:
12
+ *
13
+ * Signal:
14
+ *
15
+ * - signal: a way of creating a reference that we can dirty when we desire to notify
16
+ * - @signal: a way of creating an accessor on an object that subscribes to a signal on access
17
+ * and notifies the signal on set, or of upgrading a descriptor to be such an accessor
18
+ * - defineSignal: a way of creating a signal on an object
19
+ * - notifySignal: a way of notifying the underlying signal that it has been dirtied
20
+ * - peekSignal: a way of inspecting the signal without notifying it
21
+ *
22
+ * - gate: a memoized getter function that re-runs when on access if its signal is dirty
23
+ * conceptually, a gate is a tightly coupled signal and memo
24
+ * - @gate: a way of creating a gate on an object or upgrading a descriptor with a getter
25
+ * to be a gate
26
+ * - defineGate: a way of creating a gate on an object
27
+ * - notifySignal: a way of notifying the signal for a gate that it has been dirtied
28
+ *
29
+ * - memo:
30
+ * - @memo: a way of creating a memoized getter on an object or upgrading a descriptor with a getter
31
+ * to be a memo
32
+ * - defineMemo: a way of creating a memo on an object
33
+ *
34
+ * - signalStore: storage bucket for signals associated to an object
35
+ * - withSignalStore: a way of pre-creating a signal store on an object
36
+ *
37
+ *
38
+ * @internal
39
+ */
40
+
41
+ /**
42
+ * An Opaque type that represents a framework specific or TC39 signal.
43
+ *
44
+ * It may be an array of signals or a single signal.
45
+ *
46
+ * @private
47
+ */
48
+
49
+ /**
50
+ * The hooks which MUST be configured in order to use reactive arrays,
51
+ * resources and documents with framework specfic signals or TC39 signals.
52
+ *
53
+ * Support for multiple frameworks simultaneously can be done via
54
+ * this abstraction by returning multiple signals from the `createSignal`
55
+ * method, and consuming the correct one via the correct framework via
56
+ * the `consumeSignal` and `notifySignal` methods.
57
+ *
58
+ * Unlike many signals implementations, WarpDrive does not wrap values as
59
+ * signals directly, but instead uses signals to alert the reactive layer
60
+ * to changes in the underlying cache. E.g. a signal is associated to a value,
61
+ * but does not serve as the cache for that value directly. We refer to this as
62
+ * a "gate", the pattern has also been called "side-signals".
63
+ *
64
+ * A no-op implementation is allowed, though it may lead to performance issues
65
+ * in locations that use createMemo as no memoization would be done. This is
66
+ * typically desirable only when integrating with a framework that does its own
67
+ * memoization and does not integrate with any signals-like primitive. For these
68
+ * scenarios you may also be interested in integrating with the {@link NotificationManager}
69
+ * more directly.
70
+ *
71
+ * @public
72
+ */
73
+
74
+ /**
75
+ * Contains information a {@link SignalHooks} implementation may want
76
+ * to use, such as the specialized key used for the signal
77
+ * representing an array's contents / length.
78
+ *
79
+ * ```ts
80
+ * interface HooksOptions {
81
+ * wellknown: {
82
+ * Array: symbol | string;
83
+ * }
84
+ * }
85
+ * ```
86
+ *
87
+ * @public
88
+ */
89
+
90
+ /**
91
+ * Configures the signals implementation to use. Supports multiple
92
+ * implementations simultaneously.
93
+ *
94
+ * See {@link HooksOptions} for the options passed to the provided function
95
+ * when called.
96
+ *
97
+ * See {@link SignalHooks} for the implementation the callback function should
98
+ * return.
99
+ *
100
+ * @public
101
+ * @param buildConfig - a function that takes options and returns a configuration object
102
+ */
103
+ function setupSignals(buildConfig) {
104
+ // We want to assert this but can't because too many package manager
105
+ // and bundler bugs exist that cause this to be called multiple times
106
+ // for what should be a single call.
107
+ // assert(`Cannot override configured signal hooks`, peekTransient('signalHooks') === null);
108
+ const hooks = buildConfig({
109
+ wellknown: {
110
+ Array: ARRAY_SIGNAL
111
+ }
112
+ });
113
+ setTransient('signalHooks', hooks);
114
+ }
115
+
116
+ /**
117
+ * Internal method for consuming the configured `createSignal` hook
118
+ *
119
+ * @private
120
+ */
121
+ function createSignal(obj, key) {
122
+ const signalHooks = peekTransient('signalHooks');
123
+ (test => {
124
+ if (!test) {
125
+ throw new Error(`Signal hooks not configured`);
126
+ }
127
+ })(signalHooks);
128
+ return signalHooks.createSignal(obj, key);
129
+ }
130
+
131
+ /**
132
+ * Internal method for consuming the configured `consumeSignal` hook
133
+ *
134
+ * @private
135
+ */
136
+ function consumeSignal(signal) {
137
+ const signalHooks = peekTransient('signalHooks');
138
+ (test => {
139
+ if (!test) {
140
+ throw new Error(`Signal hooks not configured`);
141
+ }
142
+ })(signalHooks);
143
+ return signalHooks.consumeSignal(signal);
144
+ }
145
+
146
+ /**
147
+ * Internal method for consuming the configured `notifySignal` hook
148
+ *
149
+ * @private
150
+ */
151
+ function notifySignal(signal) {
152
+ const signalHooks = peekTransient('signalHooks');
153
+ (test => {
154
+ if (!test) {
155
+ throw new Error(`Signal hooks not configured`);
156
+ }
157
+ })(signalHooks);
158
+ return signalHooks.notifySignal(signal);
159
+ }
160
+ function createMemo(object, key, fn) {
161
+ const signalHooks = peekTransient('signalHooks');
162
+ (test => {
163
+ if (!test) {
164
+ throw new Error(`Signal hooks not configured`);
165
+ }
166
+ })(signalHooks);
167
+ return signalHooks.createMemo(object, key, fn);
168
+ }
169
+ function willSyncFlushWatchers() {
170
+ const signalHooks = peekTransient('signalHooks');
171
+ (test => {
172
+ if (!test) {
173
+ throw new Error(`Signal hooks not configured`);
174
+ }
175
+ })(signalHooks);
176
+ return signalHooks.willSyncFlushWatchers();
177
+ }
178
+ function waitFor(promise) {
179
+ const signalHooks = peekTransient('signalHooks');
180
+ if (signalHooks?.waitFor) {
181
+ return signalHooks.waitFor(promise);
182
+ }
183
+ return promise;
184
+ }
185
+ const INITIALIZER_PROTO = {
186
+ isInitializer: true
187
+ };
188
+ function makeInitializer(fn) {
189
+ // we use a prototype to ensure that the initializer is not enumerable
190
+ // and does not interfere with the signal's value.
191
+ return Object.assign(Object.create(INITIALIZER_PROTO), {
192
+ value: fn
193
+ });
194
+ }
195
+ function isInitializer(obj) {
196
+ return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === INITIALIZER_PROTO;
197
+ }
198
+
199
+ /**
200
+ * A WarpDriveSignal is a wrapper around a framework specific or TC39 signal
201
+ * that enables us to store and manage the signal in a universal way.
202
+ *
203
+ * WarpDrive uses signals to manage three separate concepts:
204
+ *
205
+ * - as a `storage` for a value local to the object that we want to be reactive
206
+ * (see `@local` schema field for an example)
207
+ * - as a `gate` for a memoized getter that we want to act as a reactive property
208
+ * but whose value is computed/pulled from a non-reactive source elsewhere
209
+ * and whose latest value is stored in the signal
210
+ * (see `field` schema field for an example)
211
+ * - as a `gate` with a manually managed value updated on pull when `isStale` is true
212
+ *
213
+ *
214
+ * It offers
215
+ *
216
+ * - a non-reactive way to access/update the current value
217
+ * - a non-reactive way to mark the signal as dirtied
218
+ * - a non-reactive way to store content for why the signal was dirtied
219
+ * - access to the underlying Signal(s) in-use
220
+ *
221
+ * For debugging:
222
+ * - the "key" or "name" of the signal
223
+ * - the "object identity" or "context" to which the signal is attached
224
+ *
225
+ * @private
226
+ */
227
+
228
+ /**
229
+ * We attach signals to their context object via
230
+ * a Map attached to the object via this symbol.
231
+ *
232
+ * This allows us to store multiple signals
233
+ * on the same object with smaller memory
234
+ * overhead and no WeakMap lookups.
235
+ *
236
+ * Performance sensitive objects should
237
+ * pre-warm their shape by assigning this
238
+ * during initialization.
239
+ *
240
+ * ```ts
241
+ * initializeSignalStore(obj);
242
+ * ```
243
+ *
244
+ * @private
245
+ */
246
+ const Signals = getOrSetGlobal('Signals', Symbol('Signals'));
247
+
248
+ /**
249
+ * A util that will create a signal store on the object
250
+ * if it does not already exist and returns the associated
251
+ * signal store.
252
+ *
253
+ * @private
254
+ */
255
+ function withSignalStore(obj) {
256
+ if (!obj[Signals]) {
257
+ initializeSignalStore(obj);
258
+ }
259
+ return obj[Signals];
260
+ }
261
+
262
+ /**
263
+ * A util that will create a signal store on the object
264
+ * if it does not already exist.
265
+ *
266
+ * Useful for pre-warming the shape of an object to ensure
267
+ * a key-transition to add it is not required later.
268
+ *
269
+ * @private
270
+ */
271
+ function initializeSignalStore(obj) {
272
+ (test => {
273
+ if (!test) {
274
+ throw new Error(`Signal store already exists on object`);
275
+ }
276
+ })(!obj[Signals]);
277
+ obj[Signals] = new Map();
278
+ }
279
+ function createInternalSignal(signals, obj, key, initialValue) {
280
+ const warpDriveSignal = {
281
+ key,
282
+ context: obj,
283
+ signal: createSignal(obj, key),
284
+ value: isInitializer(initialValue) ? initialValue.value.call(obj) : initialValue,
285
+ isStale: false
286
+ };
287
+ signals.set(key, warpDriveSignal);
288
+ return warpDriveSignal;
289
+ }
290
+ function getOrCreateInternalSignal(signals, obj, key, initialValue) {
291
+ let signal = peekInternalSignal(signals, key);
292
+ if (!signal) {
293
+ signal = createInternalSignal(signals, obj, key, initialValue);
294
+ }
295
+ return signal;
296
+ }
297
+ function createInternalMemo(signals, object, key, fn) {
298
+ (test => {
299
+ if (!test) {
300
+ throw new Error(`Expected no signal/memo to exist for key "${String(key)}"`);
301
+ }
302
+ })(!peekInternalSignal(signals, key));
303
+ {
304
+ return withFrame(signals, object, key, fn);
305
+ }
306
+ }
307
+ function peekInternalSignal(signals, key) {
308
+ return signals?.get(key);
309
+ }
310
+ function consumeInternalSignal(signal) {
311
+ TrackingFrame?.signals.add(signal);
312
+ consumeSignal(signal.signal);
313
+ }
314
+ function notifyInternalSignal(signal) {
315
+ if (signal) {
316
+ signal.isStale = true;
317
+ notifySignal(signal.signal);
318
+ }
319
+ }
320
+ let TrackingFrame = null;
321
+
322
+ /**
323
+ * This is currently just for signals debugging, but it could be used in production
324
+ * if we wanted to eliminate the need for frameworks to implement createMemo / to
325
+ * allow us to add our own Watcher.
326
+ *
327
+ * @internal
328
+ */
329
+ function withFrame(signals, object, key, fn) {
330
+ const frameSignals = new Set();
331
+ const frameFn = () => {
332
+ if (frameSignals.size) {
333
+ frameSignals.clear();
334
+ }
335
+ TrackingFrame = {
336
+ object,
337
+ key,
338
+ signals: frameSignals,
339
+ parent: TrackingFrame
340
+ };
341
+ try {
342
+ return fn();
343
+ } finally {
344
+ TrackingFrame = TrackingFrame.parent;
345
+ }
346
+ };
347
+ const memo = createMemo(object, key, frameFn);
348
+ // @ts-expect-error
349
+ memo.signals = frameSignals;
350
+ signals.set(key, memo);
351
+ return memo;
352
+ }
353
+ function isMemo(obj) {
354
+ // @ts-expect-error
355
+ return typeof obj === 'function' && obj.signals instanceof Set;
356
+ }
357
+ {
358
+ // @ts-expect-error adding to global API
359
+ globalThis.debugWarpDriveSignals = (obj, key) => {
360
+ const signals = obj[Signals];
361
+ if (!signals) {
362
+ log('The object has no associated signals');
363
+ return false;
364
+ }
365
+ if (key) {
366
+ const signal = signals.get(key);
367
+ if (!signal) {
368
+ log(`No signal found for key "${String(key)}"`);
369
+ return false;
370
+ }
371
+ log(signal);
372
+ if (isMemo(signal)) {
373
+ colorizeLines(printMemo(signal, key));
374
+ return true;
375
+ } else {
376
+ colorizeLines(printSignal(signal, key));
377
+ return true;
378
+ }
379
+ }
380
+ const lines = [];
381
+ for (const [k, signal] of signals) {
382
+ if (isMemo(signal)) continue;
383
+ printSignal(signal, k, lines);
384
+ }
385
+ for (const [k, signal] of signals) {
386
+ if (isMemo(signal)) {
387
+ printMemo(signal, k, lines);
388
+ }
389
+ }
390
+ log(signals);
391
+ colorizeLines(lines);
392
+ return true;
393
+ };
394
+ }
395
+ const LightColors = {
396
+ red: 'color: red;',
397
+ green: 'color: green;',
398
+ reset: 'color: inherit;'
399
+ };
400
+ const DarkColors = {
401
+ red: 'color: red;',
402
+ green: 'color: lightgreen;',
403
+ reset: 'color: inherit;'
404
+ };
405
+ function isLightMode() {
406
+ if (window?.matchMedia?.('(prefers-color-scheme: light)').matches) {
407
+ return true;
408
+ }
409
+ return false;
410
+ }
411
+ const RED = {};
412
+ const GREEN = {};
413
+ const RESET = {};
414
+ const EOL = {};
415
+ function colorizeLines(lines) {
416
+ const Colors = isLightMode() ? LightColors : DarkColors;
417
+ const colors = [];
418
+ let line = '';
419
+ for (const str of lines) {
420
+ if (str === RED) {
421
+ colors.push(Colors.red);
422
+ line += '%c';
423
+ } else if (str === GREEN) {
424
+ colors.push(Colors.green);
425
+ line += '%c';
426
+ } else if (str === RESET) {
427
+ colors.push(Colors.reset);
428
+ line += '%c';
429
+ } else if (str === EOL) {
430
+ line += '\n';
431
+ } else {
432
+ line += str;
433
+ }
434
+ }
435
+ log(line, ...colors);
436
+ }
437
+ function log(...args) {
438
+ // eslint-disable-next-line no-console
439
+ console.log(...args);
440
+ }
441
+ function isDirty(signal) {
442
+ return signal.isStale;
443
+ }
444
+ function isDirtyMemo(memo) {
445
+ // iterate simple signals first to get fastest answer
446
+ for (const signal of memo.signals) {
447
+ if (isMemo(signal)) continue;
448
+ if (isDirty(signal)) {
449
+ return true;
450
+ }
451
+ }
452
+ for (const signal of memo.signals) {
453
+ if (isMemo(signal)) {
454
+ return isDirtyMemo(signal);
455
+ }
456
+ }
457
+ return false;
458
+ }
459
+ function printSignal(signal, key, lines = [], depth = 0) {
460
+ const _dirty = isDirty(signal);
461
+ lines.push(`${''.padStart(depth * 2, ' ')}${_dirty ? '❌' : '✅'} `, _dirty ? RED : GREEN, `${String(key)}`, RESET, EOL);
462
+ return lines;
463
+ }
464
+ function printMemo(memo, key, lines = [], depth = 0) {
465
+ const _dirty = isDirtyMemo(memo);
466
+ lines.push(`${''.padStart(depth * 2, ' ')}${_dirty ? '❌' : '✅'} `, _dirty ? RED : GREEN, `<memo> ${String(key)}`, RESET, `: (consumes ${memo.signals.size} signals)`, EOL);
467
+ for (const signal of memo.signals) {
468
+ if (isMemo(signal)) continue;
469
+ printSignal(signal, signal.key, lines, depth + 1);
470
+ }
471
+ for (const signal of memo.signals) {
472
+ if (isMemo(signal)) {
473
+ printMemo(signal, signal.key, lines, depth + 1);
474
+ }
475
+ }
476
+ return lines;
477
+ }
478
+
479
+ /**
480
+ * Creates a signal for the key/object pairing and subscribes to the signal.
481
+ *
482
+ * Use when you need to ensure a signal exists and is subscribed to.
483
+ *
484
+ * @private
485
+ */
486
+ function entangleSignal(signals, obj, key, initialValue) {
487
+ let internalSignal = peekInternalSignal(signals, key);
488
+ if (!internalSignal) {
489
+ internalSignal = createInternalSignal(signals, obj, key, initialValue);
490
+ }
491
+ consumeInternalSignal(internalSignal);
492
+ return internalSignal;
493
+ }
494
+ function entangleInitiallyStaleSignal(signals, obj, key, initialValue) {
495
+ let internalSignal = peekInternalSignal(signals, key);
496
+ if (!internalSignal) {
497
+ internalSignal = createInternalSignal(signals, obj, key, initialValue);
498
+ internalSignal.isStale = true; // mark it as stale
499
+ }
500
+ consumeInternalSignal(internalSignal);
501
+ return internalSignal;
502
+ }
503
+ function createSignalDescriptor(key, intialValue) {
504
+ return {
505
+ enumerable: true,
506
+ configurable: false,
507
+ get() {
508
+ const signals = withSignalStore(this);
509
+ const internalSignal = entangleSignal(signals, this, key, intialValue);
510
+ internalSignal.isStale = false; // reset stale state
511
+ return internalSignal.value;
512
+ },
513
+ set(value) {
514
+ const signals = withSignalStore(this);
515
+ const internalSignal = getOrCreateInternalSignal(signals, this, key, intialValue);
516
+ if (internalSignal.value !== value) {
517
+ internalSignal.value = value;
518
+ notifyInternalSignal(internalSignal);
519
+ }
520
+ }
521
+ };
522
+ }
523
+
524
+ /**
525
+ * define an enumerable signal property.
526
+ *
527
+ * Akin to Object.defineProperty.
528
+ *
529
+ * The signal will be lazily created when accessed and scoped to the
530
+ * instance of the object.
531
+ *
532
+ * @private
533
+ */
534
+ function defineSignal(obj, key, v) {
535
+ Object.defineProperty(obj, key, createSignalDescriptor(key, v));
536
+ }
537
+
538
+ /**
539
+ * Define a non-enumerable signal property.
540
+ *
541
+ * @private
542
+ */
543
+ function defineNonEnumerableSignal(obj, key, v) {
544
+ const desc = createSignalDescriptor(key, v);
545
+ desc.enumerable = false;
546
+ Object.defineProperty(obj, key, desc);
547
+ }
548
+ /**
549
+ * Decorator version of creating a signal.
550
+ */
551
+ function signal(target, key, descriptor) {
552
+ // Error on `@signal()`, `@signal(...args)``
553
+ (test => {
554
+ if (!test) {
555
+ throw new Error('You attempted to use @signal(), which is not necessary nor supported. Remove the parentheses and you will be good to go!');
556
+ }
557
+ })(target !== undefined);
558
+ (test => {
559
+ if (!test) {
560
+ throw new Error(`You attempted to use @signal on with ${arguments.length > 1 ? 'arguments' : 'an argument'} ( @signal(${Array.from(arguments).map(d => `'${d}'`).join(', ')}) ), which is not supported. Dependencies are automatically tracked, so you can just use ${'`@signal`'}`);
561
+ }
562
+ })(typeof target === 'object' && typeof key === 'string' && typeof descriptor === 'object' && arguments.length === 3);
563
+ return createSignalDescriptor(key, descriptor.initializer ? makeInitializer(descriptor.initializer) : null);
564
+ }
565
+
566
+ /**
567
+ * Decorator version of creating a memoized getter
568
+ */
569
+ function memoized(target, key, descriptor) {
570
+ // Error on `@memoized()`, `@memoized(...args)`, and `@memoized propName = value;`
571
+ (test => {
572
+ if (!test) {
573
+ throw new Error('You attempted to use @memoized(), which is not necessary nor supported. Remove the parentheses and you will be good to go!');
574
+ }
575
+ })(target !== undefined);
576
+ (test => {
577
+ if (!test) {
578
+ throw new Error(`You attempted to use @memoized on with ${arguments.length > 1 ? 'arguments' : 'an argument'} ( @memoized(${Array.from(arguments).map(d => `'${d}'`).join(', ')}), which is not supported. Dependencies are automatically tracked, so you can just use ${'`@memoized`'}`);
579
+ }
580
+ })(typeof target === 'object' && typeof key === 'string' && typeof descriptor === 'object' && arguments.length === 3);
581
+ (test => {
582
+ if (!test) {
583
+ throw new Error(`The @memoized decorator must be applied to getters. '${key}' is not a getter.`);
584
+ }
585
+ })(typeof descriptor.get === 'function');
586
+
587
+ // eslint-disable-next-line @typescript-eslint/unbound-method
588
+ const getter = descriptor.get;
589
+ descriptor.get = function () {
590
+ const signals = withSignalStore(this);
591
+ let memoSignal = signals.get(key);
592
+ if (!memoSignal) {
593
+ memoSignal = createInternalMemo(signals, this, key, getter.bind(this));
594
+ }
595
+ return memoSignal();
596
+ };
597
+ return descriptor;
598
+ }
599
+
600
+ /**
601
+ * Decorator version of creating a gate.
602
+ *
603
+ * @private
604
+ */
605
+ function gate(_target, key, desc) {
606
+ // eslint-disable-next-line @typescript-eslint/unbound-method
607
+ const getter = desc.get;
608
+ // eslint-disable-next-line @typescript-eslint/unbound-method
609
+ const setter = desc.set;
610
+ const isLocal = desc.isLocal;
611
+ desc.get = function () {
612
+ const signals = withSignalStore(this);
613
+ let internalSignal = peekInternalSignal(signals, key);
614
+ if (!internalSignal) {
615
+ internalSignal = createInternalSignal(signals, this, key, getter.call(this));
616
+ } else if (internalSignal.isStale) {
617
+ internalSignal.isStale = false;
618
+ internalSignal.value = getter.call(this);
619
+ }
620
+ consumeInternalSignal(internalSignal);
621
+ return internalSignal.value;
622
+ };
623
+ if (setter) {
624
+ desc.set = function (v) {
625
+ const signals = withSignalStore(this);
626
+ let internalSignal = peekInternalSignal(signals, key);
627
+ if (!internalSignal) {
628
+ // we can't use `v` as initialValue here because setters don't
629
+ // return the value and the final value may be different
630
+ // than what the setter was called with.
631
+ internalSignal = createInternalSignal(signals, this, key, undefined);
632
+ internalSignal.isStale = true;
633
+ }
634
+ setter.call(this, v);
635
+ // when a gate is set, we do not notify the signal
636
+ // as its update is controlled externally.
637
+ // unless it specifically sets itself to be locally managed
638
+ if (isLocal) {
639
+ internalSignal.isStale = true;
640
+ notifyInternalSignal(internalSignal);
641
+ }
642
+ };
643
+ }
644
+ return desc;
645
+ }
646
+ function defineGate(obj, key, desc) {
647
+ const options = Object.assign({
648
+ enumerable: true,
649
+ configurable: false
650
+ }, gate(obj, key, desc));
651
+ Object.defineProperty(obj, key, options);
652
+ }
653
+ const RequestCache = new WeakMap();
654
+ function isAbortError(error) {
655
+ return error instanceof DOMException && error.name === 'AbortError';
656
+ }
657
+ function upgradeLoadingState(state) {
658
+ return state;
659
+ }
660
+ async function watchStream(stream, loadingState) {
661
+ const state = upgradeLoadingState(loadingState);
662
+ const reader = stream.getReader();
663
+ let bytesLoaded = 0;
664
+ let shouldForward = state._stream !== null && state._stream.readable.locked;
665
+ let isForwarding = shouldForward;
666
+ let writer = state._stream?.writable.getWriter();
667
+ const buffer = [];
668
+ state._isPending = false;
669
+ state._isStarted = true;
670
+ state._startTime = performance.now();
671
+ while (true) {
672
+ const {
673
+ value,
674
+ done
675
+ } = await reader.read();
676
+ if (done) {
677
+ break;
678
+ }
679
+ bytesLoaded += value.byteLength;
680
+ state._bytesLoaded = bytesLoaded;
681
+ state._lastPacketTime = performance.now();
682
+ shouldForward = shouldForward || state._stream !== null && state._stream.readable.locked;
683
+ if (shouldForward) {
684
+ if (!isForwarding) {
685
+ isForwarding = true;
686
+ writer = state._stream.writable.getWriter();
687
+ for (const item of buffer) {
688
+ await writer.ready;
689
+ await writer.write(item);
690
+ }
691
+ buffer.length = 0;
692
+ }
693
+ await writer.ready;
694
+ await writer.write(value);
695
+ } else {
696
+ buffer.push(value);
697
+ }
698
+ }
699
+
700
+ // if we are still forwarding, we need to close the writer
701
+ if (isForwarding) {
702
+ await writer.ready;
703
+ await writer.close();
704
+ } else if (state._stream) {
705
+ // if we are not forwarding, we need to cancel the stream
706
+ await state._stream.readable.cancel('The Stream Has Already Ended');
707
+ state._stream = null;
708
+ }
709
+ const endTime = performance.now();
710
+ state._endTime = endTime;
711
+ state._isComplete = true;
712
+ state._isStarted = false;
713
+ }
714
+
715
+ /**
716
+ * Lazily consumes the stream of a request, providing a number of
717
+ * reactive properties that can be used to build UIs that respond
718
+ * to the progress of a request.
719
+ *
720
+ * @hideconstructor
721
+ */
722
+ class RequestLoadingState {
723
+ /** @internal */
724
+
725
+ /** @internal */
726
+
727
+ /** @internal */
728
+
729
+ /** @internal */
730
+
731
+ /** @internal */
732
+
733
+ /** @internal */
734
+
735
+ /** @internal */
736
+
737
+ /** @internal */
738
+
739
+ /** @internal */
740
+
741
+ /** @internal */
742
+
743
+ /** @internal */
744
+
745
+ /** @internal */
746
+ _stream = null;
747
+ /** @internal */
748
+ _future;
749
+ /** @internal */
750
+ _triggered = false;
751
+ /** @internal */
752
+ _trigger() {
753
+ if (this._triggered) {
754
+ return;
755
+ }
756
+ this._triggered = true;
757
+ const future = this._future;
758
+ const promise = future.getStream();
759
+ if (promise.sizeHint) {
760
+ this._sizeHint = promise.sizeHint;
761
+ }
762
+ this.promise = promise.then(stream => {
763
+ if (!stream) {
764
+ this._isPending = false;
765
+ this._isComplete = true;
766
+ return;
767
+ }
768
+ return watchStream(stream, this);
769
+ }, error => {
770
+ this._isPending = false;
771
+ this._isStarted = false;
772
+ if (isAbortError(error)) {
773
+ this._isCancelled = true;
774
+ this._isComplete = true;
775
+ }
776
+ this._isErrored = true;
777
+ this._error = error;
778
+ });
779
+ }
780
+ promise = null;
781
+ get isPending() {
782
+ this._trigger();
783
+ return this._isPending;
784
+ }
785
+ get sizeHint() {
786
+ this._trigger();
787
+ return this._sizeHint;
788
+ }
789
+ get stream() {
790
+ this._trigger();
791
+ if (!this._stream) {
792
+ if (this._isComplete || this._isCancelled || this._isErrored) {
793
+ return null;
794
+ }
795
+ this._stream = new TransformStream();
796
+ }
797
+ return this._stream.readable;
798
+ }
799
+ get isStarted() {
800
+ this._trigger();
801
+ return this._isStarted;
802
+ }
803
+ get bytesLoaded() {
804
+ this._trigger();
805
+ return this._bytesLoaded;
806
+ }
807
+ get startTime() {
808
+ this._trigger();
809
+ return this._startTime;
810
+ }
811
+ get endTime() {
812
+ this._trigger();
813
+ return this._endTime;
814
+ }
815
+ get lastPacketTime() {
816
+ this._trigger();
817
+ return this._lastPacketTime;
818
+ }
819
+ get isComplete() {
820
+ this._trigger();
821
+ return this._isComplete;
822
+ }
823
+ get isCancelled() {
824
+ this._trigger();
825
+ return this._isCancelled;
826
+ }
827
+ get isErrored() {
828
+ this._trigger();
829
+ return this._isErrored;
830
+ }
831
+ get error() {
832
+ this._trigger();
833
+ return this._error;
834
+ }
835
+ get elapsedTime() {
836
+ return (this.endTime || this.lastPacketTime) - this.startTime;
837
+ }
838
+ get completedRatio() {
839
+ return this.sizeHint ? this.bytesLoaded / this.sizeHint : 0;
840
+ }
841
+ get remainingRatio() {
842
+ return 1 - this.completedRatio;
843
+ }
844
+ get duration() {
845
+ return this.endTime - this.startTime;
846
+ }
847
+ get speed() {
848
+ // bytes per second
849
+ return this.bytesLoaded / (this.elapsedTime / 1000);
850
+ }
851
+ constructor(future) {
852
+ this._future = future;
853
+ }
854
+ abort = () => {
855
+ this._future.abort();
856
+ };
857
+ }
858
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_isPending', true);
859
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_isStarted', false);
860
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_isComplete', false);
861
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_isCancelled', false);
862
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_isErrored', false);
863
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_error', null);
864
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_sizeHint', 0);
865
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_bytesLoaded', 0);
866
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_startTime', 0);
867
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_endTime', 0);
868
+ defineNonEnumerableSignal(RequestLoadingState.prototype, '_lastPacketTime', 0);
869
+
870
+ /**
871
+ * The state of a request in the "pending"
872
+ * state. This is the default initial state.
873
+ *
874
+ * Extends the {@link PendingPromise} interface.
875
+ *
876
+ */
877
+
878
+ /**
879
+ * The state of a request in the "fulfilled" state.
880
+ * This is the state of a request that has resolved
881
+ * successfully.
882
+ *
883
+ * Extends the {@link ResolvedPromise} interface.
884
+ *
885
+ */
886
+
887
+ /**
888
+ * The state of a request in the "rejected" state.
889
+ * This is the state of a request that has rejected
890
+ * with an error.
891
+ *
892
+ * Extends the {@link RejectedPromise} interface.
893
+ *
894
+ */
895
+
896
+ /**
897
+ * The state of a request in the "cancelled" state.
898
+ * This is the state of a promise that has been
899
+ * cancelled.
900
+ *
901
+ */
902
+
903
+ /**
904
+ * RequestState extends the concept of {@link PromiseState} to provide a reactive
905
+ * wrapper for a request {@link Future} which allows you write declarative code
906
+ * around a Future's control flow.
907
+ *
908
+ * It is useful in both Template and JavaScript contexts, allowing you
909
+ * to quickly derive behaviors and data from pending, error and success
910
+ * states.
911
+ *
912
+ * The key difference between a {@link Promise} and a Future is that Futures provide
913
+ * access to a {@link ReadableStream | stream} of their content, the {@link RequestKey} of the request (if any)
914
+ * as well as the ability to attempt to {@link Future.abort | abort} the request.
915
+ *
916
+ * ```ts
917
+ * interface Future<T> extends Promise<T>> {
918
+ * getStream(): Promise<ReadableStream>;
919
+ * abort(): void;
920
+ * lid: RequestKey | null;
921
+ * }
922
+ * ```
923
+ *
924
+ * These additional APIs allow us to craft even richer state experiences.
925
+ *
926
+ * To get the state of a request, use {@link getRequestState}.
927
+ *
928
+ * See also:
929
+ * - {@link PendingRequest}
930
+ * - {@link ResolvedRequest}
931
+ * - {@link RejectedRequest}
932
+ * - {@link CancelledRequest}
933
+ *
934
+ */
935
+
936
+ const RequestStateProto = {};
937
+ function performRefresh(requester, request, isReload) {
938
+ const req = Object.assign({}, request);
939
+ const cacheOptions = Object.assign({}, req.cacheOptions);
940
+ if (isReload) {
941
+ // force direct to network
942
+ cacheOptions.reload = true;
943
+ } else if (isReload === false) {
944
+ // delete reload to ensure we use backgroundReload / policy
945
+ delete cacheOptions.reload;
946
+ cacheOptions.backgroundReload = true;
947
+ } else {
948
+ // delete props to ensure we use the policy
949
+ delete cacheOptions.backgroundReload;
950
+ delete cacheOptions.reload;
951
+ }
952
+ req.cacheOptions = cacheOptions;
953
+ return requester.request(req);
954
+ }
955
+
956
+ // TODO introduce a new mechanism for defining multiple properties
957
+ // that share a common signal
958
+ defineSignal(RequestStateProto, 'reason', null);
959
+ defineSignal(RequestStateProto, 'value', null);
960
+ defineSignal(RequestStateProto, 'result', null);
961
+ defineSignal(RequestStateProto, 'error', null);
962
+ defineSignal(RequestStateProto, 'status', 'pending');
963
+ defineSignal(RequestStateProto, 'isPending', true);
964
+ defineSignal(RequestStateProto, 'isLoading', true);
965
+ defineSignal(RequestStateProto, 'isSuccess', false);
966
+ defineSignal(RequestStateProto, 'isError', false);
967
+ defineSignal(RequestStateProto, 'request', null);
968
+ defineSignal(RequestStateProto, 'response', null);
969
+ Object.defineProperty(RequestStateProto, 'isCancelled', {
970
+ get() {
971
+ return this.isError && isAbortError(this.reason);
972
+ }
973
+ });
974
+ Object.defineProperty(RequestStateProto, 'loadingState', {
975
+ get() {
976
+ if (!this._loadingState) {
977
+ this._loadingState = new RequestLoadingState(this._request);
978
+ }
979
+ return this._loadingState;
980
+ }
981
+ });
982
+ function createRequestState(future) {
983
+ const state = getPromiseResult(future);
984
+ const promiseState = Object.create(RequestStateProto);
985
+ promiseState._request = future;
986
+ // @ts-expect-error - we still attach it for PendingState
987
+ promiseState.reload = () => {
988
+ (test => {
989
+ if (!test) {
990
+ throw new Error(`Cannot reload a request that is still pending. Await or abort the original request first.`);
991
+ }
992
+ })(!promiseState.isPending);
993
+ return performRefresh(future.requester, promiseState.request, true);
994
+ };
995
+
996
+ // @ts-expect-error - we still attach it for PendingState
997
+ promiseState.refresh = (usePolicy = false) => {
998
+ (test => {
999
+ if (!test) {
1000
+ throw new Error(`Cannot refresh a request that is still pending. Await or abort the original request first.`);
1001
+ }
1002
+ })(!promiseState.isPending);
1003
+ return performRefresh(future.requester, promiseState.request, usePolicy === true ? null : false);
1004
+ };
1005
+ if (state) {
1006
+ if (state.isError) {
1007
+ promiseState.error = state.result;
1008
+ promiseState.reason = state.result;
1009
+ promiseState.status = 'rejected';
1010
+ promiseState.isError = true;
1011
+ promiseState.isPending = false;
1012
+ promiseState.isLoading = false;
1013
+ promiseState.request = state.result.request;
1014
+ promiseState.response = state.result.response;
1015
+ } else {
1016
+ promiseState.result = state.result.content;
1017
+ promiseState.value = state.result.content;
1018
+ promiseState.status = 'fulfilled';
1019
+ promiseState.isSuccess = true;
1020
+ promiseState.isPending = false;
1021
+ promiseState.isLoading = false;
1022
+ promiseState.request = state.result.request;
1023
+ promiseState.response = state.result.response;
1024
+ }
1025
+ } else {
1026
+ void future.then(result => {
1027
+ setPromiseResult(future, {
1028
+ isError: false,
1029
+ result
1030
+ });
1031
+ promiseState.result = result.content;
1032
+ promiseState.value = result.content;
1033
+ promiseState.status = 'fulfilled';
1034
+ promiseState.isSuccess = true;
1035
+ promiseState.isPending = false;
1036
+ promiseState.isLoading = false;
1037
+ promiseState.request = result.request;
1038
+ promiseState.response = result.response;
1039
+ }, error => {
1040
+ setPromiseResult(future, {
1041
+ isError: true,
1042
+ result: error
1043
+ });
1044
+ promiseState.error = error;
1045
+ promiseState.reason = error;
1046
+ promiseState.status = 'rejected';
1047
+ promiseState.isError = true;
1048
+ promiseState.isPending = false;
1049
+ promiseState.isLoading = false;
1050
+ promiseState.request = error.request;
1051
+ promiseState.response = error.response;
1052
+ });
1053
+ }
1054
+ return promiseState;
1055
+ }
1056
+
1057
+ /**
1058
+ * `getRequestState` can be used in both JavaScript and Template contexts.
1059
+ *
1060
+ * ```ts
1061
+ * import { getRequestState } from '@warp-drive/ember';
1062
+ *
1063
+ * const state = getRequestState(future);
1064
+ * ```
1065
+ *
1066
+ * For instance, we could write a getter on a component that updates whenever
1067
+ * the request state advances or the future changes, by combining the function
1068
+ * with the use of `@cached`
1069
+ *
1070
+ * ```ts
1071
+ * class Component {
1072
+ * @cached
1073
+ * get title() {
1074
+ * const state = getRequestState(this.args.request);
1075
+ * if (state.isPending) {
1076
+ * return 'loading...';
1077
+ * }
1078
+ * if (state.isError) { return null; }
1079
+ * return state.result.title;
1080
+ * }
1081
+ * }
1082
+ * ```
1083
+ *
1084
+ * Or in a template as a helper:
1085
+ *
1086
+ * ```gjs
1087
+ * import { getRequestState } from '@warp-drive/ember';
1088
+ *
1089
+ * <template>
1090
+ * {{#let (getRequestState @request) as |state|}}
1091
+ * {{#if state.isPending}}
1092
+ * <Spinner />
1093
+ * {{else if state.isError}}
1094
+ * <ErrorForm @error={{state.error}} />
1095
+ * {{else}}
1096
+ * <h1>{{state.result.title}}</h1>
1097
+ * {{/if}}
1098
+ * {{/let}}
1099
+ * </template>
1100
+ * ```
1101
+ *
1102
+ * If looking to use in a template, consider also the `<Request />` component
1103
+ * which offers a number of additional capabilities for requests *beyond* what
1104
+ * `RequestState` provides.
1105
+ *
1106
+ */
1107
+ function getRequestState(future) {
1108
+ let state = RequestCache.get(future);
1109
+ if (!state) {
1110
+ state = createRequestState(future);
1111
+ RequestCache.set(future, state);
1112
+ }
1113
+ return state;
1114
+ }
1115
+ function decorateMethodV2(prototype, prop, decorators) {
1116
+ const origDesc = Object.getOwnPropertyDescriptor(prototype, prop);
1117
+ let desc = {
1118
+ ...origDesc
1119
+ };
1120
+ for (let decorator of decorators) {
1121
+ desc = decorator(prototype, prop, desc) || desc;
1122
+ }
1123
+ if (desc.initializer !== void 0) {
1124
+ desc.value = desc.initializer ? desc.initializer.call(prototype) : void 0;
1125
+ desc.initializer = void 0;
1126
+ }
1127
+ Object.defineProperty(prototype, prop, desc);
1128
+ }
1129
+ const DEFAULT_DEADLINE = 30_000;
1130
+ const DISPOSE = Symbol.dispose || Symbol.for('dispose');
1131
+ function isNeverString(val) {
1132
+ return val;
1133
+ }
1134
+
1135
+ /**
1136
+ * Utilities to assist in recovering from the error.
1137
+ */
1138
+
1139
+ /** @deprecated use {@link RecoveryFeatures} */
1140
+
1141
+ /**
1142
+ * Utilities for keeping the request fresh
1143
+ */
1144
+
1145
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1146
+
1147
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1148
+
1149
+ /**
1150
+ * A reactive class
1151
+ *
1152
+ * @hideconstructor
1153
+ */
1154
+ class RequestSubscription {
1155
+ /**
1156
+ * Whether the browser reports that the network is online.
1157
+ */
1158
+
1159
+ /**
1160
+ * Whether the browser reports that the tab is hidden.
1161
+ */
1162
+
1163
+ /**
1164
+ * Whether the component is currently refreshing the request.
1165
+ */
1166
+
1167
+ /**
1168
+ * The most recent blocking request that was made, typically
1169
+ * the result of a reload.
1170
+ *
1171
+ * This will never be the original request passed as an arg to
1172
+ * the component.
1173
+ *
1174
+ * @internal
1175
+ */
1176
+
1177
+ /**
1178
+ * The most recent request that was made, typically due to either a
1179
+ * reload or a refresh.
1180
+ *
1181
+ * This will never be the original request passed as an arg to
1182
+ * the component.
1183
+ *
1184
+ * @internal
1185
+ */
1186
+
1187
+ /**
1188
+ * The time at which the network was reported as offline.
1189
+ *
1190
+ * @internal
1191
+ */
1192
+
1193
+ /** @internal */
1194
+
1195
+ /** @internal */
1196
+
1197
+ /** @internal */
1198
+
1199
+ /** @internal */
1200
+
1201
+ /** @internal */
1202
+
1203
+ /**
1204
+ * The event listener for network status changes,
1205
+ * cached to use the reference for removal.
1206
+ *
1207
+ * @internal
1208
+ */
1209
+
1210
+ /**
1211
+ * The event listener for visibility status changes,
1212
+ * cached to use the reference for removal.
1213
+ *
1214
+ * @internal
1215
+ */
1216
+
1217
+ /**
1218
+ * The last request passed as an arg to the component,
1219
+ * cached for comparison.
1220
+ *
1221
+ * @internal
1222
+ */
1223
+
1224
+ /**
1225
+ * The last query passed as an arg to the component,
1226
+ * cached for comparison.
1227
+ *
1228
+ * @internal
1229
+ */
1230
+
1231
+ /** @internal */
1232
+
1233
+ /** @internal */
1234
+
1235
+ /** @internal */
1236
+
1237
+ /**
1238
+ * The Store this subscription subscribes to or the RequestManager
1239
+ * which issues this request.
1240
+ */
1241
+
1242
+ /**
1243
+ * The Store or RequestManager that the last subscription is attached to.
1244
+ *
1245
+ * This differs from 'store' because a <Request /> may be passed a
1246
+ * request originating from a different store than the <Request />
1247
+ * component would use if it were to issue the request itself.
1248
+ *
1249
+ * @internal
1250
+ */
1251
+ _requester;
1252
+ constructor(store, args) {
1253
+ this._args = args;
1254
+ this.store = store;
1255
+ this._subscribedTo = null;
1256
+ this._subscription = null;
1257
+ this._intervalStart = null;
1258
+ this._invalidated = false;
1259
+ this._nextInterval = null;
1260
+ this._requester = null;
1261
+ this.isDestroyed = false;
1262
+ this[DISPOSE] = _DISPOSE;
1263
+ this._installListeners();
1264
+ void this._beginPolling();
1265
+ }
1266
+
1267
+ /**
1268
+ * @internal
1269
+ */
1270
+ async _beginPolling() {
1271
+ // await the initial request
1272
+ try {
1273
+ if (!this.isIdle) {
1274
+ await this.request;
1275
+ }
1276
+ } catch {
1277
+ // ignore errors here, we just want to wait for the request to finish
1278
+ } finally {
1279
+ if (!this.isDestroyed) {
1280
+ void this._scheduleInterval();
1281
+ }
1282
+ }
1283
+ }
1284
+ get isIdle() {
1285
+ const {
1286
+ request,
1287
+ query
1288
+ } = this._args;
1289
+ return Boolean(!request && !query);
1290
+ }
1291
+ static {
1292
+ decorateMethodV2(this.prototype, "isIdle", [memoized]);
1293
+ }
1294
+ get autorefreshTypes() {
1295
+ const {
1296
+ autorefresh
1297
+ } = this._args;
1298
+ let types;
1299
+ if (autorefresh === true) {
1300
+ types = ['online', 'invalid'];
1301
+ } else if (typeof autorefresh === 'string') {
1302
+ types = autorefresh.split(',');
1303
+ } else {
1304
+ types = [];
1305
+ }
1306
+ return new Set(types);
1307
+ }
1308
+
1309
+ // we only run this function on component creation
1310
+ // and when an update is triggered, so it does not
1311
+ // react to changes in the autorefreshThreshold
1312
+ // or autorefresh args.
1313
+ //
1314
+ // if we need to react to those changes, we can
1315
+ // use a modifier or internal component or some
1316
+ // such to trigger a re-run of this function.
1317
+ /** @internal */
1318
+ static {
1319
+ decorateMethodV2(this.prototype, "autorefreshTypes", [memoized]);
1320
+ }
1321
+ async _scheduleInterval() {
1322
+ const {
1323
+ autorefreshThreshold
1324
+ } = this._args;
1325
+ const hasValidThreshold = typeof autorefreshThreshold === 'number' && autorefreshThreshold > 0;
1326
+ if (
1327
+ // dont schedule in SSR
1328
+ typeof window === 'undefined' ||
1329
+ // dont schedule without a threshold
1330
+ !hasValidThreshold ||
1331
+ // dont schedule if we weren't told to
1332
+ !this.autorefreshTypes.has('interval') ||
1333
+ // dont schedule if we're already scheduled
1334
+ this._intervalStart !== null) {
1335
+ return;
1336
+ }
1337
+
1338
+ // if we have a current request, wait for it to finish
1339
+ // before scheduling the next one
1340
+ if (this._latestRequest) {
1341
+ try {
1342
+ await this._latestRequest;
1343
+ } catch {
1344
+ // ignore errors here, we just want to wait for the request to finish
1345
+ }
1346
+ if (this.isDestroyed) {
1347
+ return;
1348
+ }
1349
+ }
1350
+
1351
+ // setup the next interval
1352
+ this._intervalStart = Date.now();
1353
+ this._nextInterval = setTimeout(() => {
1354
+ this._maybeUpdate();
1355
+ }, autorefreshThreshold);
1356
+ }
1357
+
1358
+ /** @internal */
1359
+ _clearInterval() {
1360
+ if (this._nextInterval) {
1361
+ clearTimeout(this._nextInterval);
1362
+ this._intervalStart = null;
1363
+ }
1364
+ }
1365
+ /**
1366
+ * @internal
1367
+ */
1368
+ _updateSubscriptions() {
1369
+ if (this.isIdle) {
1370
+ return;
1371
+ }
1372
+ const requestId = this._request.lid;
1373
+
1374
+ // if we're already subscribed to this request, we don't need to do anything
1375
+ if (this._subscribedTo === requestId) {
1376
+ return;
1377
+ }
1378
+
1379
+ // if we're subscribed to a different request, we need to unsubscribe
1380
+ this._removeSubscriptions();
1381
+
1382
+ // if we have a request, we need to subscribe to it
1383
+ const store = this._getRequester();
1384
+ this._requester = store;
1385
+ if (requestId && isStore(store)) {
1386
+ this._subscribedTo = requestId;
1387
+ this._subscription = store.notifications.subscribe(requestId, (_id, op) => {
1388
+ // ignore subscription events that occur while our own component's request
1389
+ // is occurring
1390
+ if (this._isUpdating) {
1391
+ return;
1392
+ }
1393
+ switch (op) {
1394
+ case 'invalidated':
1395
+ {
1396
+ // if we're subscribed to invalidations, we need to update
1397
+ if (this.autorefreshTypes.has('invalid')) {
1398
+ this._invalidated = true;
1399
+ this._maybeUpdate();
1400
+ }
1401
+ break;
1402
+ }
1403
+ case 'state':
1404
+ {
1405
+ const latest = store.requestManager._deduped.get(requestId);
1406
+ const priority = latest?.priority;
1407
+ const state = this.reqState;
1408
+ if (!priority) {
1409
+ // if there is no priority, we have completed whatever request
1410
+ // was occurring and so we are no longer refreshing (if we were)
1411
+ this.isRefreshing = false;
1412
+ } else if (priority.blocking && !state.isLoading) {
1413
+ // if we are blocking, there is an active request for this identity
1414
+ // that MUST be fulfilled from network (not cache).
1415
+ // Thus this is not "refreshing" because we should clear out and
1416
+ // block on this request.
1417
+ //
1418
+ // we receive state notifications when either a request initiates
1419
+ // or completes.
1420
+ //
1421
+ // In the completes case: we may receive the state notification
1422
+ // slightly before the request is finalized because the NotificationManager
1423
+ // may sync flush it (and thus deliver it before the microtask completes)
1424
+ //
1425
+ // In the initiates case: we aren't supposed to receive one unless there
1426
+ // is no other request in flight for this identity.
1427
+ //
1428
+ // However, there is a race condition here where the completed
1429
+ // notification can trigger an update that generates a new request
1430
+ // thus giving us an initiated notification before the older request
1431
+ // finalizes.
1432
+ //
1433
+ // When this occurs, if the triggered update happens to have caused
1434
+ // a new request to be made for the same identity AND that request
1435
+ // is the one passed into this component as the @request arg, then
1436
+ // getRequestState will return the state of the new request.
1437
+ // We can detect this by checking if the request state is "loading"
1438
+ // as outside of this case we would have a completed request.
1439
+ //
1440
+ // That is the reason for the `&& !state.isLoading` check above.
1441
+
1442
+ // TODO should we just treat this as refreshing?
1443
+ this.isRefreshing = false;
1444
+ this._maybeUpdate('policy', true);
1445
+ } else {
1446
+ this.isRefreshing = true;
1447
+ }
1448
+ }
1449
+ }
1450
+ });
1451
+ }
1452
+ }
1453
+
1454
+ /**
1455
+ * @internal
1456
+ */
1457
+ _removeSubscriptions() {
1458
+ const store = this._requester;
1459
+ if (this._subscription && store && isStore(store)) {
1460
+ store.notifications.unsubscribe(this._subscription);
1461
+ this._subscribedTo = null;
1462
+ this._subscription = null;
1463
+ this._requester = null;
1464
+ }
1465
+ }
1466
+
1467
+ /**
1468
+ * Install the event listeners for network and visibility changes.
1469
+ * This is only done in browser environments with a global `window`.
1470
+ *
1471
+ * @internal
1472
+ */
1473
+ _installListeners() {
1474
+ if (typeof window === 'undefined') {
1475
+ return;
1476
+ }
1477
+ this.isOnline = window.navigator.onLine;
1478
+ this._unavailableStart = this.isOnline ? null : Date.now();
1479
+ this.isHidden = document.visibilityState === 'hidden';
1480
+ this._onlineChanged = event => {
1481
+ this.isOnline = event.type === 'online';
1482
+ if (event.type === 'offline' && this._unavailableStart === null) {
1483
+ this._unavailableStart = Date.now();
1484
+ }
1485
+ this._maybeUpdate();
1486
+ };
1487
+ this._backgroundChanged = () => {
1488
+ const isHidden = document.visibilityState === 'hidden';
1489
+ this.isHidden = isHidden;
1490
+ if (isHidden && this._unavailableStart === null) {
1491
+ this._unavailableStart = Date.now();
1492
+ }
1493
+ this._maybeUpdate();
1494
+ };
1495
+ window.addEventListener('online', this._onlineChanged, {
1496
+ passive: true,
1497
+ capture: true
1498
+ });
1499
+ window.addEventListener('offline', this._onlineChanged, {
1500
+ passive: true,
1501
+ capture: true
1502
+ });
1503
+ document.addEventListener('visibilitychange', this._backgroundChanged, {
1504
+ passive: true,
1505
+ capture: true
1506
+ });
1507
+ }
1508
+
1509
+ /**
1510
+ * If the network is online and the tab is visible, either reload or refresh the request
1511
+ * based on the component's configuration and the requested update mode.
1512
+ *
1513
+ * Valid modes are:
1514
+ *
1515
+ * - `'reload'`: Force a reload of the request.
1516
+ * - `'refresh'`: Refresh the request in the background.
1517
+ * - `'policy'`: Make the request, letting the store's configured CachePolicy decide whether to reload, refresh, or do nothing.
1518
+ * - `undefined`: Make the request using the component's autorefreshBehavior setting if the autorefreshThreshold has passed.
1519
+ *
1520
+ * @internal
1521
+ */
1522
+ _maybeUpdate(mode, silent) {
1523
+ if (this.isIdle) {
1524
+ return;
1525
+ }
1526
+ const {
1527
+ reqState
1528
+ } = this;
1529
+ if (reqState.isPending) {
1530
+ return;
1531
+ }
1532
+ const canAttempt = Boolean(this.isOnline && !this.isHidden && (mode || this.autorefreshTypes.size));
1533
+ if (!canAttempt) {
1534
+ if (!silent && mode && mode !== '_invalidated') {
1535
+ throw new Error(`Reload not available: the network is not online or the tab is hidden`);
1536
+ }
1537
+ return;
1538
+ }
1539
+ const {
1540
+ autorefreshTypes
1541
+ } = this;
1542
+ let shouldAttempt = this._invalidated || Boolean(mode);
1543
+ if (!shouldAttempt && autorefreshTypes.has('online')) {
1544
+ const {
1545
+ _unavailableStart
1546
+ } = this;
1547
+ const {
1548
+ autorefreshThreshold
1549
+ } = this._args;
1550
+ const deadline = typeof autorefreshThreshold === 'number' ? autorefreshThreshold : DEFAULT_DEADLINE;
1551
+ shouldAttempt = Boolean(_unavailableStart && Date.now() - _unavailableStart > deadline);
1552
+ }
1553
+ if (!shouldAttempt && autorefreshTypes.has('interval')) {
1554
+ const {
1555
+ _intervalStart
1556
+ } = this;
1557
+ const {
1558
+ autorefreshThreshold
1559
+ } = this._args;
1560
+ if (_intervalStart && typeof autorefreshThreshold === 'number' && autorefreshThreshold > 0) {
1561
+ shouldAttempt = Boolean(Date.now() - _intervalStart >= autorefreshThreshold);
1562
+ }
1563
+ }
1564
+ this._unavailableStart = null;
1565
+ this._invalidated = false;
1566
+ if (shouldAttempt) {
1567
+ this._clearInterval();
1568
+ this._isUpdating = true;
1569
+ const realMode = mode === '_invalidated' ? null : mode;
1570
+ const val = realMode ?? this._args.autorefreshBehavior ?? 'policy';
1571
+
1572
+ // if the future was generated by an older store version, it may not have
1573
+ // a requester set. In this case we append it to ensure that reload and
1574
+ // refresh will work appropriately.
1575
+ const requester = this._getRequester();
1576
+ if (!reqState._request.requester) {
1577
+ reqState._request.requester = requester;
1578
+ }
1579
+ switch (val) {
1580
+ case 'reload':
1581
+ this._latestRequest = reqState.reload();
1582
+ break;
1583
+ case 'refresh':
1584
+ this._latestRequest = reqState.refresh();
1585
+ break;
1586
+ case 'policy':
1587
+ this._latestRequest = reqState.refresh(true);
1588
+ break;
1589
+ default:
1590
+ (test => {
1591
+ {
1592
+ throw new Error(`Invalid ${mode ? 'update mode' : '@autorefreshBehavior'} for <Request />: ${isNeverString(val)}`);
1593
+ }
1594
+ })();
1595
+ }
1596
+ if (val !== 'refresh') {
1597
+ this._localRequest = this._latestRequest;
1598
+ }
1599
+ void this._scheduleInterval();
1600
+ void this._latestRequest.finally(() => {
1601
+ this._isUpdating = false;
1602
+ });
1603
+ }
1604
+ }
1605
+
1606
+ /**
1607
+ * @internal
1608
+ */
1609
+ _getRequester() {
1610
+ // Note: we check for the requester's presence
1611
+ // as well as the request's presence because we may
1612
+ // be subscribed to a request issued by a store from an older
1613
+ // version of the library that didn't yet set requester.
1614
+ if (this._args.request?.requester) {
1615
+ return this._args.request.requester;
1616
+ }
1617
+ return this.store;
1618
+ }
1619
+
1620
+ /**
1621
+ * Retry the request, reloading it from the server.
1622
+ */
1623
+ retry = async () => {
1624
+ this._maybeUpdate('reload');
1625
+ await this._localRequest;
1626
+ };
1627
+
1628
+ /**
1629
+ * Refresh the request, updating it in the background.
1630
+ */
1631
+ refresh = async () => {
1632
+ this._maybeUpdate('refresh');
1633
+ await this._latestRequest;
1634
+ };
1635
+
1636
+ /**
1637
+ * features to yield to the error slot of a component
1638
+ */
1639
+ get errorFeatures() {
1640
+ return {
1641
+ isHidden: this.isHidden,
1642
+ isOnline: this.isOnline,
1643
+ retry: this.retry
1644
+ };
1645
+ }
1646
+
1647
+ /**
1648
+ * features to yield to the content slot of a component
1649
+ */
1650
+ static {
1651
+ decorateMethodV2(this.prototype, "errorFeatures", [memoized]);
1652
+ }
1653
+ get contentFeatures() {
1654
+ const feat = {
1655
+ isHidden: this.isHidden,
1656
+ isOnline: this.isOnline,
1657
+ reload: this.retry,
1658
+ refresh: this.refresh,
1659
+ isRefreshing: this.isRefreshing,
1660
+ latestRequest: this._latestRequest
1661
+ };
1662
+ if (feat.isRefreshing) {
1663
+ feat.abort = () => {
1664
+ this._latestRequest?.abort();
1665
+ };
1666
+ }
1667
+ return feat;
1668
+ }
1669
+
1670
+ /**
1671
+ * @internal
1672
+ */
1673
+ static {
1674
+ decorateMethodV2(this.prototype, "contentFeatures", [memoized]);
1675
+ }
1676
+ get _request() {
1677
+ const {
1678
+ request,
1679
+ query
1680
+ } = this._args;
1681
+ (test => {
1682
+ if (!test) {
1683
+ throw new Error(`Cannot use both @request and @query args with the <Request> component`);
1684
+ }
1685
+ })(!request || !query);
1686
+ const {
1687
+ _localRequest,
1688
+ _originalRequest,
1689
+ _originalQuery
1690
+ } = this;
1691
+ const isOriginalRequest = request === _originalRequest && query === _originalQuery;
1692
+ if (_localRequest && isOriginalRequest) {
1693
+ return _localRequest;
1694
+ }
1695
+
1696
+ // update state checks for the next time
1697
+ this._originalQuery = query;
1698
+ this._originalRequest = request;
1699
+ if (request) {
1700
+ return request;
1701
+ }
1702
+ (test => {
1703
+ if (!test) {
1704
+ throw new Error(`You must provide either @request or an @query arg with the <Request> component`);
1705
+ }
1706
+ })(query);
1707
+ return this.store.request(query);
1708
+ }
1709
+ static {
1710
+ decorateMethodV2(this.prototype, "_request", [memoized]);
1711
+ }
1712
+ get request() {
1713
+ {
1714
+ try {
1715
+ const request = this._request;
1716
+ this._updateSubscriptions();
1717
+ return request;
1718
+ } catch (e) {
1719
+ // eslint-disable-next-line no-console
1720
+ console.log(e);
1721
+ throw new Error(`Unable to initialize the request`, {
1722
+ cause: e
1723
+ });
1724
+ }
1725
+ }
1726
+ }
1727
+ static {
1728
+ decorateMethodV2(this.prototype, "request", [memoized]);
1729
+ }
1730
+ get reqState() {
1731
+ return getRequestState(this.request);
1732
+ }
1733
+ get result() {
1734
+ return this.reqState.result;
1735
+ }
1736
+ }
1737
+ defineSignal(RequestSubscription.prototype, 'isOnline', true);
1738
+ defineSignal(RequestSubscription.prototype, 'isHidden', false);
1739
+ defineSignal(RequestSubscription.prototype, 'isRefreshing', false);
1740
+ defineSignal(RequestSubscription.prototype, '_localRequest', undefined);
1741
+ defineSignal(RequestSubscription.prototype, '_latestRequest', undefined);
1742
+ function isStore(store) {
1743
+ return 'requestManager' in store;
1744
+ }
1745
+ function createRequestSubscription(store, args) {
1746
+ return new RequestSubscription(store, args);
1747
+ }
1748
+ function upgradeSubscription(sub) {
1749
+ return sub;
1750
+ }
1751
+ function _DISPOSE() {
1752
+ const self = upgradeSubscription(this);
1753
+ self.isDestroyed = true;
1754
+ self._removeSubscriptions();
1755
+ if (typeof window === 'undefined') {
1756
+ return;
1757
+ }
1758
+ self._clearInterval();
1759
+ window.removeEventListener('online', self._onlineChanged, {
1760
+ passive: true,
1761
+ capture: true
1762
+ });
1763
+ window.removeEventListener('offline', self._onlineChanged, {
1764
+ passive: true,
1765
+ capture: true
1766
+ });
1767
+ document.removeEventListener('visibilitychange', self._backgroundChanged, {
1768
+ passive: true,
1769
+ capture: true
1770
+ });
1771
+ }
1772
+ const PromiseCache = new WeakMap();
1773
+
1774
+ /**
1775
+ * The state of a promise in the "pending"
1776
+ * state. This is the default initial state.
1777
+ *
1778
+ */
1779
+
1780
+ /**
1781
+ * The state of a promise in the "fulfilled" state.
1782
+ * This is the state of a promise that has resolved
1783
+ * successfully.
1784
+ *
1785
+ */
1786
+
1787
+ /**
1788
+ * The state of a promise in the "rejected" state.
1789
+ * This is the state of a promise that has rejected
1790
+ * with an error.
1791
+ *
1792
+ */
1793
+
1794
+ /**
1795
+ * The state of a promise. This is the type that is returned
1796
+ * from `getPromiseState`.
1797
+ *
1798
+ * See also:
1799
+ * - {@link PendingPromise}
1800
+ * - {@link ResolvedPromise}
1801
+ * - {@link RejectedPromise}
1802
+ *
1803
+ */
1804
+
1805
+ const PromiseStateProto = {};
1806
+
1807
+ // TODO introduce a new mechanism for defining multiple properties
1808
+ // that share a common signal
1809
+ defineSignal(PromiseStateProto, 'reason', null);
1810
+ defineSignal(PromiseStateProto, 'value', null);
1811
+ defineSignal(PromiseStateProto, 'result', null);
1812
+ defineSignal(PromiseStateProto, 'error', null);
1813
+ defineSignal(PromiseStateProto, 'status', 'pending');
1814
+ defineSignal(PromiseStateProto, 'isPending', true);
1815
+ defineSignal(PromiseStateProto, 'isLoading', true);
1816
+ defineSignal(PromiseStateProto, 'isSuccess', false);
1817
+ defineSignal(PromiseStateProto, 'isError', false);
1818
+ function createPromiseState(promise) {
1819
+ const state = getPromiseResult(promise);
1820
+ const promiseState = Object.create(PromiseStateProto);
1821
+ if (state) {
1822
+ if (state.isError) {
1823
+ promiseState.error = state.result;
1824
+ promiseState.reason = state.result;
1825
+ promiseState.status = 'rejected';
1826
+ promiseState.isError = true;
1827
+ promiseState.isPending = false;
1828
+ promiseState.isLoading = false;
1829
+ } else {
1830
+ promiseState.result = state.result;
1831
+ promiseState.value = state.result;
1832
+ promiseState.status = 'fulfilled';
1833
+ promiseState.isSuccess = true;
1834
+ promiseState.isPending = false;
1835
+ promiseState.isLoading = false;
1836
+ }
1837
+ } else {
1838
+ void promise.then(result => {
1839
+ setPromiseResult(promise, {
1840
+ isError: false,
1841
+ result
1842
+ });
1843
+ promiseState.result = result;
1844
+ promiseState.value = result;
1845
+ promiseState.status = 'fulfilled';
1846
+ promiseState.isSuccess = true;
1847
+ promiseState.isPending = false;
1848
+ promiseState.isLoading = false;
1849
+ }, error => {
1850
+ setPromiseResult(promise, {
1851
+ isError: true,
1852
+ result: error
1853
+ });
1854
+ promiseState.error = error;
1855
+ promiseState.reason = error;
1856
+ promiseState.status = 'rejected';
1857
+ promiseState.isError = true;
1858
+ promiseState.isPending = false;
1859
+ promiseState.isLoading = false;
1860
+ });
1861
+ }
1862
+ return promiseState;
1863
+ }
1864
+ const LegacyPromiseProxy = Symbol.for('LegacyPromiseProxy');
1865
+ function isLegacyAwaitable(promise) {
1866
+ return LegacyPromiseProxy in promise && 'promise' in promise && promise[LegacyPromiseProxy] === true;
1867
+ }
1868
+ function getPromise(promise) {
1869
+ return isLegacyAwaitable(promise) ? promise.promise : promise;
1870
+ }
1871
+
1872
+ /**
1873
+ * Returns a reactive state-machine for the provided promise or awaitable.
1874
+ *
1875
+ * Repeat calls to `getPromiseState` with the same promise will return the same state object
1876
+ * making is safe and easy to use in templates and JavaScript code to produce reactive
1877
+ * behaviors around promises.
1878
+ *
1879
+ * `getPromiseState` can be used in both JavaScript and Template contexts.
1880
+ *
1881
+ * ```ts
1882
+ * import { getPromiseState } from '@warp-drive/ember';
1883
+ *
1884
+ * const state = getPromiseState(promise);
1885
+ * ```
1886
+ *
1887
+ * For instance, we could write a getter on a component that updates whenever
1888
+ * the promise state advances or the promise changes, by combining the function
1889
+ * with the use of `@cached`
1890
+ *
1891
+ * ```ts
1892
+ * class Component {
1893
+ * @cached
1894
+ * get title() {
1895
+ * const state = getPromiseState(this.args.request);
1896
+ * if (state.isPending) {
1897
+ * return 'loading...';
1898
+ * }
1899
+ * if (state.isError) { return null; }
1900
+ * return state.result.title;
1901
+ * }
1902
+ * }
1903
+ * ```
1904
+ *
1905
+ * Or in a template as a helper:
1906
+ *
1907
+ * ```gjs
1908
+ * import { getPromiseState } from '@warp-drive/ember';
1909
+ *
1910
+ * <template>
1911
+ * {{#let (getPromiseState @request) as |state|}}
1912
+ * {{#if state.isPending}} <Spinner />
1913
+ * {{else if state.isError}} <ErrorForm @error={{state.error}} />
1914
+ * {{else}}
1915
+ * <h1>{{state.result.title}}</h1>
1916
+ * {{/if}}
1917
+ * {{/let}}
1918
+ * </template>
1919
+ * ```
1920
+ *
1921
+ * If looking to use in a template, consider also the `<Await />` component.
1922
+ *
1923
+ * See also {@link PromiseState}
1924
+ */
1925
+ function getPromiseState(promise) {
1926
+ (test => {
1927
+ if (!test) {
1928
+ throw new Error(`getPromiseState expects to be called with a promise: called with ${String(promise)}`);
1929
+ }
1930
+ })(promise);
1931
+ const _promise = getPromise(promise);
1932
+ let state = PromiseCache.get(_promise);
1933
+ if (!state) {
1934
+ state = createPromiseState(_promise);
1935
+ PromiseCache.set(_promise, state);
1936
+ }
1937
+ return state;
1938
+ }
1939
+ export { ARRAY_SIGNAL as A, DISPOSE as D, OBJECT_SIGNAL as O, Signals as S, getPromiseState as a, willSyncFlushWatchers as b, createRequestSubscription as c, defineGate as d, getOrCreateInternalSignal as e, consumeInternalSignal as f, getRequestState as g, createInternalSignal as h, createSignalDescriptor as i, defineSignal as j, entangleSignal as k, entangleInitiallyStaleSignal as l, createInternalMemo as m, notifyInternalSignal as n, waitFor as o, peekInternalSignal as p, defineNonEnumerableSignal as q, signal as r, setupSignals as s, gate as t, memoized as u, withSignalStore as w };