@adriansteffan/reactive 0.2.6 → 0.5.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 (156) hide show
  1. package/README.md +796 -229
  2. package/bin/add.js +56 -0
  3. package/bin/deploy.js +48 -0
  4. package/bin/download.js +28 -0
  5. package/bin/ghsetup.js +21 -0
  6. package/bin/native.js +81 -0
  7. package/bin/setup.js +11 -17
  8. package/bin/study-deploy.js +60 -0
  9. package/bin/undeploy.js +15 -0
  10. package/extras/transcription/compose.yaml +32 -0
  11. package/{template → extras}/transcription/transcribe.py +4 -9
  12. package/package.json +62 -64
  13. package/src/bun-env.d.ts +1 -0
  14. package/src/bun-plugin.ts +22 -0
  15. package/src/components/canvasblock.tsx +209 -537
  16. package/src/components/checkdevice.tsx +64 -84
  17. package/src/components/fullscreenblock.tsx +130 -0
  18. package/src/components/icons.tsx +50 -0
  19. package/src/components/index.ts +9 -11
  20. package/src/components/microphonecheck.tsx +76 -38
  21. package/src/components/plaininput.tsx +48 -41
  22. package/src/components/prolificending.tsx +64 -28
  23. package/src/components/quest.tsx +89 -87
  24. package/src/components/{randomdotkinetogram.tsx → randomdotkinematogram.tsx} +205 -267
  25. package/src/components/{voicerecorder.tsx → recorder.tsx} +81 -106
  26. package/src/components/requestfilepermission.tsx +63 -0
  27. package/src/components/stimulus.tsx +373 -0
  28. package/src/components/storeui.tsx +94 -148
  29. package/src/components/text.tsx +61 -59
  30. package/src/components/tutorial.tsx +45 -47
  31. package/src/components/upload.tsx +133 -309
  32. package/src/components/voicerecording.tsx +90 -94
  33. package/src/core/backend.ts +20 -0
  34. package/src/core/bytecode.ts +178 -0
  35. package/src/core/columns.ts +50 -0
  36. package/src/core/component.ts +238 -0
  37. package/src/core/development.ts +32 -0
  38. package/src/core/experiment.ts +263 -0
  39. package/src/core/files.ts +291 -0
  40. package/src/core/params.ts +166 -0
  41. package/src/core/platform.ts +29 -0
  42. package/src/core/rows.ts +106 -0
  43. package/src/core/simulation.ts +158 -0
  44. package/src/core/slides.ts +178 -0
  45. package/src/core/store.ts +22 -0
  46. package/src/core/timeline.ts +399 -0
  47. package/src/fonts/AtkinsonHyperlegible-Bold.woff2 +0 -0
  48. package/src/fonts/AtkinsonHyperlegible-BoldItalic.woff2 +0 -0
  49. package/src/fonts/AtkinsonHyperlegible-Italic.woff2 +0 -0
  50. package/src/fonts/AtkinsonHyperlegible-Regular.woff2 +0 -0
  51. package/src/index.css +5 -7
  52. package/src/mod.tsx +31 -17
  53. package/src/native.ts +127 -0
  54. package/src/quest.ts +2 -0
  55. package/src/runner/contexts.ts +35 -0
  56. package/src/runner/devpanel.tsx +68 -0
  57. package/src/runner/experimentrunner.tsx +210 -0
  58. package/src/runner/fullscreenguard.tsx +93 -0
  59. package/src/runner/paraminput.tsx +86 -0
  60. package/src/runner/progressbar.tsx +20 -0
  61. package/src/runner/settingsscreen.tsx +517 -0
  62. package/src/{utils → runner}/theme.ts +9 -8
  63. package/src/server.ts +93 -0
  64. package/src/tutorial.ts +3 -0
  65. package/src/utils/array.ts +30 -62
  66. package/src/utils/canvas.ts +66 -0
  67. package/src/utils/ddm.ts +47 -70
  68. package/src/utils/distributions.ts +352 -61
  69. package/src/utils/fullscreen.ts +38 -0
  70. package/src/utils/ids.ts +11 -0
  71. package/src/utils/keys.ts +46 -0
  72. package/src/utils/llm.ts +15 -15
  73. package/src/utils/time.ts +12 -0
  74. package/src/utils/tts.ts +24 -24
  75. package/template/.dockerignore +3 -1
  76. package/template/.env.example +5 -0
  77. package/template/.github/workflows/deploy.yml +25 -0
  78. package/template/.gitignore +14 -0
  79. package/template/Dockerfile +9 -14
  80. package/template/README.md +74 -214
  81. package/template/biome.json +34 -0
  82. package/template/build.ts +20 -0
  83. package/template/bunfig.toml +3 -0
  84. package/template/docker-compose.yaml +4 -33
  85. package/template/index.html +2 -2
  86. package/template/package.json +16 -89
  87. package/template/public/.gitkeep +0 -0
  88. package/template/server.ts +32 -0
  89. package/template/simulate.ts +4 -44
  90. package/template/src/Experiment.tsx +76 -128
  91. package/template/src/bun-env.d.ts +1 -0
  92. package/template/src/index.css +1 -9
  93. package/template/src/main.tsx +25 -10
  94. package/template/tsconfig.json +4 -6
  95. package/.claude/settings.local.json +0 -61
  96. package/.eslintrc.cjs +0 -18
  97. package/.playwright-mcp/console-2026-04-07T14-22-59-060Z.log +0 -1
  98. package/.prettierrc +0 -5
  99. package/Dockerfile +0 -20
  100. package/dist/mod-HDegGPrf.js +0 -87434
  101. package/dist/mod.d.ts +0 -946
  102. package/dist/reactive.es.js +0 -87
  103. package/dist/reactive.umd.js +0 -10255
  104. package/dist/style.css +0 -5
  105. package/dist/web-7BbR1Ad7.js +0 -435
  106. package/dist/web-CATfZO1Q.js +0 -12
  107. package/planned.md +0 -103
  108. package/postcss.config.js +0 -6
  109. package/raw-loader-hooks.mjs +0 -25
  110. package/raw-loader.mjs +0 -5
  111. package/rdk_doc.md +0 -341
  112. package/src/components/enterfullscreen.tsx +0 -230
  113. package/src/components/exitfullscreen.tsx +0 -113
  114. package/src/components/experimentprovider.tsx +0 -69
  115. package/src/components/experimentrunner.tsx +0 -497
  116. package/src/components/mobilefilepermission.tsx +0 -68
  117. package/src/components/settingsscreen.tsx +0 -770
  118. package/src/types/array.d.ts +0 -6
  119. package/src/utils/audiodevice.ts +0 -4
  120. package/src/utils/bytecode.ts +0 -261
  121. package/src/utils/common.ts +0 -291
  122. package/src/utils/ddm.test.ts +0 -233
  123. package/src/utils/distributions.test.ts +0 -209
  124. package/src/utils/nodecompat.ts +0 -11
  125. package/src/utils/overlays.ts +0 -19
  126. package/src/utils/request.ts +0 -25
  127. package/src/utils/simulation.ts +0 -299
  128. package/src/utils/upload.ts +0 -275
  129. package/src/vite-env.d.ts +0 -1
  130. package/template/.env.template +0 -2
  131. package/template/.eslintrc.cjs +0 -18
  132. package/template/.prettierrc +0 -5
  133. package/template/backend/package-lock.json +0 -2544
  134. package/template/backend/package.json +0 -31
  135. package/template/backend/src/backend.ts +0 -131
  136. package/template/backend/tsconfig.json +0 -110
  137. package/template/capacitor.config.ts +0 -15
  138. package/template/electron/main.js +0 -131
  139. package/template/electron/preload.js +0 -9
  140. package/template/electron.vite.config.js +0 -45
  141. package/template/package-lock.json +0 -12467
  142. package/template/postcss.config.js +0 -5
  143. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Bold.ttf +0 -0
  144. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-BoldItalic.ttf +0 -0
  145. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Italic.ttf +0 -0
  146. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Regular.ttf +0 -0
  147. package/template/shared.vite.config.js +0 -39
  148. package/template/src/vite-env.d.ts +0 -2
  149. package/template/tsconfig.node.json +0 -12
  150. package/template/vite.config.js +0 -11
  151. package/tsconfig.json +0 -30
  152. package/tsconfig.node.json +0 -12
  153. package/vite.config.ts +0 -39
  154. /package/{template → extras}/transcription/Dockerfile.cpu +0 -0
  155. /package/{template → extras}/transcription/Dockerfile.gpu +0 -0
  156. /package/{template/public/Atkinson_Hyperlegible → src/fonts}/OFL.txt +0 -0
