@conversation/spec 0.0.0-stage → 0.1.2

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/parse.js ADDED
@@ -0,0 +1,472 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parse = parse;
4
+ const errors_1 = require("./errors");
5
+ const plugin_1 = require("./plugin");
6
+ const plugins_1 = require("./plugins");
7
+ const schema_1 = require("./schema");
8
+ const segments_1 = require("./segments");
9
+ const suggest_1 = require("./suggest");
10
+ const values_1 = require("./values");
11
+ const INCLUDE_RE = /^@include\b\s*(.*)$/;
12
+ const PAUSE_RE = /^\[pause\s+([\d.]+)\]$/i;
13
+ const LEGACY_MUSIC_RE = /^\[music:\s*([^\s\]]+)\s*([^\]]*)\]$/i;
14
+ const DIRECTIVE_RE = /^\[([a-z][a-z0-9_-]*)(?:\s+([^\]]*))?\]$/;
15
+ const CUE_RE = /^\[([A-Z][A-Z0-9_-]*)(?:\s+([^\]]*))?\]$/;
16
+ const SOUND_NAME_RE = /^[A-Z][A-Z0-9_-]*$/;
17
+ const SOUND_DECL_RE = /^([A-Z][A-Z0-9_-]*)\s*:\s*\{(.+)\}\s*$/;
18
+ const CHAR_DECL_RE = /^([A-Z][A-Z0-9_]*)\s*:\s*\{(.+)\}\s*$/;
19
+ const TRACK_DECL_RE = /^([a-z][a-z0-9_-]*)\s*:\s*\{(.*)\}\s*$/;
20
+ const LINE_RE = /^([A-Z][A-Z0-9_]*)(?:\[([^\]]*)\])?\s*:\s*(.+)$/;
21
+ const V1_CHAR_RE = /^([A-Z][A-Z0-9_]*)\s*:\s*([a-z][a-z0-9_-]*)\s*$/;
22
+ const HEADERS = ['@characters', '@sounds', '@tracks', '@include'];
23
+ /** Parse a `.conv` script. */
24
+ function parse(text, options = {}) {
25
+ const reg = (0, plugin_1.buildRegistry)(options.plugins ?? plugins_1.defaultPlugins);
26
+ const stack = options.source ? [options.source] : [];
27
+ return parseWith(text, options, reg, false, stack);
28
+ }
29
+ function loadIncludes(lines, options, reg, stack) {
30
+ const inc = { sounds: {}, tracks: {}, origin: new Map(), problems: [], clashes: [] };
31
+ const resolver = options.include;
32
+ const banks = () => resolver?.list?.() ?? [];
33
+ for (let i = 0; i < lines.length; i++) {
34
+ const s = lines[i].trim();
35
+ if (s === '---')
36
+ break;
37
+ const m = INCLUDE_RE.exec(s);
38
+ if (!m)
39
+ continue;
40
+ const problem = (message) => inc.problems.push({ line: i + 1, text: s, message });
41
+ const ref = m[1].trim();
42
+ if (!ref) {
43
+ const list = banks();
44
+ problem('`@include` needs a bank, e.g. `@include podcast`' +
45
+ (list.length ? `\nBanks: ${list.join(', ')}` : ''));
46
+ continue;
47
+ }
48
+ if (!resolver) {
49
+ problem(`can't include \`${ref}\` — this parser was given no include resolver`);
50
+ continue;
51
+ }
52
+ const res = resolver.resolve(ref, stack[stack.length - 1]);
53
+ if ('tried' in res) {
54
+ const list = banks();
55
+ problem(`can't find \`${ref}\` — looked for ${res.tried.join(', ')}` +
56
+ (0, suggest_1.didYouMean)(ref, list) +
57
+ (list.length ? `\nBanks: ${list.join(', ')}` : ''));
58
+ continue;
59
+ }
60
+ if (stack.includes(res.id)) {
61
+ problem(`\`@include ${ref}\` goes round in a circle: ${[...stack, res.id].join(' -> ')}`);
62
+ continue;
63
+ }
64
+ let bank;
65
+ try {
66
+ bank = parseWith(res.text, { ...options, source: res.id, strict: true }, reg, true, [
67
+ ...stack,
68
+ res.id,
69
+ ]);
70
+ }
71
+ catch (e) {
72
+ if (!(e instanceof errors_1.ConvError))
73
+ throw e;
74
+ const detail = e.problems
75
+ .map((p) => `line ${p.line}: ` + p.message.replace(/\n/g, '\n '))
76
+ .join('\n');
77
+ problem(`\`${ref}\` (${res.id}) has problems — fix them there:\n${detail}`);
78
+ continue;
79
+ }
80
+ const merge = (kind, got, into) => {
81
+ for (const [name, cfg] of Object.entries(got)) {
82
+ const prior = inc.origin.get(`${kind}:${name}`);
83
+ if (prior) {
84
+ inc.clashes.push({
85
+ kind,
86
+ name,
87
+ problem: {
88
+ line: i + 1,
89
+ text: s,
90
+ message: `${kind} \`${name}\` comes from both \`${prior.ref}\` and \`${ref}\` — which one ` +
91
+ `is meant is ambiguous.\nDeclare \`${name}\` in this script to choose, or include ` +
92
+ 'only one of them.',
93
+ },
94
+ });
95
+ continue;
96
+ }
97
+ into[name] = { ...cfg };
98
+ inc.origin.set(`${kind}:${name}`, { ref, line: i + 1 });
99
+ }
100
+ };
101
+ merge('sound', bank.sounds, inc.sounds);
102
+ merge('track', bank.tracks, inc.tracks);
103
+ }
104
+ return inc;
105
+ }
106
+ function hintFor(s, mode) {
107
+ let m = /^pause\s+([\d.]+)$/i.exec(s);
108
+ if (m)
109
+ return `pauses go in brackets: \`[pause ${m[1]}]\` (this is the old v1 form)`;
110
+ m = /^([A-Za-z][\w-]*)\s*:\s*\{/.exec(s);
111
+ if (m && m[1] !== m[1].toUpperCase()) {
112
+ return mode === 'tracks'
113
+ ? `track names are lowercase: \`${m[1].toLowerCase()}: { … }\``
114
+ : `names are UPPERCASE: \`${m[1].toUpperCase()}: { … }\``;
115
+ }
116
+ m = /^([A-Za-z][\w-]*)(\[[^\]]*\])?\s*:\s*(.+)$/.exec(s);
117
+ if (m) {
118
+ const name = m[1];
119
+ if (name.includes('-')) {
120
+ return `speaker names use letters, digits and _ — not -: \`${name.replace(/-/g, '_').toUpperCase()}: …\``;
121
+ }
122
+ if (name !== name.toUpperCase()) {
123
+ return `speaker names are UPPERCASE: \`${name.toUpperCase()}${m[2] ?? ''}: ${m[3].slice(0, 30)}…\``;
124
+ }
125
+ }
126
+ m = /^\[([A-Za-z][\w-]*)/.exec(s);
127
+ if (m) {
128
+ return (`\`[${m[1]} …]\` — sound names are UPPERCASE (\`[${m[1].toUpperCase()}]\`), ` +
129
+ `track directives lowercase (\`[${m[1].toLowerCase()} SOUND]\`)`);
130
+ }
131
+ if (mode === 'tracks')
132
+ return 'inside @tracks every line is `name: { key: value, … }`';
133
+ return ('expected one of: `NAME: text`, `NAME[emotion]: text`, `[pause N]`, `[SOUND]`, ' +
134
+ '`[track SOUND]`, `# comment`, or a header (@characters, @sounds, @tracks, ---)');
135
+ }
136
+ function parseWith(text, options, reg, fragment, stack) {
137
+ const lines = text.split(/\r?\n/);
138
+ const characters = {};
139
+ const sounds = {};
140
+ const tracks = {};
141
+ const items = [];
142
+ const problems = [];
143
+ const refs = [];
144
+ const index = { character: {}, sound: {}, track: {}, speaker: {}, file: {} };
145
+ const declare = (kind, name, d, keepFirst = false) => {
146
+ if (!(keepFirst && index[kind][name]))
147
+ index[kind][name] = d;
148
+ };
149
+ const inc = loadIncludes(lines, options, reg, stack);
150
+ Object.assign(sounds, inc.sounds);
151
+ Object.assign(tracks, inc.tracks);
152
+ problems.push(...inc.problems);
153
+ for (const [key, o] of inc.origin) {
154
+ const [kind, name] = key.split(/:(.*)/s);
155
+ declare(kind, name, { line: o.line, include: o.ref });
156
+ }
157
+ // first pass: track names, so anything above @tracks can already name one
158
+ {
159
+ let m = null;
160
+ for (const raw of lines) {
161
+ const s = raw.trim();
162
+ if (s === '@tracks')
163
+ m = 'tracks';
164
+ else if (s.startsWith('@') || s === '---')
165
+ m = null;
166
+ else if (m === 'tracks') {
167
+ const tm = /^([a-z][a-z0-9_-]*)\s*:\s*\{/.exec(s);
168
+ if (tm && !reg.reserved.has(tm[1]) && !(tm[1] in tracks))
169
+ tracks[tm[1]] = null;
170
+ }
171
+ }
172
+ }
173
+ const allTracks = () => new Set([...reg.tracks, ...Object.keys(tracks)]);
174
+ const knownTrack = (n) => reg.tracks.includes(n) || n in tracks;
175
+ const opts = (what, context) => ({
176
+ reg,
177
+ tracks: allTracks(),
178
+ what,
179
+ context,
180
+ });
181
+ let mode = null;
182
+ let bodyStarted = false;
183
+ for (let i = 0; i < lines.length; i++) {
184
+ const lineno = i + 1;
185
+ const s = lines[i].trim();
186
+ const errs = [];
187
+ const flush = () => {
188
+ for (const message of errs)
189
+ problems.push({ line: lineno, text: s, message });
190
+ };
191
+ const problem = (message) => problems.push({ line: lineno, text: s, message });
192
+ if (!s || s.startsWith('#'))
193
+ continue;
194
+ if (INCLUDE_RE.test(s)) {
195
+ if (mode === 'body' || bodyStarted)
196
+ problem('`@include` belongs in the header, above `---`');
197
+ continue;
198
+ }
199
+ if (fragment && (s === '@characters' || s === '@voices' || s === '---')) {
200
+ problem('a sound bank holds only @sounds and @tracks (and @include) — characters and the ' +
201
+ 'script belong in the .conv');
202
+ mode = 'rejected';
203
+ continue;
204
+ }
205
+ if (s === '@characters' || s === '@voices') {
206
+ mode = 'chars';
207
+ continue;
208
+ }
209
+ if (s === '@sounds') {
210
+ mode = 'sounds';
211
+ continue;
212
+ }
213
+ if (s === '@tracks') {
214
+ mode = 'tracks';
215
+ continue;
216
+ }
217
+ if (s === '---') {
218
+ mode = 'body';
219
+ continue;
220
+ }
221
+ if (s.startsWith('@')) {
222
+ problem(`unknown header \`${s}\` — headers are @characters, @sounds, @tracks and @include` +
223
+ (0, suggest_1.didYouMean)(s, HEADERS));
224
+ continue;
225
+ }
226
+ if (fragment && mode !== 'sounds' && mode !== 'tracks') {
227
+ if (mode !== 'rejected') {
228
+ problem('a sound bank holds only @sounds and @tracks — put this line under one of those headers');
229
+ }
230
+ continue;
231
+ }
232
+ let m = PAUSE_RE.exec(s);
233
+ if (m) {
234
+ items.push({ type: 'pause', line: lineno, seconds: Number(m[1]) });
235
+ bodyStarted = true;
236
+ continue;
237
+ }
238
+ if (/^\[pause\b/i.test(s)) {
239
+ problem('`[pause N]` needs seconds, e.g. `[pause 1.5]`');
240
+ continue;
241
+ }
242
+ if (mode === 'tracks') {
243
+ m = TRACK_DECL_RE.exec(s);
244
+ if (m && reg.reserved.has(m[1])) {
245
+ problem(`\`${m[1]}\` is a reserved word and can't name a track — pick another name`);
246
+ continue;
247
+ }
248
+ if (m) {
249
+ const pairs = (0, values_1.readConfig)(m[2], errs);
250
+ tracks[m[1]] = (0, values_1.check)(pairs, reg.schemas.track, opts(`track \`${m[1]}\``), errs);
251
+ declare('track', m[1], { line: lineno });
252
+ flush();
253
+ continue;
254
+ }
255
+ }
256
+ m = LEGACY_MUSIC_RE.exec(s);
257
+ if (m) {
258
+ const overrides = (0, values_1.check)((0, values_1.readPlay)(m[2]), reg.schemas.play, opts('`[music: …]`'), errs);
259
+ items.push({
260
+ type: 'track',
261
+ line: lineno,
262
+ track: 'music',
263
+ action: 'play',
264
+ sound: null,
265
+ file: m[1],
266
+ overrides,
267
+ });
268
+ declare('file', m[1], { line: lineno }, true);
269
+ flush();
270
+ continue;
271
+ }
272
+ m = DIRECTIVE_RE.exec(s);
273
+ const directive = m && reg.directives.get(m[1]);
274
+ if (m && directive) {
275
+ const data = directive((m[2] ?? '').trim(), {
276
+ error: (msg) => errs.push(msg),
277
+ suggest: (w, o) => (0, suggest_1.didYouMean)(w, o),
278
+ });
279
+ if (!errs.length)
280
+ items.push({ type: 'mark', line: lineno, kind: m[1], data: data || {} });
281
+ bodyStarted = true;
282
+ flush();
283
+ continue;
284
+ }
285
+ if (m && !reg.reserved.has(m[1])) {
286
+ const name = m[1];
287
+ if (!knownTrack(name)) {
288
+ const upper = name.toUpperCase();
289
+ problem(`unknown track \`${name}\`` +
290
+ (upper in sounds
291
+ ? ` — sound names are UPPERCASE: \`[${upper}${m[2] ? ' ' + m[2] : ''}]\``
292
+ : (0, suggest_1.didYouMean)(name, allTracks())) +
293
+ `\nBuilt-in tracks: ${reg.tracks.join(', ')}. Declare others under @tracks, ` +
294
+ `e.g. \`${name}: { level: -24 }\``);
295
+ continue;
296
+ }
297
+ items.push(trackDirective(name, m[2] ?? '', lineno, s, errs));
298
+ flush();
299
+ continue;
300
+ }
301
+ if (mode === 'sounds') {
302
+ m = SOUND_DECL_RE.exec(s);
303
+ if (m) {
304
+ const cfg = (0, values_1.check)((0, values_1.readConfig)(m[2], errs), reg.schemas.sound, opts(`sound \`${m[1]}\``), errs);
305
+ if (!cfg.prompt && !cfg.file) {
306
+ errs.push(`sound \`${m[1]}\` needs a source: \`file: path/to.mp3\` or \`prompt: "what it sounds like"\``);
307
+ }
308
+ else if (cfg.prompt && cfg.file) {
309
+ errs.push(`sound \`${m[1]}\` has both \`file:\` and \`prompt:\` — keep one`);
310
+ }
311
+ sounds[m[1]] = cfg;
312
+ declare('sound', m[1], { line: lineno });
313
+ flush();
314
+ continue;
315
+ }
316
+ }
317
+ if (mode !== 'body') {
318
+ m = CHAR_DECL_RE.exec(s);
319
+ if (m) {
320
+ const cfg = (0, values_1.check)((0, values_1.readConfig)(m[2], errs), reg.schemas.character, opts(`character \`${m[1]}\``), errs);
321
+ const alias = cfg.voice ?? cfg.speaker;
322
+ if (alias && !cfg.persona)
323
+ cfg.persona = String(alias).toLowerCase();
324
+ characters[m[1]] = cfg;
325
+ declare('character', m[1], { line: lineno });
326
+ mode = 'chars';
327
+ flush();
328
+ continue;
329
+ }
330
+ }
331
+ if (mode === 'chars' && !bodyStarted) {
332
+ m = V1_CHAR_RE.exec(s);
333
+ if (m) {
334
+ problem(`character definitions need braces: \`${m[1]}: { persona: ${m[2]} }\` ` +
335
+ `(\`${m[1]}: ${m[2]}\` is the old v1 form)`);
336
+ continue;
337
+ }
338
+ }
339
+ m = CUE_RE.exec(s);
340
+ if (m) {
341
+ const overrides = (0, values_1.check)((0, values_1.readPlay)(m[2] ?? ''), reg.schemas.play, opts(`[${m[1]}]`), errs);
342
+ refs.push({ line: lineno, text: s, sound: m[1] });
343
+ items.push({ type: 'cue', line: lineno, sound: m[1], track: 'foreground', overrides });
344
+ flush();
345
+ continue;
346
+ }
347
+ m = LINE_RE.exec(s);
348
+ if (m) {
349
+ mode = 'body';
350
+ bodyStarted = true;
351
+ const lineText = m[3].trim();
352
+ const overrides = (0, values_1.check)((0, values_1.readOverrides)(m[2] ?? '', errs), reg.schemas.line, opts(`\`${m[1]}[…]\``, 'line'), errs);
353
+ const segments = (0, segments_1.splitSegments)(lineText).map((seg) => {
354
+ if (seg.type === 'break')
355
+ return { type: 'break', seconds: seg.seconds };
356
+ if (seg.type === 'sfx') {
357
+ refs.push({ line: lineno, text: s, sound: seg.sound });
358
+ return {
359
+ type: 'sfx',
360
+ sound: seg.sound,
361
+ overrides: (0, values_1.check)((0, values_1.readPlay)(seg.raw), reg.schemas.play, opts(`<sfx ${seg.sound}>`), errs),
362
+ };
363
+ }
364
+ const ov = seg.raw
365
+ ? (0, values_1.check)((0, values_1.readOverrides)(seg.raw, errs), reg.schemas.span, opts('an inline `{…: …}` span', 'span'), errs)
366
+ : {};
367
+ return { type: 'text', text: seg.text, overrides: ov };
368
+ });
369
+ items.push({ type: 'line', line: lineno, speaker: m[1], text: lineText, overrides, segments });
370
+ declare('speaker', m[1], { line: lineno }, true);
371
+ flush();
372
+ continue;
373
+ }
374
+ problem(hintFor(s, mode));
375
+ }
376
+ /** `[music BED fade-in:3]`, `[music off]`, `[music vol:0.5 ramp:2]` */
377
+ function trackDirective(name, rest, lineno, s, errs) {
378
+ let tokens = rest
379
+ .trim()
380
+ .split(/[,\s]+/)
381
+ .filter(Boolean);
382
+ let sound = null;
383
+ let action = 'set';
384
+ if (tokens.length && ['off', 'none', 'stop'].includes(tokens[0].toLowerCase())) {
385
+ action = 'off';
386
+ tokens = tokens.slice(1);
387
+ if (tokens.length && SOUND_NAME_RE.test(tokens[0]))
388
+ [sound, ...tokens] = tokens;
389
+ }
390
+ else if (tokens.length && SOUND_NAME_RE.test(tokens[0])) {
391
+ action = 'play';
392
+ [sound, ...tokens] = tokens;
393
+ }
394
+ const pairs = (0, values_1.readPlay)(tokens.join(','));
395
+ let schema;
396
+ if (action === 'play')
397
+ schema = reg.schemas.play;
398
+ else if (action === 'off')
399
+ schema = reg.schemas.off;
400
+ else if (!bodyStarted)
401
+ schema = { ...reg.schemas.track, ...reg.schemas.set };
402
+ else
403
+ schema = reg.schemas.set;
404
+ if (action === 'set') {
405
+ if (!pairs.length) {
406
+ errs.push(`\`[${name}]\` does nothing — play a sound (\`[${name} SOUND]\`), stop (\`[${name} off]\`), ` +
407
+ `or set something (\`[${name} vol:0.5]\`)`);
408
+ }
409
+ else if (bodyStarted) {
410
+ const extra = pairs.filter((p) => !(p.key in schema));
411
+ if (extra.length && extra.every((p) => p.key in reg.schemas.track)) {
412
+ const e = extra[0];
413
+ errs.push(`\`${extra.map((p) => (0, schema_1.shown)(p.key)).join(', ')}\` can't change mid-scene — only \`vol\` ` +
414
+ `(with \`ramp\`) moves over time.\nPut it on the track instead: under @tracks, ` +
415
+ `\`${name}: { ${(0, schema_1.shown)(e.key)}: ${e.value} }\``);
416
+ return { type: 'track', line: lineno, track: name, action, sound, overrides: {} };
417
+ }
418
+ }
419
+ }
420
+ const what = action === 'play' ? `a [${name} …] play` : action === 'off' ? `[${name} off]` : `[${name} …]`;
421
+ const overrides = (0, values_1.check)(pairs, schema, opts(what), errs);
422
+ const item = { type: 'track', line: lineno, track: name, action, sound, overrides };
423
+ for (const rule of reg.trackRules.get(name) ?? [])
424
+ rule(item, { error: (msg) => errs.push(msg) });
425
+ if (sound)
426
+ refs.push({ line: lineno, text: s, sound });
427
+ return item;
428
+ }
429
+ // two banks defining one name is an error unless the script settles it
430
+ for (const c of inc.clashes) {
431
+ if (index[c.kind][c.name]?.include !== undefined)
432
+ problems.push(c.problem);
433
+ }
434
+ for (const r of refs) {
435
+ if (!(r.sound in sounds)) {
436
+ problems.push({
437
+ line: r.line,
438
+ text: r.text,
439
+ message: `sound \`${r.sound}\` isn't declared under @sounds` +
440
+ (0, suggest_1.didYouMean)(r.sound, Object.keys(sounds)) +
441
+ `\nAdd it, e.g. \`${r.sound}: { file: sounds/${r.sound.toLowerCase()}.wav }\` ` +
442
+ `or \`${r.sound}: { prompt: "…", duration: 3 }\``,
443
+ });
444
+ }
445
+ }
446
+ // a bare [CUE] plays on the track its sound names, else on foreground
447
+ for (const it of items) {
448
+ if (it.type !== 'cue')
449
+ continue;
450
+ const cfg = sounds[it.sound] ?? {};
451
+ const lay = (cfg.track ?? cfg.layer);
452
+ if (lay && knownTrack(lay))
453
+ it.track = lay;
454
+ }
455
+ const scene = {
456
+ characters,
457
+ sounds,
458
+ tracks: Object.fromEntries(Object.entries(tracks).map(([k, v]) => [k, v ?? {}])),
459
+ items,
460
+ problems,
461
+ index,
462
+ };
463
+ for (const finalize of reg.finalizers) {
464
+ finalize(scene, {
465
+ problem: (item, message) => problems.push({ line: item.line, text: lines[item.line - 1]?.trim() ?? null, message }),
466
+ });
467
+ }
468
+ if (problems.length && options.strict !== false)
469
+ throw new errors_1.ConvError(problems, options.source);
470
+ scene.problems = new errors_1.ConvError(problems).problems;
471
+ return scene;
472
+ }
package/plugin.d.ts ADDED
@@ -0,0 +1,52 @@
1
+ import { KeyContext, KeySpec, Schema } from './schema';
2
+ import { Item, Scene, TrackItem } from './types';
3
+ export interface DirectiveContext {
4
+ /** report a problem on this line; the directive produces no item */
5
+ error(message: string): void;
6
+ /** `. Did you mean `x`?` when something in `options` is close, else '' */
7
+ suggest(word: string, options: Iterable<string>): string;
8
+ }
9
+ /**
10
+ * Handles `[name args]` in the script body. Return the mark's data, or nothing
11
+ * after reporting an error. The item is `{ type: 'mark', kind: name, data }`.
12
+ */
13
+ export type Directive = (args: string, ctx: DirectiveContext) => Record<string, unknown> | void;
14
+ export interface TrackRuleContext {
15
+ error(message: string): void;
16
+ }
17
+ /** Validates (and may adjust) a directive on one named track. */
18
+ export type TrackRule = (item: TrackItem, ctx: TrackRuleContext) => void;
19
+ export interface FinalizeContext {
20
+ /** report a problem against an item's line */
21
+ problem(item: Item, message: string): void;
22
+ }
23
+ export interface ConvPlugin {
24
+ name: string;
25
+ /** keys accepted per context, merged over the core keys */
26
+ keys?: Partial<Record<KeyContext, Schema>>;
27
+ /** named enums; plugins naming the same enum add to its values */
28
+ enums?: Record<string, string[]>;
29
+ /** tracks every scene has without declaring them */
30
+ tracks?: string[];
31
+ /** lowercase words that can't name a track (directive names are added automatically) */
32
+ reserved?: string[];
33
+ /** `[name …]` body directives */
34
+ directives?: Record<string, Directive>;
35
+ /** extra validation for directives on a named track */
36
+ trackRules?: Record<string, TrackRule>;
37
+ /** a pass over the finished scene, before problems are reported */
38
+ finalize?(scene: Scene, ctx: FinalizeContext): void;
39
+ }
40
+ export interface Registry {
41
+ schemas: Record<KeyContext, Schema>;
42
+ enums: Record<string, string[]>;
43
+ tracks: string[];
44
+ reserved: Set<string>;
45
+ directives: Map<string, Directive>;
46
+ trackRules: Map<string, TrackRule[]>;
47
+ finalizers: Array<NonNullable<ConvPlugin['finalize']>>;
48
+ }
49
+ export declare function buildRegistry(plugins: ConvPlugin[]): Registry;
50
+ export declare function enumValues(reg: Registry, spec: KeySpec & {
51
+ kind: 'enum';
52
+ }): string[];
package/plugin.js ADDED
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildRegistry = buildRegistry;
4
+ exports.enumValues = enumValues;
5
+ const schema_1 = require("./schema");
6
+ function buildRegistry(plugins) {
7
+ const schemas = {};
8
+ for (const ctx of schema_1.KEY_CONTEXTS)
9
+ schemas[ctx] = { ...schema_1.CORE_SCHEMAS[ctx] };
10
+ const reg = {
11
+ schemas,
12
+ enums: {},
13
+ tracks: [...schema_1.CORE_TRACKS],
14
+ reserved: new Set(schema_1.CORE_RESERVED),
15
+ directives: new Map(),
16
+ trackRules: new Map(),
17
+ finalizers: [],
18
+ };
19
+ const owner = new Map();
20
+ for (const p of plugins) {
21
+ for (const [ctx, keys] of Object.entries(p.keys ?? {})) {
22
+ Object.assign(reg.schemas[ctx], keys);
23
+ }
24
+ for (const [name, values] of Object.entries(p.enums ?? {})) {
25
+ const have = reg.enums[name] ?? [];
26
+ reg.enums[name] = [...have, ...values.filter((v) => !have.includes(v))];
27
+ }
28
+ for (const t of p.tracks ?? [])
29
+ if (!reg.tracks.includes(t))
30
+ reg.tracks.push(t);
31
+ for (const r of p.reserved ?? [])
32
+ reg.reserved.add(r);
33
+ for (const [name, fn] of Object.entries(p.directives ?? {})) {
34
+ if (reg.directives.has(name)) {
35
+ throw new Error(`conv plugins "${owner.get(name)}" and "${p.name}" both define the [${name}] directive`);
36
+ }
37
+ if (reg.tracks.includes(name)) {
38
+ throw new Error(`conv plugin "${p.name}": [${name}] is already a track`);
39
+ }
40
+ reg.directives.set(name, fn);
41
+ reg.reserved.add(name);
42
+ owner.set(name, p.name);
43
+ }
44
+ for (const [name, rule] of Object.entries(p.trackRules ?? {})) {
45
+ reg.trackRules.set(name, [...(reg.trackRules.get(name) ?? []), rule]);
46
+ }
47
+ if (p.finalize)
48
+ reg.finalizers.push(p.finalize.bind(p));
49
+ }
50
+ return reg;
51
+ }
52
+ function enumValues(reg, spec) {
53
+ return Array.isArray(spec.values) ? spec.values : (reg.enums[spec.values.named] ?? []);
54
+ }
@@ -0,0 +1,7 @@
1
+ import { ConvPlugin } from '../plugin';
2
+ export interface EffectsOptions {
3
+ /** reverb preset names a renderer offers (default: room, hall, cathedral, plate) */
4
+ reverbPresets?: string[];
5
+ }
6
+ /** Per-character, per-line, per-span and per-track effect keys. */
7
+ export declare function effects(options?: EffectsOptions): ConvPlugin;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.effects = effects;
4
+ const schema_1 = require("../schema");
5
+ /** Per-character, per-line, per-span and per-track effect keys. */
6
+ function effects(options = {}) {
7
+ const keys = {
8
+ reverb: (0, schema_1.named)('reverb'),
9
+ reverb_mix: (0, schema_1.num)(0, 1),
10
+ delay: (0, schema_1.num)(0.01, 5),
11
+ delay_feedback: (0, schema_1.num)(0, 0.95),
12
+ delay_mix: (0, schema_1.num)(0, 1),
13
+ compress: (0, schema_1.bool)(),
14
+ };
15
+ return {
16
+ name: 'effects',
17
+ enums: { reverb: options.reverbPresets ?? ['room', 'hall', 'cathedral', 'plate'] },
18
+ keys: { character: keys, line: keys, span: keys, track: keys },
19
+ };
20
+ }
@@ -0,0 +1,7 @@
1
+ import { ConvPlugin } from '../plugin';
2
+ export { effects, EffectsOptions } from './effects';
3
+ export { slides } from './slides';
4
+ export { SPEAKER_WIDGETS, speakers } from './speakers';
5
+ export { video } from './video';
6
+ /** The plugins `parse` uses when none are given. */
7
+ export declare const defaultPlugins: ConvPlugin[];
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultPlugins = exports.video = exports.speakers = exports.SPEAKER_WIDGETS = exports.slides = exports.effects = void 0;
4
+ const effects_1 = require("./effects");
5
+ const slides_1 = require("./slides");
6
+ const speakers_1 = require("./speakers");
7
+ const video_1 = require("./video");
8
+ var effects_2 = require("./effects");
9
+ Object.defineProperty(exports, "effects", { enumerable: true, get: function () { return effects_2.effects; } });
10
+ var slides_2 = require("./slides");
11
+ Object.defineProperty(exports, "slides", { enumerable: true, get: function () { return slides_2.slides; } });
12
+ var speakers_2 = require("./speakers");
13
+ Object.defineProperty(exports, "SPEAKER_WIDGETS", { enumerable: true, get: function () { return speakers_2.SPEAKER_WIDGETS; } });
14
+ Object.defineProperty(exports, "speakers", { enumerable: true, get: function () { return speakers_2.speakers; } });
15
+ var video_2 = require("./video");
16
+ Object.defineProperty(exports, "video", { enumerable: true, get: function () { return video_2.video; } });
17
+ /** The plugins `parse` uses when none are given. */
18
+ exports.defaultPlugins = [(0, effects_1.effects)(), (0, slides_1.slides)(), (0, speakers_1.speakers)(), (0, video_1.video)()];
@@ -0,0 +1,6 @@
1
+ import { ConvPlugin } from '../plugin';
2
+ /**
3
+ * `[slide ID]` / `[slide ID step:N]` — a deck shows slide ID (and its Nth build)
4
+ * from this point. Silent and timeless: a renderer records when it falls.
5
+ */
6
+ export declare function slides(): ConvPlugin;