Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

[Pages] Enable non-English Power Pages site creation  (#533)

Sandeep Satheesh8c09875b8102
diff --git a/plugins/power-pages/references/approval-gates.md b/plugins/power-pages/references/approval-gates.md
index 6f6af8938..9d0b36e38 100644
--- a/plugins/power-pages/references/approval-gates.md
+++ b/plugins/power-pages/references/approval-gates.md
@@ -477,6 +477,7 @@ When **removing** a gate, also remove its catalog row in the same PR.
| `create-site:1.5.creation-path` | not-a-gate | - | 1.5 | Route preference before catalog fetch; no project directory, Dataverse write, or durable skill state exists | - |
| `create-site:1.5.template-choice` | not-a-gate | — | 1.5 | Read-only route selection after template preview; only disposable temp preview files exist, with no project directory, Dataverse write, or durable skill state | — |
| `create-site:1.5.from-scratch-setup` | not-a-gate | — | 1.5 | Deferred framework and directory data-gathering before any scaffold files are written | — |
+| `create-site:1.5.content-language` | not-a-gate | — | 1.5 | *"Which language should the site content use?"* — validates the single SPA content locale for the from-scratch path; Dataverse and Power Pages system messages remain English | — |
| `create-site:1.5.confirm-environment` | gate | consent | 1.5 | Target environment resolved from PAC/Azure auth — confirm before any environment preflight or import mutation | template-cache |
| `create-site:1.5.unblock-js` | gate | consent | 1.5 | Target environment blocks `.js` in `blockedattachments` — remove only `js` before uploading website code | attachment-block-modified |
| `create-site:1.5.language-requirement` | not-a-gate | - | 1.5 | Route selection after blocking template-declared Dataverse language preflight; no override option exists and no org mutation has happened | - |
@@ -492,7 +493,7 @@ When **removing** a gate, also remove its catalog row in the same PR.
| `create-site:3.requirements` | gate | plan | 3 | *"Which features? / Aesthetic / Mood / Brand"* - four sub-prompts sharing this gate, plus a free-text brand follow-up (website URL, or colors and logo) when the user has a brand to match; shape the rendered Phase 4 plan | nothing |
| `create-site:4.7.plan-approval` | gate | plan | 4.7 | HTML plan rendered — *"Approve and start building / I'd like to make changes"* | nothing |
| `create-site:5.7.critique-blocked` | gate | progress | 5.7 | A critical design gate still fails after three critique rounds - *"Keep fixing / Continue and record it as a known issue / Stop here"* | nothing |
-| `create-site:5.8.localization` | not-a-gate | — | 5.8 | *"Would you like to add localization support to this site now?"* — selects whether to enter the child localization workflow after site implementation and design critique; the child workflow's Phase 3 gate approves every localization write | — |
+| `create-site:5.8.localization` | not-a-gate | — | 5.8 | *"Would you like to add more languages now?"* — selects whether to enter the child localization workflow after implementation and design critique; the child workflow preserves the detected document locale as its source/default and its Phase 3 gate approves every localization write | — |
| `create-site:7.review` | gate | plan | 7 | Live site ready — *"Would you like any changes?"* | nothing |
| `create-site:8.deploy` | gate | plan | 8 | *"Deploy now (Recommended) / Skip for now"* — invokes `/deploy-site` on Yes; when `SAMPLE CONTENT` placeholders remain, they are listed first, the question names the count, and Skip becomes the recommended option | nothing |
diff --git a/plugins/power-pages/references/framework-conventions.md b/plugins/power-pages/references/framework-conventions.md
index e345817a0..477686f92 100644
--- a/plugins/power-pages/references/framework-conventions.md
+++ b/plugins/power-pages/references/framework-conventions.md
@@ -14,7 +14,7 @@ Only static SPA frameworks are supported. Server-rendered frameworks (Next.js, N
|-----------|-----------|--------|--------------|-----------------|------------|
| React | Vite | react-router-dom | `dist` | `public/` | `index.html` (project root) |
| Vue | Vite | vue-router | `dist` | `public/` | `index.html` (project root) |
-| Angular | Angular CLI | @angular/router | `dist/__SITE_NAME__/browser` | `public/` | `src/index.html` |
+| Angular | Angular CLI | @angular/router | `dist/__SITE_NAME__/browser` | `public/` | `angular.json` build target `index`; defaults to `src/index.html` |
| Astro | Astro | File-based + View Transitions | `dist` | `public/` | `src/layouts/*.astro` or `src/pages/*.astro` |
## Framework Detection
diff --git a/plugins/power-pages/scripts/lib/localization-config.js b/plugins/power-pages/scripts/lib/localization-config.js
index 82003d93d..e1790376c 100644
--- a/plugins/power-pages/scripts/lib/localization-config.js
+++ b/plugins/power-pages/scripts/lib/localization-config.js
@@ -604,6 +604,28 @@ function validateCanonicalTag(canonicalTag, registry) {
return errors;
}
+const MAX_LOCALE_CANDIDATE_LENGTH = 255;
+const MAX_LOCALE_LIST_CANDIDATE_LENGTH = 4096;
+const SAFE_LOCALE_CANDIDATE_PATTERN =
+ /^[A-Za-z0-9]{1,8}(?:-[A-Za-z0-9]{1,8})*$/;
+
+function isSafeLocaleCandidate(value) {
+ return (
+ typeof value === 'string' &&
+ value.length <= MAX_LOCALE_CANDIDATE_LENGTH &&
+ SAFE_LOCALE_CANDIDATE_PATTERN.test(value)
+ );
+}
+
+function isSafeLocaleListCandidate(value) {
+ return (
+ typeof value === 'string' &&
+ value.length <= MAX_LOCALE_LIST_CANDIDATE_LENGTH &&
+ value.length > 0 &&
+ value.split(',').every(isSafeLocaleCandidate)
+ );
+}
+
function validateLocales(input, options = {}) {
const registry = loadRegistry(options.registryPath);
const rawValues = Array.isArray(input) ? input : String(input || '').split(',');
@@ -619,6 +641,14 @@ function validateLocales(input, options = {}) {
invalid.push({ input: original, reason: 'empty language tag' });
continue;
}
+ if (!isSafeLocaleCandidate(original)) {
+ invalid.push({
+ input: original,
+ reason:
+ 'language tag must contain only 1-8 character ASCII alphanumeric subtags separated by hyphens',
+ });
+ continue;
+ }
const lowerOriginal = original.toLowerCase();
const fullTagType = registry.sets.grandfathered?.has(lowerOriginal)
@@ -686,6 +716,92 @@ function validateLocales(input, options = {}) {
};
}
+function getLocaleDirection(locale) {
+ let canonical;
+ let parsed;
+ try {
+ [canonical] = Intl.getCanonicalLocales(locale);
+ parsed = new Intl.Locale(canonical);
+ } catch {
+ // Private-use-only tags such as x-contoso are valid BCP-47 identifiers but
+ // do not carry script metadata from which a direction can be derived.
+ return 'ltr';
+ }
+
+ // Node exposes Unicode text direction through Intl.Locale.textInfo. Keep the
+ // language fallback for older Node releases that do not implement it.
+ const intlDirection = parsed.textInfo?.direction;
+ if (intlDirection === 'rtl' || intlDirection === 'ltr') return intlDirection;
+
+ const rtlLanguages = new Set(['ar', 'dv', 'fa', 'he', 'ku', 'ps', 'sd', 'ug', 'ur', 'yi']);
+ return rtlLanguages.has(parsed.language.toLowerCase()) ? 'rtl' : 'ltr';
+}
+
+function getLocaleDisplayNames(locale) {
+ let parsed;
+ try {
+ parsed = new Intl.Locale(locale);
+ } catch {
+ // Private-use-only tags have no language subtag that Intl.DisplayNames can
+ // translate. Keep the canonical tag usable while exposing no invented name.
+ return {
+ languageName: null,
+ localeName: null,
+ nativeLanguageName: null,
+ nativeLocaleName: null,
+ };
+ }
+
+ try {
+ const englishNames = new Intl.DisplayNames(['en'], {
+ type: 'language',
+ fallback: 'none',
+ });
+ const nativeNames = new Intl.DisplayNames([locale], {
+ type: 'language',
+ fallback: 'none',
+ });
+ return {
+ languageName: englishNames.of(parsed.language) || null,
+ localeName: englishNames.of(locale) || null,
+ nativeLanguageName: nativeNames.of(parsed.language) || null,
+ nativeLocaleName: nativeNames.of(locale) || null,
+ };
+ } catch {
+ // Minimal ICU builds may not include display-name data. Callers can still
+ // use the validated canonical locale rather than guessing a language name.
+ return {
+ languageName: null,
+ localeName: null,
+ nativeLanguageName: null,
+ nativeLocaleName: null,
+ };
+ }
+}
+
+function resolveLocale(input) {
+ const validation = validateLocales([input]);
+ if (!validation.valid || validation.locales.length !== 1) {
+ return {
+ ...validation,
+ locale: null,
+ direction: null,
+ languageName: null,
+ localeName: null,
+ nativeLanguageName: null,
+ nativeLocaleName: null,
+ };
+ }
+
+ const [locale] = validation.locales;
+ return {
+ ...validation,
+ locale,
+ direction: getLocaleDirection(locale),
+ ...getLocaleDisplayNames(locale),
+ };
+}
+
function detectLocalization(projectRoot) {
const manifestPath = path.join(projectRoot, MANIFEST_NAME);
const manifestExists = fs.existsSync(manifestPath);
@@ -1039,9 +1155,356 @@ function discoverLocalizationImplementation(
};
}
+function relativeProjectPath(projectRoot, filePath) {
+ return path.relative(projectRoot, filePath).replace(/\\/g, '/');
+}
+
+function discoverAngularDocument(projectRoot) {
+ const defaultSource = 'src/index.html';
+ const angularConfigPath = path.join(projectRoot, 'angular.json');
+ if (!fs.existsSync(angularConfigPath)) {
+ return {
+ candidates: [path.join(projectRoot, defaultSource)],
+ expectedSources: [defaultSource],
+ };
+ }
+
+ const angularConfig = readJson(angularConfigPath);
+ if (!angularConfig || typeof angularConfig !== 'object' || Array.isArray(angularConfig)) {
+ return {
+ candidates: [],
+ expectedSources: ['angular.json'],
+ reason: 'document-configuration-invalid',
+ conflicts: ['angular.json is not valid JSON.'],
+ };
+ }
+
+ const configuredSources = [];
+ const projects = angularConfig.projects &&
+ typeof angularConfig.projects === 'object' &&
+ !Array.isArray(angularConfig.projects)
+ ? angularConfig.projects
+ : {};
+ for (const project of Object.values(projects)) {
+ if (!project || typeof project !== 'object' || Array.isArray(project)) continue;
+ const build = project.targets?.build || project.architect?.build;
+ const index = build?.options?.index;
+ const input = typeof index === 'string'
+ ? index
+ : index && typeof index === 'object' && typeof index.input === 'string'
+ ? index.input
+ : null;
+ if (input?.trim()) configuredSources.push(input.trim().replace(/\\/g, '/'));
+ }
+
+ const uniqueSources = [...new Set(configuredSources)];
+ if (uniqueSources.length > 1) {
+ return {
+ candidates: [],
+ expectedSources: uniqueSources,
+ reason: 'document-ambiguous',
+ conflicts: [
+ `angular.json configures multiple application index documents: ${uniqueSources.join(', ')}.`,
+ ],
+ };
+ }
+
+ const source = uniqueSources[0] || defaultSource;
+ const resolved = resolveProjectRelativePath(projectRoot, source);
+ if (!resolved.valid) {
+ return {
+ candidates: [],
+ expectedSources: [source],
+ reason: 'document-configuration-invalid',
+ conflicts: [
+ `angular.json index path "${source}" ${resolved.reason}.`,
+ ],
+ };
+ }
+
+ return {
+ candidates: [resolved.path],
+ expectedSources: [source],
+ };
+}
+
+function discoverSiteDocuments(projectRoot, framework) {
+ const resolvedRoot = path.resolve(projectRoot);
+ if (framework === 'react' || framework === 'vue') {
+ return {
+ candidates: [path.join(resolvedRoot, 'index.html')],
+ expectedSources: ['index.html'],
+ };
+ }
+ if (framework === 'angular') {
+ return discoverAngularDocument(resolvedRoot);
+ }
+ if (framework === 'astro') {
+ const candidates = [];
+ for (const relativeDirectory of ['src/layouts', 'src/pages']) {
+ const directory = path.join(resolvedRoot, relativeDirectory);
+ if (!fs.existsSync(directory)) continue;
+ for (const filePath of walkFiles(directory)) {
+ if (/\.astro$/i.test(filePath)) candidates.push(filePath);
+ }
+ }
+ return {
+ candidates,
+ expectedSources: candidates.length
+ ? candidates.map((filePath) => relativeProjectPath(resolvedRoot, filePath))
+ : ['src/layouts/**/*.astro', 'src/pages/**/*.astro'],
+ };
+ }
+ throw new Error(`Unsupported framework selection: ${framework || '<empty>'}.`);
+}
+
+function detectSiteLanguage(projectRoot, framework) {
+ const resolvedRoot = path.resolve(projectRoot);
+ const discovery = discoverSiteDocuments(resolvedRoot, framework);
+ if (discovery.reason) {
+ return {
+ detected: false,
+ valid: false,
+ locale: null,
+ direction: null,
+ source: null,
+ conflicts: discovery.conflicts || [],
+ reason: discovery.reason,
+ expectedSources: discovery.expectedSources,
+ };
+ }
+
+ const existingCandidates = discovery.candidates.filter((filePath) =>
+ fs.existsSync(filePath) && fs.statSync(filePath).isFile()
+ );
+ if (existingCandidates.length === 0) {
+ return {
+ detected: false,
+ valid: false,
+ locale: null,
+ direction: null,
+ source: null,
+ conflicts: [],
+ reason: 'document-not-found',
+ expectedSources: discovery.expectedSources,
+ };
+ }
+
+ const findings = [];
+ const documentsWithoutHtmlRoot = [];
+ for (const filePath of existingCandidates) {
+ const text = fs.readFileSync(filePath, 'utf8');
+ const htmlTag = text.match(/<html\b[^>]*>/i)?.[0];
+ const source = relativeProjectPath(resolvedRoot, filePath);
+ if (!htmlTag) {
+ documentsWithoutHtmlRoot.push(source);
+ continue;
+ }
+ const lang = htmlTag.match(/\blang\s*=\s*(["'])([^"']+)\1/i)?.[2];
+ const direction = htmlTag.match(/\bdir\s*=\s*(["'])([^"']+)\1/i)?.[2]?.toLowerCase() || null;
+ findings.push({
+ source,
+ lang: lang && !/[{}]/.test(lang) ? lang : null,
+ direction,
+ });
+ }
+
+ if (findings.length === 0) {
+ return {
+ detected: false,
+ valid: false,
+ locale: null,
+ direction: null,
+ source: null,
+ conflicts: documentsWithoutHtmlRoot.map(
+ (source) => `${source} does not contain a root html element.`
+ ),
+ reason: 'html-root-not-found',
+ expectedSources: existingCandidates.map(
+ (filePath) => relativeProjectPath(resolvedRoot, filePath)
+ ),
+ };
+ }
+
+ const conflicts = [];
+ const resolved = findings.map((finding) => ({
+ ...finding,
+ resolved: finding.lang ? resolveLocale(finding.lang) : null,
+ }));
+ for (const finding of resolved) {
+ if (!finding.lang) {
+ conflicts.push(`${finding.source} is missing a static html lang attribute.`);
+ continue;
+ }
+ if (!finding.resolved.valid) {
+ conflicts.push(
+ `${finding.source} has an invalid document language "${finding.lang}".`
+ );
+ continue;
+ }
+ if (!['ltr', 'rtl'].includes(finding.direction)) {
+ conflicts.push(`${finding.source} is missing a valid html dir attribute.`);
+ continue;
+ }
+ if (finding.direction !== finding.resolved.direction) {
+ conflicts.push(
+ `${finding.source} uses dir="${finding.direction}" but ` +
+ `${finding.resolved.locale} resolves to "${finding.resolved.direction}".`
+ );
+ }
+ }
+
+ const distinctLocales = [...new Set(
+ resolved
+ .filter((finding) => finding.resolved?.valid)
+ .map((finding) => finding.resolved.locale)
+ )];
+ if (distinctLocales.length > 1) {
+ conflicts.push(
+ `Conflicting document languages were found: ${distinctLocales.join(', ')}.`
+ );
+ }
+
+ const primary = resolved.find((finding) => finding.resolved?.valid) || resolved[0];
+ const missingAttributes = resolved.some((finding) =>
+ !finding.lang || !['ltr', 'rtl'].includes(finding.direction)
+ );
+ return {
+ detected: true,
+ valid: conflicts.length === 0,
+ locale: primary.resolved?.locale || null,
+ direction: primary.direction,
+ source: primary.source,
+ conflicts,
+ ...(conflicts.length
+ ? {
+ reason: distinctLocales.length > 1
+ ? 'document-language-conflict'
+ : missingAttributes
+ ? 'language-attributes-missing'
+ : 'document-language-invalid',
+ }
+ : {}),
+ };
+}
+
+function unresolvedSiteLanguage(reason) {
+ return {
+ detected: false,
+ valid: false,
+ locale: null,
+ direction: null,
+ source: null,
+ conflicts: [],
+ reason,
+ };
+}
+
+function resolveSiteLanguageContext(projectRoot, selectedFramework, localization) {
+ const resolvedRoot = path.resolve(projectRoot);
+ const localizationState = localization || detectLocalization(resolvedRoot);
+
+ // A localized site can legitimately have several locale-specific document roots.
+ // Its configured default locale is authoritative; scanning those documents as if
+ // they described one single-language site would create false conflicts.
+ if (localizationState.detected) {
+ const source = localizationState.manifestPath
+ ? path.relative(resolvedRoot, localizationState.manifestPath).replaceAll('\\', '/')
+ : 'localization configuration';
+ if (!localizationState.valid || !localizationState.defaultLocale) {
+ return {
+ detected: true,
+ valid: false,
+ locale: null,
+ direction: null,
+ source,
+ conflicts: localizationState.conflicts.length
+ ? [...localizationState.conflicts]
+ : ['Existing localization configuration has no valid default locale.'],
+ reason: 'localization-invalid',
+ };
+ }
+
+ const resolved = resolveLocale(localizationState.defaultLocale);
+ if (!resolved.valid) {
+ return {
+ detected: true,
+ valid: false,
+ locale: null,
+ direction: null,
+ source,
+ conflicts: ['Existing localization configuration has an invalid default locale.'],
+ reason: 'localization-invalid',
+ };
+ }
+
+ return {
+ detected: true,
+ valid: true,
+ locale: resolved.locale,
+ direction: resolved.direction,
+ source,
+ conflicts: [],
+ reason: 'localization-default',
+ };
+ }
+
+ return detectSiteLanguage(resolvedRoot, selectedFramework);
+}
+
+function detectSiteLanguageForFramework(projectRoot, selectedFramework) {
+ const resolvedRoot = path.resolve(projectRoot);
+ if (!Object.hasOwn(LOCALIZATION_CAPABILITIES.frameworks, selectedFramework)) {
+ throw new Error(`Unsupported framework selection: ${selectedFramework || '<empty>'}.`);
+ }
+
+ const detection = detectFramework(resolvedRoot);
+ const evidenceBacked = detection.framework === selectedFramework ||
+ detection.candidates.includes(selectedFramework);
+ if (!evidenceBacked) {
+ throw new Error(
+ `Framework selection "${selectedFramework}" is not supported by the detected project evidence.`
+ );
+ }
+
+ return resolveSiteLanguageContext(resolvedRoot, selectedFramework);
+}
+
function inspectProject(projectRoot) {
const resolvedRoot = path.resolve(projectRoot);
+ const framework = detectFramework(resolvedRoot);
const localization = detectLocalization(resolvedRoot);
+ const siteLanguage = framework.framework
+ ? resolveSiteLanguageContext(resolvedRoot, framework.framework, localization)
+ : unresolvedSiteLanguage(
+ framework.ambiguous ? 'framework-ambiguous' : 'framework-unsupported'
+ );
+ const safeSiteLanguage = {
+ detected: siteLanguage.detected,
+ valid: siteLanguage.valid,
+ locale: siteLanguage.locale
+ ? sanitizeUntrustedText(siteLanguage.locale, 100)
+ : null,
+ direction: siteLanguage.direction
+ ? sanitizeUntrustedText(siteLanguage.direction, 20)
+ : null,
+ source: siteLanguage.source
+ ? sanitizeUntrustedText(siteLanguage.source, 500)
+ : null,
+ conflicts: siteLanguage.conflicts.map(
+ (value) => sanitizeUntrustedText(value, 500)
+ ),
+ ...(siteLanguage.reason
+ ? { reason: sanitizeUntrustedText(siteLanguage.reason, 100) }
+ : {}),
+ ...(siteLanguage.expectedSources
+ ? {
+ expectedSources: siteLanguage.expectedSources.map(
+ (value) => sanitizeUntrustedText(value, 500)
+ ),
+ }
+ : {}),
+ };
const safeLocalization = {
detected: localization.detected,
valid: localization.valid,
@@ -1104,7 +1567,8 @@ function inspectProject(projectRoot) {
};
return {
projectRoot: sanitizeUntrustedText(resolvedRoot, 1000),
- framework: detectFramework(resolvedRoot),
+ framework,
+ siteLanguage: safeSiteLanguage,
localization: safeLocalization,
};
}
@@ -1283,15 +1747,28 @@ function runCli() {
process.stdout.write(`${JSON.stringify(inspectProject(args.projectRoot), null, 2)}\n`);
return;
}
+ if (args.command === 'detect-site-language' && args.projectRoot && args.framework) {
+ const result = detectSiteLanguageForFramework(args.projectRoot, args.framework);
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
+ return;
+ }
if (args.command === 'validate-locales' && args.locales !== undefined) {
const result = validateLocales(args.locales);
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
process.exitCode = result.valid ? 0 : 1;
return;
}
+ if (args.command === 'resolve-locale' && args.locale !== undefined) {
+ const result = resolveLocale(args.locale);
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
+ process.exitCode = result.valid ? 0 : 1;
+ return;
+ }
process.stderr.write(
'Usage: localization-config.js inspect --projectRoot <path> | ' +
- 'validate-locales --locales <comma-separated-tags>\n'
+ 'detect-site-language --projectRoot <path> --framework <framework> | ' +
+ 'validate-locales --locales <comma-separated-tags> | ' +
+ 'resolve-locale --locale <language-tag>\n'
);
process.exitCode = 1;
}
@@ -1307,9 +1784,16 @@ module.exports = {
hasLocaleNavigationSignal,
detectFramework,
detectLocalization,
+ detectSiteLanguage,
+ detectSiteLanguageForFramework,
+ resolveSiteLanguageContext,
+ getLocaleDirection,
inspectProject,
+ isSafeLocaleCandidate,
+ isSafeLocaleListCandidate,
loadRegistry,
resolveProjectRelativePath,
+ resolveLocale,
validateLocalizationManifestShape,
validateLocales,
verifyInitializationEvidence,
diff --git a/plugins/power-pages/scripts/render-createsite-plan.js b/plugins/power-pages/scripts/render-createsite-plan.js
index c796a0442..22b72c78e 100644
--- a/plugins/power-pages/scripts/render-createsite-plan.js
+++ b/plugins/power-pages/scripts/render-createsite-plan.js
@@ -15,7 +15,8 @@
* PLAN
*
* Required keys in the data:
- * SITE_NAME, PLAN_TITLE, FRAMEWORK, AESTHETIC, MOOD, SUMMARY,
+ * SITE_NAME, PLAN_TITLE, FRAMEWORK, SITE_LANGUAGE, SITE_LOCALE, SITE_DIRECTION,
+ * AESTHETIC, MOOD, SUMMARY,
* DESIGN_DIRECTION_DATA, TYPOGRAPHY_DATA, PALETTE_DATA, MOTION_DATA, BACKGROUNDS_DATA,
* PAGES_DATA, COMPONENTS_DATA, ROUTES_DATA, REVIEW_DATA, DEPLOYMENT_DATA
*/
@@ -48,6 +49,9 @@ const requiredKeys = [
'SITE_NAME',
'PLAN_TITLE',
'FRAMEWORK',
+ 'SITE_LANGUAGE',
+ 'SITE_LOCALE',
+ 'SITE_DIRECTION',
'AESTHETIC',
'MOOD',
'SUMMARY',
diff --git a/plugins/power-pages/scripts/tests/create-site-scaffold-loader.test.js b/plugins/power-pages/scripts/tests/create-site-scaffold-loader.test.js
index ffd5c05d6..8222d309f 100644
--- a/plugins/power-pages/scripts/tests/create-site-scaffold-loader.test.js
+++ b/plugins/power-pages/scripts/tests/create-site-scaffold-loader.test.js
@@ -10,6 +10,12 @@ const loaderTemplates = [
'angular/src/app/pages/home.component.ts',
'astro/src/pages/index.astro',
];
+const documentTemplates = [
+ 'react/index.html',
+ 'vue/index.html',
+ 'angular/src/index.html',
+ 'astro/src/layouts/Layout.astro',
+];
test('create-site loader keeps awaiting-input banner persistent and dismissible across templates', () => {
for (const template of loaderTemplates) {
@@ -25,3 +31,14 @@ test('create-site loader keeps awaiting-input banner persistent and dismissible
assert.match(content, /if \(!lastAwaiting\)/, template);
}
});
+
+test('create-site templates persist the selected content locale and direction', () => {
+ for (const template of documentTemplates) {
+ const content = fs.readFileSync(path.join(createSiteRoot, template), 'utf8');
+ assert.match(
+ content,
+ /<html lang="__SITE_LOCALE__" dir="__SITE_DIRECTION__">/,
+ template
+ );
+ }
+});
diff --git a/plugins/power-pages/scripts/tests/localization-config.test.js b/plugins/power-pages/scripts/tests/localization-config.test.js
index f0dac542c..c168597e9 100644
--- a/plugins/power-pages/scripts/tests/localization-config.test.js
+++ b/plugins/power-pages/scripts/tests/localization-config.test.js
@@ -2,6 +2,7 @@
const test = require('node:test');
const assert = require('node:assert/strict');
+const { spawnSync } = require('child_process');
const fs = require('fs');
const path = require('path');
@@ -9,16 +10,25 @@ const {
LOCALIZATION_CAPABILITIES,
detectFramework,
detectLocalization,
+ detectSiteLanguage,
+ detectSiteLanguageForFramework,
discoverLocalizationImplementation,
+ getLocaleDirection,
inspectProject,
+ isSafeLocaleCandidate,
+ isSafeLocaleListCandidate,
protectedTokenSignature,
resolveProjectRelativePath,
+ resolveLocale,
+ resolveSiteLanguageContext,
verifyInitializationEvidence,
validateLocalizationManifestShape,
validateLocales,
} = require('../lib/localization-config');
const { createTempProject, writeProjectFile } = require('./test-utils');
+const CONFIG_PATH = path.join(__dirname, '..', 'lib', 'localization-config.js');
+
function writePackage(projectRoot, dependencies) {
writeProjectFile(projectRoot, 'package.json', JSON.stringify({ dependencies }, null, 2));
}
@@ -260,6 +270,465 @@ test('canonicalizes, visibly deduplicates, and validates registry subtags', () =
assert.match(result.invalid[0].reason, /unknown language subtag "xx"/);
});
+test('accepts only constrained locale candidates before canonicalization', () => {
+ assert.equal(isSafeLocaleCandidate('es-ES'), true);
+ assert.equal(isSafeLocaleCandidate('zh-Hant-TW'), true);
+ assert.equal(isSafeLocaleCandidate('x-contoso'), true);
+ assert.equal(isSafeLocaleCandidate('Spanish (es-ES)'), false);
+ assert.equal(isSafeLocaleCandidate('en_US'), false);
+ assert.equal(isSafeLocaleCandidate('en-US;whoami'), false);
+ assert.equal(isSafeLocaleCandidate('$(whoami)'), false);
+ assert.equal(isSafeLocaleCandidate('en-US|whoami'), false);
+ assert.equal(isSafeLocaleCandidate("en-US\nwhoami"), false);
+ assert.equal(isSafeLocaleCandidate(`en-${'a'.repeat(256)}`), false);
+});
+
+test('accepts only compact comma-separated safe locale lists', () => {
+ assert.equal(isSafeLocaleListCandidate('en-US,fr-FR,ar-SA'), true);
+ assert.equal(isSafeLocaleListCandidate('en-US, fr-FR'), false);
+ assert.equal(isSafeLocaleListCandidate('en-US;whoami,fr-FR'), false);
+ assert.equal(isSafeLocaleListCandidate('en-US,$(whoami)'), false);
+ assert.equal(isSafeLocaleListCandidate('en-US|whoami,fr-FR'), false);
+ assert.equal(isSafeLocaleListCandidate("en-US,\nfr-FR"), false);
+ assert.equal(isSafeLocaleListCandidate(`en-US,${'a'.repeat(4096)}`), false);
+});
+
+test('rejects unsafe locale syntax before BCP-47 canonicalization', () => {
+ const result = validateLocales([
+ 'Spanish (es-ES)',
+ 'en_US',
+ 'en-US;whoami',
+ '$(whoami)',
+ 'en-US|whoami',
+ "en-US\nwhoami",
+ ]);
+
+ assert.equal(result.valid, false);
+ assert.deepEqual(result.locales, []);
+ assert.equal(result.invalid.length, 6);
+ for (const invalid of result.invalid) {
+ assert.match(invalid.reason, /ASCII alphanumeric subtags separated by hyphens/);
+ }
+});
+
+test('resolves a single locale, direction, and canonical display names', () => {
+ const spanish = resolveLocale('es-es');
+ assert.equal(spanish.locale, 'es-ES');
+ assert.equal(spanish.direction, 'ltr');
+ assert.equal(spanish.languageName, 'Spanish');
+ assert.equal(spanish.localeName, 'European Spanish');
+ assert.equal(spanish.nativeLanguageName, 'español');
+ assert.equal(spanish.nativeLocaleName, 'español de España');
+
+ const traditionalChinese = resolveLocale('zh-Hant-TW');
+ assert.equal(traditionalChinese.languageName, 'Chinese');
+ assert.match(traditionalChinese.localeName, /Traditional/);
+ assert.equal(traditionalChinese.nativeLanguageName, '中文');
+ assert.ok(traditionalChinese.nativeLocaleName);
+
+ assert.equal(getLocaleDirection('ar-SA'), 'rtl');
+ assert.equal(getLocaleDirection('x-contoso'), 'ltr');
+});
+
+test('does not invent display names for private-use-only locales', () => {
+ const result = resolveLocale('x-contoso');
+
+ assert.equal(result.valid, true);
+ assert.equal(result.locale, 'x-contoso');
+ assert.equal(result.direction, 'ltr');
+ assert.equal(result.languageName, null);
+ assert.equal(result.localeName, null);
+ assert.equal(result.nativeLanguageName, null);
+ assert.equal(result.nativeLocaleName, null);
+});
+
+test('returns null display names for invalid locale input', () => {
+ const result = resolveLocale('not_a_locale');
+
+ assert.equal(result.valid, false);
+ assert.equal(result.locale, null);
+ assert.equal(result.direction, null);
+ assert.equal(result.languageName, null);
+ assert.equal(result.localeName, null);
+ assert.equal(result.nativeLanguageName, null);
+ assert.equal(result.nativeLocaleName, null);
+});
+
+test('resolve-locale CLI returns canonical display names for create-site', () => {
+ const result = spawnSync(
+ process.execPath,
+ [CONFIG_PATH, 'resolve-locale', '--locale', 'pt-br'],
+ { encoding: 'utf8' }
+ );
+
+ assert.equal(result.status, 0, result.stderr);
+ const output = JSON.parse(result.stdout);
+ assert.equal(output.locale, 'pt-BR');
+ assert.equal(output.languageName, 'Portuguese');
+ assert.equal(output.localeName, 'Brazilian Portuguese');
+ assert.equal(output.nativeLanguageName, 'português');
+ assert.equal(output.nativeLocaleName, 'português (Brasil)');
+});
+
+test('detects the persisted single-site language from document attributes', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'index.html', '<html lang="es-ES" dir="ltr"><body></body></html>');
+
+ assert.deepEqual(detectSiteLanguage(projectRoot, 'react'), {
+ detected: true,
+ valid: true,
+ locale: 'es-ES',
+ direction: 'ltr',
+ source: 'index.html',
+ conflicts: [],
+ });
+});
+
+test('reports missing or incorrect document direction', (t) => {
+ const missingRoot = createTempProject(t);
+ writeProjectFile(missingRoot, 'src/index.html', '<html lang="ar-SA"><body></body></html>');
+ assert.match(
+ detectSiteLanguage(missingRoot, 'angular').conflicts.join('\n'),
+ /missing a valid html dir attribute/
+ );
+
+ const mismatchedRoot = createTempProject(t);
+ writeProjectFile(
+ mismatchedRoot,
+ 'src/index.html',
+ '<html lang="ar-SA" dir="ltr"><body></body></html>'
+ );
+ assert.match(
+ detectSiteLanguage(mismatchedRoot, 'angular').conflicts.join('\n'),
+ /resolves to "rtl"/
+ );
+});
+
+test('uses only the framework document path for React and Vue', (t) => {
+ for (const framework of ['react', 'vue']) {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(
+ projectRoot,
+ 'src/index.html',
+ '<html lang="fr-FR" dir="ltr"><body></body></html>'
+ );
+
+ const result = detectSiteLanguage(projectRoot, framework);
+ assert.equal(result.detected, false);
+ assert.equal(result.reason, 'document-not-found');
+ assert.deepEqual(result.expectedSources, ['index.html']);
+ }
+});
+
+test('uses the Angular index configured in angular.json', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'angular.json', JSON.stringify({
+ projects: {
+ portal: {
+ projectType: 'application',
+ targets: {
+ build: {
+ options: {
+ index: {
+ input: 'src/site-shell.html',
+ output: 'index.html',
+ },
+ },
+ },
+ },
+ },
+ },
+ }));
+ writeProjectFile(
+ projectRoot,
+ 'index.html',
+ '<html lang="de-DE" dir="ltr"><body></body></html>'
+ );
+ writeProjectFile(
+ projectRoot,
+ 'src/site-shell.html',
+ '<html lang="es-ES" dir="ltr"><body></body></html>'
+ );
+
+ const result = detectSiteLanguage(projectRoot, 'angular');
+ assert.equal(result.valid, true, result.conflicts.join('\n'));
+ assert.equal(result.locale, 'es-ES');
+ assert.equal(result.source, 'src/site-shell.html');
+});
+
+test('does not use an unrelated root index for Angular', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(
+ projectRoot,
+ 'index.html',
+ '<html lang="de-DE" dir="ltr"><body></body></html>'
+ );
+
+ const result = detectSiteLanguage(projectRoot, 'angular');
+ assert.equal(result.detected, false);
+ assert.equal(result.reason, 'document-not-found');
+ assert.deepEqual(result.expectedSources, ['src/index.html']);
+});
+
+test('reports ambiguous Angular application index configuration', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'angular.json', JSON.stringify({
+ projects: {
+ first: {
+ targets: { build: { options: { index: 'src/first.html' } } },
+ },
+ second: {
+ architect: { build: { options: { index: 'src/second.html' } } },
+ },
+ },
+ }));
+
+ const result = detectSiteLanguage(projectRoot, 'angular');
+ assert.equal(result.detected, false);
+ assert.equal(result.reason, 'document-ambiguous');
+ assert.deepEqual(result.expectedSources, ['src/first.html', 'src/second.html']);
+});
+
+test('detects Astro document language in layouts and nested pages', (t) => {
+ const layoutRoot = createTempProject(t);
+ writeProjectFile(
+ layoutRoot,
+ 'src/layouts/Base.astro',
+ '<html lang="ja-JP" dir="ltr"><body><slot /></body></html>'
+ );
+ assert.equal(detectSiteLanguage(layoutRoot, 'astro').source, 'src/layouts/Base.astro');
+
+ const pageRoot = createTempProject(t);
+ writeProjectFile(
+ pageRoot,
+ 'src/pages/account/index.astro',
+ '<html lang="ar-SA" dir="rtl"><body></body></html>'
+ );
+ const pageResult = detectSiteLanguage(pageRoot, 'astro');
+ assert.equal(pageResult.valid, true, pageResult.conflicts.join('\n'));
+ assert.equal(pageResult.locale, 'ar-SA');
+ assert.equal(pageResult.source, 'src/pages/account/index.astro');
+});
+
+test('distinguishes a missing document from missing html language attributes', (t) => {
+ const missingDocumentRoot = createTempProject(t);
+ const missingDocument = detectSiteLanguage(missingDocumentRoot, 'react');
+ assert.equal(missingDocument.reason, 'document-not-found');
+ assert.deepEqual(missingDocument.expectedSources, ['index.html']);
+
+ const missingAttributesRoot = createTempProject(t);
+ writeProjectFile(
+ missingAttributesRoot,
+ 'index.html',
+ '<html><body></body></html>'
+ );
+ const missingAttributes = detectSiteLanguage(missingAttributesRoot, 'react');
+ assert.equal(missingAttributes.detected, true);
+ assert.equal(missingAttributes.reason, 'language-attributes-missing');
+ assert.equal(missingAttributes.source, 'index.html');
+ assert.match(missingAttributes.conflicts.join('\n'), /static html lang attribute/);
+});
+
+test('does not inspect site language until one supported framework is resolved', (t) => {
+ const unsupportedRoot = createTempProject(t);
+ writePackage(unsupportedRoot, { lodash: '^4.17.21' });
+ writeProjectFile(
+ unsupportedRoot,
+ 'index.html',
+ '<html lang="fr-FR" dir="ltr"><body></body></html>'
+ );
+
+ const unsupported = inspectProject(unsupportedRoot);
+ assert.equal(unsupported.framework.framework, null);
+ assert.equal(unsupported.framework.ambiguous, false);
+ assert.deepEqual(unsupported.siteLanguage, {
+ detected: false,
+ valid: false,
+ locale: null,
+ direction: null,
+ source: null,
+ conflicts: [],
+ reason: 'framework-unsupported',
+ });
+
+ const ambiguousRoot = createTempProject(t);
+ writePackage(ambiguousRoot, {
+ react: '^19.0.0',
+ 'react-dom': '^19.0.0',
+ vue: '^3.5.0',
+ });
+ writeProjectFile(
+ ambiguousRoot,
+ 'index.html',
+ '<html lang="fr-FR" dir="ltr"><body></body></html>'
+ );
+
+ const ambiguous = inspectProject(ambiguousRoot);
+ assert.equal(ambiguous.framework.ambiguous, true);
+ assert.equal(ambiguous.siteLanguage.detected, false);
+ assert.equal(ambiguous.siteLanguage.reason, 'framework-ambiguous');
+
+ const supportedRoot = createTempProject(t);
+ writePackage(supportedRoot, { react: '^19.0.0', 'react-dom': '^19.0.0' });
+ writeProjectFile(
+ supportedRoot,
+ 'index.html',
+ '<html lang="de-DE" dir="ltr"><body></body></html>'
+ );
+
+ const supported = inspectProject(supportedRoot);
+ assert.equal(supported.framework.framework, 'react');
+ assert.equal(supported.siteLanguage.detected, true);
+ assert.equal(supported.siteLanguage.locale, 'de-DE');
+});
+
+test('detects site language after an evidence-backed framework selection', (t) => {
+ const projectRoot = createTempProject(t);
+ writePackage(projectRoot, {
+ react: '^19.0.0',
+ 'react-dom': '^19.0.0',
+ astro: '^6.1.0',
+ });
+ writeProjectFile(
+ projectRoot,
+ 'src/layouts/Layout.astro',
+ '<html lang="ar-SA" dir="rtl"><body><slot /></body></html>'
+ );
+
+ const result = detectSiteLanguageForFramework(projectRoot, 'astro');
+ assert.equal(result.detected, true);
+ assert.equal(result.locale, 'ar-SA');
+ assert.equal(result.direction, 'rtl');
+ assert.equal(result.source, 'src/layouts/Layout.astro');
+ assert.throws(
+ () => detectSiteLanguageForFramework(projectRoot, 'vue'),
+ /not supported by the detected project evidence/
+ );
+});
+
+test('uses valid localization default locale before static document attributes', (t) => {
+ const projectRoot = createTempProject(t);
+ writePackage(projectRoot, {
+ react: '^19.0.0',
+ 'react-dom': '^19.0.0',
+ i18next: '^25.0.0',
+ 'react-i18next': '^16.0.0',
+ });
+ writeProjectFile(
+ projectRoot,
+ 'index.html',
+ '<html lang="de-DE" dir="ltr"><body></body></html>'
+ );
+ writeProjectFile(projectRoot, 'src/i18n/index.ts', "i18next.init({ fallbackLng: 'es-ES' });");
+ writeProjectFile(projectRoot, 'src/i18n/locales/es-ES.json', '{"home":"Inicio"}');
+ writeProjectFile(projectRoot, 'src/i18n/locales/ar-SA.json', '{"home":"الرئيسية"}');
+ writeProjectFile(
+ projectRoot,
+ 'src/components/LanguageSelector.tsx',
+ "export function LanguageSelector(){ changeLanguage('ar-SA'); document.documentElement.lang='ar-SA'; document.documentElement.dir='rtl'; }"
+ );
+
+ const result = inspectProject(projectRoot);
+ assert.equal(result.localization.valid, true, result.localization.conflicts.join('\n'));
+ assert.deepEqual(result.siteLanguage, {
+ detected: true,
+ valid: true,
+ locale: 'es-ES',
+ direction: 'ltr',
+ source: 'localization configuration',
+ conflicts: [],
+ reason: 'localization-default',
+ });
+});
+
+test('does not treat localized document roots as single-language conflicts', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(
+ projectRoot,
+ 'src/pages/en/index.astro',
+ '<html lang="en-US" dir="ltr"><body></body></html>'
+ );
+ writeProjectFile(
+ projectRoot,
+ 'src/pages/ar/index.astro',
+ '<html lang="ar-SA" dir="rtl"><body></body></html>'
+ );
+
+ const result = resolveSiteLanguageContext(projectRoot, 'astro', {
+ detected: true,
+ valid: true,
+ manifestPath: path.join(projectRoot, '.powerpages-localization.json'),
+ defaultLocale: 'ar-SA',
+ conflicts: [],
+ });
+
+ assert.deepEqual(result, {
+ detected: true,
+ valid: true,
+ locale: 'ar-SA',
+ direction: 'rtl',
+ source: '.powerpages-localization.json',
+ conflicts: [],
+ reason: 'localization-default',
+ });
+});
+
+test('reports invalid localization instead of document-root language conflicts', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(
+ projectRoot,
+ 'src/pages/en/index.astro',
+ '<html lang="en-US" dir="ltr"><body></body></html>'
+ );
+ writeProjectFile(
+ projectRoot,
+ 'src/pages/fr/index.astro',
+ '<html lang="fr-FR" dir="ltr"><body></body></html>'
+ );
+
+ const result = resolveSiteLanguageContext(projectRoot, 'astro', {
+ detected: true,
+ valid: false,
+ manifestPath: path.join(projectRoot, '.powerpages-localization.json'),
+ defaultLocale: 'en-US',
+ conflicts: ['localization initialization could not be determined'],
+ });
+
+ assert.equal(result.reason, 'localization-invalid');
+ assert.deepEqual(result.conflicts, ['localization initialization could not be determined']);
+ assert.doesNotMatch(result.conflicts.join('\n'), /Conflicting document languages/);
+});
+
+test('detect-site-language CLI reruns detection for a selected framework', (t) => {
+ const projectRoot = createTempProject(t);
+ writePackage(projectRoot, {
+ react: '^19.0.0',
+ 'react-dom': '^19.0.0',
+ vue: '^3.5.0',
+ });
+ writeProjectFile(
+ projectRoot,
+ 'index.html',
+ '<html lang="es-ES" dir="ltr"><body></body></html>'
+ );
+
+ const result = spawnSync(
+ process.execPath,
+ [
+ CONFIG_PATH,
+ 'detect-site-language',
+ '--projectRoot',
+ projectRoot,
+ '--framework',
+ 'react',
+ ],
+ { encoding: 'utf8' }
+ );
+
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(JSON.parse(result.stdout).locale, 'es-ES');
+});
+
test('accepts scripts, regions, variants, extensions, and private-use suffixes', () => {
const result = validateLocales([
'zh-Hant-TW',
diff --git a/plugins/power-pages/scripts/tests/render-createsite-plan.test.js b/plugins/power-pages/scripts/tests/render-createsite-plan.test.js
index c21fc317b..8bc63b7fc 100644
--- a/plugins/power-pages/scripts/tests/render-createsite-plan.test.js
+++ b/plugins/power-pages/scripts/tests/render-createsite-plan.test.js
@@ -11,6 +11,9 @@ const SAMPLE_DATA = {
SITE_NAME: 'Contoso Portal',
PLAN_TITLE: 'Implementation Plan',
FRAMEWORK: 'React',
+ SITE_LANGUAGE: 'Spanish',
+ SITE_LOCALE: 'es-ES',
+ SITE_DIRECTION: 'ltr',
AESTHETIC: 'Minimal & Clean',
MOOD: 'Professional & Trustworthy',
SUMMARY: 'An internal portal for Contoso consultants with directory, announcements, and docs.',
@@ -92,6 +95,7 @@ test('render-createsite-plan renders HTML from --data file', () => {
assert.match(html, /Contoso Portal/);
assert.match(html, /Implementation Plan/);
assert.match(html, /React/);
+ assert.match(html, /Spanish \(es-ES, ltr\)/);
assert.match(html, /Minimal &amp; Clean|Minimal & Clean/);
assert.match(html, /DM Sans/);
assert.match(html, /#1E3A5F/);
diff --git a/plugins/power-pages/scripts/tests/render-generated-plan-security.test.js b/plugins/power-pages/scripts/tests/render-generated-plan-security.test.js
index 619c2b092..0187555ab 100644
--- a/plugins/power-pages/scripts/tests/render-generated-plan-security.test.js
+++ b/plugins/power-pages/scripts/tests/render-generated-plan-security.test.js
@@ -456,6 +456,9 @@ test('backend and create-site plans allowlist dynamic attributes and escape nest
SITE_NAME: attack,
PLAN_TITLE: 'Implementation Plan',
FRAMEWORK: attack,
+ SITE_LANGUAGE: 'English (United States)',
+ SITE_LOCALE: 'en-US',
+ SITE_DIRECTION: 'ltr',
AESTHETIC: attack,
MOOD: attack,
SUMMARY: attack,
diff --git a/plugins/power-pages/scripts/tests/validate-site.test.js b/plugins/power-pages/scripts/tests/validate-site.test.js
new file mode 100644
index 000000000..20fd4ee9f
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/validate-site.test.js
@@ -0,0 +1,222 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('fs');
+const path = require('path');
+const { spawnSync } = require('child_process');
+
+const { createTempProject, writeProjectFile } = require('./test-utils');
+
+const VALIDATOR_PATH = path.join(
+ __dirname,
+ '..',
+ '..',
+ 'skills',
+ 'create-site',
+ 'scripts',
+ 'validate-site.js'
+);
+
+function createProject(t, html) {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', JSON.stringify({
+ $schema: 'https://www.schemastore.org/powerpages.config.json',
+ compiledPath: 'dist',
+ siteName: 'Contoso Customer Portal',
+ defaultLandingPage: 'index.html',
+ }));
+ writeProjectFile(projectRoot, 'package.json', JSON.stringify({
+ scripts: { build: 'vite build', dev: 'vite' },
+ dependencies: { react: '^19.0.0', 'react-dom': '^19.0.0' },
+ }));
+ writeProjectFile(projectRoot, '.gitignore', 'node_modules\n');
+ writeProjectFile(projectRoot, 'index.html', html);
+ writeProjectFile(projectRoot, 'src/main.tsx', 'export {};');
+ writeProjectFile(projectRoot, '.git/HEAD', 'ref: refs/heads/main\n');
+ return projectRoot;
+}
+
+function createAngularProject(t, angularConfig, htmlPath, html) {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', JSON.stringify({
+ $schema: 'https://www.schemastore.org/powerpages.config.json',
+ compiledPath: 'dist/portal/browser',
+ siteName: 'Contoso Customer Portal',
+ defaultLandingPage: 'index.html',
+ }));
+ writeProjectFile(projectRoot, 'package.json', JSON.stringify({
+ scripts: { build: 'ng build', dev: 'ng serve' },
+ dependencies: { '@angular/core': '^20.0.0' },
+ }));
+ writeProjectFile(projectRoot, '.gitignore', 'node_modules\n');
+ writeProjectFile(projectRoot, 'angular.json', JSON.stringify(angularConfig));
+ if (htmlPath) writeProjectFile(projectRoot, htmlPath, html);
+ writeProjectFile(projectRoot, 'src/main.ts', 'export {};');
+ writeProjectFile(projectRoot, '.git/HEAD', 'ref: refs/heads/main\n');
+ return projectRoot;
+}
+
+function runValidator(projectRoot) {
+ return spawnSync(process.execPath, [VALIDATOR_PATH], {
+ input: JSON.stringify({ cwd: projectRoot }),
+ encoding: 'utf8',
+ });
+}
+
+function runValidatorWithArgs(projectRoot, locale, direction) {
+ return spawnSync(
+ process.execPath,
+ [
+ VALIDATOR_PATH,
+ '--expectedLocale',
+ locale,
+ '--expectedDirection',
+ direction,
+ ],
+ {
+ cwd: projectRoot,
+ encoding: 'utf8',
+ }
+ );
+}
+
+test('create-site validator accepts a canonical non-English document language', (t) => {
+ const projectRoot = createProject(
+ t,
+ '<html lang="es-ES" dir="ltr"><body><div id="root"></div></body></html>'
+ );
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 0, result.stderr);
+});
+
+test('create-site validator blocks a direction mismatch', (t) => {
+ const projectRoot = createProject(
+ t,
+ '<html lang="ar-SA" dir="ltr"><body><div id="root"></div></body></html>'
+ );
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 2);
+ assert.match(result.stderr, /resolves to "rtl"/);
+});
+
+test('create-site validator reports the expected missing document path', (t) => {
+ const projectRoot = createProject(
+ t,
+ '<html lang="en-US" dir="ltr"><body></body></html>'
+ );
+ fs.unlinkSync(path.join(projectRoot, 'index.html'));
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 2);
+ assert.match(result.stderr, /Root document was not found/);
+ assert.match(result.stderr, /Expected: index\.html/);
+});
+
+test('create-site validator honors a custom Angular index path', (t) => {
+ const projectRoot = createAngularProject(
+ t,
+ {
+ projects: {
+ portal: {
+ targets: {
+ build: {
+ options: { index: 'src/shell.html' },
+ },
+ },
+ },
+ },
+ },
+ 'src/shell.html',
+ '<html lang="fr-FR" dir="ltr"><body></body></html>'
+ );
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 0, result.stderr);
+});
+
+test('create-site validator reports ambiguous Angular index configuration', (t) => {
+ const projectRoot = createAngularProject(
+ t,
+ {
+ projects: {
+ first: {
+ targets: { build: { options: { index: 'src/first.html' } } },
+ },
+ second: {
+ targets: { build: { options: { index: 'src/second.html' } } },
+ },
+ },
+ },
+ null,
+ null
+ );
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 2);
+ assert.match(result.stderr, /Root document configuration is invalid/);
+ assert.match(result.stderr, /multiple application index documents/);
+});
+
+test('create-site validator accepts approved language through direct arguments', (t) => {
+ const projectRoot = createProject(
+ t,
+ '<html lang="es-ES" dir="ltr"><body></body></html>'
+ );
+
+ const result = runValidatorWithArgs(projectRoot, 'es-ES', 'ltr');
+ assert.equal(result.status, 0, result.stderr);
+});
+
+test('create-site validator blocks direct argument language mismatches', (t) => {
+ const projectRoot = createProject(
+ t,
+ '<html lang="en-US" dir="ltr"><body></body></html>'
+ );
+
+ const result = runValidatorWithArgs(projectRoot, 'es-ES', 'ltr');
+ assert.equal(result.status, 2);
+ assert.match(result.stderr, /approved site locale is "es-ES"/);
+});
+
+test('create-site validator rejects an inconsistent direct expected direction', (t) => {
+ const projectRoot = createProject(
+ t,
+ '<html lang="ar-SA" dir="rtl"><body></body></html>'
+ );
+
+ const result = runValidatorWithArgs(projectRoot, 'ar-SA', 'ltr');
+ assert.equal(result.status, 2);
+ assert.match(result.stderr, /does not match ar-SA, which resolves to "rtl"/);
+});
+
+test('create-site validator rejects incomplete or unknown direct arguments', (t) => {
+ const projectRoot = createProject(
+ t,
+ '<html lang="en-US" dir="ltr"><body></body></html>'
+ );
+
+ const incomplete = spawnSync(
+ process.execPath,
+ [VALIDATOR_PATH, '--expectedLocale', 'en-US'],
+ { cwd: projectRoot, encoding: 'utf8' }
+ );
+ assert.equal(incomplete.status, 2);
+ assert.match(incomplete.stderr, /Usage: validate-site\.js/);
+
+ const unknown = spawnSync(
+ process.execPath,
+ [
+ VALIDATOR_PATH,
+ '--expectedLocale',
+ 'en-US',
+ '--expectedDirection',
+ 'ltr',
+ '--other',
+ 'value',
+ ],
+ { cwd: projectRoot, encoding: 'utf8' }
+ );
+ assert.equal(unknown.status, 2);
+ assert.match(unknown.stderr, /Usage: validate-site\.js/);
+});
diff --git a/plugins/power-pages/skills/add-localization/SKILL.md b/plugins/power-pages/skills/add-localization/SKILL.md
index a660439eb..bd29d6a66 100644
--- a/plugins/power-pages/skills/add-localization/SKILL.md
+++ b/plugins/power-pages/skills/add-localization/SKILL.md
@@ -85,11 +85,48 @@ file and use `AskUserQuestion`:
If the maker stops, make no changes, list the files requiring review, explain
that framework repair is outside localization scope, and end.
+After the maker selects an evidence-backed framework candidate, run:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/lib/localization-config.js" detect-site-language --projectRoot "<PROJECT_ROOT>" --framework "<SELECTED_FRAMEWORK>"
+```
+
+Use this result as `siteLanguage` for the rest of the workflow. Do not reuse the
+neutral `siteLanguage` result returned while framework evidence was ambiguous.
+
+If inspection returns no supported framework and no evidence-backed candidate
+can be selected, stop without making changes. Do not use root-document language
+attributes from an unsupported project as localization evidence.
+
When no localization is detected and this is a direct invocation, display:
> **Localization scope**
> This localizes only the SPA user interface; it does not add languages to your Dataverse environment.
+When no localization is detected and `siteLanguage.detected=true` in the
+inspection result, display the declared locale, direction, source file, and any
+conflicts. Treat a valid single-site document language as the existing
+source/default locale for a new localization setup. If
+`siteLanguage.valid=false`, show every conflict and include the exact root
+`lang`/`dir` corrections in the approved localization plan.
+
+When no localization is detected and `siteLanguage.detected=false`, display:
+
+> **Source language not detected**
+> The root document does not declare a valid static `lang` attribute, so the
+> language of the existing UI cannot be determined reliably. Select the locale
+> that represents the existing UI content.
+
+Do not infer the source language from visible text, `dir`, browser preferences,
+the operating system, or the development environment. Treat the source locale
+as unknown until the maker selects a validated default locale in Phase 2. The
+approved plan must name the framework's root document and show the exact
+`lang="<DEFAULT_LOCALE>"` and `dir="<RESOLVED_DIRECTION>"` attributes that will
+be added.
+
+When localization already exists, its manifest/configuration remains the source
+of truth instead of the static root-document attributes.
+
When localization is detected, display package, mode, locales, default locale,
resource paths, and conflicts.
@@ -116,25 +153,40 @@ Ask configuration questions in this exact order.
<!-- not-a-gate: locale input is validated before it can enter the plan -->
Use `AskUserQuestion` for comma-separated BCP-47 tags. For add-languages mode,
-show existing locales and ask only for additions. Run:
+show existing locales and ask only for additions. For a new setup whose
+inspection found a valid single-site document language, show that source locale
+and ask only for additional locales; combine the source locale with the
+validated additions. Keep the raw answer as data only and never interpolate it
+into a shell command. In agent memory, convert each requested language to a
+BCP-47 candidate matching
+`^[A-Za-z0-9]{1,8}(?:-[A-Za-z0-9]{1,8})*$`, with a maximum of 255 characters
+per candidate. Join only those candidates with commas, without spaces, into
+`SAFE_COMMA_SEPARATED_TAGS`; the complete list must be at most 4096 characters.
+If any raw entry cannot be converted to that constrained form, reject and
+re-prompt before running a command. Run:
```bash
-node "${PLUGIN_ROOT}/scripts/lib/localization-config.js" validate-locales --locales "<COMMA_SEPARATED_TAGS>"
+node "${PLUGIN_ROOT}/scripts/lib/localization-config.js" validate-locales --locales "<SAFE_COMMA_SEPARATED_TAGS>"
```
-Reject invalid entries and re-prompt with each reason. Show canonicalization
-changes and duplicates. Confirm canonicalization before continuing. Require at
-least two unique locales for a new setup and at least one genuinely new locale
-for add-languages mode.
+Do not quote, escape, sanitize, or otherwise place the raw maker answer in this
+command. Reject invalid entries and re-prompt with each reason. Show
+canonicalization changes and duplicates. Confirm canonicalization before
+continuing. From this point onward, use only the canonical locales returned by
+validation, including when resolving direction; never reuse the raw answer or
+the pre-canonicalized candidates. Require at least two unique locales for a new
+setup, including the detected source locale when present, and at least one
+genuinely new locale for add-languages mode.
### 2.2 Default locale
<!-- not-a-gate: default-locale selection is validated configuration input -->
-For a new setup, use `AskUserQuestion` with only the validated canonical
-locales as options and require exactly one. In add-languages mode, preserve the
-existing default without asking. In repair mode, ask only when missing,
-invalid, conflicting, or explicitly being changed.
+For a new setup with a valid detected single-site language, preserve it as the
+default without asking. Otherwise, use `AskUserQuestion` with only the
+validated canonical locales as options and require exactly one. In
+add-languages mode, preserve the existing default without asking. In repair
+mode, ask only when missing, invalid, conflicting, or explicitly being changed.
### 2.3 Mode
@@ -308,6 +360,8 @@ Present:
- Canonical locales and additions.
- Translation method and warning.
- Exact files/packages to create, update, preserve, replace, or skip.
+- For a missing or invalid root document language, the exact root document file
+ and the approved canonical `lang` plus resolved `dir` attribute repair.
- Language-selector placement and runtime/static behavior.
- Build, validator, browser, RTL, and token checks.
- Known limitations and any approved translation replacements.
@@ -387,6 +441,10 @@ For blank mode, create complete key structures with blank target values.
Add a language selector to shared navigation/layout. Implement runtime
persistence or static route navigation exactly as described in the framework
reference. Configure `lang`, `dir`, fallback behavior, and RTL handling.
+For a new setup whose root document language was missing or invalid, apply the
+approved root-document repair: set static `lang` to the approved canonical
+default locale and `dir` to that locale's resolved direction. Do not infer or
+substitute a different source locale during implementation.
Write `.powerpages-localization.json` using reference schema version 1
after the approved implementation is complete. Record `packageVerification`
diff --git a/plugins/power-pages/skills/create-site/SKILL.md b/plugins/power-pages/skills/create-site/SKILL.md
index 980771076..151214f04 100644
--- a/plugins/power-pages/skills/create-site/SKILL.md
+++ b/plugins/power-pages/skills/create-site/SKILL.md
@@ -27,6 +27,7 @@ Guide the user through creating a complete, production-quality Power Pages code
- **Keep the scaffold loader in sync with reality**: The scaffold loader polls `public/scaffold-status.json`. Update this file before every `AskUserQuestion` (to raise the "waiting for your input" banner so the user doesn't miss a terminal prompt) and before each implementation step in Phase 5 (so the progress-bar label matches what you're actually doing while the decorative spinner continues its default cycle). See [Live Preview Status Protocol](#live-preview-status-protocol).
- **Use purposeful visuals**: Every image explains, orients, demonstrates, or reinforces identity. Prefer the site's own UI composed as a product moment, then bespoke inline SVG, then specific Unsplash photography with one art direction (see [5.3](#53-source-purposeful-visuals)). Never leave image placeholders or broken `<img>` tags pointing to nonexistent files.
- **Git checkpoints**: Commit after every individual page and component — each gets its own commit so breaking changes can be reverted.
+- **Site content language is independent of Dataverse language**: Generate every user-visible SPA string in the approved content language. Dataverse and Power Pages platform-managed messages remain English (`en-US`, LCID `1033`) in this workflow.
**Constraint**: Only static SPA frameworks are supported (React, Vue, Angular, Astro). NOT supported: Next.js, Nuxt.js, Remix, SvelteKit, Liquid.
@@ -97,8 +98,8 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read
4. From the user's answers, derive:
- `__SITE_NAME__` (Title Case, e.g., `Contoso Portal`)
- - `__SITE_SLUG__` (kebab-case derived from site name, e.g., `contoso-portal`)
- - `__SITE_DESCRIPTION__` (one-line description based on name + purpose)
+ - A preliminary `__SITE_SLUG__` (lowercase ASCII kebab-case derived from
+ the site name when possible)
5. Summarize the path-agnostic understanding and confirm with user before proceeding:
- Site name
- Site purpose/type
@@ -111,7 +112,7 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read
- **Internal**: Prioritize task completion - status, the next action, data tables, dashboards, authentication, navigation depth. The wow comes from clarity, density done right, and polish in the details rather than marketing heroes.
- **External**: Prioritize a striking first impression, a persuasive page narrative with proof at the point of doubt, SEO-friendly structure, and contact forms.
-**Output**: Clear statement of site purpose, audience, and derived naming values.
+**Output**: Clear statement of site purpose, audience, site name, and preliminary technical slug.
---
@@ -642,7 +643,53 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read
- **No, finish here**: mark **Select template or choose from-scratch** as `completed`, then stop.
- **Yes, customize now**: append the template customization tasks (see [Progress Tracking](#progress-tracking)), then continue below.
- 20. Mark **Plan template customizations** as `in_progress`, then ask what the user wants changed in `PROJECT_ROOT`. Use the existing Phase 3/4/5/6/7 implementation, verification, and review flow against the cloned project; do **not** run Phase 2 scaffold/copy-template. In Phase 3, skip the Brand sub-prompt and set `BRAND_SOURCE` to `template` - the template's existing theme tokens are the source of truth unless the user asks for a redesign. On this path Phase 5 edits the cloned project in place: keep the existing theme file, layout, and pages, change only what the approved plan names, and skip every `scaffold-status.json` step (no loader is running). Run the Phase 5.7 design critique on the pages you changed.
+ 20. Mark **Plan template customizations** as `in_progress`, then inspect the
+ cloned project before asking what the user wants changed:
+
+ ```bash
+ node "${PLUGIN_ROOT}/scripts/lib/localization-config.js" inspect --projectRoot "<PROJECT_ROOT>"
+ ```
+
+ Establish the language context required by the Phase 4 plan in this order:
+ - When `localization.detected=true` and `localization.valid=true`, use
+ `localization.defaultLocale` as the authoritative locale. Resolve it
+ with `resolve-locale`, set `SITE_LOCALE`, `SITE_DIRECTION`, and
+ `SITE_LANGUAGE` from the returned `locale`, `direction`, and
+ `languageName`, and retain `localeName` when regional or script detail
+ needs to be displayed. Do not scan locale-specific document roots as
+ though they described one single-language site.
+ - When `localization.detected=true` and `localization.valid=false`, show
+ the localization conflicts and stop before planning customization. The
+ localization configuration must be repaired; do not fall back to
+ static document attributes or report localized roots as a
+ single-language conflict.
+ - When no localization is detected and `siteLanguage.detected=true` with
+ `siteLanguage.valid=true`, resolve `siteLanguage.locale` with
+ `resolve-locale`. Use the returned `locale`, `direction`, and
+ `languageName` to establish `SITE_LOCALE`, `SITE_DIRECTION`, and
+ `SITE_LANGUAGE`.
+ - When `siteLanguage.reason` is `document-not-found`,
+ `html-root-not-found`, `document-ambiguous`, or
+ `document-configuration-invalid`, show its conflicts and
+ `expectedSources`, then stop before planning customization. Locate or
+ repair the actual application root document before asking for a
+ content language.
+ - When the document exists but its static language attributes are
+ missing or invalid, ask the **Content language** question below,
+ resolve the answer with `resolve-locale`, and include repairing
+ `siteLanguage.source` in the approved customization plan.
+
+ After `SITE_LANGUAGE`, `SITE_LOCALE`, and `SITE_DIRECTION` are all
+ established, ask what the user wants changed in `PROJECT_ROOT`. Use the
+ existing Phase 3/4/5/6/7 implementation, verification, and review flow
+ against the cloned project; do **not** run Phase 2 scaffold/copy-template.
+ In Phase 3, skip the Brand sub-prompt and set `BRAND_SOURCE` to
+ `template` - the template's existing theme tokens are the source of truth
+ unless the user asks for a redesign. On this path Phase 5 edits the cloned
+ project in place: keep the existing theme file, layout, and pages, change
+ only what the approved plan names, and skip every `scaffold-status.json`
+ step because no loader is running. Run the Phase 5.7 design critique on
+ the pages you changed.
21. After the customization plan is approved, mark **Plan template customizations** as `completed`, **Implement pages and components** as `in_progress`, and make the requested changes.
22. Run the existing validation/review flow. Do not automatically deploy unless the user explicitly asks to run `/deploy-site`.
@@ -657,17 +704,92 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read
| Which frontend framework? | Framework | React (Recommended), Vue, Angular, Astro |
| Where should the project be created? | Location | Current directory, New folder in current directory (Recommended), Any other directory |
-10. Resolve the project location:
+10. Determine the site's single content language independently of whether the
+ purpose was supplied in `$ARGUMENTS`.
+
+ - If the request explicitly names the content language, resolve it without
+ asking again and include it in the confirmation.
+ - Do not infer the desired site language merely from the language used to
+ converse with the maker.
+
+ <!-- not-a-gate: the locale is validated before it can affect scaffolding -->
+
+ When the content language was not explicit, use `AskUserQuestion`:
+
+ | Question | Header | Options |
+ |----------|--------|---------|
+ | Which language should the site content use?<br><br>Pages, navigation, buttons, forms, and accessibility text will use this language. Dataverse and Power Pages system messages will remain in English. | Site content language | English (`en-US`) (Recommended) |
+
+ The question UI's free-text option lets the maker enter another language or
+ locale, such as `Spanish (es-ES)`, `Japanese (ja-JP)`, or `Arabic (ar-SA)`.
+ Convert a language name to an appropriate BCP-47 tag, preserving an explicit
+ region or script when supplied. Keep the raw answer as data only: never place
+ it in a shell command. In agent memory, convert it to
+ `SAFE_LOCALE_CANDIDATE`, which must match
+ `^[A-Za-z0-9]{1,8}(?:-[A-Za-z0-9]{1,8})*$` and be at most 255 characters.
+ Reject and re-prompt before running a command if no safe candidate can be
+ derived. Validate and canonicalize only that constrained candidate:
+
+ ```bash
+ node "${PLUGIN_ROOT}/scripts/lib/localization-config.js" resolve-locale --locale "<SAFE_LOCALE_CANDIDATE>"
+ ```
+
+ Do not quote, escape, sanitize, or otherwise interpolate the raw maker answer
+ into this command. Reject invalid resolver output and re-prompt with the
+ reason. Record the canonical resolver output rather than inventing a
+ language label:
+
+ - `SITE_LANGUAGE` — resolver `languageName`, such as `Spanish`; if display
+ names are unavailable, show the canonical locale and ask the maker for a
+ readable label rather than guessing
+ - `SITE_LOCALE` — canonical BCP-47 tag, such as `es-ES`
+ - `SITE_DIRECTION` — `ltr` or `rtl` from the resolver
+ - `SITE_LOCALE_NAME` — resolver `localeName`, such as `European Spanish`,
+ retained for plan text that needs regional or script specificity
+
+11. Resolve the project location:
- **If "Current directory"**: Project root = `<cwd>`.
- - **If "New folder in current directory"**: Create a folder named `__SITE_NAME__` inside the cwd. Project root = `<cwd>/__SITE_NAME__/`.
+ - **If "New folder in current directory"**: Create a folder named
+ `__SITE_NAME__` inside the cwd. Project root =
+ `<cwd>/__SITE_NAME__/`. First verify that `__SITE_NAME__` is a valid
+ directory name on the current operating system. Non-Latin characters alone
+ are not a reason to reject it. If the site name contains invalid path
+ characters, is reserved by the operating system, is empty after
+ sanitization, or otherwise cannot be used safely, fall back to
+ `__SITE_SLUG__`. Before creating a fallback folder, tell the maker which
+ name will be used and why the original site name was not filesystem-safe.
- **If "Any other directory"**: Ask for the full path. Verify/create it. Project root = provided path.
After resolving, confirm: "The site will be created at `<resolved path>`."
Store this as `PROJECT_ROOT`.
-11. Append the from-scratch task list (Phases 2-8) to the todo list (see [Progress Tracking](#progress-tracking)), then mark **Select template or choose from-scratch** as `completed`.
-**Output**: cloned template site identity (`IMPORTED_SITE_NAME`, `IMPORTED_WEBSITE_RECORD_ID`) and a local project path ready for optional customization; or `CREATION_PATH = "from-scratch"` with selected framework and resolved project location.
+12. Finalize the derived values:
+ - `__SITE_NAME__` — preserve the maker's site/brand name as entered, e.g.
+ `Contoso Portal`; it does not need to match the content language.
+ - `__SITE_SLUG__` — a lowercase ASCII kebab-case technical identifier used
+ by npm, Angular project configuration, build paths, and the default folder.
+ Derive it from the site name when possible, e.g. `Contoso Portal` →
+ `contoso-portal`. Transliterate when reliable. If a non-Latin name cannot
+ produce a safe, meaningful slug, derive one from the site's purpose or ask
+ for a technical project name rather than emitting an empty or invalid
+ identifier.
+ - `__SITE_DESCRIPTION__` — one-line description written in `SITE_LANGUAGE`
+ based on the name and purpose.
+
+13. Summarize understanding and confirm with the user before proceeding. Include
+ site name, technical slug, framework, purpose, audience, project location,
+ `SITE_LANGUAGE` (`SITE_LOCALE`, `SITE_DIRECTION`), and the explicit statement
+ that Dataverse and Power Pages system messages remain English.
+
+14. Append the from-scratch task list (Phases 2-8) to the todo list (see
+ [Progress Tracking](#progress-tracking)), then mark **Select template or
+ choose from-scratch** as `completed`.
+
+**Output**: cloned template site identity (`IMPORTED_SITE_NAME`,
+`IMPORTED_WEBSITE_RECORD_ID`) and a local project path ready for optional
+customization; or `CREATION_PATH = "from-scratch"` with selected framework,
+content language, derived naming values, and resolved project location.
---
@@ -713,6 +835,8 @@ See [Live Preview Status Protocol](#live-preview-status-protocol) for the full c
After copying, replace all `__PLACEHOLDER__` tokens in every file. Use `Edit` with `replace_all: true` on each file.
- **Name/slug/description placeholders**: Use the actual values from Phase 1 (`__SITE_NAME__`, `__SITE_SLUG__`, `__SITE_DESCRIPTION__`).
+- **Document-language placeholders**: Replace `__SITE_LOCALE__` with
+ `SITE_LOCALE` and `__SITE_DIRECTION__` with `SITE_DIRECTION`.
> **Note:** The scaffold loading screen uses hardcoded Power Pages branding colors — there are no color placeholders (`__PRIMARY_COLOR__`, etc.) to replace. The user's chosen color palette is applied fresh during Phase 5 when the scaffold is completely replaced.
@@ -855,7 +979,7 @@ Immediately after the dev server starts, verify the scaffold is working:
The `marker` string is the comment tag Phase 5 emits into the page source as a reserved anchor that `/add-ai-webapi` later finds. Keep the shape uniform — one marker per placement, always the same tag, so the follow-up skill's explore step can grep for them deterministically.
5. Read the design references: `${PLUGIN_ROOT}/references/design-aesthetics.md` and `${PLUGIN_ROOT}/references/page-blueprints.md`.
-6. **Write the experience brief** (design-aesthetics.md section 1) - audience and job, primary and secondary action, principal doubt, proof strategy, design thesis, hero concept, and signature moment. Resolve the brand source first (section 2): for `website`, extract the brand from the URL with the Playwright snippet there; for `assets`, build the palette around the supplied colors; for `fresh`, start from the matching cell of the aesthetic x mood map (section 11). Record the display and body fonts, color direction, geometry, and motion direction.
+6. **Write the experience brief** (design-aesthetics.md section 1) - audience and job, primary and secondary action, principal doubt, proof strategy, design thesis, hero concept, and signature moment. Resolve the brand source first (section 2): for `website`, extract the brand from the URL with the Playwright snippet there; for `assets`, build the palette around the supplied colors; for `fresh`, start from the matching cell of the aesthetic x mood map (section 11). Record the display and body fonts, color direction, geometry, and motion direction. Font choices must support the complete writing system used by `SITE_LOCALE`; verify glyph coverage and shaping rather than selecting a Latin-only font solely because it matches the aesthetic, and use a compatible script-aware fallback stack.
7. Analyze requirements and determine needed components. Plan each page's content as narrative beats from `page-blueprints.md`, in order, one line per section with its purpose. If `AI_SUMMARY_PLACEMENTS` from step 4 implies a page that wasn't already in the plan (e.g., a `CaseDetail` page for a data-summarization pick on the support-case table), add it to the page list now. Present the component plan to the user as a table:
```
@@ -891,9 +1015,12 @@ Assemble a single JSON object with the following keys. The plan template rejects
| Key | Type | Content |
|-----|------|---------|
-| `SITE_NAME` | string | Title-case site name from Phase 1 |
+| `SITE_NAME` | string | Site/brand name from Phase 1, preserved as entered |
| `PLAN_TITLE` | string | Always `"Implementation Plan"` |
| `FRAMEWORK` | string | `React` / `Vue` / `Angular` / `Astro` |
+| `SITE_LANGUAGE` | string | Readable content-language name from Phase 1 |
+| `SITE_LOCALE` | string | Canonical BCP-47 content locale |
+| `SITE_DIRECTION` | string | `ltr` or `rtl` |
| `AESTHETIC` | string | Chosen aesthetic (e.g., `Minimal & Clean`) |
| `MOOD` | string | Chosen mood (e.g., `Professional & Trustworthy`) |
| `SUMMARY` | string | One paragraph describing what the site is and who it serves |
@@ -933,7 +1060,7 @@ Open `<OUTPUT_PATH>` in the default browser using the platform-appropriate file
Keep the terminal message short — **the full plan lives in the HTML file now**. Include:
- One sentence confirming the plan was rendered and where (the output path).
-- A 3-5 line bullet summary: the design thesis, the signature moment, framework, page and component count.
+- A 3-5 line bullet summary: the design thesis, signature moment, framework, content language, page and component count, and primary palette color.
- A pointer: "See the open browser tab for the design direction, pages, color swatches, typography samples, and deployment options."
Do NOT dump the full plan contents into the terminal — that defeats the purpose of the HTML view.
@@ -1026,6 +1153,24 @@ The scaffold is a temporary loading screen — it must be **completely replaced*
One marker per placement, exactly as defined in the `marker` field of the `AI_SUMMARY_PLACEMENTS` record. Do NOT add stub components (`<CopilotSummaryCard />`, etc.), CSS classes, or empty `<aside>` elements — the slot is just a comment. The site must ship as if AI is not a consideration; the follow-up skill does the real work.
+**Content-language requirements**:
+
+- Write content natively in `SITE_LANGUAGE`; do not author an English site and
+ mechanically translate it afterward.
+- Localize every user-visible SPA string: navigation, headings, body copy,
+ buttons, links, forms, validation, loading/error/empty states, document
+ titles, metadata, image alt text, and ARIA labels.
+- Keep code identifiers, package names, CSS classes, Dataverse logical names,
+ API endpoints, and environment variables technical and untranslated.
+- Keep route paths as stable semantic English ASCII identifiers by default
+ (for example, `/services`), while navigation labels and page titles use
+ `SITE_LANGUAGE`. Do not translate paths during single-language site creation;
+ stable routes avoid breaking bookmarks, analytics, integrations, tests, and
+ a later `/add-localization` setup. Use localized paths only when the maker
+ explicitly requests them for a permanently single-language SEO strategy.
+- For RTL locales, use logical CSS properties, preserve sensible reading order,
+ and mirror only directional controls/icons.
+
**Important**: Build real, functional UI with the design thesis applied - not placeholder "coming soon" pages, and not generic unstyled markup. Every page and component reflects the thesis from the moment it's created. The scaffold loading screen should be completely gone after this phase - no trace of the Power Pages branded animation should remain.
### 5.3 Source Purposeful Visuals
@@ -1125,12 +1270,12 @@ Use `AskUserQuestion`, naming each failing critical gate and its evidence in the
**Output**: All pages, components, and design elements implemented, critiqued, and verified
-### 5.8 Offer and Add Localization
+### 5.8 Offer Additional Languages
-Ask whether localization should be added now:
+Ask whether more languages should be added now:
-> **Would you like to add localization support to this site now?**
-> This localizes only the SPA user interface; it does not add languages to your Dataverse environment.
+> **Would you like to add more languages now?**
+> The site is currently single-language in `<SITE_LANGUAGE>`. This adds SPA localization only; Dataverse and Power Pages system messages remain English.
<!-- not-a-gate: this selects whether to enter the child workflow, whose Phase 3 gate approves every localization write -->
@@ -1138,7 +1283,7 @@ Use `AskUserQuestion` with this exact wording and these exact options:
| Question | Header | Options |
|----------|--------|---------|
-| Would you like to add localization support to this site now?<br><br>This localizes only the SPA user interface; it does not add languages to your Dataverse environment. | Localization | Yes — configure localization now, No — keep this site single-language |
+| Would you like to add more languages now?<br><br>The site is currently single-language in `<SITE_LANGUAGE>`. This adds SPA localization only; Dataverse and Power Pages system messages remain English. | Additional languages | Yes — add more languages now, No — keep the site in `<SITE_LANGUAGE>` only |
Record the answer as `LOCALIZATION_REQUESTED=true|false`. Ask at this point even
when `$ARGUMENTS` mentioned localization, so the maker's answer immediately
@@ -1159,7 +1304,27 @@ and its existing deployment prompt.
When `LOCALIZATION_REQUESTED=false`, skip the child workflow.
-> **GATE: Do NOT proceed to Phase 6 until the Phase 5.7 design critique is complete and any requested localization has completed.**
+### 5.9 Validate the Approved Site Language
+
+Run the create-site validator explicitly with the approved language context.
+Use only the canonical `SITE_LOCALE` returned by `resolve-locale` and the
+validated `SITE_DIRECTION` enum; never pass the maker's original free-text
+answer. Run the command with its working directory set to `PROJECT_ROOT`:
+
+```bash
+node "${PLUGIN_ROOT}/skills/create-site/scripts/validate-site.js" \
+ --expectedLocale "<SITE_LOCALE>" \
+ --expectedDirection "<SITE_DIRECTION>"
+```
+
+Treat exit code `2` as blocking. Repair the reported document or
+localization-default mismatch and rerun the command until it passes. The
+automatic skill validator runs without these arguments and still checks that
+the detected document or localization context is internally valid. The
+explicit invocation verifies that it also matches the locale and direction
+approved in this create-site session without temporary or persistent metadata.
+
+> **GATE: Do NOT proceed to Phase 6 until the Phase 5.7 design critique is complete, any requested localization has completed, and the approved site language validation passes.**
**Output**: All pages, components, design elements, and requested localization implemented and verified
@@ -1203,7 +1368,7 @@ For each violation found, identify the source file and apply the fix:
| Missing landmark regions | Wrap content in `<main>`, `<nav>`, `<header>`, `<footer>` |
| Skipped heading levels | Correct heading hierarchy (h1 → h2 → h3, no gaps) |
| Missing link text | Add descriptive text or `aria-label` to links |
-| Missing `lang` attribute | Add `lang="en"` to the `<html>` tag |
+| Missing or incorrect `lang`/`dir` attributes | Set `lang="<SITE_LOCALE>"` and `dir="<SITE_DIRECTION>"` on the root `<html>` element |
| Inadequate focus indicators | Add visible `outline` styles to interactive elements |
After fixing each group of related violations, commit:
@@ -1264,7 +1429,10 @@ Present a summary table to the user:
| Git Commits | 9 | scaffold + 8 feature and critique commits |
```
- Follow it with the design thesis in one sentence and the scorecard (category, score, one-line evidence), including any category recorded below 3 and why. Then list the sample content still in the site - search `src` for `SAMPLE CONTENT` markers and give each marker's file and what it stands in for - so the user can supply real content in this review.
+ Follow it with the design thesis in one sentence and the scorecard (category, score, one-line evidence), including any category recorded below 3 and why. Include `SITE_LANGUAGE`, `SITE_LOCALE`, and `SITE_DIRECTION`, and ask the maker
+ to review linguistic correctness, terminology, tone, regional wording, and
+ any legal, medical, financial, or regulated text; automated checks cannot
+ validate language quality. Then list the sample content still in the site - search `src` for `SAMPLE CONTENT` markers and give each marker's file and what it stands in for - so the user can supply real content in this review.
3. Share the dev server URL with the user and list all available routes
4. Ask the user to review using `AskUserQuestion`:
@@ -1304,6 +1472,8 @@ Present a summary table to the user:
5. Mark all todos complete
6. Present a final summary:
- Site name and purpose
+ - Site content language and the fact that Dataverse/Power Pages system
+ messages remain English
- Framework and project location
- Components created (X pages, Y components, Z design elements)
- Key files and their purposes
@@ -1365,7 +1535,7 @@ After Phase 1.5 selects the from-scratch path, append the existing from-scratch
| Scaffold and launch dev server | Scaffolding project | Copy template, replace placeholders with defaults, git init, npm install, start dev server, share URL |
| Plan site components | Planning components | Determine pages, components, design direction, and routes while user previews scaffold |
| Approve implementation plan | Getting plan approval | Present implementation plan covering design and pages, get user approval |
-| Implement pages and components | Building site | Apply design tokens, create all pages, components, routing, and navigation, run the design critique pass, then ask whether to configure localization |
+| Implement pages and components | Building site | Apply design tokens, create all pages, components, routing, and navigation in the approved content language, run the design critique pass, then ask whether to add more languages |
| Verify accessibility with axe-core | Verifying accessibility | Run axe-core on every page, fix all critical/serious violations, re-verify until passing |
| Review with user | Reviewing site | Navigate all pages, share URL, get user feedback, apply changes |
| Deploy and wrap up | Deploying site | Ask about deployment, present summary, suggest next steps |
@@ -1412,8 +1582,10 @@ Every site must meet these standards before completion:
- Passes the Phase 5.7 design critique: no critical gate fails, and every rubric category scores 3 or more or, after three rounds, is recorded below 3 with its reason (see `design-critique.md`); a critical gate the user chose to continue past is recorded as a known issue
- Design tokens (color roles, fonts, spacing, radii, shadows, motion) defined once in the theme file and consumed everywhere
- Chosen Google Fonts verified loaded by the font check
+- Complete glyph coverage and correct shaping for `SITE_LOCALE`
- All requested pages and features implemented (not placeholders)
- All routes working and navigation complete
+- Root document uses the approved `SITE_LOCALE` and `SITE_DIRECTION`
- Accessibility verified via axe-core — zero critical/serious violations on all pages
- Git commits at key milestones
- Verified via Playwright
diff --git a/plugins/power-pages/skills/create-site/assets/angular/src/index.html b/plugins/power-pages/skills/create-site/assets/angular/src/index.html
index a383c6e99..14f4ea33f 100644
--- a/plugins/power-pages/skills/create-site/assets/angular/src/index.html
+++ b/plugins/power-pages/skills/create-site/assets/angular/src/index.html
@@ -1,5 +1,5 @@
<!DOCTYPE html>
-<html lang="en">
+<html lang="__SITE_LOCALE__" dir="__SITE_DIRECTION__">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
diff --git a/plugins/power-pages/skills/create-site/assets/astro/src/layouts/Layout.astro b/plugins/power-pages/skills/create-site/assets/astro/src/layouts/Layout.astro
index 5812b05d8..84d19b32f 100644
--- a/plugins/power-pages/skills/create-site/assets/astro/src/layouts/Layout.astro
+++ b/plugins/power-pages/skills/create-site/assets/astro/src/layouts/Layout.astro
@@ -11,7 +11,7 @@ const pageTitle = title === 'Home' ? '__SITE_NAME__' : `${title} | __SITE_NAME__
---
<!DOCTYPE html>
-<html lang="en">
+<html lang="__SITE_LOCALE__" dir="__SITE_DIRECTION__">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
diff --git a/plugins/power-pages/skills/create-site/assets/create-site-plan.html b/plugins/power-pages/skills/create-site/assets/create-site-plan.html
index d55c5387e..4e5468f8c 100644
--- a/plugins/power-pages/skills/create-site/assets/create-site-plan.html
+++ b/plugins/power-pages/skills/create-site/assets/create-site-plan.html
@@ -139,6 +139,7 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi
<span>__SITE_NAME__</span>
<span class="topbar-sep">&middot;</span>
<span class="pill pill-framework">__FRAMEWORK__</span>
+ <span class="pill">__SITE_LANGUAGE__ (__SITE_LOCALE__, __SITE_DIRECTION__)</span>
</div>
</div>
</div>
diff --git a/plugins/power-pages/skills/create-site/assets/react/index.html b/plugins/power-pages/skills/create-site/assets/react/index.html
index 180bb974d..a58d136f4 100644
--- a/plugins/power-pages/skills/create-site/assets/react/index.html
+++ b/plugins/power-pages/skills/create-site/assets/react/index.html
@@ -1,5 +1,5 @@
<!DOCTYPE html>
-<html lang="en">
+<html lang="__SITE_LOCALE__" dir="__SITE_DIRECTION__">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
diff --git a/plugins/power-pages/skills/create-site/assets/vue/index.html b/plugins/power-pages/skills/create-site/assets/vue/index.html
index 0afe1b7bf..596147813 100644
--- a/plugins/power-pages/skills/create-site/assets/vue/index.html
+++ b/plugins/power-pages/skills/create-site/assets/vue/index.html
@@ -1,5 +1,5 @@
<!DOCTYPE html>
-<html lang="en">
+<html lang="__SITE_LOCALE__" dir="__SITE_DIRECTION__">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
diff --git a/plugins/power-pages/skills/create-site/scripts/validate-site.js b/plugins/power-pages/skills/create-site/scripts/validate-site.js
index 65bd0cf2d..dbeb0226a 100644
--- a/plugins/power-pages/skills/create-site/scripts/validate-site.js
+++ b/plugins/power-pages/skills/create-site/scripts/validate-site.js
@@ -6,13 +6,19 @@
const fs = require('fs');
const path = require('path');
const { approve, block, runValidation, findPath } = require('../../../scripts/lib/validation-helpers');
+const { detectFramework } = require('../../../scripts/lib/framework-detection');
+const {
+ resolveLocale,
+ resolveSiteLanguageContext,
+} = require('../../../scripts/lib/localization-config');
-runValidation((cwd) => {
+function validateSite(cwd, input = {}) {
const configPath = findPath(cwd, 'powerpages.config.json');
if (!configPath) approve(); // Not a Power Pages project, skip
const projectRoot = path.dirname(configPath);
const errors = [];
+ const expectedLanguage = input.expectedSiteLanguage;
// 1. Required files
for (const file of ['package.json', '.gitignore', 'powerpages.config.json']) {
@@ -67,12 +73,66 @@ runValidation((cwd) => {
errors.push('Missing src/ directory');
}
+ // 7. The root document is the persisted source of truth for single-site language.
+ const framework = detectFramework(projectRoot);
+ if (!framework.framework || framework.ambiguous) {
+ errors.push('Unable to determine one supported framework for language validation');
+ } else {
+ const siteLanguage = resolveSiteLanguageContext(projectRoot, framework.framework);
+ if (!siteLanguage.detected) {
+ const expected = siteLanguage.expectedSources?.length
+ ? ` Expected: ${siteLanguage.expectedSources.join(', ')}.`
+ : '';
+ if (siteLanguage.reason === 'document-not-found') {
+ errors.push(`Root document was not found.${expected}`);
+ } else if (siteLanguage.reason === 'html-root-not-found') {
+ errors.push(`Root html element was not found in the discovered document.${expected}`);
+ } else if (siteLanguage.reason === 'document-ambiguous' ||
+ siteLanguage.reason === 'document-configuration-invalid') {
+ errors.push(
+ `Root document configuration is invalid:\n ${siteLanguage.conflicts.join('\n ')}`
+ );
+ } else {
+ errors.push(`Document language could not be determined.${expected}`);
+ }
+ } else if (!siteLanguage.valid) {
+ errors.push(`Document language is invalid:\n ${siteLanguage.conflicts.join('\n ')}`);
+ } else if (expectedLanguage !== undefined) {
+ const expectedLocale = resolveLocale(expectedLanguage?.locale);
+ const expectedDirection = expectedLanguage?.direction;
+ if (!expectedLocale.valid || !['ltr', 'rtl'].includes(expectedDirection)) {
+ errors.push(
+ 'Expected site language is invalid: provide a valid locale and ltr or rtl direction'
+ );
+ } else if (expectedDirection !== expectedLocale.direction) {
+ errors.push(
+ `Expected site direction "${expectedDirection}" does not match ` +
+ `${expectedLocale.locale}, which resolves to "${expectedLocale.direction}"`
+ );
+ } else {
+ const source = siteLanguage.source || 'site language configuration';
+ if (siteLanguage.locale !== expectedLocale.locale) {
+ errors.push(
+ `${source} uses locale "${siteLanguage.locale}", but the approved site locale is ` +
+ `"${expectedLocale.locale}"`
+ );
+ }
+ if (siteLanguage.direction !== expectedDirection) {
+ errors.push(
+ `${source} uses direction "${siteLanguage.direction}", but the approved site ` +
+ `direction is "${expectedDirection}"`
+ );
+ }
+ }
+ }
+ }
+
if (errors.length > 0) {
block('Power Pages site validation failed:\n- ' + errors.join('\n- '));
}
approve();
-});
+}
const PLACEHOLDER_RE = /__[A-Z][A-Z_]{2,}__/;
@@ -103,3 +163,44 @@ function findPlaceholders(dir) {
} catch {}
return results;
}
+
+function parseExpectedLanguageArgs(argv) {
+ const values = {};
+ for (let index = 0; index < argv.length; index += 1) {
+ const option = argv[index];
+ if (!['--expectedLocale', '--expectedDirection'].includes(option)) {
+ return { valid: false };
+ }
+ const value = argv[index + 1];
+ if (!value || value.startsWith('--') || values[option] !== undefined) {
+ return { valid: false };
+ }
+ values[option] = value;
+ index += 1;
+ }
+
+ if (!values['--expectedLocale'] || !values['--expectedDirection']) {
+ return { valid: false };
+ }
+ return {
+ valid: true,
+ expectedSiteLanguage: {
+ locale: values['--expectedLocale'],
+ direction: values['--expectedDirection'],
+ },
+ };
+}
+
+const cliArgs = process.argv.slice(2);
+if (cliArgs.length) {
+ const parsed = parseExpectedLanguageArgs(cliArgs);
+ if (!parsed.valid) {
+ block(
+ 'Usage: validate-site.js --expectedLocale <canonical-bcp47-tag> ' +
+ '--expectedDirection <ltr|rtl>'
+ );
+ }
+ validateSite(process.cwd(), parsed);
+} else {
+ runValidation(validateSite);
+}