@officedk/pptxdk 0.0.0-stage → 0.2.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.
Files changed (206) hide show
  1. package/LICENSE +21 -0
  2. package/dist/build-zrZuX4fK.d.ts +3 -0
  3. package/dist/build.d.ts +35 -0
  4. package/dist/build.js +128 -0
  5. package/dist/capabilities/dist/all.js +34 -0
  6. package/dist/capabilities/dist/box/box-codegen.js +84 -0
  7. package/dist/capabilities/dist/box/box-declaration.js +32 -0
  8. package/dist/capabilities/dist/box/box-elements.js +17 -0
  9. package/dist/capabilities/dist/box/box.js +142 -0
  10. package/dist/capabilities/dist/chart/chart-codegen.js +79 -0
  11. package/dist/capabilities/dist/chart/chart-declaration.js +7 -0
  12. package/dist/capabilities/dist/chart/chart-elements.js +12 -0
  13. package/dist/capabilities/dist/chart/chart-import.js +2403 -0
  14. package/dist/capabilities/dist/chart/chart-labels.js +86 -0
  15. package/dist/capabilities/dist/chart/chart-model.js +9 -0
  16. package/dist/capabilities/dist/chart/chart-schemas.js +1088 -0
  17. package/dist/capabilities/dist/chart/chart-xml.js +788 -0
  18. package/dist/capabilities/dist/chart/chart.js +1119 -0
  19. package/dist/capabilities/dist/chart/preview/axes-and-grid.js +311 -0
  20. package/dist/capabilities/dist/chart/preview/bar-column.js +143 -0
  21. package/dist/capabilities/dist/chart/preview/data-labels.js +334 -0
  22. package/dist/capabilities/dist/chart/preview/error-bars.js +213 -0
  23. package/dist/capabilities/dist/chart/preview/index.js +192 -0
  24. package/dist/capabilities/dist/chart/preview/layout.js +592 -0
  25. package/dist/capabilities/dist/chart/preview/legend.js +273 -0
  26. package/dist/capabilities/dist/chart/preview/line-area.js +404 -0
  27. package/dist/capabilities/dist/chart/preview/markers.js +100 -0
  28. package/dist/capabilities/dist/chart/preview/number-format.js +247 -0
  29. package/dist/capabilities/dist/chart/preview/pie-doughnut.js +159 -0
  30. package/dist/capabilities/dist/chart/preview/scales.js +365 -0
  31. package/dist/capabilities/dist/chart/preview/scatter.js +131 -0
  32. package/dist/capabilities/dist/chart/preview/style.js +60 -0
  33. package/dist/capabilities/dist/chart/preview/text-render.js +116 -0
  34. package/dist/capabilities/dist/chart/preview/trendlines.js +537 -0
  35. package/dist/capabilities/dist/chart/preview/types.js +5 -0
  36. package/dist/capabilities/dist/document.js +168 -0
  37. package/dist/capabilities/dist/font/font-embedding.js +119 -0
  38. package/dist/capabilities/dist/font/font-engine.js +834 -0
  39. package/dist/capabilities/dist/font/font-import.js +766 -0
  40. package/dist/capabilities/dist/font/font-subset.js +55 -0
  41. package/dist/capabilities/dist/font/font.js +72 -0
  42. package/dist/capabilities/dist/group/group-codegen.js +74 -0
  43. package/dist/capabilities/dist/group/group-declaration.js +41 -0
  44. package/dist/capabilities/dist/group/group-elements.js +12 -0
  45. package/dist/capabilities/dist/group/group-import.js +649 -0
  46. package/dist/capabilities/dist/group/group-xml.js +8 -0
  47. package/dist/capabilities/dist/group/group.js +260 -0
  48. package/dist/capabilities/dist/image/gif-decoder.js +244 -0
  49. package/dist/capabilities/dist/image/image-codegen.js +164 -0
  50. package/dist/capabilities/dist/image/image-declaration.js +8 -0
  51. package/dist/capabilities/dist/image/image-decode.js +244 -0
  52. package/dist/capabilities/dist/image/image-elements.js +12 -0
  53. package/dist/capabilities/dist/image/image-import.js +984 -0
  54. package/dist/capabilities/dist/image/image-schemas.js +147 -0
  55. package/dist/capabilities/dist/image/image-xml.js +12 -0
  56. package/dist/capabilities/dist/image/image.js +552 -0
  57. package/dist/capabilities/dist/line/line-codegen.js +89 -0
  58. package/dist/capabilities/dist/line/line-declaration.js +72 -0
  59. package/dist/capabilities/dist/line/line-elements.js +12 -0
  60. package/dist/capabilities/dist/line/line-import.js +504 -0
  61. package/dist/capabilities/dist/line/line-xml.js +9 -0
  62. package/dist/capabilities/dist/line/line.js +331 -0
  63. package/dist/capabilities/dist/masters/footer-placeholder.js +683 -0
  64. package/dist/capabilities/dist/masters/masters-codegen.js +69 -0
  65. package/dist/capabilities/dist/masters/masters.js +250 -0
  66. package/dist/capabilities/dist/motion/motion-api.js +757 -0
  67. package/dist/capabilities/dist/motion/motion-codegen.js +406 -0
  68. package/dist/capabilities/dist/motion/motion-elements.js +43 -0
  69. package/dist/capabilities/dist/motion/motion-import.js +1568 -0
  70. package/dist/capabilities/dist/motion/motion-plan.js +2340 -0
  71. package/dist/capabilities/dist/motion/motion-query.js +423 -0
  72. package/dist/capabilities/dist/motion/motion-schemas.js +339 -0
  73. package/dist/capabilities/dist/motion/motion.js +1617 -0
  74. package/dist/capabilities/dist/notes/notes-codegen.js +19 -0
  75. package/dist/capabilities/dist/notes/notes-declaration.js +8 -0
  76. package/dist/capabilities/dist/notes/notes-elements.js +12 -0
  77. package/dist/capabilities/dist/notes/notes-import.js +292 -0
  78. package/dist/capabilities/dist/notes/notes-schemas.js +38 -0
  79. package/dist/capabilities/dist/notes/notes-xml.js +38 -0
  80. package/dist/capabilities/dist/notes/notes.js +194 -0
  81. package/dist/capabilities/dist/placeholder/placeholder-codegen.js +54 -0
  82. package/dist/capabilities/dist/placeholder/placeholder-elements.js +13 -0
  83. package/dist/capabilities/dist/placeholder/placeholder-schemas.js +33 -0
  84. package/dist/capabilities/dist/placeholder/placeholder.js +451 -0
  85. package/dist/capabilities/dist/shape/shape-codegen.js +236 -0
  86. package/dist/capabilities/dist/shape/shape-declaration.js +45 -0
  87. package/dist/capabilities/dist/shape/shape-elements.js +12 -0
  88. package/dist/capabilities/dist/shape/shape-import.js +628 -0
  89. package/dist/capabilities/dist/shape/shape-xml.js +6 -0
  90. package/dist/capabilities/dist/shape/shape.js +320 -0
  91. package/dist/capabilities/dist/shared/geometry.js +1681 -0
  92. package/dist/capabilities/dist/shared/identity.js +205 -0
  93. package/dist/capabilities/dist/shared/morph-api.js +11 -0
  94. package/dist/capabilities/dist/shared/placeholder-import.js +238 -0
  95. package/dist/capabilities/dist/shared/preset-definitions.js +22423 -0
  96. package/dist/capabilities/dist/shared/style-inheritance.js +161 -0
  97. package/dist/capabilities/dist/shared/text-schemas.js +241 -0
  98. package/dist/capabilities/dist/shared/text-service.js +2252 -0
  99. package/dist/capabilities/dist/shared/visual.js +1197 -0
  100. package/dist/capabilities/dist/slide-background/slide-background-codegen.js +44 -0
  101. package/dist/capabilities/dist/slide-background/slide-background-import.js +166 -0
  102. package/dist/capabilities/dist/slide-background/slide-background-xml.js +34 -0
  103. package/dist/capabilities/dist/slide-background/slide-background.js +238 -0
  104. package/dist/capabilities/dist/table/table-codegen.js +125 -0
  105. package/dist/capabilities/dist/table/table-declaration.js +15 -0
  106. package/dist/capabilities/dist/table/table-elements.js +27 -0
  107. package/dist/capabilities/dist/table/table-import.js +606 -0
  108. package/dist/capabilities/dist/table/table-schemas.js +334 -0
  109. package/dist/capabilities/dist/table/table-xml.js +30 -0
  110. package/dist/capabilities/dist/table/table.js +739 -0
  111. package/dist/capabilities/dist/text/text-codegen.js +198 -0
  112. package/dist/capabilities/dist/text/text-declaration.js +27 -0
  113. package/dist/capabilities/dist/text/text-elements.js +54 -0
  114. package/dist/capabilities/dist/text/text-import.js +1224 -0
  115. package/dist/capabilities/dist/text/text-xml.js +9 -0
  116. package/dist/capabilities/dist/text/text.js +320 -0
  117. package/dist/capabilities/dist/transition/transition-api.js +136 -0
  118. package/dist/capabilities/dist/transition/transition-codegen.js +45 -0
  119. package/dist/capabilities/dist/transition/transition-import.js +477 -0
  120. package/dist/capabilities/dist/transition/transition.js +260 -0
  121. package/dist/capability-BbKW9w4O.d.ts +2131 -0
  122. package/dist/cli.js +20 -0
  123. package/dist/codegen/dist/assets.js +79 -0
  124. package/dist/codegen/dist/codegen.js +691 -0
  125. package/dist/codegen/dist/identifiers.js +203 -0
  126. package/dist/codegen/dist/index.js +3 -0
  127. package/dist/codegen/dist/printer.js +143 -0
  128. package/dist/codegen/dist/types.js +77 -0
  129. package/dist/core/dist/author-ids.js +51 -0
  130. package/dist/core/dist/author-schemas.js +330 -0
  131. package/dist/core/dist/block-flex-layout.js +801 -0
  132. package/dist/core/dist/build.js +4 -0
  133. package/dist/core/dist/capability.js +15 -0
  134. package/dist/core/dist/declaration.js +16 -0
  135. package/dist/core/dist/diagnostics.js +353 -0
  136. package/dist/core/dist/document-internals.js +26 -0
  137. package/dist/core/dist/document.js +417 -0
  138. package/dist/core/dist/font-seal.js +204 -0
  139. package/dist/core/dist/geometry-schemas.js +256 -0
  140. package/dist/core/dist/grid-layout.js +449 -0
  141. package/dist/core/dist/host.js +40 -0
  142. package/dist/core/dist/index.js +15 -0
  143. package/dist/core/dist/input-values.js +61 -0
  144. package/dist/core/dist/layout-protocol.js +61 -0
  145. package/dist/core/dist/layout-schemas.js +201 -0
  146. package/dist/core/dist/layout.js +340 -0
  147. package/dist/core/dist/masters.js +194 -0
  148. package/dist/core/dist/morph.js +30 -0
  149. package/dist/core/dist/placeholders.js +275 -0
  150. package/dist/core/dist/query.js +190 -0
  151. package/dist/core/dist/resolution.js +12 -0
  152. package/dist/core/dist/resolve.js +2246 -0
  153. package/dist/core/dist/stage-options.js +300 -0
  154. package/dist/core/dist/theme.js +1023 -0
  155. package/dist/core/dist/transform-geometry.js +72 -0
  156. package/dist/document-41spD7bq.d.ts +1350 -0
  157. package/dist/emit/dist/emit.js +957 -0
  158. package/dist/emit/dist/index.js +5 -0
  159. package/dist/emit/dist/ooxml.js +661 -0
  160. package/dist/emit/dist/shape-tree.js +12 -0
  161. package/dist/import/dist/alternate-content.js +54 -0
  162. package/dist/import/dist/diagnostics.js +157 -0
  163. package/dist/import/dist/fonts.js +309 -0
  164. package/dist/import/dist/import.js +513 -0
  165. package/dist/import/dist/index.js +16 -0
  166. package/dist/import/dist/masters.js +1293 -0
  167. package/dist/import/dist/mechanism.js +10 -0
  168. package/dist/import/dist/namespaces.js +61 -0
  169. package/dist/import/dist/notes-masters.js +300 -0
  170. package/dist/import/dist/opc.js +233 -0
  171. package/dist/import/dist/resources.js +166 -0
  172. package/dist/import/dist/sections.js +139 -0
  173. package/dist/import/dist/themes.js +777 -0
  174. package/dist/import/dist/visual.js +821 -0
  175. package/dist/import/dist/xml-fragments.js +277 -0
  176. package/dist/import/dist/xml-reader.js +267 -0
  177. package/dist/index-1ag7U9Jt.d.ts +63 -0
  178. package/dist/index-BEwhk7c8.d.ts +72 -0
  179. package/dist/index-cK2KtukZ.d.ts +161 -0
  180. package/dist/index-v77CTJev.d.ts +55 -0
  181. package/dist/index.d.ts +8 -0
  182. package/dist/index.js +82 -0
  183. package/dist/node.d.ts +53 -0
  184. package/dist/node.js +225 -0
  185. package/dist/pptxdk/src/cli-commands.js +907 -0
  186. package/dist/pptxdk/src/compose.js +53 -0
  187. package/dist/pptxdk/src/slide.js +9 -0
  188. package/dist/preview/dist/index.js +342 -0
  189. package/dist/preview/dist/options.js +40 -0
  190. package/dist/preview/dist/svg-guard.js +1089 -0
  191. package/dist/preview.d.ts +12 -0
  192. package/dist/preview.js +29 -0
  193. package/dist/react/dist/append.js +66 -0
  194. package/dist/react/dist/document-adapter.js +404 -0
  195. package/dist/react/dist/elements.js +82 -0
  196. package/dist/react/dist/from-vanilla.js +57 -0
  197. package/dist/react/dist/index.js +89 -0
  198. package/dist/react/dist/mount.js +34 -0
  199. package/dist/react/dist/reconciler.js +290 -0
  200. package/dist/react.d.ts +235 -0
  201. package/dist/react.js +31 -0
  202. package/dist/transition-6n8GZxSg.d.ts +9 -0
  203. package/dist/vanilla.d.ts +4 -0
  204. package/dist/vanilla.js +15 -0
  205. package/package.json +79 -3
  206. package/README.md +0 -3
