Loading files
// jev.mjs — a tiny, dependency-free client for TypeSafe's Jev "System One" decision model,
// with a deterministic mock fallback so the whole harness runs without a key.
//
// Jev never writes text. You send it a `state` plus typed `questions`; it answers every question
// in one parallel pass, each with a calibrated probability distribution, in ~100ms. Three primitives:
// noul yes/no — returns a single probability 0..1
// choice pick one of up to 255 declared options — per-option probabilities + a `confidence`
// score a position on a 2..10 level scale — a float plus per-level probabilities
//
// Questions are authored as options[] / legend{} (or an option -> description map) and translated
// to the API's real wire format (choice: criteria map, score: criteria level list) by toWire().
//
// When TYPESAFE_API_KEY is set we call the real API (POST /v1/systemone). Without it we serve a
// deterministic local mock so development, tests and offline demos work. The generic mock reads
// word evidence out of the state text; a harness can pass its own domain reader as `mock` to
// evaluate(). The mock exercises the *plumbing* exactly as the live model would. It is deliberately
// NOT a stand-in for Jev's judgement, and every viewer badges it as MOCK.
const LIVE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
export class JevError extends Error {}
function pickClient(key) {
return key ? 'typesafe' : 'mock'
}
/** Low-hash of a string -> [0,1). Stable for the same input; varies with the salt. */
export function hash01(str, salt = 0) {
let h = 2166136261 ^ salt
for (let i = 0; i < str.length; i++) {
h ^= str.charCodeAt(i)
h = Math.imul(h, 16777619)
}
return (h >>> 0) / 4294967296
}
const STOP = new Set('a an the of to in on at for and or is are was were be been it its this that these those with as by from not no yes do does did has have had will would can could should may might if then than so such very more most less least about into over under out up down off any all each every some which who whom what when where why how i you he she we they them his her our your their my me us'.split(' '))
/** Lowercase word stems, stopwords removed. Crude on purpose: drop plural/verb endings. */
export function stems(text) {
const out = []
for (const w of String(text).toLowerCase().split(/[^a-z0-9$%]+/)) {
if (w.length < 2 || STOP.has(w)) continue
out.push(w.length > 4 ? w.replace(/(ingly|edly|ings|ing|ies|ied|ely|ed|es|ly|s)$/, '') : w)
}
return out
}
/** How much of `needle`'s vocabulary shows up in the state's stem set. 0..~3. */
function evidence(stateStems, needle) {
const want = [...new Set(stems(needle))]
if (!want.length) return 0
let hit = 0
for (const w of want) if (stateStems.has(w)) hit++
return (hit / Math.sqrt(want.length)) * 1.2
}
function softmax(raw, temp = 1) {
const m = Math.max(...raw)
const exps = raw.map((r) => Math.exp((r - m) / temp))
const sum = exps.reduce((a, b) => a + b, 0)
return exps.map((e) => e / sum)
}
// ---------------------------------------------------------------------------
// The deterministic generic mock. It turns the state text + question wording into a plausible
// distribution: evidence = how much of an option's (or level's) vocabulary the state mentions.
// ---------------------------------------------------------------------------
function mockAnswer(state, qid, q, salt) {
const text = `${state ?? ''}`
const S = new Set(stems(text))
const jitter = (key, amp) => (hash01(`${qid}::${key}::${text.length}:${text.slice(0, 64)}`, salt) - 0.5) * amp
if (q.type === 'noul') {
const yes = evidence(S, `${q.instructions} ${q.hints?.join(' ') ?? ''} ${q.raw?.true ?? ''}`)
const no = evidence(S, `${q.raw?.false ?? ''}`)
const p = 1 / (1 + Math.exp(-((yes - no) * 1.6 - 0.9 + jitter('noul', 0.8))))
return { type: 'noul', noul: clamp(p) }
}
if (q.type === 'choice') {
const options = q.options || []
if (!options.length) return { type: 'choice', choice: null, confidence: 0, probabilities: {} }
const raw = options.map((opt) => evidence(S, `${String(opt).replace(/[_-]+/g, ' ')} ${q.descriptions?.[opt] ?? ''}`) * 1.5 + jitter(String(opt), 0.5))
const probs = softmax(raw, 0.6)
const probabilities = {}
options.forEach((opt, i) => (probabilities[String(opt)] = probs[i]))
const bi = probs.indexOf(Math.max(...probs))
return { type: 'choice', choice: String(options[bi]), confidence: clamp(probs[bi]), probabilities }
}
if (q.type === 'score') {
const levels = q.levels?.length ? q.levels : Object.values(q.legend ?? { 0: 'low', 1: 'high' })
const raw = levels.map((label, i) => evidence(S, label) * 1.6 + jitter(`lv${i}`, 0.5))
// No wording evidence at all: fall back to a stable pseudo-position so it is not always level 0.
if (raw.every((r) => Math.abs(r) < 0.26)) {
const pos = hash01(`${qid}::${text.slice(0, 120)}`, salt) * (levels.length - 1)
levels.forEach((_, i) => (raw[i] = -((i - pos) ** 2) / 0.8))
}
const probs = softmax(raw, 0.7)
const probabilities = {}
levels.forEach((_, i) => (probabilities[String(i)] = probs[i]))
const score = probs.reduce((acc, p, i) => acc + p * i, 0)
return { type: 'score', score, confidence: clamp(Math.max(...probs)), legend: q.legend, probabilities }
}
return { type: q.type, ok: false }
}
function clamp(x) {
return Math.min(1, Math.max(0, x))
}
// Imports are hoisted, so they can live here with the code that needs them.
import { readFileSync, writeFileSync, renameSync, mkdirSync, chmodSync } from 'node:fs'
import { homedir } from 'node:os'
import { join, dirname } from 'node:path'
// ---------------------------------------------------------------------------
// Wire format. The live API (POST /v1/systemone) takes, per question:
// noul { type, instructions, criteria?: { true: "...", false: "..." } }
// choice { type, instructions, criteria: { "<option>": "<what it means>" } } options ARE the keys
// score { type, instructions, criteria: ["<level 0>", "<level 1>", ...] } 2+ ordered levels
// Harness code authors questions in a friendlier shape (options[] / legend{}), so we normalise
// both ways: canon() feeds the mock, toWire() feeds the live call. Sending `options` or `legend`
// straight to the API is a 422.
// ---------------------------------------------------------------------------
const isMap = (v) => v && typeof v === 'object' && !Array.isArray(v)
/** Canonical authoring shape: { type, instructions, options[], descriptions{}, legend{}, hints[] }. */
export function canon(q = {}) {
const type = q.type
const out = { ...q, type, instructions: q.instructions ?? '' }
if (type === 'choice') {
const fromCriteria = isMap(q.criteria) ? Object.keys(q.criteria) : null
out.options = (q.options ?? q.choices ?? fromCriteria ?? []).map(String)
out.descriptions = { ...(isMap(q.criteria) ? q.criteria : {}), ...(isMap(q.descriptions) ? q.descriptions : {}) }
out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
} else if (type === 'score') {
let levels
if (isMap(q.legend)) levels = Object.keys(q.legend).sort((a, b) => Number(a) - Number(b)).map((k) => String(q.legend[k]))
else if (Array.isArray(q.criteria)) levels = q.criteria.map(String)
else levels = Array.from({ length: Math.max(2, Number(q.levels) || 5) }, (_, i) => String(i))
out.levels = levels
out.legend = Object.fromEntries(levels.map((label, i) => [String(i), label]))
out.hints = []
} else {
out.hints = Array.isArray(q.criteria) ? q.criteria.map(String) : []
out.raw = isMap(q.criteria) ? q.criteria : null
}
// The mock scores evidence off `criteria` as a flat list of strings.
out.criteria = [...(out.hints ?? []), ...Object.values(out.descriptions ?? {})].filter((s) => typeof s === 'string')
return out
}
/** Exactly what the live API accepts. */
export function toWire(questions = {}) {
const wire = {}
for (const [id, raw] of Object.entries(questions)) {
const q = canon(raw)
const hint = q.hints?.length ? ` (${q.hints.join('; ')})` : ''
if (q.type === 'choice') {
const criteria = {}
for (const opt of q.options) criteria[opt] = String(q.descriptions[opt] ?? opt)
wire[id] = { type: 'choice', instructions: q.instructions + hint, criteria }
} else if (q.type === 'score') {
wire[id] = { type: 'score', instructions: q.instructions, criteria: q.levels }
} else {
const w = { type: 'noul', instructions: q.instructions + hint }
if (isMap(raw.criteria) && ('true' in raw.criteria || 'false' in raw.criteria)) w.criteria = raw.criteria
wire[id] = w
}
}
return wire
}
/** Make a live answer look like the mock's, so viewers read one shape. */
function fromWire(ans, q) {
if (!ans || typeof ans !== 'object') return { type: q.type, ok: false }
if (q.type === 'choice') {
const probabilities = isMap(ans.probabilities) ? ans.probabilities : {}
const best = ans.choice ?? Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null
const top = best != null && probabilities[best] != null ? probabilities[best] : 0
return { ...ans, type: 'choice', choice: best == null ? null : String(best), probabilities, confidence: Number(ans.confidence ?? top) }
}
if (q.type === 'score') return { ...ans, type: 'score', score: Number(ans.score ?? 0), legend: ans.legend ?? q.legend, confidence: Number(ans.confidence ?? 0) }
return { ...ans, type: 'noul', noul: Number(ans.noul ?? 0.5) }
}
// ---------------------------------------------------------------------------
// Telemetry. Every evaluate() call is metered so a viewer can show Jev's mind live: what it was
// asked, the full probability distribution it answered with, how long it took and what it cost.
// ---------------------------------------------------------------------------
export const PRICE_PER_MTOK = 0.042 // USD per million input tokens; output is free
export const telemetry = {
client: 'mock', model: 'jev-latest', calls: 0, errors: 0, retries: 0, questions: 0,
inputTokens: 0, outputTokens: 0, costUsd: 0, tokensEstimated: true,
lastLatencyMs: 0, avgLatencyMs: 0, lastError: null, last: null, startedAt: Date.now(),
}
const recent = [] // { t, n } per call, for a sliding-window rate
const latencies = []
function meter({ client, model, wire, state, answers, usage, latencyMs }) {
const now = Date.now()
const nQ = Object.keys(wire).length
const real = Number(usage?.input_tokens)
const est = Math.ceil((JSON.stringify(state ?? '').length + JSON.stringify(wire).length) / 4)
const tokens = Number.isFinite(real) && real > 0 ? real : est
telemetry.client = client
telemetry.model = model
telemetry.calls++
telemetry.questions += nQ
telemetry.inputTokens += tokens
telemetry.outputTokens += Number(usage?.output_tokens) || 0
telemetry.tokensEstimated = !(Number.isFinite(real) && real > 0)
telemetry.costUsd = (telemetry.inputTokens * PRICE_PER_MTOK) / 1e6
telemetry.lastLatencyMs = latencyMs
latencies.push(latencyMs); if (latencies.length > 60) latencies.shift()
telemetry.avgLatencyMs = latencies.reduce((a, b) => a + b, 0) / latencies.length
telemetry.lastError = null
telemetry.last = {
at: now, tokens, latencyMs,
questions: Object.entries(wire).map(([id, w]) => ({ id, type: w.type, instructions: String(w.instructions).slice(0, 160), answer: answers[id] })),
}
recent.push({ t: now, n: nQ })
while (recent.length && now - recent[0].t > 5000) recent.shift()
}
/** A JSON-safe snapshot for the viewer's /jev route. */
export function snapshot() {
const now = Date.now()
while (recent.length && now - recent[0].t > 5000) recent.shift()
const span = recent.length > 1 ? Math.max(0.5, (now - recent[0].t) / 1000) : 5
return {
...telemetry,
route: resolveCredentials()?.provider ?? null, // the live route a key is set up for, before any call is made
callsPerSec: recent.length / span,
questionsPerSec: recent.reduce((a, r) => a + r.n, 0) / span,
latencies: latencies.slice(-40),
pricePerMTok: PRICE_PER_MTOK,
uptimeMs: now - telemetry.startedAt,
}
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
// ---------------------------------------------------------------------------
// Credentials. Environment variables win. Otherwise a small KEY=VALUE file in the user's home is
// read, because a viewer started by the Harness daemon does not inherit the variables of the shell
// you happen to have open. Two live routes are supported, both speaking the same question format:
// TypeSafe direct TYPESAFE_API_KEY (api.typesafe.ai)
// Cloudflare Workers AI CLOUDFLARE_ACCOUNT_ID + CLOUDFLARE_API_TOKEN (no TypeSafe waitlist)
// OpenRouter OPENROUTER_API_KEY (no waitlist; alpha endpoint, ~0.45 s a call measured)
// When several are present the fastest wins: TypeSafe, then Cloudflare, then OpenRouter.
// The file is ~/.config/typesafe/credentials (or $TYPESAFE_CREDENTIALS). Keep it chmod 600.
// ---------------------------------------------------------------------------
const CRED_KEYS = ['TYPESAFE_API_KEY', 'TYPESAFE_API_URL', 'CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN', 'OPENROUTER_API_KEY', 'OPENROUTER_API_URL', 'OPENROUTER_JEV_MODEL']
let credCache = null
export const credentialsPath = () => process.env.TYPESAFE_CREDENTIALS || join(homedir(), '.config', 'typesafe', 'credentials')
function readCredentialFile() {
const now = Date.now()
const path = credentialsPath()
if (credCache && credCache.path === path && now - credCache.at < 5000) return credCache.values
const values = {}
try {
for (const line of readFileSync(path, 'utf8').split('\n')) {
const m = line.match(/^\s*(?:export\s+)?([A-Z_]+)\s*=\s*(.*?)\s*$/)
if (m && CRED_KEYS.includes(m[1])) values[m[1]] = m[2].replace(/^(['"])(.*)\1$/, '$2')
}
} catch { /* no file: fine */ }
credCache = { at: now, path, values }
return values
}
/** Which live route to use, or null for the offline stand-in. Never log the returned secret. */
export function resolveCredentials(explicitKey) {
if (explicitKey === '') return null // an explicit empty key forces the offline stand-in
// Test suites assume the deterministic stand-in. Under `node --test`, or with JEV_OFFLINE=1, a real
// key on the machine is ignored unless it is passed explicitly or JEV_LIVE_TESTS=1 is set.
if (!explicitKey && (process.env.JEV_OFFLINE === '1' || (process.env.NODE_TEST_CONTEXT && process.env.JEV_LIVE_TESTS !== '1'))) return null
const file = readCredentialFile()
const get = (k) => process.env[k] || file[k] || ''
const key = explicitKey || get('TYPESAFE_API_KEY')
if (key) return { provider: 'typesafe', secret: key, url: get('TYPESAFE_API_URL') || LIVE_ENDPOINT }
const account = get('CLOUDFLARE_ACCOUNT_ID'), token = get('CLOUDFLARE_API_TOKEN')
if (account && token) return { provider: 'cloudflare', secret: token, url: `${process.env.CLOUDFLARE_API_BASE || 'https://api.cloudflare.com'}/client/v4/accounts/${encodeURIComponent(account)}/ai/run` }
// OpenRouter proxies the same API on an alpha path. It wants its own model id, not "jev-latest".
const orKey = get('OPENROUTER_API_KEY')
if (orKey) return { provider: 'openrouter', secret: orKey, url: get('OPENROUTER_API_URL') || 'https://openrouter.ai/api/alpha/decisions', model: get('OPENROUTER_JEV_MODEL') || 'typesafe/jev-1.13' }
return null
}
/**
* Store one credential in the credentials file, so a pane can go live without a terminal. The file
* is created chmod 600 inside a chmod 700 folder. The value is never logged and never returned.
*/
export function saveCredential(name, value) {
if (!CRED_KEYS.includes(name)) throw new JevError(`unknown credential "${name}"`)
const v = String(value ?? '').trim()
if (v.length < 8 || v.length > 400 || /[\s'"\\#=]/.test(v)) throw new JevError('that does not look like a key')
const path = credentialsPath()
mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
let lines = []
try { lines = readFileSync(path, 'utf8').split('\n') } catch { /* first key on this machine */ }
const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
const kept = lines.filter((l) => l.trim() !== '' && !mine.test(l))
kept.push(`${name}=${v}`)
writeFileSync(path + '.tmp', kept.join('\n') + '\n', { mode: 0o600 })
renameSync(path + '.tmp', path)
try { chmodSync(path, 0o600) } catch { /* a filesystem without modes */ }
credCache = null
}
/** Remove one credential from the credentials file (used when a pasted key turns out to be wrong). */
export function removeCredential(name) {
if (!CRED_KEYS.includes(name)) return
const path = credentialsPath()
try {
const mine = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`)
const kept = readFileSync(path, 'utf8').split('\n').filter((l) => l.trim() !== '' && !mine.test(l))
writeFileSync(path + '.tmp', kept.length ? kept.join('\n') + '\n' : '', { mode: 0o600 })
renameSync(path + '.tmp', path)
} catch { /* nothing to remove */ }
credCache = null
}
/**
* A person pasted a key into a pane. Work out which route it is for, store it, and prove it with
* one tiny real call. A key the service refuses is removed again. Never throws.
* @returns {Promise<{ ok: boolean, provider?: string, error?: string }>}
*/
export async function connectKey(value, { probe = true } = {}) {
const v = String(value ?? '').trim()
const name = /^sk-or-/i.test(v) ? 'OPENROUTER_API_KEY' : 'TYPESAFE_API_KEY'
try { saveCredential(name, v) } catch (e) { return { ok: false, error: e.message } }
const cred = resolveCredentials()
// Under `node --test` or JEV_OFFLINE the stand-in stays on: the key is stored, nothing is called.
if (!cred || !probe) return { ok: true, provider: name === 'OPENROUTER_API_KEY' ? 'openrouter' : 'typesafe', stored: true, probed: false }
try {
await liveEvaluate({ model: 'jev-latest', state: { text: 'The sky is blue.' }, questions: toWire({ q: { type: 'noul', instructions: 'Does the text mention a colour?' } }) }, cred)
return { ok: true, provider: cred.provider, stored: true, probed: true }
} catch (e) {
const msg = String(e?.message ?? e)
// A refused key is not worth keeping. A good key on an account with no credit left is: the
// person only has to top it up, and throwing the key away would make that harder.
const refused = e?.status === 401 || e?.status === 403 ||
(!e?.status && /\b(401|403)\b|unauthor|invalid.*key|forbidden/i.test(msg))
if (refused) { removeCredential(name); return { ok: false, error: 'The service refused that key. Nothing was saved.' } }
return { ok: true, provider: cred.provider, stored: true, probed: false, warning: e?.provider ? msg : `The key is saved, but the test call failed: ${msg.slice(0, 160)}` }
}
}
/** One safe line for doctor scripts and panes: says which route is active, never the secret. */
export function describeCredentials() {
const c = resolveCredentials()
if (!c) return `offline stand-in (no key found in the environment or in ${credentialsPath()})`
if (c.provider === 'openrouter') return `live Jev through OpenRouter (${c.model}; alpha endpoint, about half a second a call: great for batch work, and the real-time games run at about two decisions a second)`
return c.provider === 'cloudflare' ? 'live Jev through Cloudflare Workers AI' : 'live Jev through the TypeSafe API'
}
async function liveEvaluate(body, cred) {
const endpoint = cred.url
const key = cred.secret
const payload = cred.provider === 'cloudflare' ? { model: 'typesafe/jev', input: { state: body.state, questions: body.questions } }
: cred.provider === 'openrouter' ? { ...body, model: cred.model }
: body
let lastErr
for (let attempt = 0; attempt < 3; attempt++) {
if (attempt) { telemetry.retries++; await sleep(250 * 3 ** (attempt - 1)) }
try {
const res = await fetch(endpoint, {
method: 'POST',
headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
body: JSON.stringify(payload),
signal: AbortSignal.timeout(cred.provider === 'openrouter' ? 30000 : 10000),
})
if (res.ok) {
const data = await res.json()
// Cloudflare wraps the model's reply as { result, success, errors }.
if (data && data.success === false) throw new JevError(`Jev API 422: ${JSON.stringify(data.errors ?? data).slice(0, 200)}`)
return data?.result?.answers ? data.result : data
}
const detail = await res.text().catch(() => '')
// A person reading the pane needs to know what to do, not what the server's JSON looked like.
const plain = {
401: 'That Jev key was refused. Paste a working one in the pane\'s "Jev · live mind" panel.',
402: 'The account behind that Jev key is out of credit. Top it up with your provider and press Go again.',
403: 'That Jev key is not allowed to use this model.',
429: 'Your Jev provider is rate limiting these calls. Wait a moment and try again.',
529: 'Jev is overloaded right now. Try again in a moment.',
}[res.status]
lastErr = new JevError(plain ? `${plain} (HTTP ${res.status})` : `Jev API ${res.status}: ${detail.slice(0, 200)}`)
// The caller shows this one to a person as-is: it already says what to do, so nothing should
// bury it under "nothing could be worked out".
lastErr.provider = Boolean(plain)
lastErr.status = res.status
if (res.status !== 429 && res.status !== 529 && res.status < 500) throw lastErr // 401/422: retrying cannot help
} catch (e) {
// Which ones are worth trying again is a fact about the status, not about how the message
// happens to read: the messages above are written for a person and no longer carry the code.
const worthRetrying = e.status === 429 || e.status === 529 || e.status >= 500
if (e instanceof JevError && !worthRetrying) throw e
lastErr = e instanceof JevError ? e : new JevError(`Jev API unreachable: ${e?.message ?? e}`)
}
}
throw lastErr
}
/**
* Evaluate a set of typed questions against a state. All questions share the state and are
* answered in one parallel pass — ask many at once, it is nearly free.
*
* @param {object} opts
* @param {string|object|Array} opts.state the shared context block
* @param {object} opts.questions map of id -> question (see the `jev` builders)
* @param {string} [opts.key] TYPESAFE_API_KEY; defaults to process.env
* @param {string} [opts.model] 'jev-latest' by default
* @param {number} [opts.salt] mock-only seed so different callers diverge
* @param {function} [opts.mock] mock-only domain reader: (state, id, question, salt) => answer | null
* @returns {{client, model, answers, usage, latencyMs}}
*/
export async function evaluate({ state, questions, key, model = 'jev-latest', salt = 1, mock } = {}) {
const cred = resolveCredentials(key)
const client = cred ? cred.provider : 'mock'
const wire = toWire(questions)
const t0 = performance.now()
try {
if (cred) {
const data = await liveEvaluate({ model, state, questions: wire }, cred)
const rawAnswers = data.answers || data
const answers = {}
for (const [qid, q] of Object.entries(questions)) answers[qid] = fromWire(rawAnswers[qid], canon(q))
const latencyMs = performance.now() - t0
meter({ client, model: data.model || model, wire, state, answers, usage: data.usage, latencyMs })
return { client, model: data.model || model, answers, usage: data.usage || {}, latencyMs }
}
// Mock: local, deterministic, instant.
const text = typeof state === 'string' ? state : JSON.stringify(state)
const answers = {}
for (const [qid, raw] of Object.entries(questions)) {
const q = canon(raw)
answers[qid] = (typeof mock === 'function' && mock(text, qid, q, salt)) || mockAnswer(text, qid, q, salt)
}
const latencyMs = performance.now() - t0
meter({ client, model: `${model} (mock)`, wire, state, answers, usage: null, latencyMs })
return { client: 'mock', model: `${model} (mock)`, answers, usage: { provider: 'deterministic-mock' }, latencyMs }
} catch (e) {
telemetry.errors++
telemetry.lastError = String(e?.message ?? e).slice(0, 240)
throw e
}
}
// ---------------------------------------------------------------------------
// Question builders
// ---------------------------------------------------------------------------
export const jev = {
/** Yes/no. criteria may be { true: '...', false: '...' } or a list of hints. */
noul(instructions, criteria = undefined) {
const q = { type: 'noul', instructions }
if (criteria) q.criteria = isMap(criteria) ? criteria : Array.isArray(criteria) ? criteria : [criteria]
return q
},
/**
* Pick one of up to 255 options. `options` is a list, or a map of option -> what it means
* (descriptions make Jev sharper; they are sent as the API's `criteria`).
*/
choice(options, instructions, criteria = undefined) {
const q = { type: 'choice', instructions }
if (isMap(options)) { q.options = Object.keys(options); q.descriptions = options } else q.options = options
if (criteria) q.criteria = Array.isArray(criteria) ? criteria : [criteria]
return q
},
/**
* score(legend, instructions) — legend maps level -> label, e.g. {0:'calm',1:'frustrated',2:'angry'},
* or is an ordered list of level labels. 2..10 levels.
*/
score(legend, instructions) {
const q = { type: 'score', instructions }
q.legend = Array.isArray(legend) ? Object.fromEntries(legend.map((l, i) => [String(i), l])) : legend
return q
},
}
export default jev
442335385This file is pinned to the selected release. Download the original to open it in your design tool.