@@ -1,27 +1,244 @@
1
- import mt19937 from '@stdlib/random-base-mt19937';
2
- import normalFactory from '@stdlib/random-base-normal';
3
- import poissonFactory from '@stdlib/random-base-poisson';
4
- import uniformFactory from '@stdlib/random-base-uniform';
5
- import normalQuantile from '@stdlib/stats-base-dists-normal-quantile';
6
- import poissonQuantile from '@stdlib/stats-base-dists-poisson-quantile';
7
- import generateHalton from 'halton';
1
+ import type { AsyncLocalStorage } from 'node:async_hooks';
8
2
 
9
3
  // --- Pseudorandom samplers (seedable) ---
10
4
 
11
- let normal: (mu: number, sigma: number) => number = normalFactory;
12
- let poisson: (lambda: number) => number = poissonFactory;
13
- let uniform: (min: number, max: number) => number = uniformFactory;
5
+ // Mersenne Twister MT19937, Matsumoto & Nishimura (1998), https://doi.org/10.1145/272991.272995
6
+ // Returns the generator's 32-bit integer stream. A seed of several numbers is used as the
7
+ // reference init_by_array does, so that keys like [seed, purpose, index] never share a stream.
8
+ function mt19937(seed: number | readonly number[]): () => number {
9
+ const state = new Uint32Array(624);
10
+ let index = 624;
11
+ const initialize = (value: number) => {
12
+ state[0] = value;
13
+ for (let i = 1; i < 624; i++) {
14
+ state[i] = Math.imul(1812433253, state[i - 1] ^ (state[i - 1] >>> 30)) + i;
15
+ }
16
+ };
17
+
18
+ if (typeof seed === 'number') {
19
+ initialize(seed);
20
+ } else {
21
+ initialize(19650218);
22
+ let i = 1;
23
+ let j = 0;
24
+ for (let k = Math.max(624, seed.length); k > 0; k--) {
25
+ state[i] = (state[i] ^ Math.imul(state[i - 1] ^ (state[i - 1] >>> 30), 1664525)) + seed[j] + j;
26
+ i++;
27
+ j++;
28
+ if (i >= 624) {
29
+ state[0] = state[623];
30
+ i = 1;
31
+ }
32
+ if (j >= seed.length) j = 0;
33
+ }
34
+ for (let k = 623; k > 0; k--) {
35
+ state[i] = (state[i] ^ Math.imul(state[i - 1] ^ (state[i - 1] >>> 30), 1566083941)) - i;
36
+ i++;
37
+ if (i >= 624) {
38
+ state[0] = state[623];
39
+ i = 1;
40
+ }
41
+ }
42
+ state[0] = 0x80000000;
43
+ }
44
+
45
+ return () => {
46
+ if (index === 624) {
47
+ for (let i = 0; i < 624; i++) {
48
+ const y = (state[i] & 0x80000000) | (state[(i + 1) % 624] & 0x7fffffff);
49
+ state[i] = state[(i + 397) % 624] ^ (y >>> 1) ^ (y & 1 ? 0x9908b0df : 0);
50
+ }
51
+ index = 0;
52
+ }
53
+ let y = state[index++];
54
+ y ^= y >>> 11;
55
+ y ^= (y << 7) & 0x9d2c5680;
56
+ y ^= (y << 15) & 0xefc60000;
57
+ y ^= y >>> 18;
58
+ return y >>> 0;
59
+ };
60
+ }
61
+
62
+ // Uniform in [0, 1) with 53-bit resolution, as in the reference genrand_res53
63
+ function unitFromMt19937(next: () => number): () => number {
64
+ return () => ((next() >>> 5) * 67108864 + (next() >>> 6)) / 9007199254740992;
65
+ }
66
+
67
+ let random: () => number = Math.random;
68
+ // The stream of a running withSeed, which takes precedence over all others
69
+ let override: (() => number) | undefined;
70
+ // Participants simulated at the same time each draw from their own stream, which follows them across awaits
71
+ let streams: AsyncLocalStorage<() => number> | undefined;
72
+ let draws = 0;
73
+
74
+ // Every draw of the samplers, and of Math.random once a seed is set, comes from here
75
+ function next(): number {
76
+ draws++;
77
+ return (override ?? streams?.getStore() ?? random)();
78
+ }
79
+
80
+ function seedDistributions(seed: number | readonly number[]): void {
81
+ random = unitFromMt19937(mt19937(seed));
82
+ Math.random = next;
83
+ }
84
+
85
+ // Runs fn with its own seeded stream, then continues the stream that was active before
86
+ function withSeed<T>(seed: number, fn: () => T): T {
87
+ const previousOverride = override;
88
+ const previousMathRandom = Math.random;
89
+ override = unitFromMt19937(mt19937(seed));
90
+ Math.random = next;
91
+ try {
92
+ return fn();
93
+ } finally {
94
+ override = previousOverride;
95
+ Math.random = previousMathRandom;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Runs fn with its own seeded stream, which stays with fn across awaits, so that participants
101
+ * simulated at the same time draw exactly as if each ran alone. Only available in Bun.
102
+ */
103
+ function withStream<T>(seed: number | readonly number[], fn: () => Promise<T>): Promise<T> {
104
+ streams ??= new (process.getBuiltinModule('async_hooks').AsyncLocalStorage)();
105
+ Math.random = next;
106
+ return streams.run(unitFromMt19937(mt19937(seed)), fn);
107
+ }
108
+
109
+ /** Calls fn and counts the random numbers drawn meanwhile, through Math.random or the samplers. */
110
+ async function countDraws<T>(fn: () => Promise<T>): Promise<[T, number]> {
111
+ const previousMathRandom = Math.random;
112
+ const start = draws;
113
+ Math.random = next;
114
+ try {
115
+ return [await fn(), draws - start];
116
+ } finally {
117
+ Math.random = previousMathRandom;
118
+ }
119
+ }
120
+
121
+ function uniform(min: number, max: number): number {
122
+ return min + (max - min) * next();
123
+ }
124
+
125
+ // Box-Muller transform; 1 - next() lies in (0, 1], so the logarithm stays finite
126
+ function normal(mu: number, sigma: number): number {
127
+ const radius = Math.sqrt(-2 * Math.log(1 - next()));
128
+ return mu + sigma * radius * Math.cos(2 * Math.PI * next());
129
+ }
130
+
131
+ // Knuth's multiplication method. exp(-lambda) underflows for large means, so those are drawn
132
+ // as a sum of smaller Poisson draws, which is again Poisson distributed.
133
+ function poisson(lambda: number): number {
134
+ if (!(lambda >= 0)) return NaN;
135
+ let count = 0;
136
+ for (let remaining = lambda; remaining > 0; remaining -= 500) {
137
+ const limit = Math.exp(-Math.min(remaining, 500));
138
+ let product = next();
139
+ while (product > limit) {
140
+ count++;
141
+ product *= next();
142
+ }
143
+ }
144
+ return count;
145
+ }
146
+
147
+ // --- Quantile functions ---
148
+
149
+ // Evaluates c[0] + c[1] x + c[2] x^2 + ... (Horner's method)
150
+ function polynomial(coefficients: number[], x: number): number {
151
+ return coefficients.reduceRight((sum, c) => sum * x + c, 0);
152
+ }
153
+
154
+ // Wichura (1988), Algorithm AS 241 (PPND16), https://doi.org/10.2307/2347330
155
+ // Accurate to about 1e-16 on the open interval (0, 1).
156
+ const AS241_CENTRAL = [
157
+ [
158
+ 3.3871328727963665, 133.14166789178438, 1971.5909503065513, 13731.69376550946,
159
+ 45921.95393154987, 67265.7709270087, 33430.57558358813, 2509.0809287301227,
160
+ ],
161
+ [
162
+ 1, 42.31333070160091, 687.1870074920579, 5394.196021424751, 21213.794301586597,
163
+ 39307.89580009271, 28729.085735721943, 5226.495278852854,
164
+ ],
165
+ ];
166
+ const AS241_INTERMEDIATE = [
167
+ [
168
+ 1.4234371107496835, 4.630337846156546, 5.769497221460691, 3.6478483247632045,
169
+ 1.2704582524523684, 0.2417807251774506, 0.022723844989269184,
170
+ 0.0007745450142783414,
171
+ ],
172
+ [
173
+ 1, 2.053191626637759, 1.6763848301838038, 0.6897673349851,
174
+ 0.14810397642748008, 0.015198666563616457, 0.0005475938084995345,
175
+ 1.0507500716444169e-9,
176
+ ],
177
+ ];
178
+ const AS241_TAIL = [
179
+ [
180
+ 6.657904643501103, 5.463784911164114, 1.7848265399172913, 0.29656057182850487,
181
+ 0.026532189526576124, 0.0012426609473880784, 0.000027115555687434876,
182
+ 2.0103343992922881e-7,
183
+ ],
184
+ [
185
+ 1, 0.599832206555888, 0.1369298809227358, 0.014875361290850615,
186
+ 0.0007868691311456133, 0.000018463183175100548, 1.421511758316446e-7,
187
+ 2.0442631033899397e-15,
188
+ ],
189
+ ];
190
+
191
+ function standardNormalQuantile(p: number): number {
192
+ const q = p - 0.5;
193
+ if (Math.abs(q) <= 0.425) {
194
+ const r = 0.180625 - q * q;
195
+ return (q * polynomial(AS241_CENTRAL[0], r)) / polynomial(AS241_CENTRAL[1], r);
196
+ }
197
+ const r = Math.sqrt(-Math.log(q < 0 ? p : 1 - p));
198
+ const [numerator, denominator] = r <= 5 ? AS241_INTERMEDIATE : AS241_TAIL;
199
+ const shifted = r <= 5 ? r - 1.6 : r - 5;
200
+ const x = polynomial(numerator, shifted) / polynomial(denominator, shifted);
201
+ return q < 0 ? -x : x;
202
+ }
203
+
204
+ // Hart (1968), as given by West (2005), "Better approximations to cumulative normal functions",
205
+ // Wilmott Magazine. Accurate to about 1e-15; in the tails, about 1e-9 of the probability at 1e-10.
206
+ const HART = [
207
+ [
208
+ 220.206867912376, 221.213596169931, 112.079291497871, 33.912866078383,
209
+ 6.37396220353165, 0.700383064443688, 0.0352624965998911,
210
+ ],
211
+ [
212
+ 440.413735824752, 793.826512519948, 637.333633378831, 296.564248779674,
213
+ 86.7807322029461, 16.064177579207, 1.75566716318264, 0.0883883476483184,
214
+ ],
215
+ ];
14
216
 
15
- interface StdlibPRNG {
16
- normalized: () => number;
217
+ function standardNormalCdf(x: number): number {
218
+ const z = Math.abs(x);
219
+ const exponential = Math.exp((-z * z) / 2);
220
+ const tail =
221
+ z < 5 * Math.SQRT2
222
+ ? (exponential * polynomial(HART[0], z)) / polynomial(HART[1], z)
223
+ : exponential / (z + 1 / (z + 2 / (z + 3 / (z + 4 / (z + 0.65))))) / Math.sqrt(2 * Math.PI);
224
+ return x > 0 ? 1 - tail : tail;
17
225
  }
18
226
 
19
- function seedDistributions(seed: number): void {
20
- const prng = mt19937.factory({ seed }) as unknown as StdlibPRNG;
21
- normal = normalFactory.factory({ prng: prng.normalized });
22
- poisson = poissonFactory.factory({ prng: prng.normalized });
23
- uniform = uniformFactory.factory({ prng: prng.normalized });
24
- Math.random = () => uniform(0, 1);
227
+ // Smallest k with P(X <= k) >= p. The probability mass is summed in log space so that large
228
+ // means don't underflow. In double precision the sum is accurate to about 1e-11 for means in
229
+ // the thousands, so a p closer than that to a step of the distribution can land one off.
230
+ function poissonQuantile(p: number, lambda: number): number {
231
+ if (lambda === 0) return 0;
232
+ const logLambda = Math.log(lambda);
233
+ let logMass = -lambda;
234
+ let cumulative = 0;
235
+ for (let k = 0; ; k++) {
236
+ if (k > 0) logMass += logLambda - Math.log(k);
237
+ const mass = Math.exp(logMass);
238
+ cumulative += mass;
239
+ // Past the mode, a mass of zero means rounding kept the sum just below p
240
+ if (cumulative >= p || (k > lambda && mass === 0)) return k;
241
+ }
25
242
  }
26
243
 
27
244
  // --- QMC dimension specs ---
@@ -34,6 +251,24 @@ type IntegerSpec = { distribution: 'integer'; min: number; max: number };
34
251
  type DiscreteSpec = { distribution: 'discrete'; outcomes: Array<{ value: number; weight: number }> };
35
252
  type DimensionSpec = UniformSpec | NormalSpec | PoissonSpec | IntegerSpec | DiscreteSpec;
36
253
 
254
+ /** A trait of the sampled participants: its distribution, and how it correlates with the other traits. */
255
+ type TraitSpec = DimensionSpec & {
256
+ /**
257
+ * Correlations with other traits, by their names, each pair given at one of its two traits. A
258
+ * normal trait gets the correlation as given, other distributions a somewhat weaker one.
259
+ */
260
+ correlations?: Record<string, number>;
261
+ };
262
+
263
+ // Traits as declared, whose correlations can only name the other traits
264
+ type CheckedTraits<T> = {
265
+ [K in keyof T]: T[K] extends { correlations: infer C }
266
+ ? Omit<T[K], 'correlations'> & {
267
+ correlations: { [O in keyof C]: O extends Exclude<keyof T, K> ? number : `'${O & string}' is not another trait` };
268
+ }
269
+ : T[K];
270
+ };
271
+
37
272
  // Inverse CDFs return +-Infinity at exactly 0 or 1, so clamp to open interval (0, 1).
38
273
  function clampUnit(value: number): number {
39
274
  return Math.max(1e-10, Math.min(1 - 1e-10, value));
@@ -44,7 +279,7 @@ function resolveTransform(spec: DimensionSpec): (unitValue: number) => number {
44
279
  case 'uniform':
45
280
  return (u) => spec.min + u * (spec.max - spec.min);
46
281
  case 'normal':
47
- return (u) => normalQuantile(clampUnit(u), spec.mean, spec.sd);
282
+ return (u) => spec.mean + spec.sd * standardNormalQuantile(clampUnit(u));
48
283
  case 'poisson':
49
284
  // QMC variance reduction is less effective on discrete distributions
50
285
  // due to integer clumping at quantile boundaries.
@@ -69,11 +304,8 @@ function resolveTransform(spec: DimensionSpec): (unitValue: number) => number {
69
304
  }
70
305
  }
71
306
 
72
- function transformPoints(unitPoints: number[][], specs: DimensionSpec[]): number[] | number[][] {
307
+ function transformPoints(unitPoints: number[][], specs: DimensionSpec[]): number[][] {
73
308
  const transforms = specs.map(resolveTransform);
74
- if (specs.length === 1) {
75
- return unitPoints.map((point) => transforms[0](point[0]));
76
- }
77
309
  return unitPoints.map((point) =>
78
310
  point.map((unitValue, dim) => transforms[dim](unitValue)),
79
311
  );
@@ -148,67 +380,126 @@ function generateSobol(count: number, dimensions: number): number[][] {
148
380
 
149
381
  // --- Halton sequence ---
150
382
  // Halton (1960), https://doi.org/10.1007/BF01386213
383
+ function radicalInverse(index: number, base: number): number {
384
+ let result = 0;
385
+ let fraction = 1 / base;
386
+ for (let i = index; i > 0; i = Math.floor(i / base)) {
387
+ result += fraction * (i % base);
388
+ fraction /= base;
389
+ }
390
+ return result;
391
+ }
392
+
151
393
  const PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73];
152
394
  const HALTON_MAX_EFFECTIVE_DIMS = 6;
153
395
 
154
- function sobol(count: number, specs: DimensionSpec[]): number[] | number[][] {
155
- // Generate count+1 and skip the first point (always zero in every dimension)
156
- const unitPoints = generateSobol(count + 1, specs.length).slice(1);
157
- return transformPoints(unitPoints, specs);
396
+ // Both sequences start at their second point, since the first is zero in every dimension
397
+ function sobolUnitPoints(count: number, dimensions: number): number[][] {
398
+ return generateSobol(count + 1, dimensions).slice(1);
158
399
  }
159
400
 
160
- function halton(count: number, specs: DimensionSpec[]): number[] | number[][] {
161
- if (specs.length > HALTON_MAX_EFFECTIVE_DIMS) {
401
+ function haltonUnitPoints(count: number, dimensions: number): number[][] {
402
+ if (dimensions > HALTON_MAX_EFFECTIVE_DIMS) {
162
403
  console.warn(`Halton sequence quality degrades above ${HALTON_MAX_EFFECTIVE_DIMS} dimensions. Consider using sobol() instead.`);
163
404
  }
164
- const bases = PRIMES.slice(0, specs.length);
165
- // Generate count+1 and skip the first point (always zero in every dimension)
166
- const unitPoints = (generateHalton(count + 1, bases) as number[][]).slice(1);
167
- return transformPoints(unitPoints, specs);
405
+ const bases = PRIMES.slice(0, dimensions);
406
+ return Array.from({ length: count }, (_, i) => bases.map((base) => radicalInverse(i + 1, base)));
407
+ }
408
+
409
+ function sobol(count: number, specs: DimensionSpec[]): number[][] {
410
+ return transformPoints(sobolUnitPoints(count, specs.length), specs);
411
+ }
412
+
413
+ function halton(count: number, specs: DimensionSpec[]): number[][] {
414
+ return transformPoints(haltonUnitPoints(count, specs.length), specs);
415
+ }
416
+
417
+ // The lower triangular L with L·Lᵀ = matrix, or undefined when the matrix is not positive definite
418
+ function cholesky(matrix: number[][]): number[][] | undefined {
419
+ const factor = matrix.map((row) => row.map(() => 0));
420
+ for (let i = 0; i < matrix.length; i++) {
421
+ for (let j = 0; j <= i; j++) {
422
+ let sum = matrix[i][j];
423
+ for (let k = 0; k < j; k++) sum -= factor[i][k] * factor[j][k];
424
+ if (i === j) {
425
+ if (sum <= 0) return undefined;
426
+ factor[i][i] = Math.sqrt(sum);
427
+ } else {
428
+ factor[i][j] = sum / factor[j][j];
429
+ }
430
+ }
431
+ }
432
+ return factor;
433
+ }
434
+
435
+ // The Cholesky factor of the traits' correlation matrix, or undefined when no traits correlate
436
+ function correlationFactor(keys: string[], traits: Record<string, TraitSpec>): number[][] | undefined {
437
+ const matrix: number[][] = keys.map((_, i) => keys.map((_, j) => (i === j ? 1 : 0)));
438
+ let correlated = false;
439
+ keys.forEach((key, i) => {
440
+ for (const [other, correlation] of Object.entries(traits[key].correlations ?? {})) {
441
+ const j = keys.indexOf(other);
442
+ if (matrix[i][j] !== 0) {
443
+ throw new Error(`The correlation of '${key}' and '${other}' is given at both traits; give it at one of them.`);
444
+ }
445
+ if (!(correlation > -1 && correlation < 1)) {
446
+ throw new Error(`The correlation of '${key}' and '${other}' is ${correlation}, but it has to be greater than -1 and less than 1.`);
447
+ }
448
+ matrix[i][j] = correlation;
449
+ matrix[j][i] = correlation;
450
+ correlated = true;
451
+ }
452
+ });
453
+ if (!correlated) return undefined;
454
+ const factor = cholesky(matrix);
455
+ if (!factor) {
456
+ throw new Error(
457
+ "The traits' correlations contradict each other, so no population can have them all, as with a and b at 0.9 and b and c at 0.9, but a and c at -0.9.",
458
+ );
459
+ }
460
+ return factor;
461
+ }
462
+
463
+ // A Gaussian copula: each point's unit values become normal scores, which the factor mixes, and
464
+ // back. The mixing is one-to-one, so the points stay as evenly spread as the sequence made them.
465
+ function correlate(points: number[][], factor: number[][]): number[][] {
466
+ return points.map((point) => {
467
+ const scores = point.map((unitValue) => standardNormalQuantile(clampUnit(unitValue)));
468
+ return factor.map((row) => standardNormalCdf(row.reduce((sum, weight, k) => sum + weight * scores[k], 0)));
469
+ });
168
470
  }
169
471
 
170
472
  type SamplingMethod = 'sobol' | 'halton' | 'random';
171
473
 
172
- function sampleParticipants<T extends Record<string, DimensionSpec>>(
474
+ function sampleParticipants<T extends Record<string, TraitSpec>>(
173
475
  method: SamplingMethod,
174
476
  count: number,
175
- specs: T,
477
+ specs: CheckedTraits<T>,
176
478
  ): Array<{ [K in keyof T]: number } & { index: number }> {
177
- const keys = Object.keys(specs) as (keyof T & string)[];
178
- const dimSpecs = keys.map((k) => specs[k]);
479
+ const traits = specs as Record<string, TraitSpec>;
480
+ const keys = Object.keys(traits);
179
481
 
180
- let points: number[] | number[][];
482
+ let unitPoints: number[][];
181
483
  switch (method) {
182
484
  case 'sobol':
183
- points = sobol(count, dimSpecs);
485
+ unitPoints = sobolUnitPoints(count, keys.length);
184
486
  break;
185
487
  case 'halton':
186
- points = halton(count, dimSpecs);
488
+ unitPoints = haltonUnitPoints(count, keys.length);
187
489
  break;
188
490
  case 'random':
189
- points = randomPoints(count, dimSpecs);
491
+ unitPoints = Array.from({ length: count }, () => keys.map(() => uniform(0, 1)));
190
492
  break;
191
493
  }
192
494
 
193
- return Array.from({ length: count }, (_, i) => {
194
- const row = keys.length === 1 ? [points[i] as number] : (points[i] as number[]);
195
- return { index: i, ...Object.fromEntries(keys.map((k, d) => [k, row[d]])) } as { [K in keyof T]: number } & { index: number };
196
- });
197
- }
198
-
199
- function randomPoints(count: number, specs: DimensionSpec[]): number[] | number[][] {
200
- const transforms = specs.map(resolveTransform);
201
- if (specs.length === 1) {
202
- return Array.from({ length: count }, () => transforms[0](uniform(0, 1)));
203
- }
204
- return Array.from({ length: count }, () =>
205
- transforms.map((t) => t(uniform(0, 1))),
206
- );
207
- }
208
-
209
- function draw(spec: DimensionSpec): number {
210
- return resolveTransform(spec)(uniform(0, 1));
495
+ const factor = correlationFactor(keys, traits);
496
+ const points = transformPoints(factor ? correlate(unitPoints, factor) : unitPoints, keys.map((key) => traits[key]));
497
+ return points.map((point, index) => ({ index, ...Object.fromEntries(keys.map((key, d) => [key, point[d]])) })) as Array<
498
+ { [K in keyof T]: number } & { index: number }
499
+ >;
211
500
  }
212
501
 
213
- export { normal, poisson, uniform, seedDistributions, sobol, halton, sampleParticipants, draw };
214
- export type { DimensionSpec, UniformSpec, NormalSpec, PoissonSpec, IntegerSpec, DiscreteSpec, SamplingMethod };
502
+ export { normal, poisson, uniform, seedDistributions, withSeed, withStream, countDraws, sobol, halton, sampleParticipants };
503
+ // Exported for the tests, not part of the public API
504
+ export { mt19937, standardNormalQuantile, standardNormalCdf, poissonQuantile };
505
+ export type { DimensionSpec, TraitSpec, UniformSpec, NormalSpec, PoissonSpec, IntegerSpec, DiscreteSpec, SamplingMethod };
@@ -0,0 +1,38 @@
1
+ export function isFullscreen(): boolean {
2
+ const domFs = !!(document.fullscreenElement || (document as any).webkitFullscreenElement);
3
+ if (!domFs) return false;
4
+ // On macOS Chrome, `fullscreenElement` can stay set after ESC exit. When truly
5
+ // in fullscreen, no browser chrome is visible, so outerHeight === innerHeight.
6
+ return Math.abs(window.outerHeight - window.innerHeight) < 5;
7
+ }
8
+
9
+ // Safari before 16.4 only has the prefixed API, which reports how a request went through events
10
+ function webkitRequest(start: () => void): Promise<void> {
11
+ return new Promise((resolve, reject) => {
12
+ const settle = (event: Event) => {
13
+ document.removeEventListener('webkitfullscreenchange', settle);
14
+ document.removeEventListener('webkitfullscreenerror', settle);
15
+ if (event.type === 'webkitfullscreenerror') reject(new Error('The browser refused the fullscreen request.'));
16
+ else resolve();
17
+ };
18
+ document.addEventListener('webkitfullscreenchange', settle);
19
+ document.addEventListener('webkitfullscreenerror', settle);
20
+ start();
21
+ });
22
+ }
23
+
24
+ /** Asks the browser to show the page in fullscreen; rejects if it refuses or cannot. */
25
+ export function enterFullscreen(): Promise<void> {
26
+ const element = document.documentElement as any;
27
+ if (element.requestFullscreen) return element.requestFullscreen();
28
+ if (element.webkitRequestFullscreen) return webkitRequest(() => element.webkitRequestFullscreen());
29
+ return Promise.reject(new Error('This browser has no fullscreen mode.'));
30
+ }
31
+
32
+ /** Asks the browser to leave fullscreen; rejects if it refuses or cannot. */
33
+ export function exitFullscreen(): Promise<void> {
34
+ const doc = document as any;
35
+ if (doc.exitFullscreen) return doc.exitFullscreen();
36
+ if (doc.webkitExitFullscreen) return webkitRequest(() => doc.webkitExitFullscreen());
37
+ return Promise.reject(new Error('This browser has no fullscreen mode.'));
38
+ }
package/src/utils/ids.ts CHANGED
@@ -15,3 +15,14 @@ export function alphanumericId(length: number): string {
15
15
  export function prolificId(): string {
16
16
  return alphanumericId(24);
17
17
  }
18
+
19
+ /**
20
+ * Random version 4 UUID.
21
+ */
22
+ export function uuidv4(): string {
23
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
24
+ bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
25
+ bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 10xx, RFC 9562
26
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
27
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
28
+ }
@@ -0,0 +1,46 @@
1
+ type Letter =
2
+ | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm'
3
+ | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z';
4
+ type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
5
+ type Symbol = ' ' | ',' | '.' | '/' | ';' | "'" | '[' | ']' | '\\' | '-' | '=' | '`';
6
+ type NamedKey =
7
+ | 'Enter' | 'Escape' | 'Tab' | 'Backspace' | 'Delete'
8
+ | 'ArrowLeft' | 'ArrowRight' | 'ArrowUp' | 'ArrowDown'
9
+ | 'Home' | 'End' | 'PageUp' | 'PageDown'
10
+ | 'Shift' | 'Control' | 'Alt' | 'Meta'
11
+ | `F${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12}`;
12
+
13
+ /**
14
+ * A key as the browser names it in `KeyboardEvent.key`: a letter, in either case, a digit or
15
+ * symbol, `' '` for the space bar, a named key such as `'Enter'` or `'ArrowLeft'`, or any other
16
+ * name the browser gives, such as `'ö'`.
17
+ */
18
+ // `string & {}` takes any name while editors still suggest the ones above, which `string` would hide
19
+ export type ResponseKey = Letter | Uppercase<Letter> | Digit | Symbol | NamedKey | (string & {});
20
+
21
+ /**
22
+ * The key a press counts as: the one in `keys` it matches in any case, so that caps lock, shift
23
+ * and `'enter'` for `'Enter'` make no difference; or with `true`, the pressed key, a letter in
24
+ * lowercase. `undefined` if it does not count.
25
+ */
26
+ export function responseKey(keys: readonly string[] | boolean | undefined, pressed: string): string | undefined {
27
+ if (keys === true) return pressed.length === 1 ? pressed.toLowerCase() : pressed;
28
+ if (!keys) return undefined;
29
+ return keys.find((key) => key.toLowerCase() === pressed.toLowerCase());
30
+ }
31
+
32
+ /**
33
+ * The answer a key press gives: the name of the choice whose key it is, or a listed key, or with
34
+ * `keys: true` any key, as itself. Undefined for a key that does not answer.
35
+ */
36
+ export function keyAnswer(
37
+ answers: { keys?: readonly string[] | true; choices?: Record<string, { key?: string }> } | undefined,
38
+ pressed: string,
39
+ ): { response: string; key: string } | undefined {
40
+ for (const [name, choice] of Object.entries(answers?.choices ?? {})) {
41
+ const key = choice.key === undefined ? undefined : responseKey([choice.key], pressed);
42
+ if (key !== undefined) return { response: name, key };
43
+ }
44
+ const key = responseKey(answers?.keys ?? false, pressed);
45
+ return key === undefined ? undefined : { response: key, key };
46
+ }
package/src/utils/llm.ts CHANGED
@@ -55,46 +55,46 @@ async function callLLM(config: LLMConfig, prompt: string, schema?: LLMSchema): P
55
55
  const CACHE_DIR = '.reactive-cache';
56
56
  const CACHE_FILE = 'llm.json';
57
57
  let diskCache: Record<string, string> | null = null;
58
- import { getNodeRequire } from './nodecompat';
59
58
 
60
- async function loadCache(): Promise<Record<string, string>> {
59
+ function loadCache(): Record<string, string> {
61
60
  if (diskCache) return diskCache;
62
61
  try {
63
- const req = await getNodeRequire();
64
- const fs = req('fs') as typeof import('fs');
65
- const path = req('path') as typeof import('path');
62
+ const fs = process.getBuiltinModule('fs');
63
+ const path = process.getBuiltinModule('path');
66
64
  const filePath = path.join(process.cwd(), CACHE_DIR, CACHE_FILE);
67
65
  if (fs.existsSync(filePath)) {
68
66
  diskCache = JSON.parse(fs.readFileSync(filePath, 'utf8'));
69
67
  return diskCache!;
70
68
  }
71
- } catch {}
69
+ } catch {
70
+ // No readable cache yet; start empty
71
+ }
72
72
  diskCache = {};
73
73
  return diskCache;
74
74
  }
75
75
 
76
- async function saveCache(): Promise<void> {
77
- if (!diskCache) return;
76
+ function saveCache(cache: Record<string, string>) {
78
77
  try {
79
- const req = await getNodeRequire();
80
- const fs = req('fs') as typeof import('fs');
81
- const path = req('path') as typeof import('path');
78
+ const fs = process.getBuiltinModule('fs');
79
+ const path = process.getBuiltinModule('path');
82
80
  const dirPath = path.join(process.cwd(), CACHE_DIR);
83
81
  fs.mkdirSync(dirPath, { recursive: true });
84
- fs.writeFileSync(path.join(dirPath, CACHE_FILE), JSON.stringify(diskCache, null, 2));
85
- } catch {}
82
+ fs.writeFileSync(path.join(dirPath, CACHE_FILE), JSON.stringify(cache, null, 2));
83
+ } catch {
84
+ // The cache only saves repeated API calls, so failing to write it is harmless
85
+ }
86
86
  }
87
87
 
88
88
  export async function invokeLLM(config: LLMConfig, prompt: string, schema?: LLMSchema): Promise<string> {
89
89
  const formatKey = schema ? JSON.stringify(schema) : '';
90
90
  const cacheKey = `${config.provider}:${config.model}:${prompt}:${formatKey}`;
91
- const cache = await loadCache();
91
+ const cache = loadCache();
92
92
 
93
93
  let text = cache[cacheKey];
94
94
  if (!text) {
95
95
  text = await callLLM(config, prompt, schema);
96
96
  cache[cacheKey] = text;
97
- await saveCache();
97
+ saveCache(cache);
98
98
  }
99
99
 
100
100
  return text;
@@ -0,0 +1,12 @@
1
+ /** Milliseconds since the page loaded, the clock that rows' times use. */
2
+ export function now() {
3
+ return Math.round(performance.now());
4
+ }
5
+
6
+ /**
7
+ * Half a frame at the measured refresh rate, which timed displays add to end on the frame nearest
8
+ * their time; 0 without a plausible rate.
9
+ */
10
+ export function halfFrameMs(refreshRate: number | undefined): number {
11
+ return refreshRate !== undefined && refreshRate >= 20 && refreshRate <= 300 ? 500 / refreshRate : 0;
12
+ }