@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,58 +1,16 @@
1
1
  import React, { useState, useRef } from 'react';
2
- import { BaseComponentProps } from '../utils/common';
3
- import { VoiceRecorder, VoiceRecorderHandle } from './voicerecorder';
4
- import { registerSimulation } from '../utils/simulation';
5
- import { registerFlattener, generateAudioFilename } from '../utils/upload';
6
- import { useTheme, t } from '../utils/theme';
7
- import { HiExclamationTriangle } from 'react-icons/hi2';
2
+ import { BaseComponentProps } from '../core/component';
3
+ import { Recorder, RecorderHandle } from './recorder';
4
+ import { defineComponent } from '../core/component';
5
+ import { audioFilename, markRecordingUploaded } from '../core/files';
6
+ import { useTheme, t } from '../runner/theme';
7
+ import { ExclamationTriangleIcon } from './icons';
8
8
  import { textToWebmBase64, probeAudioDurationMs } from '../utils/tts';
9
- import { post } from '../utils/request';
9
+ import { post } from '../core/backend';
10
10
 
11
11
  // 0.5s 440Hz sine tone, Opus codec; fallback when system TTS/ffmpeg unavailable
12
12
  const DUMMY_AUDIO_BASE64 = 'GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQRChYECGFOAZwEAAAAAAARQEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHYTbuMU6uEElTDZ1OsggE/TbuMU6uEHFO7a1OsggQ67AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmsirXsYMPQkBNgI1MYXZmNTguNzYuMTAwV0GNTGF2ZjU4Ljc2LjEwMESJiEB/wAAAAAAAFlSua+KuAQAAAAAAAFnXgQFzxYhRMt5OPJYVP5yBACK1nIN1bmSGhkFfT1BVU1aqg2MuoFa7hATEtACDgQLhkZ+BAbWIQOdwAAAAAABiZIEQY6KTT3B1c0hlYWQBATgBgLsAAAAAABJUw2dAm3NzAQAAAAAAACdjwIBnyAEAAAAAAAAaRaOHRU5DT0RFUkSHjUxhdmY1OC43Ni4xMDBzcwEAAAAAAABgY8CLY8WIUTLeTjyWFT9nyAEAAAAAAAAjRaOHRU5DT0RFUkSHlkxhdmM1OC4xMzQuMTAwIGxpYm9wdXNnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjUwODAwMDAwMAAAH0O2dUJU54EAo5GBAACACINtgtAc/epJ/gE/wKOZgQAVgAinGl2KmC5fWspQj0PpJrkNsG40QKOVgQApgAihLxDkXfvcBBqwyPJFmpFgo5OBAD2ACKE40Hcyqlc9/1ttqV84o5SBAFGACKE40Hcyql5YIeRahOZfwKOXgQBlgAihTMA96uabsR453W080Xeb9h6jkYEAeYAIoTjQdzKqXDNU2kjGo5aBAI2ACKDZbPIJxX8xM7SEPNZetOMco5OBAKGACKE40Hcyqla9XawRHUWoo5OBALWACKE40Hcyqmb1XKO++uAQo5SBAMmACKEvEORd+8XekK1/rf/rrKOVgQDdgAihONB3MqpWRgIfsDV4YBUIo5OBAPGACKE40Hcyql5SyE1S2QFAo5SBAQWACKE40Hcyqla+8h2o+iaxgKOVgQEZgAihONB3MqpeqdUAtSaZmdKAo5OBAS2ACKFIA0bVUn3Jmsi7ollwo5OBAUGACKE40Hcyql6pt6b1uh3oo5WBAVWACKEvEORd+9/La7aeTKZnv/CjlYEBaYAIoTjO/AZGOE9OIX9kO96+gKOTgQF9gAihONB3MqpekAQ00UpCUKOTgQGRgAihSANG1VJz2oSiMZRZKqOQgQGlgAihONB3MqpeqbeK3KORgQG5gAihLxDkXfvfy2sJCQyjmoEBzYAIosXU/J/RyZHEovOUhd6Ypj7UPC8Bo5uBAeGACKRIuuxKsgM4Wle7xUaBZDTNWofASYGgAQAAAAAAABuhkoEB9QAIBkQ+QjevBKpbiF1qJHWihADN/mAcU7trkbuPs4EAt4r3gQHxggHg8IED';