@@ -0,0 +1,907 @@
1
+ import { previewErrorOptionSchemas } from "../../core/dist/stage-options.js";
2
+ import "../../core/dist/build.js";
3
+ import { findPackageJSON } from "node:module";
4
+ import { z } from "zod";
5
+ import { randomUUID } from "node:crypto";
6
+ import { strToU8, zipSync } from "fflate";
7
+ import { basename, dirname, extname, posix, relative, resolve } from "node:path";
8
+ import { readFileSync } from "node:fs";
9
+ import { lstat, mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
10
+ import { isNodeBrokenPipe } from "@boringparts/cli-contract/node";
11
+ import { CliWriteError, defineCli, executeCli, helpCapability, parseCliInvocation, schemaCapability, text, versionCapability } from "@boringparts/cli-contract";
12
+ import { BuildError, CodegenError, ImportError, buildDiagnosticSchema, codegen, codegenDiagnosticSchema, codegenTargetSchema, fatalImportIssueSchema, fontEmbeddingModeSchema, importDiagnosticSchema, previewPlaceholderSchema, targetNameSchema, targets } from "@officedk/pptxdk";
13
+ import { SourceLoadError, buildFromSource, importPptxFile, previewFromSource } from "@officedk/pptxdk/node";
14
+ import { PreviewPageRangeError, previewPageNumberSchema } from "@officedk/pptxdk/preview";
15
+ // src/cli-commands.ts
16
+ const { version: cliVersion } = z.object({ version: z.string().min(1) }).parse(JSON.parse(readFileSync(findPackageJSON("./", import.meta.url), "utf8")));
17
+ const previewPageItemSchema = z.object({
18
+ page: previewPageNumberSchema,
19
+ id: z.string(),
20
+ output: z.string()
21
+ });
22
+ const previewErrorWithPageSchema = z.discriminatedUnion("code", [
23
+ previewErrorOptionSchemas[0].extend({ page: previewPageNumberSchema }),
24
+ previewErrorOptionSchemas[1].extend({ page: previewPageNumberSchema }),
25
+ previewErrorOptionSchemas[2].extend({ page: previewPageNumberSchema }),
26
+ previewErrorOptionSchemas[3].extend({ page: previewPageNumberSchema }),
27
+ previewErrorOptionSchemas[4].extend({ page: previewPageNumberSchema })
28
+ ]);
29
+ const buildInputSchema = z.object({
30
+ entry: z.string().min(1),
31
+ out: z.string().min(1).optional(),
32
+ export: z.string().min(1).optional(),
33
+ target: targetNameSchema.optional(),
34
+ embedFonts: fontEmbeddingModeSchema.optional()
35
+ });
36
+ function parsePagesSpec(raw) {
37
+ const parts = raw.split(",");
38
+ if (parts.length === 0) return void 0;
39
+ const selected = /* @__PURE__ */ new Set();
40
+ for (const part of parts) {
41
+ if (/^\d+$/u.test(part)) {
42
+ const parsed = previewPageNumberSchema.safeParse(Number(part));
43
+ if (!parsed.success) return void 0;
44
+ selected.add(parsed.data);
45
+ continue;
46
+ }
47
+ const rangeMatch = /^(\d+)-(\d+)$/u.exec(part);
48
+ if (rangeMatch !== null) {
49
+ const start = previewPageNumberSchema.safeParse(Number(rangeMatch[1]));
50
+ const end = previewPageNumberSchema.safeParse(Number(rangeMatch[2]));
51
+ if (!start.success || !end.success || start.data > end.data) return;
52
+ for (let page = start.data; page <= end.data; page += 1) selected.add(page);
53
+ continue;
54
+ }
55
+ return;
56
+ }
57
+ return [...selected].toSorted((a, b) => a - b);
58
+ }
59
+ const pagesOptionSchema = z.codec(z.string().min(1), z.array(previewPageNumberSchema).min(1), {
60
+ decode(raw, ctx) {
61
+ const parsed = parsePagesSpec(raw);
62
+ if (parsed === void 0) {
63
+ ctx.issues.push({
64
+ code: "custom",
65
+ input: raw,
66
+ message: "Pages must be comma-separated 1-based page numbers or ascending closed ranges (for example, 1,3-5)"
67
+ });
68
+ return z.NEVER;
69
+ }
70
+ return parsed;
71
+ },
72
+ encode(pages) {
73
+ return pages.join(",");
74
+ }
75
+ });
76
+ const previewInputSchema = z.object({
77
+ entry: z.string().min(1),
78
+ outDir: z.string().min(1).optional(),
79
+ export: z.string().min(1).optional(),
80
+ pages: pagesOptionSchema.optional()
81
+ });
82
+ const codegenInputSchema = z.object({
83
+ entry: z.string().min(1),
84
+ target: codegenTargetSchema,
85
+ outDir: z.string().min(1).optional(),
86
+ outZip: z.string().min(1).optional()
87
+ });
88
+ const builtSchema = z.object({
89
+ output: z.string(),
90
+ slides: z.number().int().nonnegative()
91
+ });
92
+ const previewedSchema = z.object({
93
+ outputDir: z.string(),
94
+ pages: z.array(previewPageItemSchema),
95
+ placeholders: z.array(previewPlaceholderSchema)
96
+ });
97
+ const generatedSourceSchema = z.object({
98
+ target: codegenTargetSchema,
99
+ delivery: z.enum(["directory", "zip"]),
100
+ output: z.string(),
101
+ entry: z.string(),
102
+ files: z.array(z.string()),
103
+ slides: z.number().int().nonnegative(),
104
+ diagnostics: z.array(importDiagnosticSchema)
105
+ });
106
+ const invalidOutputSchema = z.object({
107
+ entry: z.string(),
108
+ output: z.string()
109
+ });
110
+ const pageOutOfRangeSchema = z.object({
111
+ requestedPages: z.array(previewPageNumberSchema),
112
+ totalSlides: z.number().int().nonnegative()
113
+ });
114
+ const sourceLoadFailedSchema = z.object({ message: z.string() });
115
+ const buildFailedSchema = z.object({ diagnostics: z.array(buildDiagnosticSchema) });
116
+ const previewFailedSchema = z.object({
117
+ outputDir: z.string(),
118
+ pages: z.array(previewPageItemSchema),
119
+ placeholders: z.array(previewPlaceholderSchema),
120
+ errors: z.array(previewErrorWithPageSchema)
121
+ });
122
+ const inputReadFailedSchema = z.object({
123
+ entry: z.string(),
124
+ message: z.string()
125
+ });
126
+ const importFailedSchema = z.object({
127
+ entry: z.string(),
128
+ issue: fatalImportIssueSchema,
129
+ message: z.string()
130
+ });
131
+ const codegenFailedSchema = z.object({
132
+ entry: z.string(),
133
+ diagnostics: z.array(codegenDiagnosticSchema),
134
+ importDiagnostics: z.array(importDiagnosticSchema)
135
+ });
136
+ const writeFailedSchema = z.object({
137
+ output: z.string(),
138
+ message: z.string()
139
+ });
140
+ const cancelledSchema = z.object({});
141
+ function targetByName(name) {
142
+ return Object.values(targets).find((target) => target.name === name);
143
+ }
144
+ function errorMessage(error) {
145
+ return error instanceof Error ? error.message : String(error);
146
+ }
147
+ function errnoCode(error) {
148
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : void 0;
149
+ }
150
+ function isCancelledError(error, signal) {
151
+ if (!signal?.aborted) return false;
152
+ return error === signal.reason || errnoCode(error) === "ABORT_ERR" || error instanceof Error && error.name === "AbortError";
153
+ }
154
+ /**
155
+ * Normalize dynamic text into the non-empty, single-line, NUL-free tuple
156
+ * required by `@boringparts/cli-contract`'s `text.lines(...)` invariant.
157
+ */
158
+ function toContractTextLines(lines) {
159
+ const [first = "Unknown error", ...rest] = lines.flatMap((line) => line.replaceAll("\0", "\\0").split(/\r\n|\r|\n/u));
160
+ return [first === "" && rest.every((line) => line === "") ? "Unknown error" : first, ...rest];
161
+ }
162
+ async function writeArtifact(path, bytes) {
163
+ const directory = dirname(path);
164
+ const temporary = resolve(directory, `.${basename(path)}.${randomUUID()}.tmp`);
165
+ try {
166
+ await mkdir(directory, { recursive: true });
167
+ await writeFile(temporary, bytes, { flag: "wx" });
168
+ await rename(temporary, path);
169
+ } finally {
170
+ await rm(temporary, { force: true });
171
+ }
172
+ }
173
+ async function isSameExistingFile(left, right) {
174
+ if (left === right) return true;
175
+ try {
176
+ const [leftStats, rightStats] = await Promise.all([stat(left), stat(right)]);
177
+ return leftStats.dev === rightStats.dev && leftStats.ino === rightStats.ino;
178
+ } catch {
179
+ return false;
180
+ }
181
+ }
182
+ async function validateOutputDir(entry, outDir) {
183
+ if (outDir === entry) return { kind: "invalidOutput" };
184
+ try {
185
+ return (await stat(outDir)).isDirectory() ? { kind: "valid" } : { kind: "invalidOutput" };
186
+ } catch (error) {
187
+ const code = errnoCode(error);
188
+ if (code === "ENOTDIR" || code === "ELOOP") return { kind: "invalidOutput" };
189
+ if (code !== "ENOENT") return {
190
+ kind: "error",
191
+ error
192
+ };
193
+ try {
194
+ await lstat(outDir);
195
+ return { kind: "invalidOutput" };
196
+ } catch (lstatError) {
197
+ const lstatCode = errnoCode(lstatError);
198
+ if (lstatCode === "ENOENT") return { kind: "valid" };
199
+ if (lstatCode === "ENOTDIR" || lstatCode === "ELOOP") return { kind: "invalidOutput" };
200
+ return {
201
+ kind: "error",
202
+ error: lstatError
203
+ };
204
+ }
205
+ }
206
+ }
207
+ function formatPreviewPlaceholderLines(placeholders) {
208
+ return placeholders.map((placeholder) => ` Placeholder ${placeholder.path}: ${placeholder.url}`);
209
+ }
210
+ function presentSourceLoadFailed({ message }) {
211
+ return text.lines(toContractTextLines([`Failed to load deck source: ${message}`]));
212
+ }
213
+ function formatBuildDiagnostic(diagnostic) {
214
+ const fieldSuffix = diagnostic.field ? ` (${diagnostic.field})` : "";
215
+ const base = ` ${diagnostic.path}${fieldSuffix} [${diagnostic.code}]: ${diagnostic.message}`;
216
+ const details = [];
217
+ if ("font" in diagnostic) {
218
+ const fontIdentity = [
219
+ diagnostic.font.family,
220
+ diagnostic.font.weight,
221
+ diagnostic.font.style
222
+ ].filter((part) => part !== void 0).join(" ");
223
+ if (fontIdentity.length > 0) details.push(`font: ${fontIdentity}`);
224
+ }
225
+ if ("characters" in diagnostic && diagnostic.characters.length > 0) details.push(`missing characters: ${diagnostic.characters.join(", ")}`);
226
+ return details.length > 0 ? `${base} (${details.join("; ")})` : base;
227
+ }
228
+ function presentBuildFailed({ diagnostics }) {
229
+ return text.lines(toContractTextLines(["Build failed:", ...diagnostics.map(formatBuildDiagnostic)]));
230
+ }
231
+ const fixedZipMtime = /* @__PURE__ */ new Date("2020-01-01T00:00:00Z");
232
+ function normalizeRelativePosixPath(rawPath) {
233
+ if (rawPath.length === 0 || rawPath.includes("\\") || rawPath.includes("\0") || rawPath.startsWith("/")) return;
234
+ const normalized = posix.normalize(rawPath);
235
+ if (normalized === "." || normalized === ".." || normalized.startsWith("../") || posix.isAbsolute(normalized)) return;
236
+ return normalized;
237
+ }
238
+ function normalizeCodegenFiles(files) {
239
+ const normalizedEntries = [];
240
+ for (const [rawPath, content] of Object.entries(files)) {
241
+ const normalizedPath = normalizeRelativePosixPath(rawPath);
242
+ if (normalizedPath === void 0) throw new Error(`Invalid generated relative file path: ${rawPath}`);
243
+ normalizedEntries.push({
244
+ path: normalizedPath,
245
+ bytes: typeof content === "string" ? strToU8(content) : content
246
+ });
247
+ }
248
+ return normalizedEntries.toSorted((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
249
+ }
250
+ function isWithinDirectory(directory, candidate) {
251
+ const rel = relative(directory, candidate);
252
+ return rel.length > 0 && rel !== ".." && !rel.startsWith("../") && !rel.startsWith("..\\");
253
+ }
254
+ function formatImportLocation(location) {
255
+ const details = [location.part];
256
+ if (location.slideIndex !== void 0) details.push(`slide ${location.slideIndex + 1}`);
257
+ if (location.objectName !== void 0 && location.objectName.length > 0) details.push(`object ${JSON.stringify(location.objectName)}`);
258
+ if (location.xpath !== void 0) details.push(`at ${location.xpath}`);
259
+ return details.join(" ");
260
+ }
261
+ function formatImportDiagnostic(diagnostic) {
262
+ const locationText = formatImportLocation(diagnostic.location);
263
+ const extras = [];
264
+ switch (diagnostic.code) {
265
+ case "corrupt-part": break;
266
+ case "missing-target-part":
267
+ extras.push(`relationship=${diagnostic.relationshipId}`, `target=${diagnostic.targetPart}`);
268
+ break;
269
+ case "broken-relationship":
270
+ extras.push(`relationship=${diagnostic.relationshipId}`);
271
+ break;
272
+ case "invalid-xml-value":
273
+ extras.push(`attributeOrElement=${diagnostic.attributeOrElement}`);
274
+ if (diagnostic.rawValue !== void 0) extras.push(`value=${JSON.stringify(diagnostic.rawValue)}`);
275
+ break;
276
+ case "unsupported-mechanism":
277
+ extras.push(`element=${diagnostic.namespaceUri}:${diagnostic.localName}`);
278
+ if (diagnostic.mechanismHint !== void 0) extras.push(`hint=${diagnostic.mechanismHint}`);
279
+ if (diagnostic.loss !== void 0) extras.push(`loss=${diagnostic.loss.lost}->${diagnostic.loss.retainedAs}`);
280
+ break;
281
+ case "compatibility-fallback":
282
+ extras.push(`preferred=${diagnostic.preferredMechanism}`, `fallback=${diagnostic.selectedFallback}`, `loss=${diagnostic.loss.lost}->${diagnostic.loss.retainedAs}`);
283
+ break;
284
+ case "unconsumed-xml": extras.push(`xml=${diagnostic.kind}:${diagnostic.namespaceUri}:${diagnostic.localName}`);
285
+ }
286
+ if ("cascaded" in diagnostic && diagnostic.cascaded !== void 0) extras.push(`cascaded=${diagnostic.cascaded.length}`);
287
+ const detailSuffix = extras.length > 0 ? ` (${extras.join(", ")})` : "";
288
+ return `Import diagnostic [${diagnostic.code}] (${diagnostic.disposition}) ${locationText}${detailSuffix}`;
289
+ }
290
+ function formatFatalImportIssue(issue) {
291
+ switch (issue.code) {
292
+ case "corrupt-archive": return "Corrupt PPTX archive";
293
+ case "missing-entry": {
294
+ const expected = issue.expectedRelationshipType === void 0 ? "" : ` (expected ${issue.expectedRelationshipType})`;
295
+ return `Missing entry at ${formatImportLocation(issue.location)}${expected}`;
296
+ }
297
+ case "malformed-xml": {
298
+ const detail = issue.detail === void 0 ? "" : `: ${issue.detail}`;
299
+ return `Malformed XML at ${formatImportLocation(issue.location)}${detail}`;
300
+ }
301
+ case "broken-entry-relationship": {
302
+ const details = [issue.relationshipId === void 0 ? void 0 : `relationship=${issue.relationshipId}`, issue.target === void 0 ? void 0 : `target=${issue.target}`].filter((item) => item !== void 0);
303
+ const suffix = details.length > 0 ? ` (${details.join(", ")})` : "";
304
+ return `Broken entry relationship at ${formatImportLocation(issue.location)}${suffix}`;
305
+ }
306
+ case "invalid-presentation-root": {
307
+ const rootName = [issue.namespaceUri, issue.localName].filter((item) => item !== void 0).join(":");
308
+ const suffix = rootName.length > 0 ? ` (${rootName})` : "";
309
+ return `Invalid presentation root at ${formatImportLocation(issue.location)}${suffix}`;
310
+ }
311
+ case "unsupported-format-baseline": return `Unsupported format baseline ${issue.baseline} (${issue.detectedNamespace}) at ${formatImportLocation(issue.location)}`;
312
+ }
313
+ }
314
+ const define = defineCli();
315
+ const buildCommand = define.command("build")({
316
+ kind: "command",
317
+ parent: "pptxdk",
318
+ name: "build",
319
+ description: "Build a PowerPoint deck from a source module.",
320
+ fields: {
321
+ entry: {
322
+ kind: "positional",
323
+ description: "Deck source entrypoint"
324
+ },
325
+ out: {
326
+ kind: "valueOption",
327
+ longOption: "--out",
328
+ shortAlias: "-o",
329
+ description: "PPTX output path (defaults to <entry>.pptx in current directory)"
330
+ },
331
+ export: {
332
+ kind: "valueOption",
333
+ longOption: "--export",
334
+ shortAlias: "-e",
335
+ description: "Named deck or component exported from entry (defaults to default)"
336
+ },
337
+ target: {
338
+ kind: "valueOption",
339
+ longOption: "--target",
340
+ description: "Target name exposed by library"
341
+ },
342
+ embedFonts: {
343
+ kind: "valueOption",
344
+ longOption: "--embed-fonts",
345
+ description: "Embed full fonts or subset of used glyphs"
346
+ }
347
+ },
348
+ input: buildInputSchema,
349
+ outputs: ({ atomic }) => {
350
+ const buildDeck = atomic({
351
+ success: {
352
+ kind: "data",
353
+ variants: { built: {
354
+ description: "Built PPTX deck",
355
+ exitCode: 0,
356
+ schema: builtSchema
357
+ } }
358
+ },
359
+ failures: {
360
+ invalidOutput: {
361
+ description: "Output path overwrites deck source",
362
+ exitCode: 2,
363
+ schema: invalidOutputSchema
364
+ },
365
+ sourceLoadFailed: {
366
+ description: "Failed to load deck source",
367
+ exitCode: 1,
368
+ schema: sourceLoadFailedSchema
369
+ },
370
+ buildFailed: {
371
+ description: "Deck build failed with diagnostics",
372
+ exitCode: 1,
373
+ schema: buildFailedSchema
374
+ },
375
+ writeFailed: {
376
+ description: "Failed to write PPTX output",
377
+ exitCode: 1,
378
+ schema: writeFailedSchema
379
+ },
380
+ cancelled: {
381
+ description: "Deck build cancelled",
382
+ exitCode: 130,
383
+ schema: cancelledSchema
384
+ }
385
+ },
386
+ async handler({ input, dependencies, outcome }) {
387
+ if (dependencies.signal?.aborted) return outcome.failure.cancelled({});
388
+ const entry = resolve(dependencies.cwd, input.entry);
389
+ const output = resolve(dependencies.cwd, input.out ?? `${basename(entry, extname(entry))}.pptx`);
390
+ if (await isSameExistingFile(entry, output)) return outcome.failure.invalidOutput({
391
+ entry,
392
+ output
393
+ });
394
+ const target = input.target === void 0 ? void 0 : targetByName(input.target);
395
+ let result;
396
+ try {
397
+ result = await buildFromSource(entry, {
398
+ ...input.export !== void 0 && { exportName: input.export },
399
+ ...target !== void 0 && { target },
400
+ ...dependencies.signal !== void 0 && { signal: dependencies.signal },
401
+ ...input.embedFonts !== void 0 && { embedFonts: input.embedFonts }
402
+ });
403
+ } catch (error) {
404
+ if (isCancelledError(error, dependencies.signal)) return outcome.failure.cancelled({});
405
+ if (error instanceof BuildError) return outcome.failure.buildFailed({ diagnostics: [...error.diagnostics] });
406
+ if (error instanceof SourceLoadError) return outcome.failure.sourceLoadFailed({ message: error.message });
407
+ throw error;
408
+ }
409
+ try {
410
+ await writeArtifact(output, result.pptx);
411
+ } catch (writeError) {
412
+ if (isCancelledError(writeError, dependencies.signal)) return outcome.failure.cancelled({});
413
+ return outcome.failure.writeFailed({
414
+ output,
415
+ message: errorMessage(writeError)
416
+ });
417
+ }
418
+ return outcome.data.built({
419
+ output,
420
+ slides: result.report.slides.length
421
+ });
422
+ }
423
+ });
424
+ return {
425
+ default: "text",
426
+ modes: {
427
+ text: buildDeck.text({
428
+ description: "Human-readable text output",
429
+ success: { built: ({ output, slides }) => text.lines(toContractTextLines([`Built deck: ${output}`, `Slides: ${slides}`])) },
430
+ failures: {
431
+ invalidOutput: () => text.line("Output path cannot overwrite deck source"),
432
+ sourceLoadFailed: presentSourceLoadFailed,
433
+ buildFailed: presentBuildFailed,
434
+ writeFailed: ({ output, message }) => text.lines(toContractTextLines([`Failed to write PPTX output to ${output}: ${message}`])),
435
+ cancelled: () => text.line("Deck build cancelled")
436
+ }
437
+ }),
438
+ structured: buildDeck.structured({ description: "Structured JSON output" })
439
+ }
440
+ };
441
+ }
442
+ });
443
+ const previewCommand = define.command("preview")({
444
+ kind: "command",
445
+ parent: "pptxdk",
446
+ name: "preview",
447
+ description: "Render static PNG page previews from a source module.",
448
+ fields: {
449
+ entry: {
450
+ kind: "positional",
451
+ description: "Deck source entrypoint"
452
+ },
453
+ outDir: {
454
+ kind: "valueOption",
455
+ longOption: "--out-dir",
456
+ shortAlias: "-o",
457
+ description: "Directory for preview PNGs (defaults to <entry>-preview in current directory)"
458
+ },
459
+ export: {
460
+ kind: "valueOption",
461
+ longOption: "--export",
462
+ shortAlias: "-e",
463
+ description: "Named deck or component exported from entry (defaults to default)"
464
+ },
465
+ pages: {
466
+ kind: "valueOption",
467
+ longOption: "--pages",
468
+ shortAlias: "-p",
469
+ description: "1-based page numbers or closed ranges to preview (for example, 1,3-5)"
470
+ }
471
+ },
472
+ input: previewInputSchema,
473
+ outputs: ({ atomic }) => {
474
+ const previewDeck = atomic({
475
+ success: {
476
+ kind: "data",
477
+ variants: { previewed: {
478
+ description: "Previewed deck pages as PNG images",
479
+ exitCode: 0,
480
+ schema: previewedSchema
481
+ } }
482
+ },
483
+ failures: {
484
+ invalidOutput: {
485
+ description: "Output directory is invalid or points to a non-directory path",
486
+ exitCode: 2,
487
+ schema: invalidOutputSchema
488
+ },
489
+ pageOutOfRange: {
490
+ description: "Requested preview pages exceed total slide count",
491
+ exitCode: 2,
492
+ schema: pageOutOfRangeSchema
493
+ },
494
+ sourceLoadFailed: {
495
+ description: "Failed to load deck source",
496
+ exitCode: 1,
497
+ schema: sourceLoadFailedSchema
498
+ },
499
+ buildFailed: {
500
+ description: "Deck build failed with diagnostics",
501
+ exitCode: 1,
502
+ schema: buildFailedSchema
503
+ },
504
+ previewFailed: {
505
+ description: "Deck preview failed on one or more pages",
506
+ exitCode: 1,
507
+ schema: previewFailedSchema
508
+ },
509
+ writeFailed: {
510
+ description: "Failed to write preview image",
511
+ exitCode: 1,
512
+ schema: writeFailedSchema
513
+ },
514
+ cancelled: {
515
+ description: "Deck preview cancelled",
516
+ exitCode: 130,
517
+ schema: cancelledSchema
518
+ }
519
+ },
520
+ async handler({ input, dependencies, outcome }) {
521
+ if (dependencies.signal?.aborted) return outcome.failure.cancelled({});
522
+ const entry = resolve(dependencies.cwd, input.entry);
523
+ const outputDir = resolve(dependencies.cwd, input.outDir ?? `${basename(entry, extname(entry))}-preview`);
524
+ const outputDirCheck = await validateOutputDir(entry, outputDir);
525
+ if (outputDirCheck.kind === "invalidOutput") return outcome.failure.invalidOutput({
526
+ entry,
527
+ output: outputDir
528
+ });
529
+ if (outputDirCheck.kind === "error") return outcome.failure.writeFailed({
530
+ output: outputDir,
531
+ message: errorMessage(outputDirCheck.error)
532
+ });
533
+ let result;
534
+ try {
535
+ result = await previewFromSource(entry, {
536
+ ...input.export !== void 0 && { exportName: input.export },
537
+ ...input.pages !== void 0 && { pages: input.pages },
538
+ ...dependencies.signal !== void 0 && { signal: dependencies.signal }
539
+ });
540
+ } catch (error) {
541
+ if (isCancelledError(error, dependencies.signal)) return outcome.failure.cancelled({});
542
+ if (error instanceof BuildError) return outcome.failure.buildFailed({ diagnostics: [...error.diagnostics] });
543
+ if (input.pages !== void 0 && error instanceof PreviewPageRangeError) return outcome.failure.pageOutOfRange({
544
+ requestedPages: input.pages,
545
+ totalSlides: error.totalSlides
546
+ });
547
+ if (error instanceof SourceLoadError) return outcome.failure.sourceLoadFailed({ message: error.message });
548
+ throw error;
549
+ }
550
+ const padWidth = Math.max(2, String(result.report.slides.length).length);
551
+ const writtenPages = [];
552
+ const placeholders = [];
553
+ const failedErrors = [];
554
+ for (const pageResult of result.pages) {
555
+ if (dependencies.signal?.aborted) return outcome.failure.cancelled({});
556
+ if (pageResult.errors.length > 0 || pageResult.png === void 0) {
557
+ if (pageResult.errors.length > 0) failedErrors.push(...pageResult.errors.map((error) => ({
558
+ ...error,
559
+ page: pageResult.page
560
+ })));
561
+ else failedErrors.push({
562
+ code: "preview-unsupported-capability",
563
+ page: pageResult.page,
564
+ path: `deck/slide[${pageResult.id}]`,
565
+ message: "Preview did not produce a PNG image",
566
+ capability: "preview"
567
+ });
568
+ continue;
569
+ }
570
+ const pageOutput = resolve(outputDir, `page-${String(pageResult.page).padStart(padWidth, "0")}.png`);
571
+ try {
572
+ await writeArtifact(pageOutput, pageResult.png);
573
+ } catch (writeError) {
574
+ if (isCancelledError(writeError, dependencies.signal)) return outcome.failure.cancelled({});
575
+ return outcome.failure.writeFailed({
576
+ output: pageOutput,
577
+ message: errorMessage(writeError)
578
+ });
579
+ }
580
+ writtenPages.push({
581
+ page: pageResult.page,
582
+ id: pageResult.id,
583
+ output: pageOutput
584
+ });
585
+ placeholders.push(...pageResult.placeholders);
586
+ }
587
+ if (failedErrors.length > 0) return outcome.failure.previewFailed({
588
+ outputDir,
589
+ pages: writtenPages,
590
+ placeholders,
591
+ errors: failedErrors
592
+ });
593
+ return outcome.data.previewed({
594
+ outputDir,
595
+ pages: writtenPages,
596
+ placeholders
597
+ });
598
+ }
599
+ });
600
+ return {
601
+ default: "text",
602
+ modes: {
603
+ text: previewDeck.text({
604
+ description: "Human-readable text output",
605
+ success: { previewed: ({ outputDir, pages, placeholders }) => text.lines(toContractTextLines([
606
+ `Previewed ${pages.length} page(s) in ${outputDir}`,
607
+ ...pages.map((page) => ` Page ${page.page} (${page.id}): ${page.output}`),
608
+ ...placeholders.length > 0 ? ["Placeholders:", ...formatPreviewPlaceholderLines(placeholders)] : []
609
+ ])) },
610
+ failures: {
611
+ invalidOutput: ({ output }) => text.lines(toContractTextLines([`Output directory cannot be a non-directory path: ${output}`])),
612
+ pageOutOfRange: ({ requestedPages, totalSlides }) => text.lines(toContractTextLines([`Requested pages (${requestedPages.join(", ")}) exceed total slides (${totalSlides})`])),
613
+ sourceLoadFailed: presentSourceLoadFailed,
614
+ buildFailed: presentBuildFailed,
615
+ previewFailed: ({ pages, placeholders, errors }) => text.lines(toContractTextLines([
616
+ "Preview failed:",
617
+ ...errors.map((error) => ` Page ${error.page} ${error.path}${error.field ? ` (${error.field})` : ""} [${error.code}]: ${error.message}`),
618
+ ...pages.length > 0 ? ["Written pages:", ...pages.map((page) => ` Page ${page.page} (${page.id}): ${page.output}`)] : [],
619
+ ...placeholders.length > 0 ? ["Placeholders:", ...formatPreviewPlaceholderLines(placeholders)] : []
620
+ ])),
621
+ writeFailed: ({ output, message }) => text.lines(toContractTextLines([`Failed to write preview image to ${output}: ${message}`])),
622
+ cancelled: () => text.line("Deck preview cancelled")
623
+ }
624
+ }),
625
+ structured: previewDeck.structured({ description: "Structured JSON output" })
626
+ }
627
+ };
628
+ }
629
+ });
630
+ const codegenCommand = define.command("codegen")({
631
+ kind: "command",
632
+ parent: "pptxdk",
633
+ name: "codegen",
634
+ description: "Generate rebuildable vanilla TypeScript or React TSX source from a PPTX file.",
635
+ fields: {
636
+ entry: {
637
+ kind: "positional",
638
+ description: "Input PPTX file path"
639
+ },
640
+ target: {
641
+ kind: "valueOption",
642
+ longOption: "--target",
643
+ shortAlias: "-t",
644
+ description: "Author source syntax target"
645
+ },
646
+ outDir: {
647
+ kind: "valueOption",
648
+ longOption: "--out-dir",
649
+ description: "Directory for generated source and assets (defaults to <entry>-source in current directory)"
650
+ },
651
+ outZip: {
652
+ kind: "valueOption",
653
+ longOption: "--out-zip",
654
+ description: "ZIP archive path for generated source and assets"
655
+ }
656
+ },
657
+ usageConstraints: [{
658
+ kind: "count",
659
+ fields: ["outDir", "outZip"],
660
+ max: 1
661
+ }],
662
+ input: codegenInputSchema,
663
+ outputs: ({ atomic }) => {
664
+ const codegenDeck = atomic({
665
+ success: {
666
+ kind: "data",
667
+ variants: { generated: {
668
+ description: "Generated rebuildable source and assets",
669
+ exitCode: 0,
670
+ schema: generatedSourceSchema
671
+ } }
672
+ },
673
+ failures: {
674
+ invalidOutput: {
675
+ description: "Output path is invalid, non-directory, or overwrites input PPTX",
676
+ exitCode: 2,
677
+ schema: invalidOutputSchema
678
+ },
679
+ inputReadFailed: {
680
+ description: "Failed to read input PPTX file",
681
+ exitCode: 1,
682
+ schema: inputReadFailedSchema
683
+ },
684
+ importFailed: {
685
+ description: "PPTX import failed with fatal issue",
686
+ exitCode: 1,
687
+ schema: importFailedSchema
688
+ },
689
+ codegenFailed: {
690
+ description: "Source generation failed for editable declarations",
691
+ exitCode: 1,
692
+ schema: codegenFailedSchema
693
+ },
694
+ writeFailed: {
695
+ description: "Failed to write generated source or ZIP archive",
696
+ exitCode: 1,
697
+ schema: writeFailedSchema
698
+ },
699
+ cancelled: {
700
+ description: "Source generation cancelled",
701
+ exitCode: 130,
702
+ schema: cancelledSchema
703
+ }
704
+ },
705
+ async handler({ input, dependencies, outcome }) {
706
+ if (dependencies.signal?.aborted) return outcome.failure.cancelled({});
707
+ const entry = resolve(dependencies.cwd, input.entry);
708
+ const delivery = input.outZip === void 0 ? "directory" : "zip";
709
+ const output = input.outZip !== void 0 ? resolve(dependencies.cwd, input.outZip) : resolve(dependencies.cwd, input.outDir ?? `${basename(entry, extname(entry))}-source`);
710
+ if (delivery === "zip") {
711
+ if (await isSameExistingFile(entry, output)) return outcome.failure.invalidOutput({
712
+ entry,
713
+ output
714
+ });
715
+ } else {
716
+ const dirCheck = await validateOutputDir(entry, output);
717
+ if (dirCheck.kind === "invalidOutput") return outcome.failure.invalidOutput({
718
+ entry,
719
+ output
720
+ });
721
+ if (dirCheck.kind === "error") return outcome.failure.writeFailed({
722
+ output,
723
+ message: errorMessage(dirCheck.error)
724
+ });
725
+ }
726
+ let imported;
727
+ try {
728
+ imported = await importPptxFile(entry, { ...dependencies.signal !== void 0 && { signal: dependencies.signal } });
729
+ } catch (error) {
730
+ if (isCancelledError(error, dependencies.signal)) return outcome.failure.cancelled({});
731
+ if (error instanceof ImportError) return outcome.failure.importFailed({
732
+ entry,
733
+ issue: error.issue,
734
+ message: error.message
735
+ });
736
+ return outcome.failure.inputReadFailed({
737
+ entry,
738
+ message: errorMessage(error)
739
+ });
740
+ }
741
+ if (dependencies.signal?.aborted) return outcome.failure.cancelled({});
742
+ const importDiagnostics = [...imported.report.diagnostics];
743
+ const runCodegen = dependencies.codegen ?? codegen;
744
+ let generated;
745
+ try {
746
+ generated = runCodegen(imported.document, { target: input.target });
747
+ } catch (error) {
748
+ if (isCancelledError(error, dependencies.signal)) return outcome.failure.cancelled({});
749
+ if (error instanceof CodegenError) return outcome.failure.codegenFailed({
750
+ entry,
751
+ diagnostics: [...error.diagnostics],
752
+ importDiagnostics
753
+ });
754
+ throw error;
755
+ }
756
+ if (dependencies.signal?.aborted) return outcome.failure.cancelled({});
757
+ const normalizedFiles = normalizeCodegenFiles(generated.files);
758
+ const filePaths = normalizedFiles.map((file) => file.path);
759
+ if (delivery === "zip") {
760
+ const zipEntries = {};
761
+ for (const file of normalizedFiles) zipEntries[file.path] = file.bytes;
762
+ try {
763
+ await writeArtifact(output, zipSync(zipEntries, {
764
+ level: 6,
765
+ mtime: fixedZipMtime
766
+ }));
767
+ } catch (writeError) {
768
+ if (isCancelledError(writeError, dependencies.signal)) return outcome.failure.cancelled({});
769
+ return outcome.failure.writeFailed({
770
+ output,
771
+ message: errorMessage(writeError)
772
+ });
773
+ }
774
+ } else {
775
+ const plannedTargets = [];
776
+ for (const file of normalizedFiles) {
777
+ const targetPath = resolve(output, ...file.path.split("/"));
778
+ if (!isWithinDirectory(output, targetPath) || await isSameExistingFile(entry, targetPath)) return outcome.failure.invalidOutput({
779
+ entry,
780
+ output: targetPath
781
+ });
782
+ plannedTargets.push({
783
+ targetPath,
784
+ bytes: file.bytes
785
+ });
786
+ }
787
+ for (const item of plannedTargets) {
788
+ if (dependencies.signal?.aborted) return outcome.failure.cancelled({});
789
+ try {
790
+ await writeArtifact(item.targetPath, item.bytes);
791
+ } catch (writeError) {
792
+ if (isCancelledError(writeError, dependencies.signal)) return outcome.failure.cancelled({});
793
+ return outcome.failure.writeFailed({
794
+ output: item.targetPath,
795
+ message: errorMessage(writeError)
796
+ });
797
+ }
798
+ }
799
+ }
800
+ return outcome.data.generated({
801
+ target: generated.target,
802
+ delivery,
803
+ output,
804
+ entry: generated.entry,
805
+ files: filePaths,
806
+ slides: imported.report.slideCount,
807
+ diagnostics: importDiagnostics
808
+ });
809
+ }
810
+ });
811
+ return {
812
+ default: "text",
813
+ modes: {
814
+ text: codegenDeck.text({
815
+ description: "Human-readable text output",
816
+ success: { generated: ({ target, delivery, output, entry, files, diagnostics }) => text.lines(toContractTextLines([
817
+ ...diagnostics.map(formatImportDiagnostic),
818
+ `Generated ${target} source (${delivery}): ${output}`,
819
+ `Entry: ${entry}`,
820
+ `Files: ${files.length}`
821
+ ])) },
822
+ failures: {
823
+ invalidOutput: ({ output }) => text.lines(toContractTextLines([`Output directory cannot be a non-directory path or overwrite input: ${output}`])),
824
+ inputReadFailed: ({ entry, message }) => text.lines(toContractTextLines([`Failed to read PPTX input ${entry}: ${message}`])),
825
+ importFailed: ({ entry, issue, message }) => text.lines(toContractTextLines([`Failed to import PPTX ${entry} [${issue.code}]: ${formatFatalImportIssue(issue)} (${message})`])),
826
+ codegenFailed: ({ diagnostics, importDiagnostics }) => text.lines(toContractTextLines([
827
+ ...importDiagnostics.map(formatImportDiagnostic),
828
+ "Source generation failed:",
829
+ ...diagnostics.map((diagnostic) => ` ${diagnostic.path}${diagnostic.field !== void 0 ? ` (${diagnostic.field})` : ""} [${diagnostic.code}]: ${diagnostic.message}`)
830
+ ])),
831
+ writeFailed: ({ output, message }) => text.lines(toContractTextLines([`Failed to write generated output to ${output}: ${message}`])),
832
+ cancelled: () => text.line("Source generation cancelled")
833
+ }
834
+ }),
835
+ structured: codegenDeck.structured({ description: "Structured JSON output" })
836
+ }
837
+ };
838
+ }
839
+ });
840
+ const cliContract = define({
841
+ root: "pptxdk",
842
+ help: helpCapability({
843
+ shortAlias: "-h",
844
+ headings: {
845
+ usage: "Usage",
846
+ commands: "Commands",
847
+ arguments: "Arguments",
848
+ options: "Options",
849
+ constraints: "Constraints",
850
+ schema: "Schema"
851
+ },
852
+ wording: {
853
+ commandPlaceholder: "command",
854
+ outputModePlaceholder: "mode",
855
+ choices: "{usage} (choices: {choices})",
856
+ default: "{usage} (default: {value})",
857
+ choicesAndDefault: "{usage} (choices: {choices}, default: {value})",
858
+ list: "{left}, {right}",
859
+ countAtMost: "At most {max} of {fields} may be specified"
860
+ }
861
+ }),
862
+ version: versionCapability({
863
+ value: text.line(cliVersion),
864
+ shortAlias: "-V",
865
+ description: "Print CLI version"
866
+ }),
867
+ schema: schemaCapability({ description: text.line("Print machine-readable CLI contract schema") }),
868
+ usageFailureExitCode: 2,
869
+ commands: {
870
+ pptxdk: {
871
+ kind: "rootGroup",
872
+ name: "pptxdk",
873
+ description: "Build, preview, and generate source from PowerPoint decks."
874
+ },
875
+ ...buildCommand,
876
+ ...previewCommand,
877
+ ...codegenCommand
878
+ }
879
+ });
880
+ /**
881
+ * Run a single CLI invocation and project its outcome through `runtime.write`.
882
+ *
883
+ * Returns the contract outcome exit code, `0` when `stdout` closes with `EPIPE`,
884
+ * or `70` after attempting to report an unexpected runtime/output failure to `stderr`.
885
+ */
886
+ async function runCli(runtime) {
887
+ try {
888
+ return (await executeCli(cliContract, {
889
+ invocation: parseCliInvocation(cliContract, runtime.argv.slice(2)),
890
+ dependencies: {
891
+ cwd: runtime.cwd ?? process.cwd(),
892
+ ...runtime.signal !== void 0 && { signal: runtime.signal }
893
+ },
894
+ write: runtime.write
895
+ })).exitCode;
896
+ } catch (error) {
897
+ if (error instanceof CliWriteError && error.destination === "stdout" && isNodeBrokenPipe(error)) return 0;
898
+ try {
899
+ await runtime.write({
900
+ destination: "stderr",
901
+ chunk: "Command execution failed; please check the runtime environment or report this issue.\n"
902
+ });
903
+ } catch {}
904
+ return 70;
905
+ }
906
+ }
907
+ export { buildInputSchema, builtSchema, cliContract, codegenInputSchema, generatedSourceSchema, previewInputSchema, previewedSchema, runCli };