@ongov/ontario-design-system-component-html-generator 8.1.0-alpha.1

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.
@@ -0,0 +1,193 @@
1
+ import { buildDocument, extractOntarioComponents, flattenShadowRoot, formatHtml, stripCssComments, stripHydrationArtifacts, transformHostSelectors, } from './utils.js';
2
+ // ─── stripHydrationArtifacts ────────────────────────────────────────────────
3
+ describe('stripHydrationArtifacts', () => {
4
+ it('removes data-* attributes', () => {
5
+ const input = '<div data-foo="bar" data-stencil-id="1">text</div>';
6
+ expect(stripHydrationArtifacts(input)).not.toContain('data-');
7
+ });
8
+ it('removes s-id and c-id attributes', () => {
9
+ const input = '<ontario-button s-id="1" c-id="2">click</ontario-button>';
10
+ const result = stripHydrationArtifacts(input);
11
+ expect(result).not.toContain('s-id');
12
+ expect(result).not.toContain('c-id');
13
+ });
14
+ it('removes s-* and c-* scope attributes', () => {
15
+ const input = '<span s-cr c-x="foo">text</span>';
16
+ const result = stripHydrationArtifacts(input);
17
+ expect(result).not.toMatch(/\bs-cr\b/);
18
+ expect(result).not.toContain('c-x');
19
+ });
20
+ it('removes "hydrated" class name but preserves other classes', () => {
21
+ const input = '<ontario-button class="hydrated my-class sc-ontario-button">click</ontario-button>';
22
+ const result = stripHydrationArtifacts(input);
23
+ expect(result).toContain('class="my-class"');
24
+ expect(result).not.toContain('hydrated');
25
+ expect(result).not.toContain('sc-ontario-button');
26
+ });
27
+ it('removes class attribute entirely when only artifact classes remain', () => {
28
+ const input = '<div class="hydrated sc-foo"></div>';
29
+ const result = stripHydrationArtifacts(input);
30
+ expect(result).not.toContain('class=');
31
+ });
32
+ it('leaves markup without artifacts unchanged (aside from whitespace normalisation)', () => {
33
+ const input = '<p>Hello world</p>';
34
+ expect(stripHydrationArtifacts(input)).toBe('<p>Hello world</p>');
35
+ });
36
+ });
37
+ // ─── flattenShadowRoot ───────────────────────────────────────────────────────
38
+ describe('flattenShadowRoot', () => {
39
+ it('removes <mock:shadow-root> open and close tags', () => {
40
+ const input = '<ontario-button><mock:shadow-root><button>click</button></mock:shadow-root></ontario-button>';
41
+ const result = flattenShadowRoot(input);
42
+ expect(result).not.toContain('mock:shadow-root');
43
+ expect(result).toContain('<button>click</button>');
44
+ });
45
+ it('removes <template shadowroot> and </template>', () => {
46
+ const input = '<div><template shadowroot="open"><p>inner</p></template></div>';
47
+ const result = flattenShadowRoot(input);
48
+ expect(result).not.toContain('<template');
49
+ expect(result).not.toContain('</template>');
50
+ expect(result).toContain('<p>inner</p>');
51
+ });
52
+ it('is a no-op on plain markup', () => {
53
+ const input = '<p>No shadow DOM here</p>';
54
+ expect(flattenShadowRoot(input)).toBe(input);
55
+ });
56
+ });
57
+ // ─── transformHostSelectors ─────────────────────────────────────────────────
58
+ describe('transformHostSelectors', () => {
59
+ it('replaces :host with the component tag name', () => {
60
+ const css = ':host { display: block; }';
61
+ expect(transformHostSelectors(css, 'ontario-button')).toBe('ontario-button { display: block; }');
62
+ });
63
+ it('replaces multiple :host occurrences', () => {
64
+ const css = ':host { color: red; } :host(:hover) { color: blue; }';
65
+ const result = transformHostSelectors(css, 'ontario-input');
66
+ expect(result).toBe('ontario-input { color: red; } ontario-input(:hover) { color: blue; }');
67
+ });
68
+ it('does not alter rules without :host', () => {
69
+ const css = '.button { font-size: 16px; }';
70
+ expect(transformHostSelectors(css, 'ontario-button')).toBe(css);
71
+ });
72
+ });
73
+ // ─── stripCssComments ───────────────────────────────────────────────────────
74
+ describe('stripCssComments', () => {
75
+ it('removes single block comments', () => {
76
+ const css = '/* This is a comment */ .foo { color: red; }';
77
+ expect(stripCssComments(css)).toBe('.foo { color: red; }');
78
+ });
79
+ it('removes multi-line block comments', () => {
80
+ const css = '/*\n * Multi-line\n * comment\n */\n.bar { display: flex; }';
81
+ expect(stripCssComments(css)).toBe('.bar { display: flex; }');
82
+ });
83
+ it('normalises excess blank lines', () => {
84
+ // The empty-line strip pass removes ALL blank lines; excess runs are then collapsed.
85
+ // Four consecutive newlines become two after normalisation.
86
+ const css = '.a {}\n\n\n\n\n.b {}';
87
+ const result = stripCssComments(css);
88
+ expect(result).not.toMatch(/\n{3,}/);
89
+ expect(result).toContain('.a {}');
90
+ expect(result).toContain('.b {}');
91
+ });
92
+ it('trims leading and trailing whitespace', () => {
93
+ const css = ' .x { margin: 0; } ';
94
+ expect(stripCssComments(css)).toBe('.x { margin: 0; }');
95
+ });
96
+ it('returns empty string for comment-only input', () => {
97
+ expect(stripCssComments('/* nothing else */')).toBe('');
98
+ });
99
+ });
100
+ // ─── extractOntarioComponents ───────────────────────────────────────────────
101
+ describe('extractOntarioComponents', () => {
102
+ it('extracts a single Ontario component', () => {
103
+ const markup = '<ontario-button type="primary">Click</ontario-button>';
104
+ expect(extractOntarioComponents(markup)).toEqual(['ontario-button']);
105
+ });
106
+ it('extracts multiple distinct components', () => {
107
+ const markup = '<ontario-button>A</ontario-button><ontario-input name="x"></ontario-input>';
108
+ const result = extractOntarioComponents(markup);
109
+ expect(result).toContain('ontario-button');
110
+ expect(result).toContain('ontario-input');
111
+ expect(result).toHaveLength(2);
112
+ });
113
+ it('deduplicates repeated components', () => {
114
+ const markup = '<ontario-button>A</ontario-button><ontario-button>B</ontario-button>';
115
+ expect(extractOntarioComponents(markup)).toEqual(['ontario-button']);
116
+ });
117
+ it('normalises ontario-icon-* variants to ontario-icon', () => {
118
+ const markup = '<ontario-icon-warning></ontario-icon-warning><ontario-icon-info></ontario-icon-info>';
119
+ expect(extractOntarioComponents(markup)).toEqual(['ontario-icon']);
120
+ });
121
+ it('returns an empty array when no Ontario components are present', () => {
122
+ expect(extractOntarioComponents('<div><p>Hello</p></div>')).toEqual([]);
123
+ });
124
+ });
125
+ // ─── buildDocument ───────────────────────────────────────────────────────────
126
+ describe('buildDocument', () => {
127
+ it('wraps markup in a style block when styles are provided', () => {
128
+ const result = buildDocument('<p>hello</p>', 'p { color: red; }');
129
+ expect(result).toBe('<style>\np { color: red; }\n</style>\n\n<p>hello</p>');
130
+ });
131
+ it('returns bare markup when styles are empty', () => {
132
+ expect(buildDocument('<p>hello</p>', '')).toBe('<p>hello</p>');
133
+ });
134
+ it('returns a complete HTML document when fullDocument is true', () => {
135
+ const result = buildDocument('<main><p>hello</p></main>', 'p { color: red; }', true);
136
+ expect(result).toContain('<!DOCTYPE html>');
137
+ expect(result).toContain('<html lang="en">');
138
+ expect(result).toContain('<head>');
139
+ expect(result).toContain('<body>');
140
+ expect(result).toContain('<style>');
141
+ expect(result).toContain('<main><p>hello</p></main>');
142
+ });
143
+ });
144
+ // ─── formatHtml ──────────────────────────────────────────────────────────────
145
+ describe('formatHtml', () => {
146
+ it('removes DOCTYPE, html, head, and body wrappers', () => {
147
+ const input = '<!doctype html><html><head><title>x</title></head><body><p>content</p></body></html>';
148
+ const result = formatHtml(input);
149
+ expect(result).not.toMatch(/<!doctype/i);
150
+ expect(result).not.toMatch(/<html/i);
151
+ expect(result).not.toMatch(/<head/i);
152
+ expect(result).not.toMatch(/<body/i);
153
+ expect(result).toContain('<p>');
154
+ });
155
+ it('removes HTML comments', () => {
156
+ const input = '<div><!-- comment --><p>text</p></div>';
157
+ expect(formatHtml(input)).not.toContain('<!--');
158
+ });
159
+ it('removes <style> tags by default', () => {
160
+ const input = '<style>body { color: red; }</style><p>text</p>';
161
+ expect(formatHtml(input)).not.toContain('<style>');
162
+ });
163
+ it('preserves <style> tags when removeStyles is false', () => {
164
+ const input = '<style>body { color: red; }</style><p>text</p>';
165
+ expect(formatHtml(input, false, false)).toContain('<style>');
166
+ });
167
+ it('indents nested tags with tabs', () => {
168
+ const input = '<div><p>text</p></div>';
169
+ const result = formatHtml(input);
170
+ expect(result).toContain('\t<p>');
171
+ });
172
+ it('strips outer component tag when stripOuterComponent is true', () => {
173
+ const input = '<ontario-button><button class="btn">Click</button></ontario-button>';
174
+ const result = formatHtml(input, true);
175
+ expect(result).not.toMatch(/^<ontario-button/);
176
+ expect(result).toContain('<button');
177
+ });
178
+ it('preserves outer component tag when stripOuterComponent is false', () => {
179
+ const input = '<ontario-button><button>Click</button></ontario-button>';
180
+ const result = formatHtml(input, false);
181
+ expect(result).toMatch(/^<ontario-button/);
182
+ });
183
+ it('handles self-closing tags without increasing indent', () => {
184
+ const input = '<div><img src="a.png" /><p>text</p></div>';
185
+ const result = formatHtml(input);
186
+ const lines = result.split('\n');
187
+ const imgLine = lines.find((l) => l.includes('<img'));
188
+ const pLine = lines.find((l) => l.includes('<p>'));
189
+ // Both img and p should be at the same indent level (one tab inside div)
190
+ expect(imgLine === null || imgLine === void 0 ? void 0 : imgLine.startsWith('\t')).toBe(true);
191
+ expect(pLine === null || pLine === void 0 ? void 0 : pLine.startsWith('\t')).toBe(true);
192
+ });
193
+ });
@@ -0,0 +1,21 @@
1
+ /** @type {import('jest').Config} */
2
+ export default {
3
+ preset: 'ts-jest',
4
+ testEnvironment: 'node',
5
+ // Map .js extension imports in source to their .ts counterparts
6
+ moduleNameMapper: {
7
+ '^(\\.{1,2}/.*)\\.js$': '$1',
8
+ },
9
+ transform: {
10
+ '^.+\\.tsx?$': [
11
+ 'ts-jest',
12
+ {
13
+ tsconfig: {
14
+ module: 'CommonJS',
15
+ moduleResolution: 'node',
16
+ },
17
+ },
18
+ ],
19
+ },
20
+ testMatch: ['**/src/**/*.test.ts'],
21
+ };
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@ongov/ontario-design-system-component-html-generator",
3
+ "version": "8.1.0-alpha.1",
4
+ "description": "Generates static HTML samples for Ontario Design System web components.",
5
+ "private": false,
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "bin": {
9
+ "odscompgen": "dist/cli.js",
10
+ "ontario-design-system-component-html-generator": "dist/cli.js"
11
+ },
12
+ "scripts": {
13
+ "build": "tsc && pnpm run docs:copy:readme",
14
+ "docs:copy:readme": "tsx ../../scripts/documentation-helper.ts -f README.md -p \"---\ntitle: HTML Sample Generator\n---\n\" -df ../docusaurus/docs/07-readme-html-sample-generator.md",
15
+ "start": "node dist/cli.js",
16
+ "test": "jest"
17
+ },
18
+ "keywords": [
19
+ "ontario",
20
+ "design-system",
21
+ "docs",
22
+ "samples"
23
+ ],
24
+ "author": "",
25
+ "license": "Apache-2.0",
26
+ "type": "module",
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "exports": {
31
+ ".": {
32
+ "import": "./dist/index.js",
33
+ "types": "./dist/index.d.ts"
34
+ }
35
+ },
36
+ "dependencies": {
37
+ "@ongov/ontario-design-system-component-library": "8.1.0-alpha.1",
38
+ "commander": "^11.0.0"
39
+ },
40
+ "devDependencies": {
41
+ "@jest/globals": "^29.7.0",
42
+ "@stencil/core": "^4.38.3",
43
+ "@types/jest": "^29.5.3",
44
+ "@types/node": "^24.10.1",
45
+ "jest": "^29.7.0",
46
+ "jest-environment-node": "^29.7.0",
47
+ "puppeteer": "^24.30.0",
48
+ "ts-jest": "^29.4.9",
49
+ "tsx": "^4.20.5",
50
+ "typescript": "^5.9.3"
51
+ },
52
+ "gitHead": "434a598e5375214b6e0a0725c134b45ad62b6a08"
53
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,179 @@
1
+ #!/usr/bin/env node
2
+ import { mkdirSync, writeFileSync } from 'fs';
3
+ import { existsSync } from 'fs';
4
+ import { readFile } from 'fs/promises';
5
+ import path from 'path';
6
+ import { fileURLToPath, pathToFileURL } from 'url';
7
+ import { Command } from 'commander';
8
+ import { generateSamples } from './index.js';
9
+ import type { ComponentSample, SampleFormatterOptions } from './types.js';
10
+
11
+ const INIT_TEMPLATE = `/*
12
+ * Ontario Design System — Sample Generator config
13
+ *
14
+ * Each entry in the \`samples\` array defines one HTML sample to generate.
15
+ * Run the generator with:
16
+ *
17
+ * odscompgen --samplesFile ./samples.config.js --outputDirectory ./output
18
+ */
19
+
20
+ export const samples = [
21
+ {
22
+ component: 'ontario-button',
23
+ html: '<ontario-button type="primary" label="Click me"></ontario-button>',
24
+ outputFile: 'ontario-button.html',
25
+ description: 'Primary button from Ontario Design System',
26
+ includeStyles: true,
27
+ },
28
+ // Add more component samples here:
29
+ // {
30
+ // component: 'ontario-input',
31
+ // html: '<ontario-input name="email" label="Email address"></ontario-input>',
32
+ // outputFile: 'ontario-input.html',
33
+ // description: 'Text input from Ontario Design System',
34
+ // includeStyles: true,
35
+ // },
36
+ ];
37
+ `;
38
+
39
+ const INIT_TEMPLATE_JSON = `{
40
+ "samples": [
41
+ {
42
+ "component": "ontario-button",
43
+ "html": "<ontario-button type=\\"primary\\" label=\\"Click me\\"></ontario-button>",
44
+ "outputFile": "ontario-button.html",
45
+ "description": "Primary button from Ontario Design System",
46
+ "includeStyles": true
47
+ }
48
+ ]
49
+ }
50
+ `;
51
+
52
+ const DEFAULT_SAMPLES_PATH = fileURLToPath(new URL('./sample-config.js', import.meta.url));
53
+
54
+ async function loadSamples(samplesFilePath: string): Promise<ComponentSample[] | null> {
55
+ const resolvedPath = path.resolve(samplesFilePath);
56
+
57
+ if (resolvedPath.toLowerCase().endsWith('.json')) {
58
+ const raw = await readFile(resolvedPath, 'utf8');
59
+ const parsed = JSON.parse(raw) as unknown;
60
+
61
+ if (Array.isArray(parsed)) {
62
+ return parsed as ComponentSample[];
63
+ }
64
+
65
+ if (parsed && typeof parsed === 'object' && Array.isArray((parsed as { samples?: unknown }).samples)) {
66
+ return (parsed as { samples: ComponentSample[] }).samples;
67
+ }
68
+
69
+ return null;
70
+ }
71
+
72
+ const samplesUrl = pathToFileURL(resolvedPath).href;
73
+ const samplesModule = await import(samplesUrl);
74
+ const samples = samplesModule.samples ?? samplesModule.default;
75
+
76
+ if (!Array.isArray(samples)) {
77
+ return null;
78
+ }
79
+
80
+ return samples as ComponentSample[];
81
+ }
82
+
83
+ const program = new Command();
84
+
85
+ program
86
+ .name('odscompgen')
87
+ .description('Generate static HTML samples for Ontario Design System web components.')
88
+ .version('1.0.0');
89
+
90
+ program
91
+ .command('init')
92
+ .description('Scaffold a starter samples config file that you can customise and expand upon.')
93
+ .argument('[output]', 'Path to write the config file to')
94
+ .option('-f, --force', 'Overwrite the file if it already exists')
95
+ .option('--format <format>', 'Output format: "js" or "json"', 'js')
96
+ .action((output: string | undefined, options: { force: boolean; format: string }) => {
97
+ const format = options.format === 'json' ? 'json' : 'js';
98
+ const defaultFilename = format === 'json' ? 'samples.json' : 'samples.config.js';
99
+ const resolvedOutput = output ?? defaultFilename;
100
+ const dest = path.resolve(resolvedOutput);
101
+
102
+ if (existsSync(dest) && !options.force) {
103
+ console.error(`File already exists: ${dest}\nUse --force to overwrite.`);
104
+ process.exitCode = 1;
105
+ return;
106
+ }
107
+
108
+ const template = format === 'json' ? INIT_TEMPLATE_JSON : INIT_TEMPLATE;
109
+ mkdirSync(path.dirname(dest), { recursive: true });
110
+ writeFileSync(dest, template, 'utf8');
111
+ console.info(`Created samples config: ${dest}`);
112
+ console.info(`Edit it, then run:\n odscompgen --samplesFile ${resolvedOutput}`);
113
+ });
114
+
115
+ program
116
+ .command('generate', { isDefault: true })
117
+ .description('Generate HTML samples (default command).')
118
+ .option(
119
+ '-o, --outputDirectory <path>',
120
+ 'Directory to write generated HTML samples to',
121
+ path.resolve(process.cwd(), 'generated-samples'),
122
+ )
123
+ .option(
124
+ '-s, --samplesFile <path>',
125
+ 'Path to a JS/TS module exporting `samples` (or default) or a JSON file containing `samples` or an array',
126
+ DEFAULT_SAMPLES_PATH,
127
+ )
128
+ .option('--no-strip-outer-component', 'Keep the outer component tag in formatted markup')
129
+ .option('--no-remove-styles', 'Keep inline <style> tags from renderer output during formatting')
130
+ .option('--full-document', 'Wrap generated output in a full HTML document with DOCTYPE/html/head/body')
131
+ .action(
132
+ async (options: {
133
+ outputDirectory: string;
134
+ samplesFile: string;
135
+ stripOuterComponent: boolean;
136
+ removeStyles: boolean;
137
+ fullDocument: boolean;
138
+ }) => {
139
+ const outputDirectory = path.resolve(options.outputDirectory);
140
+ mkdirSync(outputDirectory, { recursive: true });
141
+
142
+ const samples = await loadSamples(options.samplesFile);
143
+
144
+ if (!Array.isArray(samples)) {
145
+ console.error(
146
+ `Could not load samples from: ${options.samplesFile}. Expected one of: JS/TS module with \`samples\` export, default array export, JSON array, or JSON object with \`samples\` array.`,
147
+ );
148
+ process.exitCode = 1;
149
+ return;
150
+ }
151
+
152
+ const formatterOptions: SampleFormatterOptions = {
153
+ stripOuterComponent: options.stripOuterComponent,
154
+ removeStyles: options.removeStyles,
155
+ fullDocument: options.fullDocument,
156
+ };
157
+
158
+ const result = await generateSamples({ samples, formatterOptions });
159
+
160
+ for (const item of result.items) {
161
+ if (!item.success || !item.renderedHtml) {
162
+ console.error(`Failed to render ${item.sample.component}: ${item.error ?? 'Unknown error'}`);
163
+ continue;
164
+ }
165
+
166
+ const outputPath = path.join(outputDirectory, item.sample.outputFile);
167
+ writeFileSync(outputPath, `${item.renderedHtml}\n`, 'utf8');
168
+ }
169
+
170
+ if (result.summary.failed > 0) {
171
+ console.warn(`Sample generation completed with ${result.summary.failed} failures.`);
172
+ process.exitCode = 1;
173
+ } else {
174
+ console.info(`Generated ${result.summary.succeeded} samples in ${outputDirectory}.`);
175
+ }
176
+ },
177
+ );
178
+
179
+ program.parse();
@@ -0,0 +1,24 @@
1
+ /* eslint-disable */
2
+ /* tslint:disable */
3
+ /*
4
+ * This is an autogenerated file created by the Stencil compiler.
5
+ * It contains typing information for all components that exist in this project.
6
+ */
7
+ import { HTMLStencilElement, JSXBase } from "@stencil/core/internal";
8
+ export namespace Components {
9
+ }
10
+ declare global {
11
+ interface HTMLElementTagNameMap {
12
+ }
13
+ }
14
+ declare namespace LocalJSX {
15
+ interface IntrinsicElements {
16
+ }
17
+ }
18
+ export { LocalJSX as JSX };
19
+ declare module "@stencil/core" {
20
+ export namespace JSX {
21
+ interface IntrinsicElements {
22
+ }
23
+ }
24
+ }
package/src/index.ts ADDED
@@ -0,0 +1,199 @@
1
+ /*
2
+ * Library entrypoint for sample generation.
3
+ *
4
+ * Responsibilities:
5
+ * - Render input sample HTML using a pluggable renderer.
6
+ * - Normalize/clean the rendered markup.
7
+ * - Resolve and transform component styles.
8
+ * - Return a deterministic result object (`items` + `summary`) without doing filesystem I/O.
9
+ *
10
+ * Filesystem writes and batch orchestration are intentionally handled by the CLI layer.
11
+ */
12
+
13
+ import { readFileSync } from 'fs';
14
+ import path from 'path';
15
+ import { renderToString } from '@ongov/ontario-design-system-component-library/hydrate';
16
+ import type {
17
+ ComponentSample,
18
+ GeneratedSampleItem,
19
+ SampleFormatterOptions,
20
+ SampleGeneratorConfig,
21
+ SampleGeneratorResult,
22
+ } from './types.js';
23
+ import {
24
+ buildDocument,
25
+ extractOntarioComponents,
26
+ flattenShadowRoot,
27
+ formatHtml,
28
+ stripCssComments,
29
+ stripHydrationArtifacts,
30
+ transformHostSelectors,
31
+ } from './utils.js';
32
+
33
+ export type {
34
+ ComponentSample,
35
+ GeneratedSampleItem,
36
+ SampleFormatterOptions,
37
+ SampleGeneratorConfig,
38
+ SampleGeneratorResult,
39
+ } from './types.js';
40
+
41
+ interface RenderedSampleParts {
42
+ markup: string;
43
+ styles: string;
44
+ renderedHtml: string;
45
+ }
46
+
47
+ type SampleRenderer = NonNullable<SampleGeneratorConfig['renderer']>;
48
+ type SampleStyleLoader = NonNullable<SampleGeneratorConfig['styleLoader']>;
49
+
50
+ /**
51
+ * Dynamically generates CSS file paths for Ontario components.
52
+ * All Ontario components follow the same directory structure in the component library.
53
+ */
54
+ function getComponentStylePath(tagName: string): string {
55
+ return path.join(
56
+ process.cwd(),
57
+ 'node_modules',
58
+ '@ongov',
59
+ 'ontario-design-system-component-library',
60
+ 'dist',
61
+ 'collection',
62
+ 'components',
63
+ tagName,
64
+ `${tagName}.css`,
65
+ );
66
+ }
67
+
68
+ async function defaultRenderer(html: string): Promise<string> {
69
+ const hydrated = await renderToString(html, {
70
+ prettyHtml: true,
71
+ });
72
+
73
+ return hydrated.html ?? '';
74
+ }
75
+
76
+ function defaultStyleLoader(tagName: string): string {
77
+ const cssPath = getComponentStylePath(tagName);
78
+ if (!cssPath) {
79
+ return '';
80
+ }
81
+
82
+ try {
83
+ const css = readFileSync(cssPath, 'utf8');
84
+ const transformed = transformHostSelectors(css, tagName);
85
+ return stripCssComments(transformed);
86
+ } catch {
87
+ return '';
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Loads CSS file for a component, transforms :host selectors, and strips comments.
93
+ */
94
+ async function loadComponentStyles(tagName: string, styleLoader: SampleStyleLoader): Promise<string> {
95
+ try {
96
+ const css = await styleLoader(tagName);
97
+ if (!css) {
98
+ return '';
99
+ }
100
+
101
+ const transformed = transformHostSelectors(css, tagName);
102
+ return stripCssComments(transformed);
103
+ } catch {
104
+ return '';
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Resolves CSS for a sample and nested Ontario components (e.g., icons).
110
+ */
111
+ async function buildStyles(sample: ComponentSample, markup: string, styleLoader: SampleStyleLoader): Promise<string> {
112
+ if (sample.includeStyles !== false) {
113
+ const mainCss = await loadComponentStyles(sample.component, styleLoader);
114
+
115
+ const nestedComponents = extractOntarioComponents(markup);
116
+ const nestedCss = (
117
+ await Promise.all(
118
+ nestedComponents.filter((tag) => tag !== sample.component).map((tag) => loadComponentStyles(tag, styleLoader)),
119
+ )
120
+ )
121
+ .filter((css) => css.length > 0)
122
+ .join('\n\n');
123
+
124
+ const allCss = [mainCss, nestedCss].filter(Boolean).join('\n\n');
125
+
126
+ return allCss;
127
+ }
128
+
129
+ return '';
130
+ }
131
+
132
+ /**
133
+ * Renders Ontario Design System components using server-side rendering (renderToString)
134
+ * for fast, clean HTML output.
135
+ */
136
+ async function renderSample(
137
+ sample: ComponentSample,
138
+ renderer: SampleRenderer,
139
+ styleLoader: SampleStyleLoader,
140
+ formatterOptions: SampleFormatterOptions,
141
+ ): Promise<RenderedSampleParts> {
142
+ const hydratedHtml = await renderer(sample.html);
143
+
144
+ const renderedMarkup = stripHydrationArtifacts(flattenShadowRoot(hydratedHtml));
145
+ const markup = formatHtml(
146
+ renderedMarkup,
147
+ formatterOptions.stripOuterComponent ?? true,
148
+ formatterOptions.removeStyles ?? true,
149
+ );
150
+ const styles = await buildStyles(sample, markup, styleLoader);
151
+ const renderedHtml = buildDocument(markup, styles, formatterOptions.fullDocument ?? false);
152
+
153
+ return {
154
+ markup,
155
+ styles,
156
+ renderedHtml,
157
+ };
158
+ }
159
+
160
+ /**
161
+ * Orchestrates the sample generation process.
162
+ */
163
+ export async function generateSamples(config: SampleGeneratorConfig): Promise<SampleGeneratorResult> {
164
+ const renderer = config.renderer ?? defaultRenderer;
165
+ const styleLoader = config.styleLoader ?? defaultStyleLoader;
166
+ const formatterOptions = config.formatterOptions ?? {};
167
+ const items: GeneratedSampleItem[] = [];
168
+
169
+ for (const sample of config.samples) {
170
+ try {
171
+ const renderedSample = await renderSample(sample, renderer, styleLoader, formatterOptions);
172
+ items.push({
173
+ sample,
174
+ success: true,
175
+ markup: renderedSample.markup,
176
+ styles: renderedSample.styles,
177
+ renderedHtml: renderedSample.renderedHtml,
178
+ });
179
+ } catch (error) {
180
+ items.push({
181
+ sample,
182
+ success: false,
183
+ error: error instanceof Error ? error.message : String(error),
184
+ });
185
+ }
186
+ }
187
+
188
+ const succeeded = items.filter((item) => item.success).length;
189
+ const failed = items.length - succeeded;
190
+
191
+ return {
192
+ items,
193
+ summary: {
194
+ total: items.length,
195
+ succeeded,
196
+ failed,
197
+ },
198
+ };
199
+ }