@slopit/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aaron Steven White
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,600 @@
1
+ # @slopit/core
2
+
3
+ Core type definitions, schemas, and utilities for the slopit behavioral capture toolkit.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @slopit/core
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import {
15
+ generateSessionId,
16
+ hashText,
17
+ validateSession,
18
+ captureEnvironment,
19
+ } from "@slopit/core";
20
+
21
+ // generate unique identifiers
22
+ const sessionId = generateSessionId();
23
+
24
+ // hash sensitive text
25
+ const hash = await hashText("user input text");
26
+
27
+ // capture browser environment
28
+ const env = captureEnvironment();
29
+
30
+ // validate session data
31
+ const result = validateSession(sessionData);
32
+ if (!result.success) {
33
+ console.error("Validation errors:", result.errors);
34
+ }
35
+ ```
36
+
37
+ ## Type Definitions
38
+
39
+ ### Session Types
40
+
41
+ #### SlopitSession
42
+
43
+ The top-level container for all data from a research session.
44
+
45
+ ```typescript
46
+ interface SlopitSession {
47
+ schemaVersion: string;
48
+ sessionId: string;
49
+ participantId?: string;
50
+ studyId?: string;
51
+ platform: PlatformInfo;
52
+ environment: EnvironmentInfo;
53
+ timing: SessionTiming;
54
+ trials: SlopitTrial[];
55
+ globalEvents: GlobalEvents;
56
+ }
57
+ ```
58
+
59
+ #### SlopitTrial
60
+
61
+ Data for a single trial within a session.
62
+
63
+ ```typescript
64
+ interface SlopitTrial {
65
+ trialId: string;
66
+ trialIndex: number;
67
+ trialType: string;
68
+ startTime: number;
69
+ endTime: number;
70
+ rt: number;
71
+ stimulus?: StimulusInfo;
72
+ response?: ResponseInfo;
73
+ behavioral?: BehavioralData;
74
+ captureFlags?: CaptureFlag[];
75
+ platformData?: Record<string, unknown>;
76
+ }
77
+ ```
78
+
79
+ #### PlatformInfo
80
+
81
+ Information about the experiment platform.
82
+
83
+ ```typescript
84
+ interface PlatformInfo {
85
+ name: string; // e.g., "jspsych"
86
+ version: string; // platform version
87
+ adapterVersion: string; // slopit adapter version
88
+ }
89
+ ```
90
+
91
+ #### EnvironmentInfo
92
+
93
+ Browser and system environment data.
94
+
95
+ ```typescript
96
+ interface EnvironmentInfo {
97
+ userAgent: string;
98
+ language: string;
99
+ platform: string;
100
+ screenWidth: number;
101
+ screenHeight: number;
102
+ windowWidth: number;
103
+ windowHeight: number;
104
+ devicePixelRatio: number;
105
+ timezone: string;
106
+ timezoneOffset: number;
107
+ }
108
+ ```
109
+
110
+ #### SessionTiming
111
+
112
+ Timing information for the session.
113
+
114
+ ```typescript
115
+ interface SessionTiming {
116
+ startTime: number; // Unix timestamp in milliseconds
117
+ endTime: number; // Unix timestamp in milliseconds
118
+ duration: number; // Total duration in milliseconds
119
+ }
120
+ ```
121
+
122
+ ### Behavioral Event Types
123
+
124
+ #### KeystrokeEvent
125
+
126
+ A single keystroke event.
127
+
128
+ | Field | Type | Description |
129
+ |-------|------|-------------|
130
+ | time | number | Time since trial start in milliseconds |
131
+ | key | string | Key value from KeyboardEvent.key (e.g., "a", "Enter", "Backspace") |
132
+ | code | string | Physical key code from KeyboardEvent.code (e.g., "KeyA", "Enter") |
133
+ | event | "keydown" \| "keyup" | Event type |
134
+ | textLength | number? | Current text length at this moment |
135
+ | modifiers | ModifierState? | Modifier key states |
136
+
137
+ #### ModifierState
138
+
139
+ Modifier key states at time of keystroke.
140
+
141
+ ```typescript
142
+ interface ModifierState {
143
+ shift: boolean;
144
+ ctrl: boolean;
145
+ alt: boolean;
146
+ meta: boolean;
147
+ }
148
+ ```
149
+
150
+ #### FocusEvent
151
+
152
+ A focus or visibility change event.
153
+
154
+ | Field | Type | Description |
155
+ |-------|------|-------------|
156
+ | time | number | Time since trial start in milliseconds |
157
+ | event | "focus" \| "blur" \| "visibilitychange" | Event type |
158
+ | visibility | "visible" \| "hidden"? | For visibilitychange events, the new state |
159
+ | blurDuration | number? | For blur events, duration until refocus (filled retrospectively) |
160
+
161
+ #### PasteEvent
162
+
163
+ A paste event.
164
+
165
+ | Field | Type | Description |
166
+ |-------|------|-------------|
167
+ | time | number | Time since trial start in milliseconds |
168
+ | textLength | number | Length of pasted text in characters |
169
+ | textPreview | string? | First N characters of pasted text (default N=100) |
170
+ | textHash | string? | SHA-256 hash of full pasted text |
171
+ | precedingKeystrokes | number | Number of keystrokes in preceding 2 seconds |
172
+ | blocked | boolean | Whether paste was blocked by configuration |
173
+
174
+ #### MouseEvent
175
+
176
+ A mouse event.
177
+
178
+ | Field | Type | Description |
179
+ |-------|------|-------------|
180
+ | time | number | Time since trial start in milliseconds |
181
+ | event | "mousemove" \| "mousedown" \| "mouseup" \| "click" | Event type |
182
+ | x | number | X coordinate relative to viewport |
183
+ | y | number | Y coordinate relative to viewport |
184
+ | velocity | number? | Velocity in pixels per millisecond (for mousemove) |
185
+ | distance | number? | Distance traveled since last event in pixels |
186
+ | deltaTime | number? | Time since last mouse event in milliseconds |
187
+ | isDragging | boolean? | Whether this event is part of a drag operation |
188
+
189
+ #### ScrollEvent
190
+
191
+ A scroll event.
192
+
193
+ | Field | Type | Description |
194
+ |-------|------|-------------|
195
+ | time | number | Time since trial start in milliseconds |
196
+ | direction | "up" \| "down" | Direction of scroll |
197
+ | deltaY | number | Scroll delta in pixels |
198
+ | scrollTop | number | Current scroll position from top |
199
+ | scrollHeight | number | Scrollable element height |
200
+ | clientHeight | number | Viewport height |
201
+ | velocity | number? | Velocity in pixels per millisecond |
202
+
203
+ #### ClipboardCopyEvent
204
+
205
+ A clipboard copy or cut event.
206
+
207
+ | Field | Type | Description |
208
+ |-------|------|-------------|
209
+ | time | number | Time since trial start in milliseconds |
210
+ | event | "copy" \| "cut" | Event type |
211
+ | textLength | number | Length of selected text |
212
+ | textPreview | string? | First N characters of copied text |
213
+ | textHash | string? | SHA-256 hash of copied text |
214
+ | selectionStart | number? | Selection start index in input element |
215
+ | selectionEnd | number? | Selection end index in input element |
216
+
217
+ #### InputDurationEvent
218
+
219
+ An input duration event tracking focus sessions.
220
+
221
+ | Field | Type | Description |
222
+ |-------|------|-------------|
223
+ | focusTime | number | Time since trial start when focus was gained |
224
+ | blurTime | number | Time since trial start when focus was lost |
225
+ | duration | number | Duration focused in milliseconds |
226
+ | elementId | string? | Element identifier (id or name attribute) |
227
+ | keystrokesDuringFocus | number? | Number of keystrokes during focus |
228
+ | pastesDuringFocus | number? | Number of paste events during focus |
229
+
230
+ ### Behavioral Metrics Types
231
+
232
+ #### BehavioralData
233
+
234
+ Container for all behavioral capture data.
235
+
236
+ ```typescript
237
+ interface BehavioralData {
238
+ keystrokes?: KeystrokeEvent[];
239
+ focus?: FocusEvent[];
240
+ paste?: PasteEvent[];
241
+ mouse?: MouseEvent[];
242
+ scroll?: ScrollEvent[];
243
+ clipboard?: ClipboardCopyEvent[];
244
+ inputDuration?: InputDurationEvent[];
245
+ metrics?: BehavioralMetrics;
246
+ }
247
+ ```
248
+
249
+ #### BehavioralMetrics
250
+
251
+ Computed metrics from behavioral data.
252
+
253
+ ```typescript
254
+ interface BehavioralMetrics {
255
+ keystroke?: KeystrokeMetrics;
256
+ focus?: FocusMetrics;
257
+ timing?: TimingMetrics;
258
+ mouse?: MouseMetrics;
259
+ scroll?: ScrollMetrics;
260
+ inputDuration?: InputDurationMetrics;
261
+ }
262
+ ```
263
+
264
+ #### KeystrokeMetrics
265
+
266
+ Metrics computed from keystroke data.
267
+
268
+ | Field | Type | Description |
269
+ |-------|------|-------------|
270
+ | totalKeystrokes | number | Total number of keystrokes |
271
+ | printableKeystrokes | number | Number of printable character keystrokes |
272
+ | deletions | number | Number of deletion keystrokes (Backspace, Delete) |
273
+ | meanIKI | number | Mean inter-keystroke interval in milliseconds |
274
+ | stdIKI | number | Standard deviation of IKI |
275
+ | medianIKI | number | Median IKI |
276
+ | pauseCount | number | Number of pauses (IKI > threshold) |
277
+ | productProcessRatio | number | Ratio of final characters to total keystrokes |
278
+
279
+ #### FocusMetrics
280
+
281
+ Metrics computed from focus data.
282
+
283
+ | Field | Type | Description |
284
+ |-------|------|-------------|
285
+ | blurCount | number | Number of blur events |
286
+ | totalBlurDuration | number | Total time in milliseconds with window blurred |
287
+ | hiddenCount | number | Number of visibility hidden events |
288
+ | totalHiddenDuration | number | Total time in milliseconds with document hidden |
289
+
290
+ #### TimingMetrics
291
+
292
+ Timing metrics.
293
+
294
+ | Field | Type | Description |
295
+ |-------|------|-------------|
296
+ | firstKeystrokeLatency | number? | Time from trial start to first keystroke |
297
+ | totalResponseTime | number | Time from trial start to response submission |
298
+ | charactersPerMinute | number? | Characters per minute (excluding deletions) |
299
+
300
+ #### MouseMetrics
301
+
302
+ Metrics computed from mouse data.
303
+
304
+ | Field | Type | Description |
305
+ |-------|------|-------------|
306
+ | totalEvents | number | Total number of mouse events |
307
+ | clickCount | number | Number of click events |
308
+ | meanVelocity | number | Mean mouse velocity in pixels per millisecond |
309
+ | totalDistance | number | Total distance traveled by cursor in pixels |
310
+ | totalIdleTime | number | Total idle time with no mouse movement |
311
+ | idlePeriodCount | number | Number of idle periods exceeding threshold |
312
+
313
+ #### ScrollMetrics
314
+
315
+ Metrics computed from scroll data.
316
+
317
+ | Field | Type | Description |
318
+ |-------|------|-------------|
319
+ | totalScrollEvents | number | Total number of scroll events |
320
+ | totalScrollDistance | number | Total scroll distance in pixels |
321
+ | directionChanges | number | Number of scroll direction changes |
322
+ | meanScrollVelocity | number | Mean scroll velocity |
323
+ | upDownRatio | number | Time spent scrolling up vs down ratio |
324
+
325
+ #### InputDurationMetrics
326
+
327
+ Metrics computed from input duration data.
328
+
329
+ | Field | Type | Description |
330
+ |-------|------|-------------|
331
+ | totalFocusDuration | number | Total focus duration across all inputs |
332
+ | meanFocusDuration | number | Mean focus duration per input session |
333
+ | focusSessionCount | number | Number of focus sessions |
334
+ | maxFocusDuration | number | Longest single focus session |
335
+
336
+ ### Flag Types
337
+
338
+ #### CaptureFlag
339
+
340
+ Flag generated during data capture.
341
+
342
+ ```typescript
343
+ interface CaptureFlag {
344
+ type: string; // Flag type identifier
345
+ severity: Severity; // "info" | "low" | "medium" | "high"
346
+ message: string; // Human-readable description
347
+ timestamp: number; // Timestamp when flag was generated
348
+ details?: Record<string, unknown>; // Additional details
349
+ }
350
+ ```
351
+
352
+ #### AnalysisFlag
353
+
354
+ Flag generated during server-side analysis.
355
+
356
+ ```typescript
357
+ interface AnalysisFlag {
358
+ type: string; // Flag type identifier
359
+ analyzer: string; // Analyzer that generated this flag
360
+ severity: Severity; // "info" | "low" | "medium" | "high"
361
+ message: string; // Human-readable description
362
+ confidence?: number; // Confidence score (0.0 to 1.0)
363
+ evidence?: Record<string, unknown>;// Evidence supporting this flag
364
+ trialIds?: string[]; // Related trial IDs if trial-specific
365
+ }
366
+ ```
367
+
368
+ #### Severity
369
+
370
+ Severity level for flags.
371
+
372
+ ```typescript
373
+ type Severity = "info" | "low" | "medium" | "high";
374
+ ```
375
+
376
+ ## Validation
377
+
378
+ ### validateSession
379
+
380
+ Validates a session object against the schema.
381
+
382
+ ```typescript
383
+ import { validateSession } from "@slopit/core";
384
+
385
+ const result = validateSession(sessionData);
386
+
387
+ if (result.success) {
388
+ console.log("Session is valid");
389
+ } else {
390
+ console.error("Validation errors:", result.errors);
391
+ }
392
+ ```
393
+
394
+ ### isValidSession
395
+
396
+ Type guard for checking session validity.
397
+
398
+ ```typescript
399
+ import { isValidSession } from "@slopit/core";
400
+
401
+ if (isValidSession(data)) {
402
+ // data is typed as SlopitSession
403
+ console.log(data.sessionId);
404
+ }
405
+ ```
406
+
407
+ ### Zod Schemas
408
+
409
+ The package exports Zod schemas for all types.
410
+
411
+ ```typescript
412
+ import {
413
+ SlopitSessionSchema,
414
+ SlopitTrialSchema,
415
+ BehavioralDataSchema,
416
+ KeystrokeEventSchema,
417
+ FocusEventSchema,
418
+ PasteEventSchema,
419
+ CaptureFlagSchema,
420
+ AnalysisFlagSchema,
421
+ } from "@slopit/core";
422
+
423
+ // parse and validate data
424
+ const keystroke = KeystrokeEventSchema.parse(rawData);
425
+
426
+ // safe parse with error handling
427
+ const result = SlopitTrialSchema.safeParse(trialData);
428
+ if (!result.success) {
429
+ console.error(result.error.issues);
430
+ }
431
+ ```
432
+
433
+ ## Utility Functions
434
+
435
+ ### ID Generation
436
+
437
+ #### generateSessionId
438
+
439
+ Generates a unique session identifier.
440
+
441
+ ```typescript
442
+ import { generateSessionId } from "@slopit/core";
443
+
444
+ const id = generateSessionId();
445
+ // Returns: "session_1706123456789_a1b2c3d4"
446
+ ```
447
+
448
+ #### generateTrialId
449
+
450
+ Generates a unique trial identifier.
451
+
452
+ ```typescript
453
+ import { generateTrialId } from "@slopit/core";
454
+
455
+ const id = generateTrialId();
456
+ // Returns: "trial_1706123456789_e5f6g7h8"
457
+ ```
458
+
459
+ ### Hashing
460
+
461
+ #### hashText
462
+
463
+ Computes SHA-256 hash of text using Web Crypto API.
464
+
465
+ ```typescript
466
+ import { hashText } from "@slopit/core";
467
+
468
+ const hash = await hashText("Hello, world!");
469
+ // Returns: "315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3"
470
+ ```
471
+
472
+ #### simpleHash
473
+
474
+ Synchronous simple hash for non-cryptographic purposes.
475
+
476
+ ```typescript
477
+ import { simpleHash } from "@slopit/core";
478
+
479
+ const hash = simpleHash("Hello, world!");
480
+ // Returns: "0a1b2c3d" (8-character hex string)
481
+ ```
482
+
483
+ ### Timing
484
+
485
+ #### now
486
+
487
+ Returns current Unix timestamp in milliseconds.
488
+
489
+ ```typescript
490
+ import { now } from "@slopit/core";
491
+
492
+ const timestamp = now();
493
+ // Returns: 1706123456789
494
+ ```
495
+
496
+ #### highResTime
497
+
498
+ Returns high-resolution timestamp for performance measurement.
499
+
500
+ ```typescript
501
+ import { highResTime } from "@slopit/core";
502
+
503
+ const start = highResTime();
504
+ // ... do work
505
+ const elapsed = highResTime() - start;
506
+ ```
507
+
508
+ #### duration
509
+
510
+ Calculates duration between two timestamps.
511
+
512
+ ```typescript
513
+ import { duration } from "@slopit/core";
514
+
515
+ const elapsed = duration(startTime); // from startTime to now
516
+ const elapsed = duration(startTime, endTime); // from startTime to endTime
517
+ ```
518
+
519
+ #### formatDuration
520
+
521
+ Formats a duration in human-readable format.
522
+
523
+ ```typescript
524
+ import { formatDuration } from "@slopit/core";
525
+
526
+ formatDuration(65000); // "1m 5s"
527
+ formatDuration(3661000); // "1h 1m 1s"
528
+ formatDuration(500); // "500ms"
529
+ ```
530
+
531
+ #### toTimestamp / fromTimestamp
532
+
533
+ Converts between Date objects and Unix timestamps.
534
+
535
+ ```typescript
536
+ import { toTimestamp, fromTimestamp } from "@slopit/core";
537
+
538
+ const timestamp = toTimestamp(new Date());
539
+ const date = fromTimestamp(1706123456789);
540
+ ```
541
+
542
+ ### Environment
543
+
544
+ #### captureEnvironment
545
+
546
+ Captures browser and system environment information.
547
+
548
+ ```typescript
549
+ import { captureEnvironment } from "@slopit/core";
550
+
551
+ const env = captureEnvironment();
552
+ /*
553
+ {
554
+ userAgent: "Mozilla/5.0 ...",
555
+ language: "en-US",
556
+ platform: "MacIntel",
557
+ screenWidth: 2560,
558
+ screenHeight: 1440,
559
+ windowWidth: 1920,
560
+ windowHeight: 1080,
561
+ devicePixelRatio: 2,
562
+ timezone: "America/New_York",
563
+ timezoneOffset: -300
564
+ }
565
+ */
566
+ ```
567
+
568
+ ## Constants
569
+
570
+ ```typescript
571
+ import {
572
+ SCHEMA_VERSION,
573
+ DEFAULT_CONFIG,
574
+ SEVERITY_LEVELS,
575
+ KNOWN_PLATFORMS,
576
+ } from "@slopit/core";
577
+
578
+ console.log(SCHEMA_VERSION); // "1.0.0"
579
+ console.log(SEVERITY_LEVELS); // ["info", "low", "medium", "high"]
580
+ console.log(KNOWN_PLATFORMS); // ["jspsych", "pavlovia", "gorilla", ...]
581
+ ```
582
+
583
+ ## Package Exports
584
+
585
+ The package provides multiple entry points:
586
+
587
+ ```typescript
588
+ // main entry point with all exports
589
+ import { ... } from "@slopit/core";
590
+
591
+ // schemas only
592
+ import { ... } from "@slopit/core/schemas";
593
+
594
+ // validation only
595
+ import { ... } from "@slopit/core/validation";
596
+ ```
597
+
598
+ ## License
599
+
600
+ MIT