psytools 0.3.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 +21 -0
- package/README.md +189 -0
- package/dist/cjs/assessment.d.ts +58 -0
- package/dist/cjs/assessment.js +233 -0
- package/dist/cjs/errors.d.ts +5 -0
- package/dist/cjs/errors.js +13 -0
- package/dist/cjs/evaluation.d.ts +10 -0
- package/dist/cjs/evaluation.js +102 -0
- package/dist/cjs/i18n.d.ts +10 -0
- package/dist/cjs/i18n.js +35 -0
- package/dist/cjs/index.d.ts +8 -0
- package/dist/cjs/index.js +23 -0
- package/dist/cjs/inventories/common.d.ts +8 -0
- package/dist/cjs/inventories/common.js +47 -0
- package/dist/cjs/inventories/dass21.d.ts +11 -0
- package/dist/cjs/inventories/dass21.js +288 -0
- package/dist/cjs/inventories/gad7.d.ts +10 -0
- package/dist/cjs/inventories/gad7.js +121 -0
- package/dist/cjs/inventories/index.d.ts +15 -0
- package/dist/cjs/inventories/index.js +33 -0
- package/dist/cjs/inventories/phq9.d.ts +11 -0
- package/dist/cjs/inventories/phq9.js +156 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/response.d.ts +77 -0
- package/dist/cjs/response.js +231 -0
- package/dist/cjs/types.d.ts +219 -0
- package/dist/cjs/types.js +10 -0
- package/dist/esm/assessment.d.ts +58 -0
- package/dist/esm/assessment.js +228 -0
- package/dist/esm/errors.d.ts +5 -0
- package/dist/esm/errors.js +9 -0
- package/dist/esm/evaluation.d.ts +10 -0
- package/dist/esm/evaluation.js +99 -0
- package/dist/esm/i18n.d.ts +10 -0
- package/dist/esm/i18n.js +31 -0
- package/dist/esm/index.d.ts +8 -0
- package/dist/esm/index.js +6 -0
- package/dist/esm/inventories/common.d.ts +8 -0
- package/dist/esm/inventories/common.js +44 -0
- package/dist/esm/inventories/dass21.d.ts +11 -0
- package/dist/esm/inventories/dass21.js +285 -0
- package/dist/esm/inventories/gad7.d.ts +10 -0
- package/dist/esm/inventories/gad7.js +118 -0
- package/dist/esm/inventories/index.d.ts +15 -0
- package/dist/esm/inventories/index.js +25 -0
- package/dist/esm/inventories/phq9.d.ts +11 -0
- package/dist/esm/inventories/phq9.js +153 -0
- package/dist/esm/response.d.ts +77 -0
- package/dist/esm/response.js +227 -0
- package/dist/esm/types.d.ts +219 -0
- package/dist/esm/types.js +9 -0
- package/package.json +64 -0
- package/schema/assessment-definition.schema.json +129 -0
- package/src/assessment.ts +266 -0
- package/src/errors.ts +10 -0
- package/src/evaluation.ts +140 -0
- package/src/i18n.ts +40 -0
- package/src/index.ts +43 -0
- package/src/inventories/common.ts +47 -0
- package/src/inventories/dass21.ts +291 -0
- package/src/inventories/gad7.ts +121 -0
- package/src/inventories/index.ts +31 -0
- package/src/inventories/phq9.ts +156 -0
- package/src/response.ts +263 -0
- package/src/types.ts +250 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Samed Kahyaoglu
|
|
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,189 @@
|
|
|
1
|
+
# psytools
|
|
2
|
+
|
|
3
|
+
Zero-dependency TypeScript toolkit for psychological assessments: a serializable data model, response collection with validation, declarative scoring, and predefined inventories (PHQ-9, GAD-7, DASS-21) in English, Turkish, and German.
|
|
4
|
+
|
|
5
|
+
Built for therapy apps and research tools where therapists or researchers use standardized tests or define their own, collect responses from clients or study participants, and track results over time.
|
|
6
|
+
|
|
7
|
+
- **Zero runtime dependencies** — works in Node (>= 18), browsers, and edge runtimes; ships ESM and CommonJS builds with full type declarations.
|
|
8
|
+
- **Everything is plain JSON** — assessments and responses `stringify()`/`parse()` losslessly, so definitions can live in a database and travel between backend and frontend.
|
|
9
|
+
- **Declarative scoring** — severity bands, subscales, and clinical flags are data, not code, so they survive serialization. Custom evaluator functions are supported when you need more.
|
|
10
|
+
- **Multilingual by design** — every text is a `{ locale: string }` record; `localize()` produces a flat, render-ready view for any locale with sensible fallbacks.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npm install psytools
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Quick start
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { loadInventory } from "psytools";
|
|
22
|
+
|
|
23
|
+
const phq9 = loadInventory("phq9");
|
|
24
|
+
|
|
25
|
+
// 1. Render — get a flat, single-locale view for your UI.
|
|
26
|
+
const view = phq9.localize("tr");
|
|
27
|
+
// { id, locale, title, instructions, questions: [{ id, index, text, options: [{ value, label }] }] }
|
|
28
|
+
|
|
29
|
+
// 2. Collect answers — one by one or all at once.
|
|
30
|
+
const response = phq9.createResponse({ respondentId: "client-42" });
|
|
31
|
+
response.status; // "empty"
|
|
32
|
+
response.answer("phq9-1", 2); // one by one, validated immediately
|
|
33
|
+
response.status; // "in-progress"
|
|
34
|
+
response.answerAll([2, 1, 3, 1, 0, 1, 2, 0, 0]); // or all at once (question order)
|
|
35
|
+
response.status; // "complete"
|
|
36
|
+
response.submit(); // validates, freezes, timestamps -> "submitted"
|
|
37
|
+
|
|
38
|
+
// 3. Evaluate.
|
|
39
|
+
const result = phq9.evaluate(response);
|
|
40
|
+
// {
|
|
41
|
+
// kind: "scale", score: 10, min: 0, max: 27,
|
|
42
|
+
// band: { id: "moderate", label: { en: "Moderate depression", tr: ..., de: ... } },
|
|
43
|
+
// flags: [] // phq9-9 > 0 would raise the "suicidality" flag here
|
|
44
|
+
// }
|
|
45
|
+
|
|
46
|
+
// Responses walk a simple state machine — empty -> in-progress -> complete
|
|
47
|
+
// -> submitted — exposed as `response.status`. `evaluate()` refuses
|
|
48
|
+
// responses that are not complete/submitted; score partial data explicitly:
|
|
49
|
+
phq9.evaluate(inProgressResponse, undefined, { allowIncomplete: true });
|
|
50
|
+
|
|
51
|
+
// 4. Persist — both sides are plain JSON.
|
|
52
|
+
db.save(response.stringify()); // response -> DB
|
|
53
|
+
db.save(phq9.stringify()); // definition -> DB
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Restore later and continue where you left off:
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { Assessment, AssessmentResponse } from "psytools";
|
|
60
|
+
|
|
61
|
+
const assessment = Assessment.parse(jsonFromDb); // validated on parse
|
|
62
|
+
const response = AssessmentResponse.parse(assessment, rowFromDb); // answers re-validated
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Predefined inventories
|
|
66
|
+
|
|
67
|
+
| Id | Instrument | Items | Scoring | Locales |
|
|
68
|
+
| --- | --- | --- | --- | --- |
|
|
69
|
+
| `phq9` | Patient Health Questionnaire-9 (depression) | 9 | Sum 0–27, 5 severity bands, item-9 suicidality flag | en, tr, de |
|
|
70
|
+
| `gad7` | Generalized Anxiety Disorder-7 | 7 | Sum 0–21, 4 severity bands | en, tr, de |
|
|
71
|
+
| `dass21` | Depression Anxiety Stress Scales (short form) | 21 | 3 subscales × 7 items, sums doubled, banded per subscale | en, tr, de |
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import { loadInventory, inventories, dass21 } from "psytools";
|
|
75
|
+
|
|
76
|
+
loadInventory("dass21"); // ready-to-use Assessment instance
|
|
77
|
+
inventories; // { phq9, gad7, dass21 } raw definitions
|
|
78
|
+
dass21; // a plain AssessmentDefinition you can clone and adapt
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
DASS-21 evaluates to a multi-scale result:
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
const result = assessment.evaluate(response);
|
|
85
|
+
// { kind: "multiscale", scales: [
|
|
86
|
+
// { id: "depression", score: 14, min: 0, max: 42, band: { id: "moderate", ... }, label: {...} },
|
|
87
|
+
// { id: "anxiety", ... }, { id: "stress", ... }
|
|
88
|
+
// ], flags: [] }
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Defining your own assessment
|
|
92
|
+
|
|
93
|
+
An assessment is one plain object — questions, an enumerated option scale, and optional declarative scoring:
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
import { Assessment, type AssessmentDefinition } from "psytools";
|
|
97
|
+
|
|
98
|
+
const definition: AssessmentDefinition = {
|
|
99
|
+
id: "my-clinic/sleep-check",
|
|
100
|
+
version: "1.0.0",
|
|
101
|
+
title: { en: "Sleep Check", tr: "Uyku Kontrolü" },
|
|
102
|
+
instructions: { en: "Over the last week...", tr: "Geçen hafta boyunca..." },
|
|
103
|
+
defaultLocale: "en",
|
|
104
|
+
options: [
|
|
105
|
+
{ value: 0, label: { en: "Never", tr: "Hiçbir zaman" } },
|
|
106
|
+
{ value: 1, label: { en: "Sometimes", tr: "Bazen" } },
|
|
107
|
+
{ value: 2, label: { en: "Often", tr: "Sık sık" } },
|
|
108
|
+
],
|
|
109
|
+
questions: [
|
|
110
|
+
{ id: "s1", text: { en: "I had trouble falling asleep", tr: "Uykuya dalmakta zorlandım" } },
|
|
111
|
+
{ id: "s2", text: { en: "I woke up rested", tr: "Dinlenmiş uyandım" }, reverseScored: true },
|
|
112
|
+
{ id: "s3", text: { en: "Anything else? (optional)", tr: "Başka bir şey? (isteğe bağlı)" }, optional: true },
|
|
113
|
+
],
|
|
114
|
+
scoring: {
|
|
115
|
+
kind: "sum",
|
|
116
|
+
bands: [
|
|
117
|
+
{ id: "ok", min: 0, max: 2, label: { en: "No concern", tr: "Sorun yok" } },
|
|
118
|
+
{ id: "follow-up", min: 3, max: 6, label: { en: "Follow up", tr: "Takip edilmeli" } },
|
|
119
|
+
],
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const assessment = new Assessment(definition); // throws PsytoolsError on malformed definitions
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Questions may also carry their own `options` to override the default scale, and `validateDefinition(input)` checks user-created definitions without throwing (returns `{ valid, issues }`) — useful before persisting a therapist-authored test.
|
|
127
|
+
|
|
128
|
+
Non-JavaScript backends can validate stored definitions against the published [JSON Schema](schema/assessment-definition.schema.json) (shipped in the npm package under `schema/`).
|
|
129
|
+
|
|
130
|
+
## Custom evaluation
|
|
131
|
+
|
|
132
|
+
Declarative scoring is optional. Pass an evaluator for anything beyond sums and subscales — it can return a single scale, multiple scales, a category, or arbitrary data:
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
import type { Evaluator } from "psytools";
|
|
136
|
+
|
|
137
|
+
const attachmentStyle: Evaluator = (definition, answers) => {
|
|
138
|
+
const avoidance = answers["a1"]! + answers["a2"]!;
|
|
139
|
+
const anxiety = answers["b1"]! + answers["b2"]!;
|
|
140
|
+
return {
|
|
141
|
+
kind: "categorical",
|
|
142
|
+
category: avoidance > 3 ? (anxiety > 3 ? "fearful" : "dismissive") : anxiety > 3 ? "preoccupied" : "secure",
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
assessment.evaluate(response, attachmentStyle);
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
Result shapes: `scale` (single score + band + flags), `multiscale` (named subscales), `categorical`, and `custom` (escape hatch).
|
|
150
|
+
|
|
151
|
+
## Tracking progress over time
|
|
152
|
+
|
|
153
|
+
Responses carry `respondentId`, `startedAt`/`submittedAt` timestamps, the assessment id/version, and free-form `meta` — store the serialized responses and evaluate them in bulk:
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
const history = rows
|
|
157
|
+
.map((row) => AssessmentResponse.parse(phq9, row))
|
|
158
|
+
.map((r) => ({ at: r.submittedAt, score: phq9.evaluate(r).score }));
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## API overview
|
|
162
|
+
|
|
163
|
+
| Export | Purpose |
|
|
164
|
+
| --- | --- |
|
|
165
|
+
| `Assessment` | Wraps a definition: validation, `localize()`, `createResponse()`, `evaluate()`, `stringify()`/`parse()` |
|
|
166
|
+
| `AssessmentResponse` | `answer()`, `answerAll()`, `clearAnswer()`, `status`, `progress()`, `validate()`, `submit()`, `stringify()`/`parse()` |
|
|
167
|
+
| `evaluate(definition, answers, evaluator?)` | Standalone scoring (also available as `Assessment#evaluate`) |
|
|
168
|
+
| `validateDefinition(input)` | Non-throwing structural validation of definitions |
|
|
169
|
+
| `loadInventory(id)` / `inventories` / `phq9`, `gad7`, `dass21` | Predefined instruments |
|
|
170
|
+
| `localize(text, locale, fallback?)` / `collectLocales(texts)` | Locale helpers |
|
|
171
|
+
| `PsytoolsError` | All errors carry a stable `code` (e.g. `invalid_value`, `already_submitted`) |
|
|
172
|
+
|
|
173
|
+
## Development
|
|
174
|
+
|
|
175
|
+
```sh
|
|
176
|
+
npm install
|
|
177
|
+
npm test # node:test on TypeScript sources (no test framework needed)
|
|
178
|
+
npm run build # ESM + CJS + type declarations into dist/
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
## Important notes
|
|
182
|
+
|
|
183
|
+
- **Not a diagnostic tool.** Scores, severity bands, and flags implement the published scoring rules of screening instruments; they are not diagnoses and do not replace clinical judgment.
|
|
184
|
+
- **Crisis-relevant answers.** PHQ-9 item 9 raises a `suicidality` flag — applications should surface this to a responsible clinician and provide crisis resources to respondents.
|
|
185
|
+
- **Instrument licensing.** PHQ-9, GAD-7 (Pfizer grant, public domain) and DASS-21 (Lovibond & Lovibond) are free to use. Bundled translations follow published validated versions; verify wording against the official versions before clinical use.
|
|
186
|
+
|
|
187
|
+
## License
|
|
188
|
+
|
|
189
|
+
MIT
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { AssessmentDefinition, AssessmentOption, AssessmentQuestion, EvaluationResult, Evaluator, LocalizedAssessmentView, ValidationResult } from "./types.ts";
|
|
2
|
+
import { AssessmentResponse } from "./response.ts";
|
|
3
|
+
/**
|
|
4
|
+
* Structurally validates an assessment definition (useful before persisting
|
|
5
|
+
* user-created assessments). Returns issues instead of throwing.
|
|
6
|
+
*/
|
|
7
|
+
export declare function validateDefinition(input: unknown): ValidationResult;
|
|
8
|
+
/**
|
|
9
|
+
* An assessment: questions plus an enumerated option scale, with helpers for
|
|
10
|
+
* localization, serialization, response creation, and evaluation.
|
|
11
|
+
*/
|
|
12
|
+
export declare class Assessment {
|
|
13
|
+
readonly definition: AssessmentDefinition;
|
|
14
|
+
private readonly questionIndex;
|
|
15
|
+
/** @throws PsytoolsError `invalid_definition` when the definition is malformed. */
|
|
16
|
+
constructor(definition: AssessmentDefinition);
|
|
17
|
+
get id(): string;
|
|
18
|
+
get questions(): readonly AssessmentQuestion[];
|
|
19
|
+
/** Locales for which at least one text of this assessment is available. */
|
|
20
|
+
get locales(): string[];
|
|
21
|
+
question(questionId: string): AssessmentQuestion | undefined;
|
|
22
|
+
/** The option scale that applies to a question (its own or the default). */
|
|
23
|
+
optionsFor(questionId: string): readonly AssessmentOption[];
|
|
24
|
+
title(locale?: string): string;
|
|
25
|
+
/**
|
|
26
|
+
* Flat, render-ready projection in one locale — hand this straight to a
|
|
27
|
+
* frontend to display the questionnaire.
|
|
28
|
+
*/
|
|
29
|
+
localize(locale?: string): LocalizedAssessmentView;
|
|
30
|
+
/** Starts a new (empty) response for this assessment. */
|
|
31
|
+
createResponse(options?: {
|
|
32
|
+
respondentId?: string;
|
|
33
|
+
meta?: Record<string, unknown>;
|
|
34
|
+
}): AssessmentResponse;
|
|
35
|
+
/**
|
|
36
|
+
* Evaluates a response (or raw answers) with the definition's declarative
|
|
37
|
+
* scoring, or with `evaluator` when provided.
|
|
38
|
+
*
|
|
39
|
+
* When given an `AssessmentResponse`, its status must be `complete` or
|
|
40
|
+
* `submitted` — pass `allowIncomplete` to score partial responses anyway.
|
|
41
|
+
* Raw answer maps are scored as-is (low-level escape hatch).
|
|
42
|
+
*
|
|
43
|
+
* @throws PsytoolsError `incomplete_response` | `no_scoring`
|
|
44
|
+
*/
|
|
45
|
+
evaluate(response: AssessmentResponse | Record<string, number>, evaluator?: Evaluator, options?: {
|
|
46
|
+
allowIncomplete?: boolean;
|
|
47
|
+
}): EvaluationResult;
|
|
48
|
+
/** The plain serializable definition (used by `JSON.stringify`). */
|
|
49
|
+
toJSON(): AssessmentDefinition;
|
|
50
|
+
/** Serializes the definition to a JSON string (for DB storage etc.). */
|
|
51
|
+
stringify(space?: number): string;
|
|
52
|
+
/**
|
|
53
|
+
* Parses and validates a definition from a JSON string or plain object.
|
|
54
|
+
* @throws PsytoolsError `invalid_json` | `invalid_definition`
|
|
55
|
+
*/
|
|
56
|
+
static parse(input: string | object): Assessment;
|
|
57
|
+
private text;
|
|
58
|
+
}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Assessment = void 0;
|
|
4
|
+
exports.validateDefinition = validateDefinition;
|
|
5
|
+
const errors_ts_1 = require("./errors.js");
|
|
6
|
+
const i18n_ts_1 = require("./i18n.js");
|
|
7
|
+
const response_ts_1 = require("./response.js");
|
|
8
|
+
const evaluation_ts_1 = require("./evaluation.js");
|
|
9
|
+
/**
|
|
10
|
+
* Structurally validates an assessment definition (useful before persisting
|
|
11
|
+
* user-created assessments). Returns issues instead of throwing.
|
|
12
|
+
*/
|
|
13
|
+
function validateDefinition(input) {
|
|
14
|
+
const issues = [];
|
|
15
|
+
const malformed = (message) => ({
|
|
16
|
+
valid: false,
|
|
17
|
+
issues: [{ code: "malformed", message }],
|
|
18
|
+
});
|
|
19
|
+
if (typeof input !== "object" || input === null || Array.isArray(input)) {
|
|
20
|
+
return malformed("definition must be an object");
|
|
21
|
+
}
|
|
22
|
+
const def = input;
|
|
23
|
+
if (typeof def.id !== "string" || def.id.length === 0) {
|
|
24
|
+
issues.push({ code: "malformed", message: "id must be a non-empty string" });
|
|
25
|
+
}
|
|
26
|
+
if (!isLocalizedText(def.title)) {
|
|
27
|
+
issues.push({ code: "malformed", message: "title must map locales to strings" });
|
|
28
|
+
}
|
|
29
|
+
if (typeof def.defaultLocale !== "string" || def.defaultLocale.length === 0) {
|
|
30
|
+
issues.push({ code: "malformed", message: "defaultLocale must be a non-empty string" });
|
|
31
|
+
}
|
|
32
|
+
if (!Array.isArray(def.options) || def.options.length === 0) {
|
|
33
|
+
issues.push({ code: "malformed", message: "options must be a non-empty array" });
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
def.options.forEach((option, i) => {
|
|
37
|
+
if (!isOption(option)) {
|
|
38
|
+
issues.push({ code: "malformed", message: `options[${i}] must have a numeric value and a localized label` });
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
if (!Array.isArray(def.questions) || def.questions.length === 0) {
|
|
43
|
+
issues.push({ code: "malformed", message: "questions must be a non-empty array" });
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
const seen = new Set();
|
|
47
|
+
def.questions.forEach((question, i) => {
|
|
48
|
+
if (typeof question !== "object" || question === null) {
|
|
49
|
+
issues.push({ code: "malformed", message: `questions[${i}] must be an object` });
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const q = question;
|
|
53
|
+
if (typeof q.id !== "string" || q.id.length === 0) {
|
|
54
|
+
issues.push({ code: "malformed", message: `questions[${i}].id must be a non-empty string` });
|
|
55
|
+
}
|
|
56
|
+
else if (seen.has(q.id)) {
|
|
57
|
+
issues.push({ code: "duplicate_question", message: `duplicate question id "${q.id}"`, questionId: q.id });
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
seen.add(q.id);
|
|
61
|
+
}
|
|
62
|
+
if (!isLocalizedText(q.text)) {
|
|
63
|
+
issues.push({ code: "malformed", message: `questions[${i}].text must map locales to strings`, questionId: typeof q.id === "string" ? q.id : undefined });
|
|
64
|
+
}
|
|
65
|
+
if (q.options !== undefined && (!Array.isArray(q.options) || q.options.length === 0 || !q.options.every(isOption))) {
|
|
66
|
+
issues.push({ code: "malformed", message: `questions[${i}].options, when present, must be a non-empty array of options`, questionId: typeof q.id === "string" ? q.id : undefined });
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
if (def.scoring && typeof def.scoring === "object") {
|
|
70
|
+
const scoring = def.scoring;
|
|
71
|
+
if (scoring.kind === "subscales" && Array.isArray(scoring.subscales)) {
|
|
72
|
+
for (const subscale of scoring.subscales) {
|
|
73
|
+
for (const questionId of subscale.questionIds ?? []) {
|
|
74
|
+
if (!seen.has(questionId)) {
|
|
75
|
+
issues.push({ code: "unknown_question", message: `subscale "${subscale.id}" references unknown question "${questionId}"`, questionId });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const flags = scoring.kind === "sum" || scoring.kind === "subscales" ? scoring.flags ?? [] : [];
|
|
81
|
+
for (const flag of flags) {
|
|
82
|
+
if (!seen.has(flag.questionId)) {
|
|
83
|
+
issues.push({ code: "unknown_question", message: `flag "${flag.id}" references unknown question "${flag.questionId}"`, questionId: flag.questionId });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return { valid: issues.length === 0, issues };
|
|
89
|
+
}
|
|
90
|
+
function isLocalizedText(value) {
|
|
91
|
+
return (typeof value === "object" &&
|
|
92
|
+
value !== null &&
|
|
93
|
+
!Array.isArray(value) &&
|
|
94
|
+
Object.keys(value).length > 0 &&
|
|
95
|
+
Object.values(value).every((entry) => typeof entry === "string"));
|
|
96
|
+
}
|
|
97
|
+
function isOption(value) {
|
|
98
|
+
return (typeof value === "object" &&
|
|
99
|
+
value !== null &&
|
|
100
|
+
typeof value.value === "number" &&
|
|
101
|
+
Number.isFinite(value.value) &&
|
|
102
|
+
isLocalizedText(value.label));
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* An assessment: questions plus an enumerated option scale, with helpers for
|
|
106
|
+
* localization, serialization, response creation, and evaluation.
|
|
107
|
+
*/
|
|
108
|
+
class Assessment {
|
|
109
|
+
definition;
|
|
110
|
+
questionIndex;
|
|
111
|
+
/** @throws PsytoolsError `invalid_definition` when the definition is malformed. */
|
|
112
|
+
constructor(definition) {
|
|
113
|
+
const result = validateDefinition(definition);
|
|
114
|
+
if (!result.valid) {
|
|
115
|
+
const details = result.issues.map((issue) => issue.message).join("; ");
|
|
116
|
+
throw new errors_ts_1.PsytoolsError("invalid_definition", `Invalid assessment definition: ${details}`);
|
|
117
|
+
}
|
|
118
|
+
this.definition = definition;
|
|
119
|
+
this.questionIndex = new Map(definition.questions.map((q) => [q.id, q]));
|
|
120
|
+
}
|
|
121
|
+
get id() {
|
|
122
|
+
return this.definition.id;
|
|
123
|
+
}
|
|
124
|
+
get questions() {
|
|
125
|
+
return this.definition.questions;
|
|
126
|
+
}
|
|
127
|
+
/** Locales for which at least one text of this assessment is available. */
|
|
128
|
+
get locales() {
|
|
129
|
+
return (0, i18n_ts_1.collectLocales)([
|
|
130
|
+
this.definition.title,
|
|
131
|
+
this.definition.description,
|
|
132
|
+
this.definition.instructions,
|
|
133
|
+
...this.definition.questions.map((q) => q.text),
|
|
134
|
+
]);
|
|
135
|
+
}
|
|
136
|
+
question(questionId) {
|
|
137
|
+
return this.questionIndex.get(questionId);
|
|
138
|
+
}
|
|
139
|
+
/** The option scale that applies to a question (its own or the default). */
|
|
140
|
+
optionsFor(questionId) {
|
|
141
|
+
const question = this.questionIndex.get(questionId);
|
|
142
|
+
if (!question) {
|
|
143
|
+
throw new errors_ts_1.PsytoolsError("unknown_question", `Unknown question "${questionId}" in assessment "${this.id}"`);
|
|
144
|
+
}
|
|
145
|
+
return question.options ?? this.definition.options;
|
|
146
|
+
}
|
|
147
|
+
title(locale) {
|
|
148
|
+
return this.text(this.definition.title, locale);
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Flat, render-ready projection in one locale — hand this straight to a
|
|
152
|
+
* frontend to display the questionnaire.
|
|
153
|
+
*/
|
|
154
|
+
localize(locale) {
|
|
155
|
+
const resolved = locale ?? this.definition.defaultLocale;
|
|
156
|
+
const view = {
|
|
157
|
+
id: this.id,
|
|
158
|
+
locale: resolved,
|
|
159
|
+
title: this.text(this.definition.title, resolved),
|
|
160
|
+
questions: this.definition.questions.map((question, i) => ({
|
|
161
|
+
id: question.id,
|
|
162
|
+
index: i + 1,
|
|
163
|
+
text: this.text(question.text, resolved),
|
|
164
|
+
optional: question.optional ?? false,
|
|
165
|
+
options: (question.options ?? this.definition.options).map((option) => ({
|
|
166
|
+
value: option.value,
|
|
167
|
+
label: this.text(option.label, resolved),
|
|
168
|
+
})),
|
|
169
|
+
})),
|
|
170
|
+
};
|
|
171
|
+
if (this.definition.description) {
|
|
172
|
+
view.description = this.text(this.definition.description, resolved);
|
|
173
|
+
}
|
|
174
|
+
if (this.definition.instructions) {
|
|
175
|
+
view.instructions = this.text(this.definition.instructions, resolved);
|
|
176
|
+
}
|
|
177
|
+
return view;
|
|
178
|
+
}
|
|
179
|
+
/** Starts a new (empty) response for this assessment. */
|
|
180
|
+
createResponse(options) {
|
|
181
|
+
return new response_ts_1.AssessmentResponse(this, options);
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Evaluates a response (or raw answers) with the definition's declarative
|
|
185
|
+
* scoring, or with `evaluator` when provided.
|
|
186
|
+
*
|
|
187
|
+
* When given an `AssessmentResponse`, its status must be `complete` or
|
|
188
|
+
* `submitted` — pass `allowIncomplete` to score partial responses anyway.
|
|
189
|
+
* Raw answer maps are scored as-is (low-level escape hatch).
|
|
190
|
+
*
|
|
191
|
+
* @throws PsytoolsError `incomplete_response` | `no_scoring`
|
|
192
|
+
*/
|
|
193
|
+
evaluate(response, evaluator, options) {
|
|
194
|
+
if (response instanceof response_ts_1.AssessmentResponse) {
|
|
195
|
+
const scorable = response.status === "complete" || response.status === "submitted";
|
|
196
|
+
if (!scorable && !options?.allowIncomplete) {
|
|
197
|
+
const missing = response.unanswered().join(", ");
|
|
198
|
+
throw new errors_ts_1.PsytoolsError("incomplete_response", `Cannot evaluate a response with status "${response.status}" (unanswered: ${missing}); ` +
|
|
199
|
+
"pass { allowIncomplete: true } to score it anyway");
|
|
200
|
+
}
|
|
201
|
+
return (0, evaluation_ts_1.evaluate)(this.definition, response.answers, evaluator);
|
|
202
|
+
}
|
|
203
|
+
return (0, evaluation_ts_1.evaluate)(this.definition, response, evaluator);
|
|
204
|
+
}
|
|
205
|
+
/** The plain serializable definition (used by `JSON.stringify`). */
|
|
206
|
+
toJSON() {
|
|
207
|
+
return this.definition;
|
|
208
|
+
}
|
|
209
|
+
/** Serializes the definition to a JSON string (for DB storage etc.). */
|
|
210
|
+
stringify(space) {
|
|
211
|
+
return JSON.stringify(this.definition, null, space);
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Parses and validates a definition from a JSON string or plain object.
|
|
215
|
+
* @throws PsytoolsError `invalid_json` | `invalid_definition`
|
|
216
|
+
*/
|
|
217
|
+
static parse(input) {
|
|
218
|
+
let raw = input;
|
|
219
|
+
if (typeof input === "string") {
|
|
220
|
+
try {
|
|
221
|
+
raw = JSON.parse(input);
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
throw new errors_ts_1.PsytoolsError("invalid_json", `Not valid JSON: ${error.message}`);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return new Assessment(raw);
|
|
228
|
+
}
|
|
229
|
+
text(text, locale) {
|
|
230
|
+
return (0, i18n_ts_1.localize)(text, locale ?? this.definition.defaultLocale, this.definition.defaultLocale);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
exports.Assessment = Assessment;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PsytoolsError = void 0;
|
|
4
|
+
/** Error thrown by psytools, carrying a stable machine-readable code. */
|
|
5
|
+
class PsytoolsError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
constructor(code, message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = "PsytoolsError";
|
|
10
|
+
this.code = code;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
exports.PsytoolsError = PsytoolsError;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AnswerMap, AssessmentDefinition, EvaluationResult, Evaluator } from "./types.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Evaluates answers against an assessment definition.
|
|
4
|
+
*
|
|
5
|
+
* Uses `evaluator` when given; otherwise applies the definition's
|
|
6
|
+
* declarative `scoring` (`sum` or `subscales`).
|
|
7
|
+
*
|
|
8
|
+
* @throws PsytoolsError `no_scoring` when neither is available.
|
|
9
|
+
*/
|
|
10
|
+
export declare function evaluate(definition: AssessmentDefinition, answers: AnswerMap, evaluator?: Evaluator): EvaluationResult;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.evaluate = evaluate;
|
|
4
|
+
const errors_ts_1 = require("./errors.js");
|
|
5
|
+
/**
|
|
6
|
+
* Evaluates answers against an assessment definition.
|
|
7
|
+
*
|
|
8
|
+
* Uses `evaluator` when given; otherwise applies the definition's
|
|
9
|
+
* declarative `scoring` (`sum` or `subscales`).
|
|
10
|
+
*
|
|
11
|
+
* @throws PsytoolsError `no_scoring` when neither is available.
|
|
12
|
+
*/
|
|
13
|
+
function evaluate(definition, answers, evaluator) {
|
|
14
|
+
if (evaluator)
|
|
15
|
+
return evaluator(definition, answers);
|
|
16
|
+
const scoring = definition.scoring;
|
|
17
|
+
if (!scoring) {
|
|
18
|
+
throw new errors_ts_1.PsytoolsError("no_scoring", `Assessment "${definition.id}" has no scoring definition; pass a custom evaluator`);
|
|
19
|
+
}
|
|
20
|
+
switch (scoring.kind) {
|
|
21
|
+
case "sum":
|
|
22
|
+
return evaluateSum(definition, answers, scoring.bands, scoring.flags);
|
|
23
|
+
case "subscales": {
|
|
24
|
+
const scales = scoring.subscales.map((subscale) => {
|
|
25
|
+
const questions = subscale.questionIds.map((id) => requireQuestion(definition, id));
|
|
26
|
+
const multiplier = subscale.multiplier ?? 1;
|
|
27
|
+
const { score, min, max } = sumQuestions(definition, questions, answers, multiplier);
|
|
28
|
+
return {
|
|
29
|
+
id: subscale.id,
|
|
30
|
+
label: subscale.label,
|
|
31
|
+
score,
|
|
32
|
+
min,
|
|
33
|
+
max,
|
|
34
|
+
...bandOf(score, subscale.bands),
|
|
35
|
+
};
|
|
36
|
+
});
|
|
37
|
+
return {
|
|
38
|
+
kind: "multiscale",
|
|
39
|
+
scales,
|
|
40
|
+
flags: triggeredFlags(answers, scoring.flags),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
default:
|
|
44
|
+
throw new errors_ts_1.PsytoolsError("no_scoring", `Unsupported scoring kind "${scoring.kind}"`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function evaluateSum(definition, answers, bands, flags) {
|
|
48
|
+
const { score, min, max } = sumQuestions(definition, definition.questions, answers, 1);
|
|
49
|
+
return {
|
|
50
|
+
kind: "scale",
|
|
51
|
+
score,
|
|
52
|
+
min,
|
|
53
|
+
max,
|
|
54
|
+
...bandOf(score, bands),
|
|
55
|
+
flags: triggeredFlags(answers, flags),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function sumQuestions(definition, questions, answers, multiplier) {
|
|
59
|
+
let score = 0;
|
|
60
|
+
let min = 0;
|
|
61
|
+
let max = 0;
|
|
62
|
+
for (const question of questions) {
|
|
63
|
+
const values = (question.options ?? definition.options).map((o) => o.value);
|
|
64
|
+
const lowest = Math.min(...values);
|
|
65
|
+
const highest = Math.max(...values);
|
|
66
|
+
min += lowest;
|
|
67
|
+
max += highest;
|
|
68
|
+
const answered = answers[question.id];
|
|
69
|
+
if (answered === undefined)
|
|
70
|
+
continue;
|
|
71
|
+
score += question.reverseScored ? highest + lowest - answered : answered;
|
|
72
|
+
}
|
|
73
|
+
return { score: score * multiplier, min: min * multiplier, max: max * multiplier };
|
|
74
|
+
}
|
|
75
|
+
function bandOf(score, bands) {
|
|
76
|
+
const match = bands?.find((band) => score >= band.min && score <= band.max);
|
|
77
|
+
return match ? { band: { id: match.id, label: match.label } } : {};
|
|
78
|
+
}
|
|
79
|
+
function triggeredFlags(answers, flags) {
|
|
80
|
+
if (!flags)
|
|
81
|
+
return [];
|
|
82
|
+
const triggered = [];
|
|
83
|
+
for (const flag of flags) {
|
|
84
|
+
const value = answers[flag.questionId];
|
|
85
|
+
if (value !== undefined && value >= flag.minValue) {
|
|
86
|
+
triggered.push({
|
|
87
|
+
id: flag.id,
|
|
88
|
+
questionId: flag.questionId,
|
|
89
|
+
value,
|
|
90
|
+
label: flag.label,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return triggered;
|
|
95
|
+
}
|
|
96
|
+
function requireQuestion(definition, questionId) {
|
|
97
|
+
const question = definition.questions.find((q) => q.id === questionId);
|
|
98
|
+
if (!question) {
|
|
99
|
+
throw new errors_ts_1.PsytoolsError("unknown_question", `Scoring references unknown question "${questionId}" in assessment "${definition.id}"`);
|
|
100
|
+
}
|
|
101
|
+
return question;
|
|
102
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { LocalizedText } from "./types.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Resolves a `LocalizedText` to a string for the given locale.
|
|
4
|
+
*
|
|
5
|
+
* Resolution order: exact locale -> base language of the locale
|
|
6
|
+
* (`"de-AT"` -> `"de"`) -> `fallbackLocale` -> first available entry.
|
|
7
|
+
*/
|
|
8
|
+
export declare function localize(text: LocalizedText, locale: string, fallbackLocale?: string): string;
|
|
9
|
+
/** Collects the union of locales present in a set of localized texts. */
|
|
10
|
+
export declare function collectLocales(texts: Array<LocalizedText | undefined>): string[];
|