@deckspec/dsl 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 hayaoo
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@deckspec/dsl",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "dependencies": {
8
+ "js-yaml": "^4.1.0",
9
+ "zod": "^3.23.0",
10
+ "@deckspec/schema": "0.1.0"
11
+ },
12
+ "devDependencies": {
13
+ "@types/js-yaml": "^4.0.9",
14
+ "@types/node": "^25.5.0",
15
+ "typescript": "^5.9.3"
16
+ },
17
+ "license": "Apache-2.0",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/hayaoo/deckspec",
21
+ "directory": "packages/dsl"
22
+ },
23
+ "homepage": "https://github.com/hayaoo/deckspec",
24
+ "bugs": {
25
+ "url": "https://github.com/hayaoo/deckspec/issues"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "scripts": {
31
+ "build": "tsc",
32
+ "typecheck": "tsc --noEmit",
33
+ "test": "vitest run"
34
+ }
35
+ }
package/src/index.ts ADDED
@@ -0,0 +1,28 @@
1
+ // Types
2
+ export type {
3
+ SlideValidationResult,
4
+ ValidationResult,
5
+ } from "./types.js";
6
+
7
+ // Parser
8
+ export {
9
+ parseDeckYaml,
10
+ loadDeckFile,
11
+ resolveSlideFile,
12
+ type ResolvedSlideFile,
13
+ } from "./parser.js";
14
+
15
+ // Validator
16
+ export { validateDeck, type ValidationContext } from "./validator.js";
17
+
18
+ // State mutations
19
+ export {
20
+ approveSlide,
21
+ rejectSlide,
22
+ archiveDeck,
23
+ activateDeck,
24
+ lockSlide,
25
+ } from "./state.js";
26
+
27
+ // Scanner
28
+ export { scanDecks, type DeckSummary, type SlideSummary } from "./scanner.js";
package/src/parser.ts ADDED
@@ -0,0 +1,108 @@
1
+ import yaml from "js-yaml";
2
+ import { readFile, access } from "node:fs/promises";
3
+ import { resolve, extname } from "node:path";
4
+
5
+ /**
6
+ * Parses a YAML string into a raw JavaScript object.
7
+ * Does not perform any schema validation — returns the parsed value as-is.
8
+ *
9
+ * @throws Error with a descriptive message if YAML parsing fails.
10
+ */
11
+ export function parseDeckYaml(yamlString: string): unknown {
12
+ try {
13
+ return yaml.load(yamlString);
14
+ } catch (error) {
15
+ const message =
16
+ error instanceof Error ? error.message : "Unknown YAML parse error";
17
+ throw new Error(`Failed to parse deck YAML: ${message}`);
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Reads a deck YAML file from disk and parses it.
23
+ *
24
+ * @throws Error if the file cannot be read or the YAML is malformed.
25
+ */
26
+ export async function loadDeckFile(filePath: string): Promise<unknown> {
27
+ let content: string;
28
+ try {
29
+ content = await readFile(filePath, "utf-8");
30
+ } catch (error) {
31
+ const message =
32
+ error instanceof Error ? error.message : "Unknown file read error";
33
+ throw new Error(`Failed to read deck file "${filePath}": ${message}`);
34
+ }
35
+ return parseDeckYaml(content);
36
+ }
37
+
38
+ /**
39
+ * Resolved slide file reference.
40
+ */
41
+ export interface ResolvedSlideFile {
42
+ type: "html" | "pattern";
43
+ path: string;
44
+ /** True when the resolved pattern is a .tsx source file (needs on-the-fly compilation) */
45
+ tsx?: boolean;
46
+ }
47
+
48
+ /**
49
+ * Resolves a slide `file:` value to an absolute path and type.
50
+ *
51
+ * Resolution priority (ADR-022):
52
+ * 1. Deck-local pattern: {basePath}/patterns/{name}/index.tsx
53
+ * 2. Deck-local pattern: {basePath}/patterns/{name}/index.js
54
+ * 3. Theme pattern: {patternsDir}/{name}/index.js
55
+ * 4. Theme pattern: {patternsDir}/{name}.js
56
+ *
57
+ * Files with extensions (.html etc) are resolved relative to basePath as passthrough.
58
+ */
59
+ export async function resolveSlideFile(
60
+ file: string,
61
+ basePath: string,
62
+ patternsDir: string,
63
+ ): Promise<ResolvedSlideFile> {
64
+ const ext = extname(file);
65
+
66
+ if (ext) {
67
+ // File with extension → relative to deck directory
68
+ const fullPath = resolve(basePath, file);
69
+ return { type: "html", path: fullPath };
70
+ }
71
+
72
+ // No extension → pattern name
73
+ // 1. Deck-local: {basePath}/patterns/{name}/index.tsx
74
+ const localTsxPath = resolve(basePath, "patterns", file, "index.tsx");
75
+ try {
76
+ await access(localTsxPath);
77
+ return { type: "pattern", path: localTsxPath, tsx: true };
78
+ } catch {
79
+ // continue
80
+ }
81
+
82
+ // 2. Deck-local: {basePath}/patterns/{name}/index.js
83
+ const localJsPath = resolve(basePath, "patterns", file, "index.js");
84
+ try {
85
+ await access(localJsPath);
86
+ return { type: "pattern", path: localJsPath };
87
+ } catch {
88
+ // continue
89
+ }
90
+
91
+ // 3. Theme: patterns/{name}/index.js (directory)
92
+ const dirIndexPath = resolve(patternsDir, file, "index.js");
93
+ try {
94
+ await access(dirIndexPath);
95
+ return { type: "pattern", path: dirIndexPath };
96
+ } catch {
97
+ // 4. Theme: patterns/{name}.js (flat file)
98
+ const flatPath = resolve(patternsDir, `${file}.js`);
99
+ try {
100
+ await access(flatPath);
101
+ return { type: "pattern", path: flatPath };
102
+ } catch {
103
+ throw new Error(
104
+ `Pattern "${file}" not found. Looked in:\n ${localTsxPath}\n ${localJsPath}\n ${dirIndexPath}\n ${flatPath}`,
105
+ );
106
+ }
107
+ }
108
+ }
@@ -0,0 +1,93 @@
1
+ import { describe, it, expect, beforeEach } from "vitest";
2
+ import { writeFile, mkdir } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import yaml from "js-yaml";
6
+ import { scanDecks } from "./scanner.js";
7
+
8
+ function makeDeckYaml(title: string, slides: Array<{ file: string; state?: string; vars?: Record<string, unknown> }>): string {
9
+ return yaml.dump({
10
+ meta: { title, theme: "noir-display", state: "active" },
11
+ slides: slides.map((s) => ({
12
+ file: s.file,
13
+ ...(s.state ? { state: s.state } : {}),
14
+ ...(s.vars ? { vars: s.vars } : {}),
15
+ })),
16
+ });
17
+ }
18
+
19
+ describe("scanDecks", () => {
20
+ let tmpDir: string;
21
+
22
+ beforeEach(async () => {
23
+ tmpDir = join(tmpdir(), `deckspec-scan-${Date.now()}-${Math.random().toString(36).slice(2)}`);
24
+ await mkdir(tmpDir, { recursive: true });
25
+ });
26
+
27
+ it("finds deck.yaml files recursively", async () => {
28
+ const deckDir = join(tmpDir, "decks", "sample");
29
+ await mkdir(deckDir, { recursive: true });
30
+ await writeFile(
31
+ join(deckDir, "deck.yaml"),
32
+ makeDeckYaml("Sample", [
33
+ { file: "slides/01.html" },
34
+ { file: "slides/02.html" },
35
+ ]),
36
+ );
37
+
38
+ const results = await scanDecks(tmpDir);
39
+ expect(results).toHaveLength(1);
40
+ expect(results[0].meta.title).toBe("Sample");
41
+ expect(results[0].slideCount).toBe(2);
42
+ expect(results[0].relativePath).toContain("deck.yaml");
43
+ });
44
+
45
+ it("returns correct approval counts", async () => {
46
+ const deckDir = join(tmpDir, "decks", "mixed");
47
+ await mkdir(deckDir, { recursive: true });
48
+ await writeFile(
49
+ join(deckDir, "deck.yaml"),
50
+ makeDeckYaml("Mixed", [
51
+ { file: "slides/01.html", state: "approved" },
52
+ { file: "slides/02.html", state: "generated" },
53
+ { file: "title-center", state: "locked", vars: { title: "Hi", subtitle: "there" } },
54
+ ]),
55
+ );
56
+
57
+ const results = await scanDecks(tmpDir);
58
+ expect(results[0].approvedCount).toBe(2); // approved + locked
59
+ expect(results[0].slideSummaries[0].state).toBe("approved");
60
+ expect(results[0].slideSummaries[1].state).toBe("generated");
61
+ expect(results[0].slideSummaries[2].state).toBe("locked");
62
+ });
63
+
64
+ it("extracts labels from vars or file name", async () => {
65
+ const deckDir = join(tmpDir, "decks", "labels");
66
+ await mkdir(deckDir, { recursive: true });
67
+ await writeFile(
68
+ join(deckDir, "deck.yaml"),
69
+ makeDeckYaml("Labels", [
70
+ { file: "title-center", vars: { title: "My Title", subtitle: "Sub" } },
71
+ { file: "slides/02-feature.html" },
72
+ ]),
73
+ );
74
+
75
+ const results = await scanDecks(tmpDir);
76
+ expect(results[0].slideSummaries[0].label).toBe("My Title");
77
+ expect(results[0].slideSummaries[1].label).toBe("02-feature");
78
+ });
79
+
80
+ it("returns empty array for directory with no decks", async () => {
81
+ const results = await scanDecks(tmpDir);
82
+ expect(results).toHaveLength(0);
83
+ });
84
+
85
+ it("skips invalid YAML files gracefully", async () => {
86
+ const deckDir = join(tmpDir, "decks", "bad");
87
+ await mkdir(deckDir, { recursive: true });
88
+ await writeFile(join(deckDir, "deck.yaml"), "not: valid: yaml: [[[");
89
+
90
+ const results = await scanDecks(tmpDir);
91
+ expect(results).toHaveLength(0);
92
+ });
93
+ });
package/src/scanner.ts ADDED
@@ -0,0 +1,111 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import { join, relative } from "node:path";
3
+ import yaml from "js-yaml";
4
+
5
+ export interface SlideSummary {
6
+ index: number;
7
+ state: string;
8
+ /** Label extracted from first <h1> or <h2> in the HTML */
9
+ label?: string;
10
+ }
11
+
12
+ export interface DeckSummary {
13
+ filePath: string;
14
+ relativePath: string;
15
+ meta: {
16
+ title: string;
17
+ theme: string;
18
+ state: string;
19
+ };
20
+ slideCount: number;
21
+ slideSummaries: SlideSummary[];
22
+ approvedCount: number;
23
+ }
24
+
25
+ const HEADING_RE = /<h[12][^>]*>(.*?)<\/h[12]>/i;
26
+
27
+ function extractLabel(html: string): string | undefined {
28
+ const match = HEADING_RE.exec(html);
29
+ if (match) {
30
+ // Strip any nested HTML tags from the heading content
31
+ return match[1].replace(/<[^>]*>/g, "").trim() || undefined;
32
+ }
33
+ return undefined;
34
+ }
35
+
36
+ async function findDeckFiles(dir: string): Promise<string[]> {
37
+ const results: string[] = [];
38
+
39
+ async function walk(current: string): Promise<void> {
40
+ const entries = await readdir(current, { withFileTypes: true });
41
+ for (const entry of entries) {
42
+ const fullPath = join(current, entry.name);
43
+ if (entry.isDirectory() && entry.name !== "node_modules" && entry.name !== ".git") {
44
+ await walk(fullPath);
45
+ } else if (entry.isFile() && entry.name === "deck.yaml") {
46
+ results.push(fullPath);
47
+ }
48
+ }
49
+ }
50
+
51
+ await walk(dir);
52
+ return results.sort();
53
+ }
54
+
55
+ /**
56
+ * Scans a directory recursively for deck.yaml files and returns summaries.
57
+ */
58
+ export async function scanDecks(dir: string): Promise<DeckSummary[]> {
59
+ const files = await findDeckFiles(dir);
60
+ const summaries: DeckSummary[] = [];
61
+
62
+ for (const filePath of files) {
63
+ try {
64
+ const content = await readFile(filePath, "utf-8");
65
+ const raw = yaml.load(content) as {
66
+ meta?: Record<string, unknown>;
67
+ slides?: Array<Record<string, unknown>>;
68
+ };
69
+
70
+ if (!raw?.meta || !raw?.slides || !Array.isArray(raw.slides)) {
71
+ continue;
72
+ }
73
+
74
+ const slideSummaries: SlideSummary[] = raw.slides.map((slide, index) => {
75
+ const state = String(slide.state ?? "generated");
76
+ // For file-based slides: use file name as label fallback
77
+ const file = typeof slide.file === "string" ? slide.file : undefined;
78
+ // Try extracting from vars (pattern slides)
79
+ const vars = slide.vars as Record<string, unknown> | undefined;
80
+ const varsTitle = vars?.title ?? vars?.headline;
81
+ const label = typeof varsTitle === "string"
82
+ ? varsTitle
83
+ : file
84
+ ? file.replace(/\.[^.]+$/, "").split("/").pop()
85
+ : undefined;
86
+ return { index, state, label };
87
+ });
88
+
89
+ const approvedCount = slideSummaries.filter(
90
+ (s) => s.state === "approved" || s.state === "locked",
91
+ ).length;
92
+
93
+ summaries.push({
94
+ filePath,
95
+ relativePath: relative(dir, filePath),
96
+ meta: {
97
+ title: String(raw.meta.title ?? "Untitled"),
98
+ theme: String(raw.meta.theme ?? "noir-display"),
99
+ state: String(raw.meta.state ?? "active"),
100
+ },
101
+ slideCount: raw.slides.length,
102
+ slideSummaries,
103
+ approvedCount,
104
+ });
105
+ } catch {
106
+ // Skip files that can't be parsed
107
+ }
108
+ }
109
+
110
+ return summaries;
111
+ }
@@ -0,0 +1,140 @@
1
+ import { describe, it, expect, beforeEach } from "vitest";
2
+ import { writeFile, readFile, mkdir } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import yaml from "js-yaml";
6
+ import { approveSlide, rejectSlide, archiveDeck, activateDeck, lockSlide } from "./state.js";
7
+
8
+ function makeDeckYaml(overrides: {
9
+ metaState?: string;
10
+ slideStates?: (string | undefined)[];
11
+ } = {}): string {
12
+ const slides = (overrides.slideStates ?? [undefined, undefined]).map(
13
+ (state, i) => ({
14
+ file: `slides/0${i}.html`,
15
+ ...(state ? { state } : {}),
16
+ }),
17
+ );
18
+
19
+ return yaml.dump({
20
+ meta: {
21
+ title: "Test Deck",
22
+ theme: "noir-display",
23
+ state: overrides.metaState ?? "active",
24
+ },
25
+ slides,
26
+ });
27
+ }
28
+
29
+ async function readDeckYaml(filePath: string): Promise<{
30
+ meta: { state?: string };
31
+ slides: Array<{ file?: string; state?: string; vars?: Record<string, unknown> }>;
32
+ }> {
33
+ const content = await readFile(filePath, "utf-8");
34
+ return yaml.load(content) as any;
35
+ }
36
+
37
+ describe("state mutations", () => {
38
+ let tmpDir: string;
39
+ let deckPath: string;
40
+
41
+ beforeEach(async () => {
42
+ tmpDir = join(tmpdir(), `deckspec-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
43
+ await mkdir(tmpDir, { recursive: true });
44
+ deckPath = join(tmpDir, "deck.yaml");
45
+ });
46
+
47
+ describe("approveSlide", () => {
48
+ it("approves a generated slide", async () => {
49
+ await writeFile(deckPath, makeDeckYaml());
50
+ await approveSlide(deckPath, 0);
51
+ const result = await readDeckYaml(deckPath);
52
+ expect(result.slides[0].state).toBe("approved");
53
+ });
54
+
55
+ it("approves a derived slide", async () => {
56
+ await writeFile(deckPath, makeDeckYaml({ slideStates: ["derived"] }));
57
+ await approveSlide(deckPath, 0);
58
+ const result = await readDeckYaml(deckPath);
59
+ expect(result.slides[0].state).toBe("approved");
60
+ });
61
+
62
+ it("rejects approval of already approved slide", async () => {
63
+ await writeFile(deckPath, makeDeckYaml({ slideStates: ["approved"] }));
64
+ await expect(approveSlide(deckPath, 0)).rejects.toThrow("Invalid state transition");
65
+ });
66
+
67
+ it("rejects approval of locked slide", async () => {
68
+ await writeFile(deckPath, makeDeckYaml({ slideStates: ["locked"] }));
69
+ await expect(approveSlide(deckPath, 0)).rejects.toThrow("Invalid state transition");
70
+ });
71
+
72
+ it("throws on out-of-range index", async () => {
73
+ await writeFile(deckPath, makeDeckYaml());
74
+ await expect(approveSlide(deckPath, 5)).rejects.toThrow("out of range");
75
+ });
76
+ });
77
+
78
+ describe("rejectSlide", () => {
79
+ it("rejects an approved slide back to generated", async () => {
80
+ await writeFile(deckPath, makeDeckYaml({ slideStates: ["approved"] }));
81
+ await rejectSlide(deckPath, 0);
82
+ const result = await readDeckYaml(deckPath);
83
+ expect(result.slides[0].state).toBe("generated");
84
+ });
85
+
86
+ it("throws when rejecting a generated slide", async () => {
87
+ await writeFile(deckPath, makeDeckYaml());
88
+ await expect(rejectSlide(deckPath, 0)).rejects.toThrow("Only \"approved\" slides can be rejected");
89
+ });
90
+
91
+ it("throws when rejecting a locked slide", async () => {
92
+ await writeFile(deckPath, makeDeckYaml({ slideStates: ["locked"] }));
93
+ await expect(rejectSlide(deckPath, 0)).rejects.toThrow("Only \"approved\" slides can be rejected");
94
+ });
95
+ });
96
+
97
+ describe("lockSlide", () => {
98
+ it("locks an approved slide as a pattern", async () => {
99
+ await writeFile(deckPath, makeDeckYaml({ slideStates: ["approved"] }));
100
+ await lockSlide(deckPath, 0, "my-pattern", { title: "Hello", subtitle: "World" });
101
+ const result = await readDeckYaml(deckPath);
102
+ expect(result.slides[0].state).toBe("locked");
103
+ expect(result.slides[0].file).toBe("my-pattern");
104
+ expect(result.slides[0].vars).toEqual({ title: "Hello", subtitle: "World" });
105
+ });
106
+
107
+ it("throws when locking a generated slide", async () => {
108
+ await writeFile(deckPath, makeDeckYaml());
109
+ await expect(lockSlide(deckPath, 0, "test", {})).rejects.toThrow("Invalid state transition");
110
+ });
111
+ });
112
+
113
+ describe("archiveDeck", () => {
114
+ it("archives an active deck", async () => {
115
+ await writeFile(deckPath, makeDeckYaml({ metaState: "active" }));
116
+ await archiveDeck(deckPath);
117
+ const result = await readDeckYaml(deckPath);
118
+ expect(result.meta.state).toBe("archived");
119
+ });
120
+
121
+ it("throws when already archived", async () => {
122
+ await writeFile(deckPath, makeDeckYaml({ metaState: "archived" }));
123
+ await expect(archiveDeck(deckPath)).rejects.toThrow("already archived");
124
+ });
125
+ });
126
+
127
+ describe("activateDeck", () => {
128
+ it("activates an archived deck", async () => {
129
+ await writeFile(deckPath, makeDeckYaml({ metaState: "archived" }));
130
+ await activateDeck(deckPath);
131
+ const result = await readDeckYaml(deckPath);
132
+ expect(result.meta.state).toBe("active");
133
+ });
134
+
135
+ it("throws when already active", async () => {
136
+ await writeFile(deckPath, makeDeckYaml({ metaState: "active" }));
137
+ await expect(activateDeck(deckPath)).rejects.toThrow("already active");
138
+ });
139
+ });
140
+ });
package/src/state.ts ADDED
@@ -0,0 +1,153 @@
1
+ import yaml from "js-yaml";
2
+ import { readFile, writeFile } from "node:fs/promises";
3
+ import type { SlideState, DeckLifecycle } from "@deckspec/schema";
4
+
5
+ /**
6
+ * Valid slide state transitions.
7
+ * Only these transitions are allowed:
8
+ * generated → approved
9
+ * derived → approved
10
+ * approved → locked
11
+ */
12
+ const VALID_SLIDE_TRANSITIONS: Record<string, SlideState[]> = {
13
+ generated: ["approved"],
14
+ derived: ["approved"],
15
+ approved: ["locked"],
16
+ locked: [],
17
+ };
18
+
19
+ interface RawDeck {
20
+ meta: { state?: string; [key: string]: unknown };
21
+ slides: Array<{ state?: string; [key: string]: unknown }>;
22
+ }
23
+
24
+ async function loadRawYaml(filePath: string): Promise<{ raw: RawDeck; content: string }> {
25
+ const content = await readFile(filePath, "utf-8");
26
+ const raw = yaml.load(content) as RawDeck;
27
+ if (!raw?.slides || !Array.isArray(raw.slides)) {
28
+ throw new Error(`Invalid deck file: ${filePath}`);
29
+ }
30
+ return { raw, content };
31
+ }
32
+
33
+ async function saveYaml(filePath: string, data: RawDeck): Promise<void> {
34
+ const output = yaml.dump(data, {
35
+ lineWidth: -1,
36
+ noRefs: true,
37
+ quotingType: '"',
38
+ forceQuotes: false,
39
+ });
40
+ await writeFile(filePath, output, "utf-8");
41
+ }
42
+
43
+ function validateSlideTransition(from: SlideState, to: SlideState): void {
44
+ const allowed = VALID_SLIDE_TRANSITIONS[from];
45
+ if (!allowed || !allowed.includes(to)) {
46
+ throw new Error(
47
+ `Invalid state transition: "${from}" → "${to}". Allowed from "${from}": [${(allowed ?? []).join(", ")}]`,
48
+ );
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Approve a slide — sets its state to "approved".
54
+ */
55
+ export async function approveSlide(
56
+ filePath: string,
57
+ slideIndex: number,
58
+ ): Promise<void> {
59
+ const { raw } = await loadRawYaml(filePath);
60
+ if (slideIndex < 0 || slideIndex >= raw.slides.length) {
61
+ throw new Error(
62
+ `Slide index ${slideIndex} out of range (0–${raw.slides.length - 1})`,
63
+ );
64
+ }
65
+ const current = (raw.slides[slideIndex].state ?? "generated") as SlideState;
66
+ validateSlideTransition(current, "approved");
67
+ raw.slides[slideIndex].state = "approved";
68
+ await saveYaml(filePath, raw);
69
+ }
70
+
71
+ /**
72
+ * Reject a slide — resets its state to "generated".
73
+ * Only allowed from "approved" state.
74
+ */
75
+ export async function rejectSlide(
76
+ filePath: string,
77
+ slideIndex: number,
78
+ ): Promise<void> {
79
+ const { raw } = await loadRawYaml(filePath);
80
+ if (slideIndex < 0 || slideIndex >= raw.slides.length) {
81
+ throw new Error(
82
+ `Slide index ${slideIndex} out of range (0–${raw.slides.length - 1})`,
83
+ );
84
+ }
85
+ const current = (raw.slides[slideIndex].state ?? "generated") as SlideState;
86
+ if (current !== "approved") {
87
+ throw new Error(
88
+ `Cannot reject slide in "${current}" state. Only "approved" slides can be rejected.`,
89
+ );
90
+ }
91
+ raw.slides[slideIndex].state = "generated";
92
+ await saveYaml(filePath, raw);
93
+ }
94
+
95
+ /**
96
+ * Archive a deck — sets meta.state to "archived".
97
+ */
98
+ export async function archiveDeck(filePath: string): Promise<void> {
99
+ const { raw } = await loadRawYaml(filePath);
100
+ const current = (raw.meta.state ?? "active") as DeckLifecycle;
101
+ if (current === "archived") {
102
+ throw new Error("Deck is already archived.");
103
+ }
104
+ raw.meta.state = "archived";
105
+ await saveYaml(filePath, raw);
106
+ }
107
+
108
+ /**
109
+ * Activate a deck — sets meta.state to "active".
110
+ */
111
+ export async function activateDeck(filePath: string): Promise<void> {
112
+ const { raw } = await loadRawYaml(filePath);
113
+ const current = (raw.meta.state ?? "active") as DeckLifecycle;
114
+ if (current === "active") {
115
+ throw new Error("Deck is already active.");
116
+ }
117
+ raw.meta.state = "active";
118
+ await saveYaml(filePath, raw);
119
+ }
120
+
121
+ /**
122
+ * Lock a slide — sets state to "locked" and rewrites it as a pattern reference.
123
+ * The slide must be in "approved" state.
124
+ *
125
+ * @param filePath - Path to the deck YAML file.
126
+ * @param slideIndex - Zero-based index of the slide to lock.
127
+ * @param patternName - Name for the new pattern.
128
+ * @param vars - Variables extracted from the slide.
129
+ */
130
+ export async function lockSlide(
131
+ filePath: string,
132
+ slideIndex: number,
133
+ patternName: string,
134
+ vars: Record<string, unknown>,
135
+ ): Promise<void> {
136
+ const { raw } = await loadRawYaml(filePath);
137
+ if (slideIndex < 0 || slideIndex >= raw.slides.length) {
138
+ throw new Error(
139
+ `Slide index ${slideIndex} out of range (0–${raw.slides.length - 1})`,
140
+ );
141
+ }
142
+ const current = (raw.slides[slideIndex].state ?? "generated") as SlideState;
143
+ validateSlideTransition(current, "locked");
144
+
145
+ // Rewrite the slide entry
146
+ raw.slides[slideIndex] = {
147
+ file: patternName,
148
+ state: "locked",
149
+ vars,
150
+ };
151
+
152
+ await saveYaml(filePath, raw);
153
+ }
package/src/types.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { ZodError } from "zod";
2
+
3
+ /**
4
+ * Validation result for a single slide.
5
+ */
6
+ export interface SlideValidationResult {
7
+ /** Zero-based index of the slide in the deck. */
8
+ index: number;
9
+ /** Whether the slide passed validation. */
10
+ valid: boolean;
11
+ /** Zod validation errors, present only when valid is false. */
12
+ errors?: ZodError;
13
+ }
14
+
15
+ /**
16
+ * Validation result for an entire deck.
17
+ */
18
+ export interface ValidationResult {
19
+ /** Whether all slides (and deck structure) passed validation. */
20
+ valid: boolean;
21
+ /** Per-slide validation results. */
22
+ results: SlideValidationResult[];
23
+ /** Deck-level structural error, if any. */
24
+ deckError?: ZodError;
25
+ }
@@ -0,0 +1,124 @@
1
+ import { access } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ import { deckSchema } from "@deckspec/schema";
4
+ import type { ValidationResult, SlideValidationResult } from "./types.js";
5
+ import { resolveSlideFile } from "./parser.js";
6
+
7
+ export interface ValidationContext {
8
+ basePath: string;
9
+ patternsDir: string;
10
+ /** Optional function to compile .tsx files on-the-fly. Provided by renderer. */
11
+ compileTsx?: (tsxPath: string) => Promise<string>;
12
+ }
13
+
14
+ /**
15
+ * Validates a raw parsed deck object.
16
+ *
17
+ * Validates the overall deck structure (meta + slides array) with deckSchema.
18
+ * For each slide:
19
+ * - .html files: checks file exists on disk
20
+ * - pattern names: imports compiled .js, validates vars against exported schema
21
+ * - .tsx patterns (deck-local): compiled via compileTsx if provided, otherwise skips vars validation
22
+ */
23
+ export async function validateDeck(
24
+ raw: unknown,
25
+ context?: ValidationContext,
26
+ ): Promise<ValidationResult> {
27
+ const deckResult = deckSchema.safeParse(raw);
28
+
29
+ if (!deckResult.success) {
30
+ return {
31
+ valid: false,
32
+ results: [],
33
+ deckError: deckResult.error,
34
+ };
35
+ }
36
+
37
+ const deck = deckResult.data;
38
+ const results: SlideValidationResult[] = [];
39
+ let allValid = true;
40
+
41
+ for (let index = 0; index < deck.slides.length; index++) {
42
+ const slide = deck.slides[index];
43
+
44
+ // If no context provided, only do structural validation
45
+ if (!context) {
46
+ results.push({ index, valid: true });
47
+ continue;
48
+ }
49
+
50
+ try {
51
+ const resolved = await resolveSlideFile(
52
+ slide.file,
53
+ context.basePath,
54
+ context.patternsDir,
55
+ );
56
+
57
+ if (resolved.type === "html") {
58
+ // Check file exists
59
+ await access(resolved.path);
60
+ results.push({ index, valid: true });
61
+ } else {
62
+ // Pattern: import module and validate vars
63
+ let modulePath = resolved.path;
64
+ if (resolved.tsx && context.compileTsx) {
65
+ modulePath = await context.compileTsx(resolved.path);
66
+ } else if (resolved.tsx) {
67
+ // No compiler provided — just check file exists (structural validation only)
68
+ await access(resolved.path);
69
+ results.push({ index, valid: true });
70
+ continue;
71
+ }
72
+
73
+ const mod = await import(modulePath);
74
+
75
+ // Check asset file existence
76
+ if (mod.assets && Array.isArray(mod.assets) && slide.vars) {
77
+ for (const spec of mod.assets as Array<{ field: string; type: string }>) {
78
+ const val = slide.vars[spec.field];
79
+ if (typeof val === "string" && !val.startsWith("https://")) {
80
+ await access(resolve(context.basePath, val));
81
+ }
82
+ }
83
+ }
84
+
85
+ if (mod.schema && slide.vars) {
86
+ const parseResult = mod.schema.safeParse(slide.vars);
87
+ if (!parseResult.success) {
88
+ results.push({ index, valid: false, errors: parseResult.error });
89
+ allValid = false;
90
+ continue;
91
+ }
92
+ } else if (mod.schema && !slide.vars) {
93
+ // Check if schema has required fields
94
+ const parseResult = mod.schema.safeParse({});
95
+ if (!parseResult.success) {
96
+ results.push({ index, valid: false, errors: parseResult.error });
97
+ allValid = false;
98
+ continue;
99
+ }
100
+ }
101
+
102
+ results.push({ index, valid: true });
103
+ }
104
+ } catch (err) {
105
+ const message = err instanceof Error ? err.message : String(err);
106
+ // Create a synthetic ZodError-like structure for file resolution errors
107
+ const { ZodError, ZodIssueCode } = await import("zod");
108
+ const zodError = new ZodError([
109
+ {
110
+ code: ZodIssueCode.custom,
111
+ path: ["slides", index, "file"],
112
+ message,
113
+ },
114
+ ]);
115
+ results.push({ index, valid: false, errors: zodError });
116
+ allValid = false;
117
+ }
118
+ }
119
+
120
+ return {
121
+ valid: allValid,
122
+ results,
123
+ };
124
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist",
5
+ "rootDir": "src",
6
+ "composite": true
7
+ },
8
+ "include": ["src/"],
9
+ "exclude": ["src/**/*.test.ts"],
10
+ "references": [
11
+ { "path": "../schema" }
12
+ ]
13
+ }