13
13
 
14
- export { DUMMY_AUDIO_BASE64 };
15
-
16
- registerFlattener('VoiceRecording', 'session');
17
- registerSimulation('VoiceRecording', async (_trialProps, _experimentState, simulators, participant) => {
18
- const respond = simulators.respondTTS ?? simulators.respondBase64;
19
- const result = await respond(_trialProps, participant);
20
- const { participantState } = result;
21
-
22
- let data64: string;
23
- if (simulators.respondTTS) {
24
- const text = result.value as string;
25
- const ttsResult = await textToWebmBase64(text);
26
- if (!ttsResult) throw new Error('TTS failed. Ensure say/espeak and ffmpeg are installed.');
27
- data64 = ttsResult;
28
- } else {
29
- data64 = result.value as string;
30
- }
31
-
32
- // Exact duration via ffprobe, fall back to estimate from file size
33
- const recordingDuration = (await probeAudioDurationMs(data64)) ?? Math.round(data64.length / 4);
34
- return {
35
- responseData: {
36
- type: 'audiorecording',
37
- data64,
38
- timestamp: new Date().toISOString(),
39
- recordingDuration,
40
- },
41
- participantState,
42
- duration: recordingDuration,
43
- };
44
- }, {
45
- /** Returns text to be spoken via platform TTS. Default: generic test sentence. */
46
- respondTTS: (_input: any, participant: any) => ({
47
- value: 'This is a simulated voice recording for testing purposes.',
48
- participantState: participant,
49
- }),
50
- /** Returns raw base64-encoded WebM audio directly. Default: dummy 0.5s sine tone. */
51
- respondBase64: (_input: any, participant: any) => ({
52
- value: DUMMY_AUDIO_BASE64,
53
- participantState: participant,
54
- }),
55
- });
56
14
 
