@rohal12/spindle 0.60.3 → 0.61.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/README.md +1 -1
- package/dist/pkg/format.js +1 -1
- package/dist/pkg/headless.js +18671 -18510
- package/dist/pkg/play-worker.js +181 -0
- package/dist/pkg/play.js +398 -0
- package/dist/pkg/story-variables.js +11016 -153
- package/package.json +19 -1
- package/src/action-registry.ts +43 -3
- package/src/components/PassageDialog.tsx +29 -27
- package/src/components/dialog-close-context.ts +5 -1
- package/src/components/macros/Button.tsx +3 -3
- package/src/components/macros/Checkbox.tsx +3 -2
- package/src/components/macros/Cycle.tsx +3 -4
- package/src/components/macros/Dialog.tsx +3 -3
- package/src/components/macros/Listbox.tsx +3 -4
- package/src/components/macros/MacroLink.tsx +3 -3
- package/src/components/macros/MenubarButtons.tsx +3 -3
- package/src/components/macros/PassageDisplay.tsx +14 -9
- package/src/components/macros/Radiobutton.tsx +3 -2
- package/src/components/macros/detached-body.tsx +1 -4
- package/src/components/macros/input-macro.ts +10 -8
- package/src/define-macro.ts +0 -4
- package/src/execute-mutation.ts +10 -6
- package/src/format/fenced-code.ts +59 -0
- package/src/format/format-passage.ts +100 -11
- package/src/headless.ts +25 -1
- package/src/hooks/use-action.ts +44 -4
- package/src/hooks/use-modal-focus.ts +1 -30
- package/src/markup/ast.ts +4 -3
- package/src/markup/pair.ts +22 -9
- package/src/markup/parse.ts +2 -0
- package/src/markup/validate.ts +5 -3
- package/src/observe/observable-text.ts +6 -24
- package/src/observe/observe.ts +4 -1
- package/src/play/index.ts +15 -0
- package/src/play/optional.ts +41 -0
- package/src/play/protocol.ts +35 -0
- package/src/play/resolve-story.ts +265 -0
- package/src/play/session.ts +253 -0
- package/src/play/worker.ts +169 -0
- package/src/registry.ts +36 -1
- package/src/runtime-errors.ts +5 -0
- package/src/saves/save-manager.ts +48 -7
- package/src/saves/storage.ts +3 -1
- package/src/saves/types.ts +1 -0
- package/src/store.ts +13 -6
- package/src/story-init.ts +6 -1
- package/src/structural.ts +126 -66
- package/src/tooling.ts +2 -0
- package/src/types-drift-check.ts +55 -0
- package/src/utils/element-visibility.ts +61 -0
- package/types/headless.d.ts +14 -0
- package/types/index.d.ts +2 -0
- package/types/play.d.ts +83 -0
- package/types/tooling.d.ts +2 -0
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
2
|
+
//#region src/utils/error-message.ts
|
|
3
|
+
/**
|
|
4
|
+
* The message to show for a caught value. Anything can be thrown, not only
|
|
5
|
+
* Errors: an Error gives its message, a string is its own message, and any
|
|
6
|
+
* other value gives `fallback` when one is passed, else its string form
|
|
7
|
+
* (never `undefined`). An empty message also gives `fallback`, or for an
|
|
8
|
+
* Error its string form (e.g. "Error").
|
|
9
|
+
*/
|
|
10
|
+
function errorMessage(err, fallback) {
|
|
11
|
+
try {
|
|
12
|
+
if (err instanceof Error) return err.message || fallback || String(err);
|
|
13
|
+
if (typeof err === "string" && err !== "") return err;
|
|
14
|
+
return fallback ?? String(err);
|
|
15
|
+
} catch {
|
|
16
|
+
return fallback ?? "Unprintable error";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region src/play/optional.ts
|
|
21
|
+
var defaultImporter = (pkg) => import(pkg);
|
|
22
|
+
function isMissingPackage(err, pkg) {
|
|
23
|
+
return err instanceof Error && err.code === "ERR_MODULE_NOT_FOUND" && err.message.includes(`'${pkg}'`);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Import `pkg`, rejecting with an install hint when it isn't installed. Any
|
|
27
|
+
* other import error (a failure inside the package, a different missing
|
|
28
|
+
* module) is rethrown unchanged.
|
|
29
|
+
*/
|
|
30
|
+
async function loadOptional(pkg, feature, importer = defaultImporter) {
|
|
31
|
+
try {
|
|
32
|
+
return await importer(pkg);
|
|
33
|
+
} catch (err) {
|
|
34
|
+
if (isMissingPackage(err, pkg)) throw new Error(`spindle: ${feature} needs ${pkg}; install it with npm i -D ${pkg}`);
|
|
35
|
+
throw err;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
//#endregion
|
|
39
|
+
//#region src/play/worker.ts
|
|
40
|
+
/**
|
|
41
|
+
* The worker thread of a play session: boots the story on happy-dom and
|
|
42
|
+
* answers the session handle's calls (see `protocol.ts`). Built to
|
|
43
|
+
* `dist/pkg/play-worker.js`.
|
|
44
|
+
*/
|
|
45
|
+
var stderr = process.stderr;
|
|
46
|
+
Object.defineProperty(process, "stdout", {
|
|
47
|
+
configurable: true,
|
|
48
|
+
get: () => stderr
|
|
49
|
+
});
|
|
50
|
+
var port = parentPort;
|
|
51
|
+
var data = workerData;
|
|
52
|
+
/** Make happy-dom's window the global environment Spindle runs in. */
|
|
53
|
+
async function installDom() {
|
|
54
|
+
const { Window } = await loadOptional("happy-dom", "play sessions");
|
|
55
|
+
const window = new Window({ url: "http://localhost/" });
|
|
56
|
+
const global = globalThis;
|
|
57
|
+
const source = window;
|
|
58
|
+
global.window = window;
|
|
59
|
+
global.document = window.document;
|
|
60
|
+
for (const name of Object.getOwnPropertyNames(window)) if (!(name in globalThis)) global[name] = source[name];
|
|
61
|
+
for (const name of HAPPY_DOM_GLOBALS) Object.defineProperty(globalThis, name, {
|
|
62
|
+
configurable: true,
|
|
63
|
+
writable: true,
|
|
64
|
+
value: source[name]
|
|
65
|
+
});
|
|
66
|
+
Object.defineProperty(globalThis, "BroadcastChannel", {
|
|
67
|
+
configurable: true,
|
|
68
|
+
writable: true,
|
|
69
|
+
value: void 0
|
|
70
|
+
});
|
|
71
|
+
Object.defineProperty(globalThis, "Story", {
|
|
72
|
+
configurable: true,
|
|
73
|
+
get: () => source.Story
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Globals happy-dom's window replaces even where Node has its own:
|
|
78
|
+
* - the event classes: happy-dom's dispatchEvent() refuses events made with
|
|
79
|
+
* Node's (`new CustomEvent(':storyready')` at boot);
|
|
80
|
+
* - the storages: Node 25+ has a `localStorage` that is undefined without
|
|
81
|
+
* `--localstorage-file`, and Node's would be shared by every session;
|
|
82
|
+
* - `navigator`: Node's `navigator.locks` is shared by every worker in the
|
|
83
|
+
* process.
|
|
84
|
+
*/
|
|
85
|
+
var HAPPY_DOM_GLOBALS = [
|
|
86
|
+
"Event",
|
|
87
|
+
"CustomEvent",
|
|
88
|
+
"EventTarget",
|
|
89
|
+
"localStorage",
|
|
90
|
+
"sessionStorage",
|
|
91
|
+
"navigator"
|
|
92
|
+
];
|
|
93
|
+
/**
|
|
94
|
+
* A value as the reply will carry it (structured clone keeps Map, Set, Date
|
|
95
|
+
* and cycles), or a marker when it cannot be cloned (a function, a Map
|
|
96
|
+
* holding one).
|
|
97
|
+
*/
|
|
98
|
+
function encode(value) {
|
|
99
|
+
try {
|
|
100
|
+
return structuredClone(value);
|
|
101
|
+
} catch (err) {
|
|
102
|
+
return `[unserializable: ${errorMessage(err)}]`;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function encodeAll(values) {
|
|
106
|
+
const out = {};
|
|
107
|
+
for (const [name, value] of Object.entries(values)) out[name] = encode(value);
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
async function start() {
|
|
111
|
+
await installDom();
|
|
112
|
+
const headless = await import(
|
|
113
|
+
/* @vite-ignore */
|
|
114
|
+
data.headlessUrl
|
|
115
|
+
);
|
|
116
|
+
const story = await headless.bootStory({
|
|
117
|
+
html: data.html,
|
|
118
|
+
transitions: data.transitions
|
|
119
|
+
});
|
|
120
|
+
const transcript = headless.createTranscript(story, data.transcript);
|
|
121
|
+
const ops = {
|
|
122
|
+
observe: () => story.observe(),
|
|
123
|
+
step: ([id, value]) => transcript.step(id, value),
|
|
124
|
+
goto: async ([passage]) => {
|
|
125
|
+
const name = passage;
|
|
126
|
+
const refused = headless.gotoError(name);
|
|
127
|
+
if (refused !== null) throw new Error(`spindle: ${refused}`);
|
|
128
|
+
story.goto(name);
|
|
129
|
+
await story.waitForActions();
|
|
130
|
+
return story.observe();
|
|
131
|
+
},
|
|
132
|
+
get: ([names]) => {
|
|
133
|
+
if (names === void 0) return encodeAll(headless.storyVariables());
|
|
134
|
+
const values = {};
|
|
135
|
+
for (const name of names) {
|
|
136
|
+
const key = name.replace(/^\$/, "");
|
|
137
|
+
values[key] = story.get(key);
|
|
138
|
+
}
|
|
139
|
+
return encodeAll(values);
|
|
140
|
+
},
|
|
141
|
+
set: async ([values]) => {
|
|
142
|
+
story.set(values);
|
|
143
|
+
await story.waitForActions();
|
|
144
|
+
},
|
|
145
|
+
transcript: () => [...transcript.entries]
|
|
146
|
+
};
|
|
147
|
+
port.on("message", async ({ id, op, args }) => {
|
|
148
|
+
let reply;
|
|
149
|
+
try {
|
|
150
|
+
reply = {
|
|
151
|
+
id,
|
|
152
|
+
ok: true,
|
|
153
|
+
result: await ops[op](args)
|
|
154
|
+
};
|
|
155
|
+
} catch (err) {
|
|
156
|
+
reply = {
|
|
157
|
+
id,
|
|
158
|
+
ok: false,
|
|
159
|
+
error: { message: errorMessage(err) }
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
try {
|
|
163
|
+
port.postMessage(reply);
|
|
164
|
+
} catch (err) {
|
|
165
|
+
port.postMessage({
|
|
166
|
+
id,
|
|
167
|
+
ok: false,
|
|
168
|
+
error: { message: errorMessage(err) }
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
port.postMessage({ ready: true });
|
|
173
|
+
}
|
|
174
|
+
start().catch((err) => {
|
|
175
|
+
port.postMessage({
|
|
176
|
+
ready: false,
|
|
177
|
+
error: { message: errorMessage(err) }
|
|
178
|
+
});
|
|
179
|
+
process.exit(1);
|
|
180
|
+
});
|
|
181
|
+
//#endregion
|
package/dist/pkg/play.js
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
import { glob, readFile, stat } from "node:fs/promises";
|
|
2
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { Worker } from "node:worker_threads";
|
|
5
|
+
//#region src/utils/error-message.ts
|
|
6
|
+
/**
|
|
7
|
+
* The message to show for a caught value. Anything can be thrown, not only
|
|
8
|
+
* Errors: an Error gives its message, a string is its own message, and any
|
|
9
|
+
* other value gives `fallback` when one is passed, else its string form
|
|
10
|
+
* (never `undefined`). An empty message also gives `fallback`, or for an
|
|
11
|
+
* Error its string form (e.g. "Error").
|
|
12
|
+
*/
|
|
13
|
+
function errorMessage(err, fallback) {
|
|
14
|
+
try {
|
|
15
|
+
if (err instanceof Error) return err.message || fallback || String(err);
|
|
16
|
+
if (typeof err === "string" && err !== "") return err;
|
|
17
|
+
return fallback ?? String(err);
|
|
18
|
+
} catch {
|
|
19
|
+
return fallback ?? "Unprintable error";
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/play/optional.ts
|
|
24
|
+
var defaultImporter = (pkg) => import(pkg);
|
|
25
|
+
function isMissingPackage(err, pkg) {
|
|
26
|
+
return err instanceof Error && err.code === "ERR_MODULE_NOT_FOUND" && err.message.includes(`'${pkg}'`);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Import `pkg`, rejecting with an install hint when it isn't installed. Any
|
|
30
|
+
* other import error (a failure inside the package, a different missing
|
|
31
|
+
* module) is rethrown unchanged.
|
|
32
|
+
*/
|
|
33
|
+
async function loadOptional(pkg, feature, importer = defaultImporter) {
|
|
34
|
+
try {
|
|
35
|
+
return await importer(pkg);
|
|
36
|
+
} catch (err) {
|
|
37
|
+
if (isMissingPackage(err, pkg)) throw new Error(`spindle: ${feature} needs ${pkg}; install it with npm i -D ${pkg}`);
|
|
38
|
+
throw err;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
//#region src/play/resolve-story.ts
|
|
43
|
+
/**
|
|
44
|
+
* twee-ts takes a format ID to be the name of the folder holding format.js,
|
|
45
|
+
* not the name inside it. The package keeps its format in `dist/pkg/`, and
|
|
46
|
+
* `formatSearchDir` is `dist/`.
|
|
47
|
+
*/
|
|
48
|
+
var FORMAT_FOLDER = "pkg";
|
|
49
|
+
var HTML_PATH = /\.html?$/i;
|
|
50
|
+
var GLOB_CHARS = /[*?[\]{}]/;
|
|
51
|
+
/** `file:line: message` per error; just the message without a location. */
|
|
52
|
+
function formatDiagnostic(d) {
|
|
53
|
+
return d.file !== void 0 && d.line !== void 0 ? `${d.file}:${d.line}: ${d.message}` : d.message;
|
|
54
|
+
}
|
|
55
|
+
function diagnosticsError(diagnostics, fallback) {
|
|
56
|
+
const errors = diagnostics.filter((d) => d.level === "error");
|
|
57
|
+
return new Error(errors.length > 0 ? errors.map(formatDiagnostic).join("\n") : fallback);
|
|
58
|
+
}
|
|
59
|
+
/** The files a glob pattern matches, sorted. */
|
|
60
|
+
async function expandGlob(pattern) {
|
|
61
|
+
const matches = [];
|
|
62
|
+
for await (const file of glob(pattern)) matches.push(file);
|
|
63
|
+
return matches.sort();
|
|
64
|
+
}
|
|
65
|
+
/** A path segment with glob syntax in it (as `path.matchesGlob` reads it). */
|
|
66
|
+
var GLOB_SEGMENT = /[*?[\]{}()!+@]/;
|
|
67
|
+
/**
|
|
68
|
+
* An `exclude` glob of the project config as twee-ts matches it: against
|
|
69
|
+
* paths relative to the working directory. A relative glob is relative to the
|
|
70
|
+
* project directory; an absolute one has its literal leading folders made
|
|
71
|
+
* relative. Either way the folder part added or rewritten is escaped.
|
|
72
|
+
*/
|
|
73
|
+
function rebaseExclude(dir, pattern) {
|
|
74
|
+
let base = dir;
|
|
75
|
+
let rest = pattern.replace(/^\.\//, "");
|
|
76
|
+
if (isAbsolute(pattern)) {
|
|
77
|
+
const parts = pattern.split("/");
|
|
78
|
+
let literal = parts.findIndex((part) => GLOB_SEGMENT.test(part));
|
|
79
|
+
if (literal === -1) literal = parts.length;
|
|
80
|
+
base = parts.slice(0, literal).join("/") || "/";
|
|
81
|
+
rest = parts.slice(literal).join("/");
|
|
82
|
+
}
|
|
83
|
+
const fromCwd = globLiteral(relative(process.cwd(), base).split(sep).join("/"));
|
|
84
|
+
if (fromCwd === "") return rest;
|
|
85
|
+
return rest === "" ? fromCwd : `${fromCwd}/${rest}`;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The project config with its paths made independent of the working
|
|
89
|
+
* directory. twee-ts reads `sources`, `modules` and `headFile` relative to
|
|
90
|
+
* the working directory, and matches `exclude` globs against paths relative
|
|
91
|
+
* to it, so each is rebased from the project directory.
|
|
92
|
+
*/
|
|
93
|
+
function rebaseConfig(dir, config) {
|
|
94
|
+
const rebased = {
|
|
95
|
+
...config,
|
|
96
|
+
sources: (config.sources ?? ["."]).map((s) => resolve(dir, s))
|
|
97
|
+
};
|
|
98
|
+
if (config.modules) rebased.modules = config.modules.map((m) => resolve(dir, m));
|
|
99
|
+
if (config.headFile !== void 0) rebased.headFile = resolve(dir, config.headFile);
|
|
100
|
+
if (config.exclude) rebased.exclude = config.exclude.map((e) => rebaseExclude(dir, e));
|
|
101
|
+
return rebased;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The project config less its output and format options. Those are ours: the
|
|
105
|
+
* project's own would write a file, compile for another format, or fetch one.
|
|
106
|
+
*/
|
|
107
|
+
function withoutFormatOptions(config) {
|
|
108
|
+
return Object.fromEntries(Object.entries(config).filter(([key]) => !key.startsWith("format") && !key.startsWith("output") && key !== "useTweegoPath" && key !== "noRemote"));
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* `text` as a glob matching only itself, for Node's `path.matchesGlob` (which
|
|
112
|
+
* twee-ts uses): a metacharacter goes in brackets. Braces and `!` cannot be
|
|
113
|
+
* bracketed there, so each becomes `?` (any one character).
|
|
114
|
+
*/
|
|
115
|
+
function globLiteral(text) {
|
|
116
|
+
return text.replace(/[*?[\]()+@]/g, (c) => `[${c}]`).replace(/[{}!]/g, "?");
|
|
117
|
+
}
|
|
118
|
+
/** The compile sources and project config for a path (or glob). */
|
|
119
|
+
async function sourcesFor(tweeTs, path) {
|
|
120
|
+
let isDirectory = false;
|
|
121
|
+
try {
|
|
122
|
+
isDirectory = (await stat(path)).isDirectory();
|
|
123
|
+
} catch (err) {
|
|
124
|
+
if (!GLOB_CHARS.test(path)) throw new Error(`spindle: cannot read story ${path}: ${errorMessage(err)}`);
|
|
125
|
+
const sources = await expandGlob(path);
|
|
126
|
+
if (sources.length === 0) throw new Error(`spindle: no story files match ${path}`);
|
|
127
|
+
return {
|
|
128
|
+
sources,
|
|
129
|
+
config: {}
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
if (!isDirectory) return {
|
|
133
|
+
sources: [path],
|
|
134
|
+
config: {}
|
|
135
|
+
};
|
|
136
|
+
const found = tweeTs.loadConfig(path);
|
|
137
|
+
if (!found) return {
|
|
138
|
+
sources: [path],
|
|
139
|
+
config: {}
|
|
140
|
+
};
|
|
141
|
+
const config = rebaseConfig(resolve(path), found);
|
|
142
|
+
if (config.sources?.length === 0) throw new Error(`spindle: ${path} has a twee-ts config with no sources`);
|
|
143
|
+
return {
|
|
144
|
+
sources: config.sources ?? [],
|
|
145
|
+
config
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/** The diagnostics a thrown twee-ts error carries, when it has any. */
|
|
149
|
+
function thrownDiagnostics(err) {
|
|
150
|
+
const diagnostics = err?.diagnostics;
|
|
151
|
+
return Array.isArray(diagnostics) ? diagnostics : [];
|
|
152
|
+
}
|
|
153
|
+
async function compileTwee(path, env) {
|
|
154
|
+
const tweeTs = await loadOptional("@rohal12/twee-ts", "compiling Twee", env.importer);
|
|
155
|
+
const { sources, config } = await sourcesFor(tweeTs, path);
|
|
156
|
+
let result;
|
|
157
|
+
try {
|
|
158
|
+
result = await tweeTs.compile({
|
|
159
|
+
...withoutFormatOptions(config),
|
|
160
|
+
sources,
|
|
161
|
+
outputMode: "html",
|
|
162
|
+
formatPaths: [env.formatSearchDir],
|
|
163
|
+
formatId: FORMAT_FOLDER,
|
|
164
|
+
noRemote: true
|
|
165
|
+
});
|
|
166
|
+
} catch (err) {
|
|
167
|
+
const diagnostics = thrownDiagnostics(err);
|
|
168
|
+
throw diagnostics.length > 0 ? diagnosticsError(diagnostics, errorMessage(err)) : err;
|
|
169
|
+
}
|
|
170
|
+
if (result.diagnostics.some((d) => d.level === "error")) throw diagnosticsError(result.diagnostics, "spindle: Twee did not compile");
|
|
171
|
+
return result.output;
|
|
172
|
+
}
|
|
173
|
+
/** The `format-version` of the story's `<tw-storydata>`, if it has one. */
|
|
174
|
+
function storyFormatVersion(html) {
|
|
175
|
+
return /<tw-storydata\b[^>]*?\sformat-version="([^"]*)"/.exec(html)?.[1];
|
|
176
|
+
}
|
|
177
|
+
/** `resolveStoryHtml` with its environment passed in, for tests. */
|
|
178
|
+
async function resolveStoryHtmlWith(input, env) {
|
|
179
|
+
let html;
|
|
180
|
+
if ("html" in input) html = input.html;
|
|
181
|
+
else if (HTML_PATH.test(input.path)) try {
|
|
182
|
+
html = await readFile(input.path, "utf8");
|
|
183
|
+
} catch (err) {
|
|
184
|
+
throw new Error(`spindle: cannot read story ${input.path}: ${errorMessage(err)}`);
|
|
185
|
+
}
|
|
186
|
+
else html = await compileTwee(input.path, env);
|
|
187
|
+
const notes = [];
|
|
188
|
+
const compiledWith = storyFormatVersion(html);
|
|
189
|
+
if (compiledWith !== void 0 && compiledWith !== env.version) notes.push(`The story was compiled with Spindle ${compiledWith}; it runs on the installed Spindle ${env.version}.`);
|
|
190
|
+
return {
|
|
191
|
+
html,
|
|
192
|
+
notes
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Turn a story into HTML: inline HTML as given, an `.html` path read, and
|
|
197
|
+
* anything else (a `.twee` file, a glob or a project directory) compiled with
|
|
198
|
+
* the installed Spindle format.
|
|
199
|
+
*/
|
|
200
|
+
async function resolveStoryHtml(input) {
|
|
201
|
+
const { version } = JSON.parse(await readFile(new URL(
|
|
202
|
+
/* @vite-ignore */
|
|
203
|
+
"../../package.json",
|
|
204
|
+
import.meta.url
|
|
205
|
+
), "utf8"));
|
|
206
|
+
return resolveStoryHtmlWith(input, {
|
|
207
|
+
formatSearchDir: fileURLToPath(new URL(
|
|
208
|
+
/* @vite-ignore */
|
|
209
|
+
"..",
|
|
210
|
+
import.meta.url
|
|
211
|
+
)),
|
|
212
|
+
version
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
//#endregion
|
|
216
|
+
//#region src/play/session.ts
|
|
217
|
+
/**
|
|
218
|
+
* The main-thread handle of a play session. The story runs in its own worker
|
|
219
|
+
* thread (see `protocol.ts`); this file queues calls so they run one at a
|
|
220
|
+
* time, times them out, and closes the session when the worker dies.
|
|
221
|
+
*/
|
|
222
|
+
var DEFAULT_STEP_TIMEOUT_MS = 1e4;
|
|
223
|
+
/** The largest delay setTimeout accepts. */
|
|
224
|
+
var MAX_TIMEOUT_MS = 2147483647;
|
|
225
|
+
var CLOSED_MESSAGE = "spindle: play session is closed";
|
|
226
|
+
/**
|
|
227
|
+
* The host's Node flags for the worker, less `--input-type` (as
|
|
228
|
+
* `--input-type=<type>` or `--input-type <type>`): it only applies to `-e`
|
|
229
|
+
* and stdin, and a worker started with it fails.
|
|
230
|
+
*/
|
|
231
|
+
function workerExecArgv(execArgv) {
|
|
232
|
+
const kept = [];
|
|
233
|
+
for (let i = 0; i < execArgv.length; i++) {
|
|
234
|
+
const arg = execArgv[i];
|
|
235
|
+
if (arg === "--input-type") i++;
|
|
236
|
+
else if (!arg.startsWith("--input-type=")) kept.push(arg);
|
|
237
|
+
}
|
|
238
|
+
return kept;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Opens a session that runs the story in a worker. There `window` is
|
|
242
|
+
* happy-dom's window, not `globalThis`: story code sees `Story` and the DOM
|
|
243
|
+
* globals, but `window.foo = 1` does not make a bare global `foo`.
|
|
244
|
+
*/
|
|
245
|
+
function openPlaySession(options) {
|
|
246
|
+
return openPlaySessionWith(options, {
|
|
247
|
+
workerUrl: new URL(
|
|
248
|
+
/* @vite-ignore */
|
|
249
|
+
"./play-worker.js",
|
|
250
|
+
import.meta.url
|
|
251
|
+
),
|
|
252
|
+
headlessUrl: new URL(
|
|
253
|
+
/* @vite-ignore */
|
|
254
|
+
"./headless.js",
|
|
255
|
+
import.meta.url
|
|
256
|
+
)
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
/** Internal: `openPlaySession` with the worker and headless URLs given (for tests). */
|
|
260
|
+
function openPlaySessionWith(options, urls) {
|
|
261
|
+
const stepTimeoutMs = options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS;
|
|
262
|
+
if (typeof stepTimeoutMs !== "number" || !Number.isFinite(stepTimeoutMs) || stepTimeoutMs <= 0 || stepTimeoutMs > MAX_TIMEOUT_MS) return Promise.reject(/* @__PURE__ */ new Error(`spindle: openPlaySession(): "stepTimeoutMs" must be a positive number of milliseconds, got ${String(stepTimeoutMs)}`));
|
|
263
|
+
const timeoutMessage = `spindle: play session timed out after ${stepTimeoutMs} ms (the story may be stuck in a loop)`;
|
|
264
|
+
const workerData = {
|
|
265
|
+
html: options.html,
|
|
266
|
+
headlessUrl: urls.headlessUrl.href,
|
|
267
|
+
transcript: options.transcript ?? { limit: 10 },
|
|
268
|
+
transitions: options.transitions ?? false
|
|
269
|
+
};
|
|
270
|
+
return new Promise((resolveOpen, rejectOpen) => {
|
|
271
|
+
const worker = new Worker(urls.workerUrl, {
|
|
272
|
+
workerData,
|
|
273
|
+
execArgv: workerExecArgv(process.execArgv)
|
|
274
|
+
});
|
|
275
|
+
let booted = false;
|
|
276
|
+
let closed = false;
|
|
277
|
+
let nextId = 1;
|
|
278
|
+
let active = null;
|
|
279
|
+
const queue = [];
|
|
280
|
+
let terminated = null;
|
|
281
|
+
const terminate = () => {
|
|
282
|
+
terminated ??= worker.terminate().then(() => void 0, () => void 0);
|
|
283
|
+
return terminated;
|
|
284
|
+
};
|
|
285
|
+
const bootTimer = setTimeout(() => {
|
|
286
|
+
rejectOpen(new Error(timeoutMessage));
|
|
287
|
+
terminate();
|
|
288
|
+
}, stepTimeoutMs);
|
|
289
|
+
/** Marks the session closed and settles everything still pending. */
|
|
290
|
+
const shutdown = (runningError, queuedError) => {
|
|
291
|
+
if (closed) return;
|
|
292
|
+
closed = true;
|
|
293
|
+
const running = active;
|
|
294
|
+
active = null;
|
|
295
|
+
if (running) {
|
|
296
|
+
clearTimeout(running.timer);
|
|
297
|
+
running.job.reject(runningError);
|
|
298
|
+
}
|
|
299
|
+
for (const job of queue.splice(0)) job.reject(queuedError);
|
|
300
|
+
};
|
|
301
|
+
const pump = () => {
|
|
302
|
+
if (closed || active) return;
|
|
303
|
+
const job = queue.shift();
|
|
304
|
+
if (!job) return;
|
|
305
|
+
const id = nextId++;
|
|
306
|
+
const request = {
|
|
307
|
+
id,
|
|
308
|
+
op: job.op,
|
|
309
|
+
args: job.args
|
|
310
|
+
};
|
|
311
|
+
try {
|
|
312
|
+
worker.postMessage(request);
|
|
313
|
+
} catch (err) {
|
|
314
|
+
job.reject(new Error(errorMessage(err)));
|
|
315
|
+
pump();
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
active = {
|
|
319
|
+
id,
|
|
320
|
+
job,
|
|
321
|
+
timer: setTimeout(() => {
|
|
322
|
+
const timeout = new Error(timeoutMessage);
|
|
323
|
+
shutdown(timeout, /* @__PURE__ */ new Error(CLOSED_MESSAGE));
|
|
324
|
+
terminate();
|
|
325
|
+
}, stepTimeoutMs)
|
|
326
|
+
};
|
|
327
|
+
};
|
|
328
|
+
const call = (op, args) => new Promise((resolve, reject) => {
|
|
329
|
+
if (closed) {
|
|
330
|
+
reject(/* @__PURE__ */ new Error(CLOSED_MESSAGE));
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
queue.push({
|
|
334
|
+
op,
|
|
335
|
+
args,
|
|
336
|
+
resolve,
|
|
337
|
+
reject
|
|
338
|
+
});
|
|
339
|
+
pump();
|
|
340
|
+
});
|
|
341
|
+
const session = {
|
|
342
|
+
observe: () => call("observe", []),
|
|
343
|
+
step: (id, value) => call("step", value === void 0 ? [id] : [id, value]),
|
|
344
|
+
goto: (passage) => call("goto", [passage]),
|
|
345
|
+
get: (names) => call("get", names === void 0 ? [] : [names]),
|
|
346
|
+
set: (values) => call("set", [values]),
|
|
347
|
+
transcript: () => call("transcript", []),
|
|
348
|
+
async close() {
|
|
349
|
+
const closedError = /* @__PURE__ */ new Error(CLOSED_MESSAGE);
|
|
350
|
+
shutdown(closedError, closedError);
|
|
351
|
+
await terminate();
|
|
352
|
+
},
|
|
353
|
+
get closed() {
|
|
354
|
+
return closed;
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
const failWorker = (message) => {
|
|
358
|
+
if (!booted) {
|
|
359
|
+
clearTimeout(bootTimer);
|
|
360
|
+
rejectOpen(new Error(message));
|
|
361
|
+
terminate();
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
const error = new Error(message);
|
|
365
|
+
shutdown(error, error);
|
|
366
|
+
terminate();
|
|
367
|
+
};
|
|
368
|
+
worker.on("message", (message) => {
|
|
369
|
+
if ("ready" in message) {
|
|
370
|
+
if (booted) return;
|
|
371
|
+
clearTimeout(bootTimer);
|
|
372
|
+
if (message.ready) {
|
|
373
|
+
booted = true;
|
|
374
|
+
resolveOpen(session);
|
|
375
|
+
} else {
|
|
376
|
+
rejectOpen(new Error(message.error.message));
|
|
377
|
+
terminate();
|
|
378
|
+
}
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
if (!active || active.id !== message.id) return;
|
|
382
|
+
const { job, timer } = active;
|
|
383
|
+
active = null;
|
|
384
|
+
clearTimeout(timer);
|
|
385
|
+
if (message.ok) job.resolve(message.result);
|
|
386
|
+
else job.reject(new Error(message.error.message));
|
|
387
|
+
pump();
|
|
388
|
+
});
|
|
389
|
+
worker.on("error", (err) => failWorker(errorMessage(err)));
|
|
390
|
+
worker.on("exit", (code) => {
|
|
391
|
+
if (closed) return;
|
|
392
|
+
failWorker(`spindle: play session worker exited with code ${code}`);
|
|
393
|
+
});
|
|
394
|
+
worker.unref();
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
//#endregion
|
|
398
|
+
export { openPlaySession, resolveStoryHtml };
|