57
15
  function VoiceRecording({
58
16
  content,
@@ -61,68 +19,68 @@ function VoiceRecording({
61
19
  className = '',
62
20
  containerClass,
63
21
  next,
22
+ data,
64
23
  store,
65
- minDuration,
66
- shortRecordingWarning,
24
+ minDurationMs,
25
+ shortRecordingContent,
67
26
  showVisualizer = true,
68
27
  eagerUpload = true,
69
28
  animate = false,
70
29
  name,
71
- silenceWarningSec,
72
- silenceWarningText,
30
+ silenceWarningMs,
31
+ silenceWarningContent,
73
32
  }: BaseComponentProps & {
74
33
  content?: React.ReactNode;
75
34
  buttonText?: string;
76
- /** Button text when recording is shorter than minDuration. Defaults to buttonText. */
35
+ /** Button text when the recording is shorter than minDurationMs. */
77
36
  shortButtonText?: string;
78
37
  className?: string;
79
38
  containerClass?: string;
80
- /** Minimum recording duration in ms. If shorter, a warning is shown when paused. */
81
- minDuration?: number;
82
- /** Custom warning text for short recordings. */
83
- shortRecordingWarning?: React.ReactNode;
39
+ /** Minimum recording duration. If shorter, a warning is shown when paused. */
40
+ minDurationMs?: number;
41
+ /** Shown when the recording is shorter than minDurationMs. */
42
+ shortRecordingContent?: React.ReactNode;
84
43
  /** Show the volume level meter during recording. Default true. */
85
44
  showVisualizer?: boolean;
86
45
  /** Upload audio immediately after recording to reduce final upload size. Default true. */
87
46
  eagerUpload?: boolean;
88
47
  animate?: boolean;
89
- name?: string;
90
- /** Seconds of continuous silence before a "speak up" banner appears. Disabled when undefined. */
91
- silenceWarningSec?: number;
92
- /** Text shown in the silence banner. */
93
- silenceWarningText?: string;
48
+ /** Milliseconds of continuous silence before a "speak up" banner appears. Disabled when undefined. */
49
+ silenceWarningMs?: number;
50
+ /** Shown in the silence banner. */
51
+ silenceWarningContent?: React.ReactNode;
94
52
  }) {
95
53
  const th = t(useTheme());
96
- const resolvedButtonText = buttonText ?? (minDuration != null ? 'Save & Continue' : 'Continue');
97
- const recorderRef = useRef<VoiceRecorderHandle>(null);
54
+ const resolvedButtonText = buttonText ?? (minDurationMs != null ? 'Save & Continue' : 'Continue');
55
+ const recorderRef = useRef<RecorderHandle>(null);
98
56
  const pendingContinueRef = useRef(false);
99
57
 
100
58
  const [recordingData, setRecordingData] = useState<object | null>(null);
101
59
  const [paused, setPaused] = useState(false);
102
60
  const [pausedDuration, setPausedDuration] = useState(0);
103
61
 
104
- const isTooShort = minDuration != null && pausedDuration < minDuration;
62
+ const isTooShort = minDurationMs != null && pausedDuration < minDurationMs;
105
63
 
106
- const handleSave = (data: any) => {
107
- // Eager upload: POST audio to backend immediately.
108
- // Flag is only set after confirmed success.
109
- // If the POST fails, the flag stays false and the final Upload handles it.
110
- if (eagerUpload && data.data64 && store?._uploadId) {
111
- const filename = generateAudioFilename(name ?? 'recording');
64
+ const handleSave = (recording: any) => {
65
+ // Named after the trial number this trial's row will get, which makes the name unique in the session
66
+ const saved = { ...recording, audioFile: audioFilename(name ?? 'VoiceRecording', data.trials.length + 1) };
67
+ // Uploads the recording now, so the final upload is smaller; if this fails, the final upload sends it
68
+ if (eagerUpload && saved.data64 && store.__uploadId) {
112
69
  post('/data', {
113
- sessionId: store._uploadId,
114
- files: [{ filename, content: data.data64, encoding: 'base64' }],
115
- }).then(() => {
116
- data._audioPreUploaded = true;
117
- data._audioPreUploadedFilename = filename;
118
- }).catch(() => { /* ignore — final Upload handles it */ });
70
+ sessionId: store.__uploadId,
71
+ files: [{ filename: saved.audioFile, content: saved.data64, encoding: 'base64' }],
72
+ })
73
+ .then((response) => {
74
+ if (response.ok) markRecordingUploaded(saved.audioFile, saved.data64);
75
+ })
76
+ .catch(() => {});
119
77
  }
120
78
 
121
- setRecordingData(data);
79
+ setRecordingData(saved);
122
80
  setPaused(false);
123
81
  if (pendingContinueRef.current) {
124
82
  pendingContinueRef.current = false;
125
- next(data);
83
+ next(saved);
126
84
  }
127
85
  };
128
86
 
@@ -145,22 +103,22 @@ function VoiceRecording({
145
103
  <div className={`max-w-prose mx-auto ${className} pt-20 pb-20 px-4 ${animate ? 'animate-fade-in opacity-0' : ''}`}>
146
104
  {content && (
147
105
  <article
148
- className={`prose prose-2xl ${th.prose} text-xl ${th.proseLink} prose-a:underline prose-h1:text-4xl prose-h1:mb-10 prose-h1:font-bold prose-p:mb-4 prose-strong:font-bold ${th.text} leading-relaxed`}
106
+ className={th.article}
149
107
  >
150
108
  {content}
151
109
  </article>
152
110
  )}
153
111
 
154
112
  <div className='pt-6'>
155
- <VoiceRecorder
113
+ <Recorder
156
114
  ref={recorderRef}
157
115
  handleSaveVoiceData={handleSave}
158
116
  handleDiscardVoiceData={() => { setRecordingData(null); setPaused(false); }}
159
- showStop={minDuration == null}
160
- showDiscard={minDuration != null}
117
+ showStop={minDurationMs == null}
118
+ showDiscard={minDurationMs != null}
161
119
  showVisualizer={showVisualizer}
162
- silenceWarningSec={silenceWarningSec}
163
- silenceWarningText={silenceWarningText}
120
+ silenceWarningMs={silenceWarningMs}
121
+ silenceWarningContent={silenceWarningContent}
164
122
  onPause={handlePause}
165
123
  onResume={handleResume}
166
124
  />
@@ -168,31 +126,31 @@ function VoiceRecording({
168
126
 
169
127
  {paused && isTooShort && (
170
128
  <div className={`mt-8 flex items-start space-x-3 p-4 border-2 ${th.buttonBorder} ${th.text} ${animate ? 'animate-fade-in opacity-0' : ''}`}>
171
- <HiExclamationTriangle className='w-6 h-6 text-yellow-500 flex-shrink-0 mt-0.5' />
129
+ <ExclamationTriangleIcon className='w-6 h-6 text-yellow-500 flex-shrink-0 mt-0.5' />
172
130
  <p className='text-sm'>
173
- {shortRecordingWarning ?? 'Your recording seems quite short. Please consider adding more detail to your description.'}
131
+ {shortRecordingContent ?? 'Your recording seems quite short. Please consider adding more detail to your description.'}
174
132
  </p>
175
133
  </div>
176
134
  )}
177
135
 
178
- {/* Continue button (visible when paused, minDuration mode only) */}
179
- {paused && minDuration != null && (
136
+ {/* Continue button (visible when paused, minDurationMs mode only) */}
137
+ {paused && minDurationMs != null && (
180
138
  <div className={`mt-8 flex justify-center ${animate ? 'animate-fade-in opacity-0' : ''}`}>
181
139
  <button
182
140
  onClick={finalize}
183
- className={`${th.buttonBg} cursor-pointer px-8 py-3 border-2 ${th.buttonBorder} font-bold ${th.buttonText} text-lg rounded-xl ${th.buttonShadow} hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-none`}
141
+ className={th.button}
184
142
  >
185
143
  {isTooShort ? shortButtonText : resolvedButtonText}
186
144
  </button>
187
145
  </div>
188
146
  )}
189
147
 
190
- {/* Continue button after recording is stopped (non-minDuration mode) */}
148
+ {/* Continue button after recording is stopped (non-minDurationMs mode) */}
191
149
  {recordingData && !paused && (
192
150
  <div className={`mt-16 flex justify-center ${animate ? 'animate-fade-in opacity-0' : ''}`}>
193
151
  <button
194
152
  onClick={() => next(recordingData)}
195
- className={`${th.buttonBg} cursor-pointer px-8 py-3 border-2 ${th.buttonBorder} font-bold ${th.buttonText} text-lg rounded-xl ${th.buttonShadow} hover:translate-x-[2px] hover:translate-y-[2px] hover:shadow-none`}
153
+ className={th.button}
196
154
  >
197
155
  {resolvedButtonText}
198
156
  </button>
@@ -203,4 +161,42 @@ function VoiceRecording({
203
161
  );
204
162
  }
205
163
 
206
- export default VoiceRecording;
164
+ export default defineComponent({
165
+ name: 'VoiceRecording',
166
+ component: VoiceRecording,
167
+ session: true,
168
+ simulate: async ({ props, simulators, participant }) => {
169
+ // A trial can set respondTTS to undefined to use the base64 simulator instead
170
+ const { respondTTS } = simulators as Partial<typeof simulators>;
171
+ const result = await (respondTTS ?? simulators.respondBase64)({ props, participant });
172
+
173
+ let data64: string;
174
+ if (respondTTS) {
175
+ const text = result.value as string;
176
+ const ttsResult = await textToWebmBase64(text);
177
+ if (!ttsResult) throw new Error('TTS failed. Ensure say/espeak and ffmpeg are installed.');
178
+ data64 = ttsResult;
179
+ } else {
180
+ data64 = result.value as string;
181
+ }
182
+
183
+ // Exact duration via ffprobe, fall back to estimate from file size
184
+ const recordingDurationMs = (await probeAudioDurationMs(data64)) ?? Math.round(data64.length / 4);
185
+ return {
186
+ recorded: {
187
+ type: 'audiorecording',
188
+ data64,
189
+ timestamp: new Date().toISOString(),
190
+ recordingDurationMs,
191
+ },
192
+ participant: result.participant,
193
+ durationMs: recordingDurationMs,
194
+ };
195
+ },
196
+ defaultSimulators: {
197
+ /** Returns text to be spoken via platform TTS. Default: generic test sentence. */
198
+ respondTTS: () => ({ value: 'This is a simulated voice recording for testing purposes.' }),
199
+ /** Returns raw base64-encoded WebM audio directly. Default: dummy 0.5s sine tone. */
200
+ respondBase64: () => ({ value: DUMMY_AUDIO_BASE64 }),
201
+ },
202
+ });
@@ -0,0 +1,20 @@
1
+ // The experiment's server: its routes on the page's own origin, or the simulation's server while simulating
2
+ let backendUrl = '/backend';
3
+
4
+ /** The address of the experiment's server, for components that talk to its routes. */
5
+ export function getBackendUrl() {
6
+ return backendUrl;
7
+ }
8
+
9
+ export function setBackendUrl(url: string) {
10
+ backendUrl = url;
11
+ }
12
+
13
+ /** Sends JSON to one of the server's routes. */
14
+ export function post(endpoint: string, body: object) {
15
+ return fetch(`${backendUrl}${endpoint}`, {
16
+ method: 'POST',
17
+ headers: { 'Content-Type': 'application/json' },
18
+ body: JSON.stringify(body),
19
+ });
20
+ }
@@ -0,0 +1,178 @@
1
+ import { freezeInDevelopment } from './development';
2
+ import type { Store } from './store';
3
+ import type { TimelineContext } from './timeline';
4
+
5
+ export const BLOCK: unique symbol = Symbol('reactive.block');
6
+
7
+ type Condition = (context: TimelineContext) => boolean;
8
+
9
+ /** A block of control flow. */
10
+ export type BlockSpec =
11
+ | { kind: 'if'; cond: Condition; items: readonly unknown[]; else?: readonly unknown[] }
12
+ | { kind: 'while'; cond: Condition; body: readonly unknown[] }
13
+ | { kind: 'updateStore'; update: (context: TimelineContext) => Record<string, any> }
14
+ | { kind: 'marker'; id: string }
15
+ | { kind: 'ifGoto'; cond: Condition; marker: string }
16
+ | { kind: 'fullscreen'; items: readonly unknown[] };
17
+
18
+ export function isBlock(item: unknown): item is { [BLOCK]: BlockSpec } {
19
+ return typeof item === 'object' && item !== null && BLOCK in item;
20
+ }
21
+
22
+ // IfGoto jumps when its condition holds, UnlessGoto when it does not
23
+ type Instruction<Content> =
24
+ | { type: 'ExecuteContent'; content: Content }
25
+ | { type: 'Goto'; marker: string }
26
+ | { type: 'IfGoto'; cond: Condition; marker: string }
27
+ | { type: 'UnlessGoto'; cond: Condition; marker: string }
28
+ | { type: 'UpdateStore'; update: (context: TimelineContext) => Record<string, any> };
29
+
30
+ /** A compiled timeline: instructions over content of type `Content`. */
31
+ export interface Bytecode<Content> {
32
+ instructions: Instruction<Content>[];
33
+ markers: Record<string, number>;
34
+ /** The spans of instructions that run in fullscreen, each from its first to just after its last. */
35
+ fullscreen: [number, number][];
36
+ }
37
+
38
+ // The if-branches an item sits in, from the outside in
39
+ export type BranchPath = readonly { block: number; arm: 'then' | 'else' }[];
40
+
41
+ /**
42
+ * Lowers a timeline to bytecode. Nested lists are flattened and `false`, `null` and `undefined`
43
+ * are skipped; everything that is not a block becomes content through `toContent`.
44
+ */
45
+ export function compileTimeline<Content>(
46
+ timeline: readonly unknown[],
47
+ toContent: (item: unknown, branch: BranchPath) => Content,
48
+ ): Bytecode<Content> {
49
+ const instructions: Instruction<Content>[] = [];
50
+ const markers: Record<string, number> = {};
51
+ const fullscreen: [number, number][] = [];
52
+ const gotoTargets: string[] = [];
53
+ let blockCount = 0;
54
+
55
+ function emit(items: readonly unknown[], branch: BranchPath) {
56
+ for (const item of items) {
57
+ if (item === false || item === null || item === undefined) continue;
58
+ if (Array.isArray(item)) {
59
+ emit(item, branch);
60
+ continue;
61
+ }
62
+ if (!isBlock(item)) {
63
+ instructions.push({ type: 'ExecuteContent', content: toContent(item, branch) });
64
+ continue;
65
+ }
66
+
67
+ const block = item[BLOCK];
68
+ const id = blockCount++;
69
+ switch (block.kind) {
70
+ case 'marker':
71
+ if (`user_${block.id}` in markers) {
72
+ throw new Error(`The marker '${block.id}' is in the timeline twice, so ifGoto could not tell which one to jump to.`);
73
+ }
74
+ markers[`user_${block.id}`] = instructions.length;
75
+ break;
76
+ case 'ifGoto':
77
+ instructions.push({ type: 'IfGoto', cond: block.cond, marker: `user_${block.marker}` });
78
+ gotoTargets.push(block.marker);
79
+ break;
80
+ case 'updateStore':
81
+ instructions.push({ type: 'UpdateStore', update: block.update });
82
+ break;
83
+ case 'if': {
84
+ const end = `if_end_${id}`;
85
+ const elseStart = `if_else_${id}`;
86
+ instructions.push({ type: 'UnlessGoto', cond: block.cond, marker: block.else ? elseStart : end });
87
+ emit(block.items, [...branch, { block: id, arm: 'then' }]);
88
+ if (block.else) {
89
+ instructions.push({ type: 'Goto', marker: end });
90
+ markers[elseStart] = instructions.length;
91
+ emit(block.else, [...branch, { block: id, arm: 'else' }]);
92
+ }
93
+ markers[end] = instructions.length;
94
+ break;
95
+ }
96
+ case 'fullscreen': {
97
+ const start = instructions.length;
98
+ emit(block.items, branch);
99
+ fullscreen.push([start, instructions.length]);
100
+ break;
101
+ }
102
+ case 'while': {
103
+ const start = `while_start_${id}`;
104
+ const end = `while_end_${id}`;
105
+ markers[start] = instructions.length;
106
+ instructions.push({ type: 'UnlessGoto', cond: block.cond, marker: end });
107
+ emit(block.body, branch);
108
+ instructions.push({ type: 'Goto', marker: start });
109
+ markers[end] = instructions.length;
110
+ break;
111
+ }
112
+ }
113
+ }
114
+ }
115
+
116
+ emit(timeline, []);
117
+
118
+ for (const target of gotoTargets) {
119
+ if (!(`user_${target}` in markers)) {
120
+ throw new Error(`ifGoto jumps to the marker '${target}', which is not in the timeline.`);
121
+ }
122
+ }
123
+
124
+ return { instructions, markers, fullscreen };
125
+ }
126
+
127
+ // No timeline runs this many steps of control flow between two trials or slides unless it loops forever
128
+ const MAX_CONTROL_STEPS = 100_000;
129
+
130
+ // What a jump back to the marker repeats, as the timeline was written
131
+ const repeated = (marker: string) =>
132
+ marker.startsWith('user_') ? `the ifGoto back to the marker '${marker.slice('user_'.length)}'` : 'a whileBlock';
133
+
134
+ /**
135
+ * Runs control flow from `fromPointer` on. Returns the pointer of the next content instruction,
136
+ * or the length of the bytecode once the timeline is finished, and the store as the store
137
+ * updates on the way left it.
138
+ */
139
+ export function advanceToNextContent<Content>(
140
+ bytecode: Bytecode<Content>,
141
+ fromPointer: number,
142
+ fromStore: Store,
143
+ contextFor: (store: Store) => TimelineContext,
144
+ ): { pointer: number; store: Store } {
145
+ let pointer = fromPointer;
146
+ let store = fromStore;
147
+ let steps = 0;
148
+ let loop = '';
149
+ while (pointer < bytecode.instructions.length) {
150
+ const instruction = bytecode.instructions[pointer];
151
+ if (instruction.type === 'ExecuteContent') break;
152
+ // It always throws, since a timeline that never reaches its next trial cannot go on
153
+ if (++steps > MAX_CONTROL_STEPS) {
154
+ throw new Error(
155
+ `The timeline repeats ${loop} without reaching anything to show, so it would never end. Its condition has to change, or a trial or slide has to run inside it.`,
156
+ );
157
+ }
158
+ const from = pointer;
159
+
160
+ if (instruction.type === 'Goto') {
161
+ pointer = bytecode.markers[instruction.marker];
162
+ } else if (instruction.type === 'IfGoto') {
163
+ pointer = instruction.cond(contextFor(store)) ? bytecode.markers[instruction.marker] : pointer + 1;
164
+ } else if (instruction.type === 'UnlessGoto') {
165
+ pointer = instruction.cond(contextFor(store)) ? pointer + 1 : bytecode.markers[instruction.marker];
166
+ } else {
167
+ const updates = instruction.update(contextFor(store));
168
+ if (typeof updates === 'object' && updates !== null) {
169
+ store = freezeInDevelopment({ ...store, ...updates });
170
+ } else {
171
+ console.warn('A store update did not return an object, so the store is unchanged.');
172
+ }
173
+ pointer++;
174
+ }
175
+ if (pointer <= from && 'marker' in instruction) loop = repeated(instruction.marker);
176
+ }
177
+ return { pointer, store };
178
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The prefixes of the CSV columns the library writes: a trial's own fields, its metadata, response
3
+ * fields that would otherwise start with one of these, URL params that nothing declares, the
4
+ * Upload's `sessionData`, and a CanvasBlock's metadata next to that of its slides.
5
+ */
6
+ export const columnPrefixes = {
7
+ trial: 'trial_',
8
+ meta: 'meta_',
9
+ response: 'response_',
10
+ url: 'url_',
11
+ session: 'session_',
12
+ slideblockMeta: 'slideblock_meta_',
13
+ } as const;
14
+
15
+ /** The session CSV's columns that hold the session itself, before its params and trials. */
16
+ export const sessionColumns = ['sessionId', 'userAgent', 'buildSeed'] as const;
17
+
18
+ const reserved: readonly string[] = Object.values(columnPrefixes);
19
+
20
+ /** The prefixes of the session CSV's columns that are neither params nor trials. */
21
+ export const sessionPrefixes = [columnPrefixes.url, columnPrefixes.session] as const;
22
+
23
+ /**
24
+ * The CSV column for a field of a response. A field whose name starts with one of the prefixes gets
25
+ * `response_` in front, so that it can never take the place of a column the library writes.
26
+ */
27
+ export function responseColumn(field: string): string {
28
+ return reserved.some((prefix) => field.startsWith(prefix)) ? columnPrefixes.response + field : field;
29
+ }
30
+
31
+ /** Whether a param, which is a session CSV column of its own name, would take a column the library writes. */
32
+ export function isReservedParamName(name: string): boolean {
33
+ return (
34
+ (sessionColumns as readonly string[]).includes(name) ||
35
+ sessionPrefixes.some((prefix) => name.startsWith(prefix))
36
+ );
37
+ }
38
+
39
+ /** Whether a trial, whose session CSV columns are `<name>_<field>`, would take columns the library writes. */
40
+ export function isReservedTrialName(name: string): boolean {
41
+ return sessionPrefixes.some((prefix) => `${name}_`.startsWith(prefix));
42
+ }
43
+
44
+ type SessionPrefix = (typeof sessionPrefixes)[number];
45
+
46
+ /** The param names `isReservedParamName` rejects, for the types. */
47
+ export type ReservedParamName = (typeof sessionColumns)[number] | `${SessionPrefix}${string}`;
48
+
49
+ /** The trial names `isReservedTrialName` rejects, for the types: a prefix with or without its `_`, and names that start with one. */
50
+ export type ReservedTrialName = `${SessionPrefix}${string}` | (SessionPrefix extends `${infer Base}_` ? Base : never);