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.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
Use manifest-driven template solution imports (#719)
Priyanshu Agrawal3dd0cfba2193
diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.mdindex e00bf4de2..55cd9f69b 100644--- a/plugins/power-pages/README.md+++ b/plugins/power-pages/README.md@@ -50,7 +50,13 @@ The plugin provides 36 skills that cover the full lifecycle of a Power Pages sit>> "Create a site from a Power Pages SPA template"-Starts a complete code site either from a curated SPA template or from a fresh framework scaffold. The template path previews installable templates, imports the selected unmanaged solution into your environment, applies optional seed data, activates the site, and opens the live URL. The from-scratch path turns your aesthetic, mood, and optional brand (an existing website, or your colors and logo) into a design thesis and a page-by-page narrative, builds the pages and components with a live preview throughout, and then screenshots every page at desktop and mobile widths and refines it against a ten-category design rubric before the accessibility audit.+Starts a complete code site either from a curated SPA template or from a fresh framework scaffold.+The template path previews installable templates, imports each selected unmanaged solution, applies optional seed data, activates the site, and opens the live URL.+Solutions marked `publishChanges` in the template manifest use `pac solution import --publish-changes`; other solutions import without that flag.+The install confirmation warns that PAC's publication step can include other pending customizations in the target environment.+Financial seed rows use an explicitly selected existing active currency with their amounts unchanged.+Declared attachment uploads omit generated file-name fields from record creation, and seed summaries report partial failures explicitly.+The from-scratch path turns your aesthetic, mood, and optional brand (an existing website, or your colors and logo) into a design thesis and a page-by-page narrative, builds the pages and components with a live preview throughout, and then screenshots every page at desktop and mobile widths and refines it against a ten-category design rubric before the accessibility audit.- Start from a curated SPA template or scaffold from scratch- Choose from React, Vue, Angular, or Astrodiff --git a/plugins/power-pages/references/approval-gates.md b/plugins/power-pages/references/approval-gates.mdindex 62e6b4af8..29979c5f3 100644--- a/plugins/power-pages/references/approval-gates.md+++ b/plugins/power-pages/references/approval-gates.md@@ -470,7 +470,7 @@ When **removing** a gate, also remove its catalog row in the same PR.----### 6.13 `create-site` (22 calls: 15 gates + 7 not-a-gates)+### 6.13 `create-site` (24 calls: 15 gates + 9 not-a-gates)| ID | Kind | Category | Phase | Trigger / question | Cancel leaves ||---|---|---|---|---|---|@@ -491,6 +491,7 @@ When **removing** a gate, also remove its catalog row in the same PR.| `create-site:1.5.clone-failed` | gate | progress | 1.5 | Packaged SPA clone, identity inspection, dependency installation, build/output validation, or code-site upload failed - choose retry, from-scratch fallback, or stop | partial-template-clone || `create-site:1.5.reinstall-unknown` | gate | consent | 1.5 | Installed-state detection failed for one discovered solution — confirm whether to import it anyway, start from scratch, or stop; fires per matching solution iteration | template-cache || `create-site:1.5.import-failed` | gate | progress | 1.5 | Import failed or partial — choose retry, from-scratch fallback, or stop; fires per failed solution iteration | partial-unmanaged-template-import |+| `create-site:1.5.seed-currency` | not-a-gate | - | 1.5 | Read-only seed planning found financial rows — choose an existing active currency with unchanged amounts or skip sample data before background writes | - || `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 | Localized HTML plan rendered with agent verification separated from maker review — *"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 |diff --git a/plugins/power-pages/scripts/apply-seed-data.js b/plugins/power-pages/scripts/apply-seed-data.jsindex 198bed692..b3f49c01a 100644--- a/plugins/power-pages/scripts/apply-seed-data.js+++ b/plugins/power-pages/scripts/apply-seed-data.js@@ -1,32 +1,47 @@#!/usr/bin/env node'use strict';-const { applySeedData } = require('./lib/apply-seed-data');+const { applySeedData, planSeedData, emptyPlan } = require('./lib/apply-seed-data');const { formatJsonResult, runBestEffortJsonCli } = require('./lib/template-cli-args');// Accepted argv shape:// --seedDir ~/.power-platform-skills/template-cache/<sha>/templates/spa/<id>/seed-data// [--seedFile ~/.power-platform-skills/template-cache/<sha>/templates/spa/<id>/seed-data/data.json]-// --envUrl https://org.crm.dynamics.com+// --envUrl https://contoso.crm.dynamics.com [--plan] [--currencyCode SGD]// Missing args are returned as `{ ok:false }` so create-site can continue to// activation; seeding is best-effort and must never block go-live.function parseArgs(argv) {const args = {};for (let i = 0; i < argv.length; i++) {const arg = argv[i];- if (arg === '--seedDir') args.seedDir = argv[++i];- else if (arg === '--seedFile') args.seedFile = argv[++i];- else if (arg === '--envUrl') args.envUrl = argv[++i];+ if (arg === '--plan') {+ args.plan = true;+ } else if (['--seedDir', '--seedFile', '--envUrl', '--currencyCode'].includes(arg)) {+ const value = argv[++i];+ if (!value || value.startsWith('--')) throw new Error(`${arg} requires a value`);+ args[arg.slice(2)] = value;+ } else {+ throw new Error(`Unknown seed argument: ${arg}`);+ }}return args;}-async function run(argv = process.argv.slice(2)) {- const args = parseArgs(argv);+async function run(argv = process.argv.slice(2), deps = {}) {+ let args;+ const argsFailure = (message) => ({+ ...(argv.includes('--plan') ? emptyPlan() : { inserted: 0, failed: 1, skipped: 0 }),+ ok: false, errors: [{ scope: 'args', message }],+ });+ try {+ args = parseArgs(argv);+ } catch (err) {+ return argsFailure(err.message);+ }if (!args.seedDir || !args.envUrl) {- return { ok: false, inserted: 0, failed: 1, skipped: 0, errors: [{ scope: 'args', message: 'Usage: apply-seed-data.js --seedDir <dir> --envUrl <url>' }] };+ return argsFailure('Usage: apply-seed-data.js --seedDir <dir> --envUrl <url>');}- return applySeedData(args);+ return args.plan ? planSeedData(args, deps) : applySeedData(args, deps);}if (require.main === module) {diff --git a/plugins/power-pages/scripts/emit-create-site-template-outcome.js b/plugins/power-pages/scripts/emit-create-site-template-outcome.jsindex e8abeb18c..00db45f75 100644--- a/plugins/power-pages/scripts/emit-create-site-template-outcome.js+++ b/plugins/power-pages/scripts/emit-create-site-template-outcome.js@@ -13,7 +13,7 @@ const { formatJsonResult } = require('./lib/template-cli-args');// Accepted argv shape:// --eventName template_used --templateId company-portal --templateKind spa --framework react --audience internal// --eventName template_import_success --templateId company-portal --templateKind spa --framework react --audience internal --seedApplied true-// --eventName template_import_failure --templateId company-portal --templateKind spa --framework react --audience internal --outcome failure --errorClass ImportSolutionAsync+// --eventName template_import_failure --templateId company-portal --templateKind spa --framework react --audience internal --outcome failure --errorClass PacSolutionImport// --eventName template_clone_success --templateId company-portal --templateKind spa --framework react --audience internal// --eventName template_clone_failure --templateId company-portal --templateKind spa --framework react --audience internal --outcome failure --errorClass PacPagesClone// Scratch branch sends:diff --git a/plugins/power-pages/scripts/fetch-template-variant.js b/plugins/power-pages/scripts/fetch-template-variant.jsindex 6bca62a54..b07f2f61c 100644--- a/plugins/power-pages/scripts/fetch-template-variant.js+++ b/plugins/power-pages/scripts/fetch-template-variant.js@@ -9,6 +9,17 @@ function parseArgs(argv) {const kindIndex = argv.indexOf('--kind');const templateIdIndex = argv.indexOf('--templateId');const variantIndex = argv.indexOf('--variant');+ const solutionSettingsIndex = argv.indexOf('--solutionSettingsJson');+ let solutionSettings = [];+ let solutionSettingsError;+ if (solutionSettingsIndex >= 0) {+ try {+ solutionSettings = JSON.parse(argv[solutionSettingsIndex + 1]);+ } catch {+ solutionSettings = null;+ solutionSettingsError = '--solutionSettingsJson must be valid JSON';+ }+ }return {owner: DEFAULT_OWNER,repo: DEFAULT_REPO,@@ -16,15 +27,26 @@ function parseArgs(argv) {kind: kindIndex >= 0 ? argv[kindIndex + 1] : undefined,templateId: templateIdIndex >= 0 ? argv[templateIdIndex + 1] : undefined,variant: variantIndex >= 0 ? argv[variantIndex + 1] : undefined,+ solutionSettings,+ ...(solutionSettingsError ? { solutionSettingsError } : {}),};}function run(argv = process.argv.slice(2), deps = {}) {const args = parseArgs(argv);- if (!args.sha || !args.kind || !args.templateId || !args.variant) {+ const validSolutionSettings = Array.isArray(args.solutionSettings) &&+ args.solutionSettings.every(solution =>+ solution &&+ typeof solution === 'object' &&+ !Array.isArray(solution) &&+ typeof solution.uniqueName === 'string' &&+ typeof solution.publishChanges === 'boolean'+ );+ if (!args.sha || !args.kind || !args.templateId || !args.variant || !validSolutionSettings) {return {ok: false,- error: 'Usage: fetch-template-variant.js --sha <sha> --kind <spa|traditional> --templateId <id> --variant <name>',+ error: args.solutionSettingsError ||+ 'Usage: fetch-template-variant.js --sha <sha> --kind <spa|traditional> --templateId <id> --variant <name> [--solutionSettingsJson <json-array>]',};}return downloadTemplateVariant(args, deps);diff --git a/plugins/power-pages/scripts/import-template-solution.js b/plugins/power-pages/scripts/import-template-solution.jsnew file mode 100644index 000000000..b12c5f205--- /dev/null+++ b/plugins/power-pages/scripts/import-template-solution.js@@ -0,0 +1,113 @@+#!/usr/bin/env node+'use strict';++const fs = require('fs');+const path = require('path');+const { commandError, runPac } = require('./lib/pac-command');+const { validateZipContainsSolution } = require('./lib/template-catalog');+const { validateDataverseEnvironmentUrl } = require('./lib/validation-helpers');++const MAX_ASYNC_WAIT_MINUTES = 40;+const PROCESS_TIMEOUT_MS = 45 * 60 * 1000;++function parseArgs(argv) {+ const args = { publishChanges: false };+ for (let i = 0; i < argv.length; i++) {+ if (argv[i] === '--zipPath') args.zipPath = argv[++i];+ else if (argv[i] === '--envUrl') args.envUrl = argv[++i];+ else if (argv[i] === '--publishChanges') {+ const value = argv[++i];+ if (value === 'true') args.publishChanges = true;+ else if (value === 'false') args.publishChanges = false;+ else args.publishChanges = null;+ } else {+ args.unknown = argv[i];+ }+ }+ return args;+}++function validateZip(zipPath, fsImpl = fs) {+ const resolved = path.resolve(zipPath || '');+ if (!zipPath || !fsImpl.existsSync(resolved)) return null;+ const stat = fsImpl.lstatSync(resolved);+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size === 0) return null;+ return validateZipContainsSolution(resolved, { fs: fsImpl }) ? resolved : null;+}++function importTemplateSolution(options = {}, deps = {}) {+ try {+ if (typeof options.publishChanges !== 'boolean') {+ throw new Error('publishChanges must be true or false');+ }+ const zipPath = validateZip(options.zipPath, deps.fs || fs);+ if (!zipPath) throw new Error('zipPath must be a valid solution zip');+ const envUrl = validateDataverseEnvironmentUrl(options.envUrl);+ // `--publish-changes` is intentionally manifest-controlled: most template+ // solutions import without it, while solutions that ship forms or views+ // can request publication as part of the same PAC operation.+ // See: https://learn.microsoft.com/power-platform/developer/cli/reference/solution#pac-solution-import+ const args = [+ 'solution', 'import',+ '--environment', envUrl,+ '--path', zipPath,+ '--force-overwrite',+ '--activate-plugins',+ '--async',+ '--max-async-wait-time', String(MAX_ASYNC_WAIT_MINUTES),+ ];+ if (options.publishChanges) args.push('--publish-changes');+ const pac = deps.runPac || ((pacArgs) => runPac(pacArgs, {+ ...deps,+ timeoutMs: PROCESS_TIMEOUT_MS,+ }));+ const result = pac(args);+ if (result.status !== 0) {+ return {+ ok: false,+ phase: 'import',+ publishChanges: options.publishChanges,+ error: commandError('pac solution import', result),+ };+ }+ return {+ ok: true,+ imported: true,+ publishChanges: options.publishChanges,+ };+ } catch (error) {+ return {+ ok: false,+ phase: 'validation',+ publishChanges: options.publishChanges === true,+ error: error.message,+ };+ }+}++function run(argv = process.argv.slice(2), deps = {}) {+ const args = parseArgs(argv);+ if (args.unknown || !args.zipPath || !args.envUrl || args.publishChanges === null) {+ return {+ ok: false,+ phase: 'validation',+ error: 'Usage: import-template-solution.js --zipPath <solution.zip> --envUrl <environment-url> [--publishChanges <true|false>]',+ };+ }+ return importTemplateSolution(args, deps);+}++if (require.main === module) {+ const result = run();+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);+ if (!result.ok) process.exitCode = 1;+}++module.exports = {+ MAX_ASYNC_WAIT_MINUTES,+ PROCESS_TIMEOUT_MS,+ importTemplateSolution,+ parseArgs,+ run,+ validateZip,+};diff --git a/plugins/power-pages/scripts/lib/apply-seed-data.js b/plugins/power-pages/scripts/lib/apply-seed-data.jsindex 113e8a7e3..9bc949058 100644--- a/plugins/power-pages/scripts/lib/apply-seed-data.js+++ b/plugins/power-pages/scripts/lib/apply-seed-data.js@@ -6,6 +6,7 @@ const {getAuthToken,makeRequest,validateDataverseEnvironmentUrl,+ odataGet,} = require('./validation-helpers');const generateUuid = require('../generate-uuid');@@ -25,6 +26,11 @@ function emptySummary() {return { ok: true, inserted: 0, failed: 0, skipped: 0, errors: [] };}+function emptyPlan() {+ return { ok: true, writes: 0, counts: { tables: 0, records: 0, files: 0 },+ financialEntitySets: [], currencies: [], requiresCurrencySelection: false, errors: [] };+}+function listSeedFiles(seedDir, deps = {}, seedFile = null) {const fsImpl = deps.fs || fs;if (!seedDir || !fsImpl.existsSync(seedDir)) return [];@@ -93,9 +99,31 @@ function readSeedFile(filePath, deps = {}) {function splitReservedFiles(record) {const { __files: files = null, ...recordBody } = record;+ // File uploads populate the file GUID and its read-only <column>_name companion.+ // Strip only declared uploads; ordinary business name columns remain writable.+ // https://learn.microsoft.com/power-apps/developer/data-platform/file-column-data+ if (files && typeof files === 'object' && !Array.isArray(files)) {+ for (const column of Object.keys(files)) {+ delete recordBody[column];+ delete recordBody[`${column}_name`];+ }+ }return { recordBody, files };}+function uploadFileName(record, columnName, filePath) {+ const companion = `${columnName}_name`;+ const name = Object.prototype.hasOwnProperty.call(record, companion)+ ? record[companion] : path.basename(filePath);+ if (typeof name !== 'string' || !name.trim() || name !== name.trim() ||+ name === '.' || name === '..' || /[\\/:<>"|?*\x00-\x1f\x7f]/.test(name) ||+ /%(?:2f|5c|00)/i.test(name) ||+ /[. ]$/.test(name) || name.length > 255) {+ throw new Error(`Invalid upload filename for ${columnName}; expected a non-empty filename without path segments`);+ }+ return name;+}+function splitCreateAndStateUpdate(seed, record) {const createRecord = { ...record };const stateUpdate = {};@@ -142,7 +170,21 @@ function validateSeedLookupContract(seedEntries) {const errors = [];for (const { file, seed } of seedEntries) {+ if (!ODATA_IDENTIFIER_RE.test(String(seed.entitySetName || ''))) {+ errors.push({ file, entitySetName: seed.entitySetName,+ message: `Invalid Dataverse OData operation name: ${seed.entitySetName}` });+ continue;+ }+ if ((seed.logicalName !== undefined && !ODATA_IDENTIFIER_RE.test(String(seed.logicalName))) ||+ (seed.primaryKey !== undefined && !ODATA_IDENTIFIER_RE.test(String(seed.primaryKey)))) {+ errors.push({ file, entitySetName: seed.entitySetName, message: 'Invalid seed logicalName or primaryKey identifier' });+ continue;+ }for (const record of seed.records) {+ if (!record || typeof record !== 'object' || Array.isArray(record)) {+ errors.push({ file, entitySetName: seed.entitySetName, message: 'Seed record must be an object' });+ continue;+ }for (const [key, value] of Object.entries(record || {})) {if (isCamelCaseLookupKey(key) && typeof value === 'string') {errors.push({@@ -152,28 +194,42 @@ function validateSeedLookupContract(seedEntries) {});continue;}- if (!key.endsWith('@odata.bind') || typeof value !== 'string') continue;+ if (!key.endsWith('@odata.bind')) continue;// Seed lookups use the OData bind shape:// "[email protected]":// "/spa311_categories(11111111-1111-1111-1111-111111111111)"// Validate references to records in this seed set before any writes. The// navigation-property key itself remains authoritative solution metadata.- const match = value.match(/^\/([^/()]+)\(([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)$/i);- if (!match) {- errors.push({- file,- entitySetName: seed.entitySetName,- message: `Lookup ${key} must use /<entitySetName>(<guid>)`,- });- continue;- }- const target = idToTarget.get(match[2].toLowerCase());- if (target && target.entitySetName !== match[1]) {- errors.push({- file,- entitySetName: seed.entitySetName,- message: `Lookup ${key} targets ${match[1]}, but the referenced seed record belongs to ${target.entitySetName}`,- });+ // Collection-valued binds associate N:N rows on create, e.g.+ // "[email protected]": ["/contacts(<guid>)", "/contacts(<guid>)"].+ // Validate each member without converting it to intersect-table upserts.+ // https://learn.microsoft.com/power-apps/developer/data-platform/webapi/associate-disassociate-entities-using-web-api+ const references = Array.isArray(value) ? value : [value];+ let collectionEntitySet = null;+ for (const reference of references) {+ const match = typeof reference === 'string' &&+ reference.match(/^\/([A-Za-z_][A-Za-z0-9_]*)\(([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\)$/i);+ if (!match) {+ errors.push({+ file,+ entitySetName: seed.entitySetName,+ message: `Lookup ${key} must use /<entitySetName>(<guid>)`,+ });+ continue;+ }+ if (collectionEntitySet && collectionEntitySet !== match[1]) {+ errors.push({ file, entitySetName: seed.entitySetName,+ message: `Lookup ${key} collection must reference one entity set` });+ }+ collectionEntitySet = match[1];+ const target = idToTarget.get(match[2].toLowerCase());+ if (target && target.entitySetName !== match[1]) {+ errors.push({+ file,+ entitySetName: seed.entitySetName,+ message: `Lookup ${key} targets ${match[1]}, but the referenced seed record belongs to ${target.entitySetName}`,+ });+ }}}}@@ -186,21 +242,39 @@ function normalizeDataverseExportSeed(seed) {return null;}const idToEntitySet = new Map();+ const idCounts = new Map();for (const table of Object.values(seed.tables)) {if (!table || typeof table !== 'object' || !Array.isArray(table.records) || typeof table.idColumn !== 'string' || typeof table.entitySet !== 'string') {- continue;+ throw new Error('Expected export tables to declare entitySet, idColumn and records');}for (const record of table.records) {+ if (!record || typeof record !== 'object' || Array.isArray(record)) {+ throw new Error('Export seed record must be an object');+ }const id = record && record[table.idColumn];- if (typeof id === 'string') idToEntitySet.set(id.toLowerCase(), table.entitySet);+ if (typeof id === 'string') {+ idToEntitySet.set(id.toLowerCase(), table.entitySet);+ idCounts.set(id.toLowerCase(), (idCounts.get(id.toLowerCase()) || 0) + 1);+ }}}const filesByRecordId = new Map();- for (const fileExport of Array.isArray(seed.fileExports) ? seed.fileExports : []) {- if (!fileExport || typeof fileExport !== 'object') continue;+ if (seed.fileExports !== undefined && !Array.isArray(seed.fileExports)) {+ throw new Error('fileExports must be an array of declared uploads');+ }+ for (const fileExport of seed.fileExports || []) {+ if (!fileExport || typeof fileExport !== 'object') throw new Error('Invalid fileExports upload declaration');const { attachmentId, fileColumn, path: filePath } = fileExport;- if (typeof attachmentId !== 'string' || typeof fileColumn !== 'string' || typeof filePath !== 'string') continue;+ if (typeof attachmentId !== 'string' || !DATAVERSE_GUID_RE.test(attachmentId) ||+ typeof fileColumn !== 'string' || !ODATA_IDENTIFIER_RE.test(fileColumn) ||+ typeof filePath !== 'string' || !filePath.trim()) {+ throw new Error('fileExports upload requires GUID attachmentId, fileColumn and path');+ }+ if (idCounts.get(attachmentId.toLowerCase()) !== 1) {+ throw new Error('fileExports attachmentId must identify exactly one source record');+ }const current = filesByRecordId.get(attachmentId.toLowerCase()) || {};+ if (Object.prototype.hasOwnProperty.call(current, fileColumn)) throw new Error('Duplicate fileExports upload column for attachmentId');current[fileColumn] = filePath;filesByRecordId.set(attachmentId.toLowerCase(), current);}@@ -209,6 +283,7 @@ function normalizeDataverseExportSeed(seed) {.map((table) => ({entitySetName: table.entitySet,primaryKey: table.idColumn,+ ...(table.logicalName !== undefined ? { logicalName: table.logicalName } : {}),records: table.records.map((record) => normalizeExportRecord(record, table.idColumn, idToEntitySet, filesByRecordId)),}));}@@ -260,6 +335,7 @@ function validateFilesContract({ seedDir, seed, record }, deps = {}) {return '__files must be an object mapping file column logical names to seed-data-relative paths';}if (!seed.primaryKey) return 'Seed file with __files must declare primaryKey';+ if (!ODATA_IDENTIFIER_RE.test(seed.primaryKey)) return 'Invalid file primaryKey identifier';const recordId = record[seed.primaryKey];if (typeof recordId !== 'string' || !DATAVERSE_GUID_RE.test(recordId)) {return `Record with __files must include GUID primary key ${seed.primaryKey}`;@@ -274,6 +350,11 @@ function validateFilesContract({ seedDir, seed, record }, deps = {}) {if (!absolutePath.startsWith(seedRoot + path.sep)) return `Attachment path must stay under seed-data root: ${relativePath}`;const containmentError = validateContainedPath(seedRoot, absolutePath, fsImpl);if (containmentError) return containmentError;+ try {+ uploadFileName(record, columnName, absolutePath);+ } catch (err) {+ return err.message;+ }}return null;}@@ -340,6 +421,7 @@ function validateAttachmentFile(filePath, deps = {}) {if (!fsImpl.existsSync(filePath)) return `Attachment file not found: ${filePath}`;const stat = fsImpl.lstatSync(filePath);if (!stat.isFile()) return `Attachment path is not a file: ${filePath}`;+ if (stat.size === 0) return `Attachment file is empty: ${filePath}`;// Git LFS pointer files start with:// version https://git-lfs.github.com/spec/v1// Spec: https://github.com/git-lfs/git-lfs/blob/main/docs/spec.md@@ -407,9 +489,16 @@ function entityLogicalNameFromPrimaryKey(primaryKey) {return primaryKey.replace(/id$/i, '');}-async function uploadFileColumn({ envUrl, tokenProvider, primaryKey, recordId, columnName, filePath }, deps = {}) {- const fileName = path.basename(filePath);+async function uploadFileColumn({ envUrl, tokenProvider, primaryKey, recordId, columnName, filePath, fileName = path.basename(filePath) }, deps = {}) {+ if (!ODATA_IDENTIFIER_RE.test(String(primaryKey || '')) ||+ !ODATA_IDENTIFIER_RE.test(String(columnName || '')) || !DATAVERSE_GUID_RE.test(String(recordId || ''))) {+ throw new Error('File upload requires valid primaryKey, recordId and columnName identifiers');+ }+ uploadFileName({ [`${columnName}_name`]: fileName }, columnName, filePath);+ const fileError = validateAttachmentFile(filePath, deps);+ if (fileError) throw new Error(fileError);const entityLogicalName = entityLogicalNameFromPrimaryKey(primaryKey);+ if (!ODATA_IDENTIFIER_RE.test(entityLogicalName)) throw new Error('Invalid file target logical name');// Dataverse file columns use actions rather than setting bytes in the record:// InitializeFileBlocksUpload -> UploadBlock* -> CommitFileBlocksUpload// See: https://learn.microsoft.com/power-apps/developer/data-platform/file-column-data@@ -421,9 +510,7 @@ async function uploadFileColumn({ envUrl, tokenProvider, primaryKey, recordId, cFileName: fileName,FileAttributeName: columnName,} }, deps);- if (init.error || init.statusCode < 200 || init.statusCode >= 300) {- throw new Error(init.error || init.body || `InitializeFileBlocksUpload failed (${init.statusCode})`);- }+ requireSuccess(init, 'InitializeFileBlocksUpload');// InitializeFileBlocksUpload returns a JSON payload shaped as:// { "FileContinuationToken": "<opaque token>" }// Older/proxy-failed responses can be empty or non-JSON even with an HTTP@@ -431,25 +518,33 @@ async function uploadFileColumn({ envUrl, tokenProvider, primaryKey, recordId, clet tokenPayload;try {tokenPayload = JSON.parse(init.body || '{}');- } catch (err) {- throw new Error(`InitializeFileBlocksUpload returned invalid JSON: ${err.message}`);+ } catch {+ // JSON parser messages can quote response bytes containing the opaque upload token.+ throw new Error('InitializeFileBlocksUpload returned invalid JSON');}- const continuation = tokenPayload.FileContinuationToken;- if (!continuation) throw new Error('InitializeFileBlocksUpload did not return FileContinuationToken');+ const continuation = tokenPayload && tokenPayload.FileContinuationToken;+ if (typeof continuation !== 'string' || !continuation.trim()) throw new Error('InitializeFileBlocksUpload did not return a valid FileContinuationToken');const blockIds = [];const randomBlockId = deps.randomBlockId || defaultBlockId;const fsImpl = deps.fs || fs;- const fileSize = fsImpl.statSync(filePath).size || 0;+ const fileSize = fsImpl.statSync(filePath).size;+ if (!Number.isSafeInteger(fileSize) || fileSize <= 0) throw new Error('Attachment file must have a non-zero valid size');const fileHandle = typeof fsImpl.openSync === 'function' ? fsImpl.openSync(filePath, 'r') : null;try {let offset = 0;while (offset < fileSize) {const block = Buffer.alloc(Math.min(FILE_BLOCK_SIZE_BYTES, fileSize - offset));if (fileHandle !== null && typeof fsImpl.readSync === 'function') {- fsImpl.readSync(fileHandle, block, 0, block.length, offset);+ let bytesRead = 0;+ while (bytesRead < block.length) {+ const count = fsImpl.readSync(fileHandle, block, bytesRead, block.length - bytesRead, offset + bytesRead);+ if (!Number.isInteger(count) || count <= 0) throw new Error('Attachment read ended before the expected file size');+ bytesRead += count;+ }} else {- fsImpl.readFileSync(filePath).copy(block, 0, offset, offset + block.length);+ const bytesRead = fsImpl.readFileSync(filePath).copy(block, 0, offset, offset + block.length);+ if (bytesRead !== block.length) throw new Error('Attachment read ended before the expected file size');}offset += block.length;const blockId = randomBlockId();@@ -459,9 +554,7 @@ async function uploadFileColumn({ envUrl, tokenProvider, primaryKey, recordId, cBlockData: block.toString('base64'),FileContinuationToken: continuation,} }, deps);- if (res.error || res.statusCode < 200 || res.statusCode >= 300) {- throw new Error(res.error || res.body || `UploadBlock failed (${res.statusCode})`);- }+ requireSuccess(res, 'UploadBlock');}} finally {if (fileHandle !== null && typeof fsImpl.closeSync === 'function') fsImpl.closeSync(fileHandle);@@ -472,8 +565,14 @@ async function uploadFileColumn({ envUrl, tokenProvider, primaryKey, recordId, cFileName: fileName,MimeType: contentTypeForFile(filePath),} }, deps);- if (commit.error || commit.statusCode < 200 || commit.statusCode >= 300) {- throw new Error(commit.error || commit.body || `CommitFileBlocksUpload failed (${commit.statusCode})`);+ requireSuccess(commit, 'CommitFileBlocksUpload');+}++function requireSuccess(response, operation) {+ if (!response || !Number.isInteger(response.statusCode) ||+ response.error || response.statusCode < 200 || response.statusCode >= 300) {+ throw new Error(response && (response.error || response.body) ||+ `${operation} failed (HTTP ${response && response.statusCode || 'invalid response'})`);}}@@ -492,7 +591,7 @@ function postDataverseJson({ envUrl, tokenProvider, apiPath, body, includeHeader}, deps);}-function requestDataverseJson({+async function requestDataverseJson({envUrl,tokenProvider,apiPath,@@ -501,7 +600,7 @@ function requestDataverseJson({body,includeHeaders = false,}, deps = {}) {- const request = deps.makeRequest || makeRequest;+ const request = safeSeedRequest(envUrl, deps);const trustedEnvUrl = validateDataverseEnvironmentUrl(envUrl);if (!ODATA_IDENTIFIER_RE.test(String(apiPath || ''))) {throw new Error(`Invalid Dataverse OData operation name: ${apiPath}`);@@ -513,7 +612,7 @@ function requestDataverseJson({throw new Error(`Invalid Dataverse record id: ${recordId}`);}const headers = {- Authorization: `Bearer ${tokenProvider()}`,+ Authorization: `Bearer ${requireToken(tokenProvider())}`,Accept: 'application/json','Content-Type': 'application/json',};@@ -540,26 +639,297 @@ function createTokenProvider({ envUrl, initialToken, resolveToken, refreshEverytoken = resolveToken(envUrl);calls = 0;}+ if (typeof token !== 'string' || !token.trim()) throw new Error('Azure CLI token unavailable');calls += 1;return token;};}-async function applySeedData({ seedDir, seedFile, envUrl }, deps = {}) {- const summary = emptySummary();+function loadSeedEntries({ seedDir, seedFile }, deps, summary) {+ const seedEntries = [];+ for (const filePath of listSeedFiles(seedDir, deps, seedFile)) {+ try {+ const seed = readSeedFile(filePath, deps);+ for (const seedEntry of (Array.isArray(seed) ? seed : [seed])) {+ seedEntries.push({ file: path.basename(filePath), seed: seedEntry });+ }+ } catch (err) {+ summary.errors.push({ file: path.basename(filePath), message: err.message });+ }+ }+ return seedEntries;+}++function normalizeCurrencyCode(currencyCode) {+ if (typeof currencyCode !== 'string' || !/^[A-Za-z]{3}$/.test(currencyCode)) {+ throw new Error('currencyCode must contain exactly three ASCII letters (ISO currency code)');+ }+ return currencyCode.toUpperCase();+}++function runTokenProvider(envUrl, deps) {+ const resolveToken = deps.getAuthToken || getAuthToken;+ const token = deps.token || resolveToken(envUrl);+ if (typeof token !== 'string' || !token.trim()) {+ const error = new Error(`Azure CLI token unavailable for ${envUrl}`);+ error.code = 'SEED_AUTH_UNAVAILABLE';+ throw error;+ }+ return deps.tokenProvider || createTokenProvider({+ envUrl, initialToken: token, resolveToken,+ refreshEvery: deps.tokenRefreshEvery || TOKEN_REFRESH_EVERY_REQUESTS,+ });+}++function requireToken(token) {+ if (typeof token !== 'string' || !token.trim()) throw new Error('Azure CLI token unavailable');+ return token;+}++function redactDiagnostic(message, secrets = []) {+ let text = String(message);+ for (const secret of secrets) {+ if (typeof secret === 'string' && secret) text = text.split(secret).join('<REDACTED>');+ }+ return text.replace(/("FileContinuationToken"\s*:\s*")[^"]*"/gi, '$1<REDACTED>"')+ .replace(/Bearer\s+\S+/gi, 'Bearer <REDACTED>');+}++function safeSeedRequest(envUrl, deps) {+ const origin = new URL(validateDataverseEnvironmentUrl(envUrl)).origin;+ const request = deps.makeRequest || makeRequest;+ return async (options) => {+ const url = new URL(options.url, origin);+ if (url.origin !== origin || url.username || url.password || url.hash ||+ !url.pathname.startsWith('/api/data/v9.2/')) {+ throw new Error('Seed request must remain on the current Dataverse origin and Web API path');+ }+ const authorization = options.headers && options.headers.Authorization;+ const secrets = [typeof authorization === 'string' ? authorization.replace(/^Bearer /, '') : null];+ if (options.body) {+ const body = JSON.parse(options.body);+ secrets.push(body.FileContinuationToken);+ }+ try {+ const response = await request({ ...options, url: url.href });+ if (!response || typeof response !== 'object') throw new Error('Invalid Dataverse response');+ return {+ ...response,+ ...(response.error ? { error: redactDiagnostic(response.error, secrets) } : {}),+ // Success bodies include continuation tokens needed by the next upload action.+ // Redact only error bodies, so diagnostics cannot echo bearer or file tokens.+ ...((response.error || !Number.isInteger(response.statusCode) || response.statusCode < 200 || response.statusCode >= 300)+ ? { body: redactDiagnostic(response.body || '', secrets) } : {}),+ };+ } catch (err) {+ throw new Error(redactDiagnostic(err.message, secrets));+ }+ };+}++async function seedGetAll(envUrl, apiPath, tokenProvider, deps) {+ const request = safeSeedRequest(envUrl, deps);+ const guardedRequest = async (options) => {+ const response = await request(options);+ requireSuccess(response, 'Metadata/currency query');+ return response;+ };+ const rows = [];+ let next = `${envUrl}/api/data/v9.2/${apiPath}`;+ const visited = new Set();+ while (next) {+ if (visited.has(next) || visited.size >= 100) throw new Error('Metadata/currency pagination did not terminate');+ visited.add(next);+ const token = requireToken(tokenProvider());+ let page;+ try {+ page = await odataGet(next, token, guardedRequest);+ } catch (err) {+ if (err instanceof SyntaxError) throw new Error('Metadata/currency query returned invalid JSON');+ throw new Error(redactDiagnostic(err.message, [token]));+ }+ if (!page || !Array.isArray(page.value)) throw new Error('Metadata/currency query must return a JSON value array');+ rows.push(...page.value);+ next = page['@odata.nextLink'];+ if (next !== undefined && (typeof next !== 'string' || !next.trim())) {+ throw new Error('Invalid metadata/currency @odata.nextLink');+ }+ }+ return rows;+}++async function discoverFinancialEntities(seedEntries, envUrl, tokenProvider, deps) {+ const byEntitySet = new Map();+ for (const { seed } of seedEntries) {+ if (seed.entitySetName === 'transactioncurrencies') {+ throw new Error('Currency selection cannot create currencies from seed data; choose an existing target currency');+ }+ const group = byEntitySet.get(seed.entitySetName) || { seeds: [], records: [] };+ group.seeds.push(seed);+ group.records.push(...seed.records);+ byEntitySet.set(seed.entitySetName, group);+ }+ const financial = [];+ for (const [entitySetName, group] of byEntitySet) {+ if (!ODATA_IDENTIFIER_RE.test(entitySetName)) throw new Error(`Invalid Dataverse OData operation name: ${entitySetName}`);+ if (group.records.length === 0) continue;+ const entities = await seedGetAll(envUrl,+ `EntityDefinitions?$select=LogicalName,EntitySetName,PrimaryIdAttribute&$filter=EntitySetName eq '${entitySetName}'`,+ tokenProvider, deps);+ if (entities.length !== 1 || !entities[0] || entities[0].EntitySetName !== entitySetName ||+ !ODATA_IDENTIFIER_RE.test(String(entities[0].LogicalName || '')) ||+ !ODATA_IDENTIFIER_RE.test(String(entities[0].PrimaryIdAttribute || ''))) {+ throw new Error(`Unsupported or ambiguous entity metadata for ${entitySetName}`);+ }+ const logicalName = entities[0].LogicalName;+ if (group.seeds.some((seed) => seed.logicalName && seed.logicalName !== logicalName)) {+ throw new Error(`Seed logicalName disagrees with target metadata for ${entitySetName}`);+ }+ // Money detection uses the typed metadata endpoint, never amount/price/name heuristics.+ // https://learn.microsoft.com/power-apps/developer/data-platform/webapi/query-metadata-web-api+ const attributes = await seedGetAll(envUrl,+ `EntityDefinitions(LogicalName='${logicalName}')/Attributes/Microsoft.Dynamics.CRM.MoneyAttributeMetadata?$select=LogicalName,IsValidForCreate`,+ tokenProvider, deps);+ if (attributes.some((attr) => !attr || !ODATA_IDENTIFIER_RE.test(String(attr.LogicalName || '')) ||+ typeof attr.IsValidForCreate !== 'boolean') ||+ new Set(attributes.map((attr) => attr.LogicalName)).size !== attributes.length) {+ throw new Error(`Unsupported Money metadata for ${entitySetName}`);+ }+ const usedAttributes = attributes.filter((attr) =>+ group.records.some((record) => Object.prototype.hasOwnProperty.call(record, attr.LogicalName)));+ if (usedAttributes.length === 0) continue;+ if (usedAttributes.some((attr) => !attr.IsValidForCreate)) {+ throw new Error(`Unsupported non-creatable Money attribute in ${entitySetName}`);+ }+ const moneyAttributes = usedAttributes.map((attr) => attr.LogicalName).sort();+ const records = group.records.filter((record) =>+ moneyAttributes.some((attr) => Object.prototype.hasOwnProperty.call(record, attr)));+ const relationships = await seedGetAll(envUrl,+ `EntityDefinitions(LogicalName='${logicalName}')/ManyToOneRelationships?$select=ReferencedEntity,ReferencingEntity,ReferencingAttribute,ReferencingEntityNavigationPropertyName&$filter=ReferencedEntity eq 'transactioncurrency'`,+ tokenProvider, deps);+ const currencyRelationships = relationships.filter((r) => r && r.ReferencedEntity === 'transactioncurrency' &&+ r.ReferencingEntity === logicalName && r.ReferencingAttribute === 'transactioncurrencyid');+ if (currencyRelationships.length !== 1 ||+ !ODATA_IDENTIFIER_RE.test(String(currencyRelationships[0].ReferencingEntityNavigationPropertyName || ''))) {+ throw new Error(`Unsupported or ambiguous currency navigation metadata for ${entitySetName}`);+ }+ // Lookup writes require the exact metadata navigation property, including case.+ // https://learn.microsoft.com/power-apps/developer/data-platform/webapi/web-api-navigation-properties+ financial.push({ entitySetName, logicalName, moneyAttributes, records,+ navigationProperty: currencyRelationships[0].ReferencingEntityNavigationPropertyName });+ }+ return financial;+}++async function queryTargetCurrencies(envUrl, tokenProvider, deps, currencyCode) {+ const rows = await seedGetAll(envUrl,+ 'transactioncurrencies?$select=transactioncurrencyid,isocurrencycode,currencyname,statecode&$filter=statecode eq 0' ++ (currencyCode ? ` and isocurrencycode eq '${currencyCode}'` : ''), tokenProvider, deps);+ const currencies = rows.map((row) => {+ if (!row || row.statecode !== 0 || !DATAVERSE_GUID_RE.test(String(row.transactioncurrencyid || '')) ||+ typeof row.currencyname !== 'string' || !row.currencyname.trim()) {+ throw new Error('Target currency query returned invalid or inactive currency metadata');+ }+ const code = normalizeCurrencyCode(row.isocurrencycode);+ if (currencyCode && code !== currencyCode) throw new Error('Target currency query returned a mismatched code');+ return { code, name: row.currencyname, id: row.transactioncurrencyid };+ });+ if (currencyCode && currencies.length !== 1) {+ throw new Error(`Expected one existing active ${currencyCode} target currency; found ${currencies.length}`);+ }+ if (!currencies.length) throw new Error('No existing active target currencies are available');+ if (new Set(currencies.map((currency) => currency.code)).size !== currencies.length) {+ throw new Error('Target active currency codes are ambiguous (duplicate codes)');+ }+ return currencies;+}++function bindTargetCurrency(financial, currency) {+ const bind = `/transactioncurrencies(${currency.id})`;+ // Check every row first. A conflict must stop the run before even unrelated tables write.+ for (const entity of financial) {+ for (const record of entity.records) {+ for (const [key, value] of Object.entries(record)) {+ if (!key.endsWith('@odata.bind')) continue;+ const references = Array.isArray(value) ? value : [value];+ if (key === `${entity.navigationProperty}@odata.bind` ||+ references.some((reference) => typeof reference === 'string' && /^\/transactioncurrencies\(/i.test(reference))) {+ if (key !== `${entity.navigationProperty}@odata.bind` || typeof value !== 'string' ||+ value.toLowerCase() !== bind.toLowerCase()) {+ throw new Error(`Explicit currency binding disagrees with selected ${currency.code} for ${entity.entitySetName}`);+ }+ }+ }+ if (Object.prototype.hasOwnProperty.call(record, 'transactioncurrencyid')) {+ throw new Error(`Currency lookup must use exact metadata navigation for ${entity.entitySetName}`);+ }+ }+ }+ for (const entity of financial) {+ for (const record of entity.records) {+ // Source lookup GUIDs and exchange rates are environment-specific.+ // Select only the reviewed target currency; Dataverse owns its exchange rate.+ // https://learn.microsoft.com/power-apps/developer/data-platform/transaction-currency-currency-entity+ delete record._transactioncurrencyid_value;+ delete record.exchangerate;+ record[`${entity.navigationProperty}@odata.bind`] = bind;+ }+ }+}++async function planSeedData({ seedDir, seedFile, envUrl, currencyCode }, deps = {}) {+ const plan = emptyPlan();try {envUrl = validateDataverseEnvironmentUrl(envUrl);- const seedEntries = [];- for (const filePath of listSeedFiles(seedDir, deps, seedFile)) {- try {- const seed = readSeedFile(filePath, deps);- for (const seedEntry of (Array.isArray(seed) ? seed : [seed])) {- seedEntries.push({ file: path.basename(filePath), seed: seedEntry });+ if (currencyCode !== undefined) currencyCode = normalizeCurrencyCode(currencyCode);+ const entries = loadSeedEntries({ seedDir, seedFile }, deps, plan);+ if (!entries.length && !plan.errors.length) throw new Error('No seed JSON source was found');+ plan.errors.push(...validateSeedLookupContract(entries));+ plan.counts.tables = new Set(entries.map(({ seed }) => seed.entitySetName)).size;+ for (const { file, seed } of entries) {+ plan.counts.records += seed.records.length;+ for (const record of seed.records) {+ try {+ const error = validateFilesContract({ seedDir, seed, record }, deps);+ if (error) throw new Error(error);+ const { recordBody, files } = splitReservedFiles(record);+ splitCreateAndStateUpdate(seed, recordBody);+ for (const relativePath of Object.values(files || {})) {+ plan.counts.files += 1;+ const fileError = validateAttachmentFile(path.join(seedDir, relativePath), { ...deps, seedDir });+ if (fileError) throw new Error(fileError);+ }+ } catch (err) {+ plan.errors.push({ file, entitySetName: seed.entitySetName, message: err.message });}- } catch (err) {- summary.errors.push({ file: path.basename(filePath), message: err.message });}}+ if (plan.errors.length) {+ plan.ok = false;+ return plan;+ }+ const tokenProvider = runTokenProvider(envUrl, deps);+ const financial = await discoverFinancialEntities(entries, envUrl, tokenProvider, deps);+ plan.financialEntitySets = financial.map(({ entitySetName, logicalName, records, moneyAttributes }) =>+ ({ entitySetName, logicalName, recordCount: records.length, moneyAttributes }));+ if (financial.length || currencyCode) {+ plan.currencies = await queryTargetCurrencies(envUrl, tokenProvider, deps, currencyCode);+ if (currencyCode) bindTargetCurrency(financial, plan.currencies[0]);+ }+ plan.requiresCurrencySelection = financial.length > 0 && !currencyCode;+ } catch (err) {+ plan.ok = false;+ plan.errors.push({ scope: 'plan', message: err.message });+ }+ return plan;+}++async function applySeedData({ seedDir, seedFile, envUrl, currencyCode }, deps = {}) {+ const summary = emptySummary();+ try {+ envUrl = validateDataverseEnvironmentUrl(envUrl);+ if (currencyCode !== undefined) currencyCode = normalizeCurrencyCode(currencyCode);+ const seedEntries = loadSeedEntries({ seedDir, seedFile }, deps, summary);summary.errors.push(...validateSeedLookupContract(seedEntries));if (summary.errors.length > 0) {summary.ok = false;@@ -567,12 +937,13 @@ async function applySeedData({ seedDir, seedFile, envUrl }, deps = {}) {return summary;}- const resolveToken = deps.getAuthToken || getAuthToken;- const token = deps.token || resolveToken(envUrl);- if (!token) {- return { ...summary, ok: false, failed: 1, errors: [{ scope: 'auth', message: `Azure CLI token unavailable for ${envUrl}` }] };+ const tokenProvider = runTokenProvider(envUrl, deps);+ if (!seedEntries.length) throw new Error('No seed JSON source was found');+ if (currencyCode) {+ const financial = await discoverFinancialEntities(seedEntries, envUrl, tokenProvider, deps);+ const [currency] = await queryTargetCurrencies(envUrl, tokenProvider, deps, currencyCode);+ bindTargetCurrency(financial, currency);}- const tokenProvider = deps.tokenProvider || createTokenProvider({ envUrl, initialToken: token, resolveToken, refreshEvery: deps.tokenRefreshEvery || TOKEN_REFRESH_EVERY_REQUESTS });for (const { file, seed: seedEntry } of seedEntries) {for (const record of seedEntry.records) {const context = { file, entitySetName: seedEntry.entitySetName };@@ -592,12 +963,14 @@ async function applySeedData({ seedDir, seedFile, envUrl }, deps = {}) {summary.errors.push({ ...context, message: res.error });} else if (isDuplicateConflict(res)) {outcome = 'skipped';- } else if (res.statusCode >= 200 && res.statusCode < 300) {+ } else if (Number.isInteger(res.statusCode) && res.statusCode >= 200 && res.statusCode < 300) {outcome = 'inserted';} else {summary.failed += 1;summary.errors.push({ ...context, statusCode: res.statusCode, message: res.body || `HTTP ${res.statusCode}` });}+ if (outcome === 'inserted') summary.inserted += 1;+ if (outcome === 'skipped') summary.skipped += 1;if (outcome && stateUpdate) {const stateRes = await patchRecordState({envUrl,@@ -606,12 +979,8 @@ async function applySeedData({ seedDir, seedFile, envUrl }, deps = {}) {recordId,stateUpdate,}, deps);- if (stateRes.error || stateRes.statusCode < 200 || stateRes.statusCode >= 300) {- throw new Error(stateRes.error || stateRes.body || `State update failed (${stateRes.statusCode})`);- }+ requireSuccess(stateRes, 'State update');}- if (outcome === 'inserted') summary.inserted += 1;- if (outcome === 'skipped') summary.skipped += 1;if (outcome && files) {await uploadRecordFiles({ seedDir, seed: seedEntry, record, files, envUrl, tokenProvider, summary, context }, deps);}@@ -624,8 +993,9 @@ async function applySeedData({ seedDir, seedFile, envUrl }, deps = {}) {} catch (err) {summary.ok = false;summary.failed += 1;- summary.errors.push({ scope: 'seedDir', message: err.message });+ summary.errors.push({ scope: err.code === 'SEED_AUTH_UNAVAILABLE' ? 'auth' : 'seedDir', message: err.message });}+ summary.ok = summary.failed === 0 && summary.errors.length === 0;return summary;}@@ -642,6 +1012,7 @@ async function uploadRecordFiles({ seedDir, seed, record, files, envUrl, tokenPrrecordId: record[seed.primaryKey],columnName,filePath,+ fileName: uploadFileName(record, columnName, filePath),}, deps);} catch (err) {summary.failed += 1;@@ -652,7 +1023,9 @@ async function uploadRecordFiles({ seedDir, seed, record, files, envUrl, tokenPrmodule.exports = {applySeedData,+ planSeedData,emptySummary,+ emptyPlan,listSeedFiles,readSeedFile,normalizeDataverseExportSeed,diff --git a/plugins/power-pages/scripts/lib/create-site-template-telemetry.js b/plugins/power-pages/scripts/lib/create-site-template-telemetry.jsindex 2eb3b842f..22171e8c2 100644--- a/plugins/power-pages/scripts/lib/create-site-template-telemetry.js+++ b/plugins/power-pages/scripts/lib/create-site-template-telemetry.js@@ -17,6 +17,7 @@ const FRAMEWORKS = new Set(['react', 'vue', 'angular', 'astro']);const AUDIENCES = new Set(['internal', 'external']);const ERROR_CLASSES = new Set(['ImportSolutionAsync',+ 'PacSolutionImport','PacPagesClone','NpmInstall','NpmBuild',diff --git a/plugins/power-pages/scripts/lib/template-catalog.js b/plugins/power-pages/scripts/lib/template-catalog.jsindex 109b58328..0eb72b605 100644--- a/plugins/power-pages/scripts/lib/template-catalog.js+++ b/plugins/power-pages/scripts/lib/template-catalog.js@@ -15,6 +15,7 @@ const DEFAULT_CATALOG_PATH = 'templates/manifest.json';const FRAMEWORKS = new Set(['react', 'vue', 'angular', 'astro', 'none', 'other']);const TEMPLATE_KINDS = new Set(['spa', 'traditional']);const ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;+const IDENTIFIER_PATTERN = /^[a-z_][a-z0-9_]*$/i;const CACHE_MARKER_FILE = '.powerpages-template-cache.json';const CACHE_MARKER_VERSION = 1;@@ -189,6 +190,33 @@ function isNonEmptyString(value) {return typeof value === 'string' && value.trim().length > 0;}+function validateSolutionSettings(solutions, templateId) {+ if (solutions === undefined) return null;+ if (!Array.isArray(solutions)) return `template ${templateId} solutions must be an array`;+ const names = new Set();+ for (const [index, solution] of solutions.entries()) {+ if (!solution || typeof solution !== 'object' || Array.isArray(solution)) {+ return `template ${templateId} solution at index ${index} is not an object`;+ }+ const keys = Object.keys(solution);+ if (keys.some(key => !['uniqueName', 'publishChanges'].includes(key))) {+ return `template ${templateId} solution ${solution.uniqueName || index} has unsupported fields`;+ }+ if (!isNonEmptyString(solution.uniqueName) || !IDENTIFIER_PATTERN.test(solution.uniqueName)) {+ return `template ${templateId} solution ${index} uniqueName must be a Dataverse identifier`;+ }+ if (typeof solution.publishChanges !== 'boolean') {+ return `template ${templateId} solution ${solution.uniqueName} publishChanges must be boolean`;+ }+ const normalizedName = solution.uniqueName.toLowerCase();+ if (names.has(normalizedName)) {+ return `template ${templateId} has duplicate solution uniqueName: ${solution.uniqueName}`;+ }+ names.add(normalizedName);+ }+ return null;+}+function isNestedFamilyTemplate(template) {return template && typeof template.variants === 'object' && template.variants && !Array.isArray(template.variants);}@@ -211,6 +239,9 @@ function validateCatalogShape(catalog) {// "keywords": ["311", "citizen-services"],// "audience": ["makers", "developers"],// "requiredDataverseLanguages": [1033],+ // "solutions": [+ // { "uniqueName": "SupplierPortal", "publishChanges": true }+ // ],// "previewImages": ["spa/311-portal/previews/home.png"],// "seedDataPath": "spa/311-portal/seed/data.json",// "author": "Microsoft" }@@ -255,6 +286,8 @@ function validateCatalogShape(catalog) {if (!Array.isArray(template.previewImages)) {return `template ${template.id} previewImages must be an array`;}+ const solutionSettingsError = validateSolutionSettings(template.solutions, template.id);+ if (solutionSettingsError) return solutionSettingsError;if (isNestedFamilyTemplate(template)) {const seenFrameworks = new Set();const variantEntries = Object.entries(template.variants);@@ -268,6 +301,9 @@ function validateCatalogShape(catalog) {if (variant.solutionPath !== undefined || variant.websiteCodePath !== undefined) {return `template ${template.id} variant ${framework} must not define derivable solutionPath or websiteCodePath`;}+ if (variant.solutions !== undefined) {+ return `template ${template.id} solution settings must be defined at the family level`;+ }if (variant.previewImages !== undefined && !Array.isArray(variant.previewImages)) {return `template ${template.id} variant ${framework} previewImages must be an array`;}@@ -350,6 +386,7 @@ function normalizeCatalogFamilies(catalog = {}) {requiredDataverseLanguages: template.requiredDataverseLanguages || [],previewImages: template.previewImages || [],...(template.seedDataPath ? { seedDataPath: template.seedDataPath } : {}),+ ...(template.solutions?.length ? { solutions: template.solutions } : {}),author: template.author,variants: [{familyId: template.id,@@ -364,6 +401,7 @@ function normalizeCatalogFamilies(catalog = {}) {requiredDataverseLanguages: template.requiredDataverseLanguages || [],previewImages: template.previewImages || [],...(template.seedDataPath ? { seedDataPath: template.seedDataPath } : {}),+ ...(template.solutions?.length ? { solutions: template.solutions } : {}),author: template.author,}],};@@ -378,6 +416,7 @@ function normalizeCatalogFamilies(catalog = {}) {requiredDataverseLanguages: template.requiredDataverseLanguages || [],previewImages: template.previewImages || [],...(template.seedDataPath ? { seedDataPath: template.seedDataPath } : {}),+ ...(template.solutions?.length ? { solutions: template.solutions } : {}),author: template.author,variants: Object.entries(template.variants).map(([framework, variant]) => {const variantKey = framework.toLowerCase();@@ -394,6 +433,7 @@ function normalizeCatalogFamilies(catalog = {}) {requiredDataverseLanguages: variant.requiredDataverseLanguages || template.requiredDataverseLanguages || [],previewImages: Array.isArray(variant.previewImages) ? variant.previewImages : (template.previewImages || []),...(variant.seedDataPath || template.seedDataPath ? { seedDataPath: variant.seedDataPath || template.seedDataPath } : {}),+ ...(template.solutions?.length ? { solutions: template.solutions } : {}),author: template.author,};}),@@ -981,6 +1021,23 @@ function inspectTemplateSolutions(localSolutionsPath, kind, deps = {}) {return { ok: true, solutions };}+function applySolutionSettings(solutions, solutionSettings = []) {+ const settingsByName = new Map(solutionSettings.map(solution => [+ solution.uniqueName,+ solution,+ ]));+ const discoveredNames = new Set(solutions.map(solution => solution.uniqueName));+ for (const setting of solutionSettings) {+ if (!discoveredNames.has(setting.uniqueName)) {+ throw new Error(`Template manifest declares unknown solution: ${setting.uniqueName}`);+ }+ }+ return solutions.map(solution => ({+ ...solution,+ publishChanges: settingsByName.get(solution.uniqueName)?.publishChanges || false,+ }));+}+function inspectTemplateVariantDirectory(localVariantPath, kind, deps = {}) {const websiteCodePath = path.join(localVariantPath, 'website-code');const websiteCodeError = validateWebsiteCodeDirectory(websiteCodePath, { kind }, deps);@@ -997,7 +1054,13 @@ function validateTemplateVariantDirectory(localVariantPath, kind, deps = {}) {}function downloadTemplateVariant(options = {}, deps = {}) {- const { catalogPath = DEFAULT_CATALOG_PATH, kind, templateId, variant } = options;+ const {+ catalogPath = DEFAULT_CATALOG_PATH,+ kind,+ templateId,+ variant,+ solutionSettings = [],+ } = options;try {const familyRoot = templateFamilyRoot({ catalogPath, kind, templateId });const variantRoot = templateVariantRoot({ catalogPath, kind, templateId, variant });@@ -1023,7 +1086,7 @@ function downloadTemplateVariant(options = {}, deps = {}) {ok: true,variantPath: variantResult.localPath,websiteCodePath: inspectedVariant.websiteCodePath,- solutions: inspectedSolutions.solutions,+ solutions: applySolutionSettings(inspectedSolutions.solutions, solutionSettings),cached: variantResult.cached && solutionsResult.cached,};} catch (err) {@@ -1120,6 +1183,7 @@ module.exports = {templateFamilyRoot,templateVariantRoot,inspectTemplateSolutions,+ applySolutionSettings,inspectTemplateVariantDirectory,validateTemplateVariantDirectory,validateCatalogShape,diff --git a/plugins/power-pages/scripts/tests/apply-seed-data.test.js b/plugins/power-pages/scripts/tests/apply-seed-data.test.jsindex 76026511e..0bcf9ed56 100644--- a/plugins/power-pages/scripts/tests/apply-seed-data.test.js+++ b/plugins/power-pages/scripts/tests/apply-seed-data.test.js@@ -3,7 +3,7 @@const test = require('node:test');const assert = require('node:assert/strict');const fs = require('fs');-const os = require('os');+const { randomUUID } = require('crypto');const path = require('path');const {@@ -14,11 +14,598 @@ const {createTokenProvider,validateSeedLookupContract,validateAttachmentFile,+ splitReservedFiles,+ planSeedData,} = require('../lib/apply-seed-data');const { parseArgs, run } = require('../apply-seed-data');function tempDir() {- return fs.mkdtempSync(path.join(os.tmpdir(), 'apply-seed-data-test-'));+ const dir = path.resolve(`.seed-test-${randomUUID()}`);+ fs.mkdirSync(dir);+ return dir;+}++const TEST_ENV = 'https://contoso.crm.dynamics.com';+const RECORD_ID = '11111111-1111-1111-1111-111111111111';++function seedFixture(t, data, attachment = '%PDF-1.4\nsynthetic fixture\n') {+ const seedDir = tempDir();+ t.after(() => fs.rmSync(seedDir, { recursive: true, force: true }));+ fs.mkdirSync(path.join(seedDir, 'files'));+ fs.writeFileSync(path.join(seedDir, 'files', 'stored.pdf'), attachment);+ const seedFile = path.join(seedDir, 'data.json');+ fs.writeFileSync(seedFile, JSON.stringify(data));+ return { seedDir, seedFile, envUrl: TEST_ENV };+}++function attachmentSeed() {+ return {+ entitySetName: 'cr123_attachments',+ primaryKey: 'cr123_attachmentid',+ records: [{+ cr123_attachmentid: RECORD_ID,+ cr123_name: 'Business title',+ cr123_file: '22222222-2222-2222-2222-222222222222',+ cr123_file_name: 'Reviewed invoice.pdf',+ __files: { cr123_file: 'files/stored.pdf' },+ statecode: 0,+ statuscode: 1,+ }],+ };+}++for (const shape of ['flat __files', 'export fileExports']) {+ test(`applySeedData creates and uploads original ${shape} without generated file properties`, async (t) => {+ const flat = attachmentSeed();+ const data = shape === 'flat __files' ? flat : {+ tables: { attachments: {+ logicalName: 'cr123_attachment',+ entitySet: flat.entitySetName,+ idColumn: flat.primaryKey,+ records: flat.records.map(({ __files, ...record }) => record),+ } },+ fileExports: [{ attachmentId: RECORD_ID, fileColumn: 'cr123_file', path: 'files/stored.pdf' }],+ };+ const original = JSON.stringify(data);+ const args = seedFixture(t, data);+ const requests = [];+ const result = await applySeedData(args, {+ token: 'test-token',+ randomBlockId: () => 'block-1',+ makeRequest: async (request) => {+ const body = JSON.parse(request.body);+ requests.push({ ...request, body });+ if (request.url.endsWith('/cr123_attachments') &&+ ('cr123_file' in body || 'cr123_file_name' in body)) {+ return { statusCode: 400, body: 'File and derived name cannot be set on create' };+ }+ if (request.url.endsWith('/InitializeFileBlocksUpload')) {+ return { statusCode: 200, body: '{"FileContinuationToken":"private-continuation"}' };+ }+ return { statusCode: 204 };+ },+ });+ assert.deepEqual(result, { ok: true, inserted: 1, failed: 0, skipped: 0, errors: [] });+ assert.deepEqual(requests.map((r) => r.method), ['POST', 'PATCH', 'POST', 'POST', 'POST']);+ assert.deepEqual(requests[0].body, { cr123_attachmentid: RECORD_ID, cr123_name: 'Business title' });+ assert.deepEqual(requests[1].body, { statecode: 0, statuscode: 1 });+ assert.equal(requests[2].body.FileName, 'Reviewed invoice.pdf');+ assert.equal(requests[2].body.Target.cr123_attachmentid, RECORD_ID);+ assert.equal(requests[3].body.BlockData, Buffer.from('%PDF-1.4\nsynthetic fixture\n').toString('base64'));+ assert.equal(requests[4].body.FileName, 'Reviewed invoice.pdf');+ assert.equal(JSON.stringify(data), original);+ });+}++test('splitReservedFiles preserves source objects and unrelated business name fields', () => {+ const record = attachmentSeed().records[0];+ const before = JSON.stringify(record);+ const { recordBody, files } = splitReservedFiles(record);+ assert.equal(recordBody.cr123_file, undefined);+ assert.equal(recordBody.cr123_file_name, undefined);+ assert.equal(recordBody.cr123_name, 'Business title');+ assert.deepEqual(files, { cr123_file: 'files/stored.pdf' });+ assert.equal(JSON.stringify(record), before);+});++const CURRENCY_ID = '33333333-3333-3333-3333-333333333333';+const CURRENCY_NAV = 'cr123_InvoiceCurrency';++function financialSeed() {+ return {+ tables: {+ contacts: { logicalName: 'contact', entitySet: 'contacts', idColumn: 'contactid',+ records: [{ contactid: RECORD_ID, firstname: 'Unaffected', creditdescription: 'Not Money' }] },+ invoices: { logicalName: 'cr123_invoice', entitySet: 'cr123_invoices', idColumn: 'cr123_invoiceid',+ records: [{+ cr123_invoiceid: '22222222-2222-2222-2222-222222222222',+ cr123_total: 125.25,+ _transactioncurrencyid_value: '44444444-4444-4444-4444-444444444444',+ '_transactioncurrencyid_value@Microsoft.Dynamics.CRM.associatednavigationproperty': CURRENCY_NAV,+ }, { cr123_name: 'No monetary values' }] },+ },+ };+}++function currencyRequests(requests, override = () => null) {+ return async (req) => {+ requests.push(req);+ const custom = override(req);+ if (custom) return custom;+ if (req.method === 'POST' || req.method === 'PATCH') return { statusCode: 204 };+ let value;+ if (req.url.includes('EntityDefinitions?')) {+ const invoice = req.url.includes('cr123_invoices');+ value = [{ EntitySetName: invoice ? 'cr123_invoices' : 'contacts',+ LogicalName: invoice ? 'cr123_invoice' : 'contact',+ PrimaryIdAttribute: invoice ? 'cr123_invoiceid' : 'contactid' }];+ } else if (req.url.includes('MoneyAttributeMetadata')) {+ value = req.url.includes("'cr123_invoice'")+ ? [{ LogicalName: 'cr123_total', IsValidForCreate: true }] : [];+ } else if (req.url.includes('ManyToOneRelationships')) {+ value = [{+ ReferencedEntity: 'transactioncurrency',+ ReferencingEntity: 'cr123_invoice',+ ReferencingAttribute: 'transactioncurrencyid',+ ReferencingEntityNavigationPropertyName: CURRENCY_NAV,+ }];+ } else if (req.url.includes('transactioncurrencies?')) {+ value = [{ transactioncurrencyid: CURRENCY_ID, isocurrencycode: 'SGD',+ currencyname: 'Singapore Dollar', statecode: 0 }];+ } else {+ throw new Error(`unexpected metadata request: ${req.url}`);+ }+ return { statusCode: 200, body: JSON.stringify({ value }) };+ };+}++ for (const filename of ['', ' ', null, 7, {}, '../invoice.pdf', 'dir/invoice.pdf',+ 'dir\\invoice.pdf', 'C:\\invoice.pdf', 'invoice.pdf\n', 'invoice.pdf\u0000', '..']) {+ test(`upload filename ${JSON.stringify(filename)} is rejected before record creation`, async (t) => {+ const seed = attachmentSeed();+ seed.records[0].cr123_file_name = filename;+ let calls = 0;+ const result = await applySeedData(seedFixture(t, seed), {+ token: 'test-token', makeRequest: async () => { calls++; return { statusCode: 204 }; },+ });+ assert.equal(result.ok, false);+ assert.equal(result.failed, 1);+ assert.equal(result.inserted, 0);+ assert.equal(calls, 0);+ assert.match(result.errors[0].message, /upload filename/);+ });+ }++ test('absent upload companion retains attachment basename and unrelated name properties', async (t) => {+ const seed = attachmentSeed();+ delete seed.records[0].cr123_file_name;+ seed.records[0].cr123_business_name = 'Unrelated';+ const requests = [];+ const result = await applySeedData(seedFixture(t, seed), {+ token: 'test-token', randomBlockId: () => 'block-1',+ makeRequest: async (req) => {+ requests.push(req);+ return req.url.endsWith('/InitializeFileBlocksUpload')+ ? { statusCode: 200, body: '{"FileContinuationToken":"continuation"}' } : { statusCode: 204 };+ },+ });+ assert.equal(result.ok, true);+ assert.equal(JSON.parse(requests[0].body).cr123_business_name, 'Unrelated');+ assert.equal(JSON.parse(requests[2].body).FileName, 'stored.pdf');+ assert.equal(JSON.parse(requests.at(-1).body).FileName, 'stored.pdf');+ });++ for (const scenario of [+ 'state http', 'state transport', 'state throw',+ 'init http', 'init transport', 'init throw', 'init invalid JSON', 'init no token', 'init invalid token',+ 'init invalid status', 'block http', 'block transport', 'block throw', 'block invalid status',+ 'commit http', 'commit transport', 'commit throw', 'commit invalid status',+ 'read error', 'short read', 'empty file',+ ]) {+ test(`state/file ${scenario} fails truthfully after creation and continues later records`, async (t) => {+ const seed = attachmentSeed();+ seed.records.push({ cr123_name: 'Later record' });+ const args = seedFixture(t, seed, scenario === 'empty file' ? '' : '%PDF-1.4\nfixture');+ const requests = [];+ const fileFs = scenario === 'read error' || scenario === 'short read' ? {+ ...fs,+ readSync: (...args) => {+ if (args[3] === 200) return fs.readSync(...args);+ if (scenario === 'read error') throw new Error('file read rejected');+ return 0;+ },+ } : fs;+ const result = await applySeedData(args, {+ token: 'private-bearer', fs: fileFs, randomBlockId: () => 'block-1',+ makeRequest: async (req) => {+ requests.push(req);+ const operation = req.method === 'PATCH' ? 'state' :+ req.url.endsWith('/InitializeFileBlocksUpload') ? 'init' :+ req.url.endsWith('/UploadBlock') ? 'block' :+ req.url.endsWith('/CommitFileBlocksUpload') ? 'commit' : 'record';+ if (scenario.startsWith(`${operation} `)) {+ if (scenario.endsWith('transport')) return { error: 'transport rejected' };+ if (scenario.endsWith('throw')) throw new Error('request rejected private-bearer private-continuation');+ if (scenario.endsWith('http')) return { statusCode: 400, body: 'operation rejected' };+ if (scenario.endsWith('invalid status')) return {};+ if (scenario.endsWith('invalid JSON')) return { statusCode: 200, body: 'not JSON' };+ if (scenario.endsWith('no token')) return { statusCode: 200, body: '{}' };+ if (scenario.endsWith('invalid token')) return { statusCode: 200, body: '{"FileContinuationToken":7}' };+ }+ return operation === 'init' ? { statusCode: 200, body: '{"FileContinuationToken":"private-continuation"}' }+ : { statusCode: 204 };+ },+ });+ assert.equal(result.ok, false);+ assert.equal(result.inserted, 2);+ assert.equal(result.failed, 1);+ assert.equal(result.skipped, 0);+ assert.equal(result.errors.length, 1);+ assert.equal(JSON.parse(requests.at(-1).body).cr123_name, 'Later record');+ assert.ok(!JSON.stringify(result).includes('private-bearer'));+ if (scenario.startsWith('block ') || scenario.startsWith('commit ')) {+ assert.ok(!JSON.stringify(result).includes('private-continuation'));+ }+ if (scenario.startsWith('state ')) assert.ok(!requests.some((r) => r.url.endsWith('/InitializeFileBlocksUpload')));+ if (scenario.startsWith('block ') || scenario === 'short read' || scenario === 'read error') {+ assert.ok(!requests.some((r) => r.url.endsWith('/CommitFileBlocksUpload')));+ }+ });+ }++ test('duplicates without failures remain successful and state PATCH behavior is preserved', async (t) => {+ const seed = attachmentSeed();+ delete seed.records[0].__files;+ delete seed.records[0].cr123_file;+ delete seed.records[0].cr123_file_name;+ const requests = [];+ const result = await applySeedData(seedFixture(t, seed), {+ token: 'test-token',+ makeRequest: async (req) => {+ requests.push(req);+ return req.method === 'POST' ? { statusCode: 409, body: 'Cannot insert duplicate key' } : { statusCode: 204 };+ },+ });+ assert.deepEqual(result, { ok: true, inserted: 0, skipped: 1, failed: 0, errors: [] });+ assert.equal(requests[1].method, 'PATCH');+ assert.equal(requests[1].headers['If-Match'], '*');+ });++ for (const scenario of ['invalid record', 'invalid file', 'invalid source JSON', 'invalid query JSON', 'auth']) {+ test(`plan rejects ${scenario} without writes`, async (t) => {+ const data = scenario === 'invalid record' ? { entitySetName: 'contacts', records: [null] }+ : scenario === 'invalid file' ? attachmentSeed() : financialSeed();+ if (scenario === 'invalid file') data.records[0].__files.cr123_file = '../outside.pdf';+ const args = seedFixture(t, data);+ if (scenario === 'invalid source JSON') fs.writeFileSync(args.seedFile, '{');+ const requests = [];+ const result = await planSeedData(args, {+ ...(scenario !== 'auth' ? { token: 'test-token' } : { getAuthToken: () => null }),+ makeRequest: currencyRequests(requests, () => scenario === 'invalid query JSON'+ ? { statusCode: 200, body: '{}' } : null),+ });+ assert.equal(result.ok, false);+ assert.equal(result.writes, 0);+ assert.ok(result.errors.length);+ assert.ok(requests.every((r) => !r.method || r.method === 'GET'));+ });+ }+test('explicit currency resolves metadata and active target before first write without changing amounts or nonfinancial rows', async (t) => {+ const args = seedFixture(t, financialSeed());+ const requests = [];+ const result = await applySeedData({ ...args, currencyCode: 'sgd' }, {+ token: 'test-token',+ makeRequest: currencyRequests(requests),+ });+ assert.equal(result.ok, true);+ const writes = requests.filter((r) => r.method === 'POST');+ const gets = requests.filter((r) => !r.method || r.method === 'GET');+ assert.ok(gets.length >= 6);+ assert.ok(requests.indexOf(writes[0]) > requests.indexOf(gets.at(-1)));+ assert.deepEqual(JSON.parse(writes[0].body), {+ contactid: RECORD_ID, firstname: 'Unaffected', creditdescription: 'Not Money',+ });+ assert.deepEqual(JSON.parse(writes[1].body), {+ cr123_invoiceid: '22222222-2222-2222-2222-222222222222', cr123_total: 125.25,+ [`${CURRENCY_NAV}@odata.bind`]: `/transactioncurrencies(${CURRENCY_ID})`,+ });+ assert.deepEqual(JSON.parse(writes[2].body), { cr123_name: 'No monetary values' });+});++test('planSeedData reports validated source counts, financial rows and active currencies with GETs only', async (t) => {+ const args = seedFixture(t, financialSeed());+ const requests = [];+ const result = await planSeedData(args, { token: 'test-token', makeRequest: currencyRequests(requests) });+ assert.equal(result.ok, true);+ assert.equal(result.writes, 0);+ assert.deepEqual(result.counts, { tables: 2, records: 3, files: 0 });+ assert.deepEqual(result.financialEntitySets, [{+ entitySetName: 'cr123_invoices', logicalName: 'cr123_invoice', recordCount: 1,+ moneyAttributes: ['cr123_total'],+ }]);+ assert.deepEqual(result.currencies, [{ code: 'SGD', name: 'Singapore Dollar', id: CURRENCY_ID }]);+ assert.equal(result.requiresCurrencySelection, true);+ assert.ok(requests.every((r) => !r.method || r.method === 'GET'));+ assert.ok(!JSON.stringify(result).includes('test-token'));+});++for (const references of [+ ['invalid'],+ [42],+ [`/accounts(${RECORD_ID})`, `/contacts(${CURRENCY_ID})`],+ [`/accounts(${RECORD_ID})`],+ [`/contacts(${RECORD_ID})`, null],+ [`/contacts/../accounts(${CURRENCY_ID})`],+]) {+ test(`collection bind preflight rejects ${JSON.stringify(references)} before any write`, async (t) => {+ const data = {+ tables: {+ contacts: { entitySet: 'contacts', idColumn: 'contactid', records: [{ contactid: RECORD_ID }] },+ accounts: { entitySet: 'accounts', idColumn: 'accountid', records: [{+ accountid: CURRENCY_ID, '[email protected]': references,+ }] },+ },+ };+ const args = seedFixture(t, data);+ let calls = 0;+ const result = await applySeedData(args, {+ token: 'test-token', makeRequest: async () => { calls++; return { statusCode: 204 }; },+ });+ assert.equal(result.ok, false);+ assert.equal(result.inserted, 0);+ assert.equal(calls, 0);+ assert.match(result.errors[0].message, /Lookup/);+ });+}++test('collection binds associate contacts on create unchanged, including valid external targets', async (t) => {+ const references = [`/accounts(${CURRENCY_ID})`, '/accounts(55555555-5555-5555-5555-555555555555)'];+ const args = seedFixture(t, {+ tables: {+ accounts: { entitySet: 'accounts', idColumn: 'accountid', records: [{ accountid: CURRENCY_ID }] },+ contacts: { entitySet: 'contacts', idColumn: 'contactid', records: [{+ contactid: RECORD_ID, '[email protected]': references,+ }] },+ },+ });+ const requests = [];+ const result = await applySeedData(args, {+ token: 'test-token',+ makeRequest: async (req) => { requests.push(req); return { statusCode: 204 }; },+ });+ assert.equal(result.ok, true);+ assert.equal(requests.length, 2);+ assert.deepEqual(JSON.parse(requests[1].body)['[email protected]'], references);+ assert.ok(requests[1].url.endsWith('/contacts'));+});++test('CLI parses plan and currency and reports missing flag values explicitly', async () => {+ assert.deepEqual(parseArgs(['--plan', '--seedDir', 'seed', '--envUrl', TEST_ENV, '--currencyCode', 'sgd']), {+ plan: true, seedDir: 'seed', envUrl: TEST_ENV, currencyCode: 'sgd',+ });+ const usage = ['--seedDir', 'seed', '--envUrl', TEST_ENV];+ for (const argv of [[...usage, '--currencyCode'], [...usage, '--currencyCode', '--plan']]) {+ const result = await run(argv);+ assert.equal(result.ok, false);+ assert.match(result.errors[0].message, /currencyCode.*value/i);+ }+});++ test('CLI plan is read-only and no financial payload means no currency query or selection', async (t) => {+ const args = seedFixture(t, { entitySetName: 'contacts', records: [{ firstname: 'No Money' }] });+ const requests = [];+ const result = await run(['--seedDir', args.seedDir, '--seedFile', args.seedFile,+ '--envUrl', TEST_ENV, '--plan'], { token: 'test-token', makeRequest: currencyRequests(requests) });+ assert.equal(result.ok, true);+ assert.equal(result.writes, 0);+ assert.equal(result.requiresCurrencySelection, false);+ assert.deepEqual(result.financialEntitySets, []);+ assert.deepEqual(result.currencies, []);+ assert.equal(requests.length, 2);+ assert.ok(requests.every((r) => !r.method || r.method === 'GET'));+ });++ test('currency default path performs no metadata queries and preserves explicit currency intent', async (t) => {+ const data = { entitySetName: 'cr123_invoices', records: [{+ cr123_total: 9, '[email protected]': `/transactioncurrencies(${CURRENCY_ID})`,+ }] };+ const requests = [];+ const result = await applySeedData(seedFixture(t, data), {+ token: 'test-token',+ makeRequest: async (req) => { requests.push(req); return { statusCode: 204 }; },+ });+ assert.equal(result.ok, true);+ assert.equal(requests.length, 1);+ assert.equal(requests[0].method, 'POST');+ assert.deepEqual(JSON.parse(requests[0].body), data.records[0]);+ });++ for (const code of ['', 'SG', 'SGDD', 'S9D', ' Sgd ', 'SGD', null]) {+ test(`invalid currency code ${JSON.stringify(code)} fails before auth or requests`, async (t) => {+ let calls = 0;+ const result = await applySeedData({ ...seedFixture(t, financialSeed()), currencyCode: code }, {+ getAuthToken: () => { calls++; throw new Error('must not authenticate'); },+ makeRequest: async () => { calls++; throw new Error('must not query'); },+ });+ assert.equal(result.ok, false);+ assert.equal(calls, 0);+ assert.match(result.errors[0].message, /three ASCII letters/);+ });+ }++ for (const scenario of [+ 'missing currency', 'duplicate currency', 'inactive currency', 'invalid currency id',+ 'invalid currency code', 'wrong currency code', 'missing Money metadata',+ 'unsupported Money metadata', 'missing navigation', 'ambiguous navigation', 'unsafe navigation',+ 'missing entity', 'wrong entity', 'unsafe logical name', 'wrong source logical name',+ 'metadata http', 'metadata transport', 'metadata throw', 'metadata invalid JSON',+ 'metadata missing value', 'currency http', 'currency invalid JSON',+ 'cross-origin nextLink', 'pagination cycle',+ ]) {+ test(`explicit currency fails before writes for ${scenario}`, async (t) => {+ const data = financialSeed();+ if (scenario === 'wrong source logical name') data.tables.invoices.logicalName = 'cr123_other';+ const requests = [];+ const override = (req) => {+ const metadata = req.url.includes('EntityDefinitions?') && req.url.includes('cr123_invoices');+ const money = req.url.includes('MoneyAttributeMetadata') && req.url.includes("'cr123_invoice'");+ const navigation = req.url.includes('ManyToOneRelationships');+ const currency = req.url.includes('transactioncurrencies?');+ const response = (value) => ({ statusCode: 200, body: JSON.stringify({ value }) });+ if (metadata) {+ if (scenario === 'missing entity') return response([]);+ if (scenario === 'wrong entity') return response([{ EntitySetName: 'wrong', LogicalName: 'invoice', PrimaryIdAttribute: 'invoiceid' }]);+ if (scenario === 'unsafe logical name') return response([{ EntitySetName: 'cr123_invoices', LogicalName: "'injected'", PrimaryIdAttribute: 'invoiceid' }]);+ if (scenario === 'metadata http') return { statusCode: 403, body: 'metadata denied' };+ if (scenario === 'metadata transport') return { error: 'metadata network error' };+ if (scenario === 'metadata throw') throw new Error('metadata request exploded');+ if (scenario === 'metadata invalid JSON') return { statusCode: 200, body: '{' };+ if (scenario === 'metadata missing value') return { statusCode: 200, body: '{}' };+ if (scenario === 'cross-origin nextLink') return { statusCode: 200, body: JSON.stringify({+ value: [], '@odata.nextLink': 'https://other.crm.dynamics.com/api/data/v9.2/EntityDefinitions',+ }) };+ if (scenario === 'pagination cycle') return { statusCode: 200, body: JSON.stringify({+ value: [], '@odata.nextLink': req.url,+ }) };+ }+ if (money) {+ if (scenario === 'missing Money metadata') return { statusCode: 200, body: '{}' };+ if (scenario === 'unsupported Money metadata') return response([{ LogicalName: 'cr123_total', IsValidForCreate: false }]);+ }+ if (navigation) {+ if (scenario === 'missing navigation') return response([]);+ if (scenario === 'ambiguous navigation' || scenario === 'unsafe navigation') {+ const row = { ReferencedEntity: 'transactioncurrency', ReferencingEntity: 'cr123_invoice',+ ReferencingAttribute: 'transactioncurrencyid',+ ReferencingEntityNavigationPropertyName: scenario === 'unsafe navigation' ? '../invalid' : CURRENCY_NAV };+ return response(scenario === 'ambiguous navigation' ? [row, row] : [row]);+ }+ }+ if (currency) {+ if (scenario === 'missing currency') return response([]);+ if (scenario === 'currency http') return { statusCode: 401, body: 'currency denied' };+ if (scenario === 'currency invalid JSON') return { statusCode: 200, body: 'not JSON' };+ const row = { transactioncurrencyid: CURRENCY_ID, isocurrencycode: 'SGD',+ currencyname: 'Singapore Dollar', statecode: 0 };+ if (scenario === 'duplicate currency') return response([row, { ...row, transactioncurrencyid: RECORD_ID }]);+ if (scenario === 'inactive currency') return response([{ ...row, statecode: 1 }]);+ if (scenario === 'invalid currency id') return response([{ ...row, transactioncurrencyid: 'not-a-guid' }]);+ if (scenario === 'invalid currency code') return response([{ ...row, isocurrencycode: '' }]);+ if (scenario === 'wrong currency code') return response([{ ...row, isocurrencycode: 'USD' }]);+ }+ return null;+ };+ const result = await applySeedData({ ...seedFixture(t, data), currencyCode: 'SGD' }, {+ token: 'test-token', makeRequest: currencyRequests(requests, override),+ });+ assert.equal(result.ok, false);+ assert.equal(result.inserted, 0);+ assert.equal(result.failed, 1);+ assert.ok(result.errors[0].message);+ assert.ok(requests.every((r) => !r.method || r.method === 'GET'));+ assert.ok(requests.every((r) => new URL(r.url).origin === TEST_ENV));+ });+ }++ for (const binding of [+ '/transactioncurrencies(55555555-5555-5555-5555-555555555555)',+ [`/transactioncurrencies(${CURRENCY_ID})`],+ `/contacts(${CURRENCY_ID})`,+ ]) {+ test(`explicit conflicting currency ${JSON.stringify(binding)} stops unrelated earlier writes`, async (t) => {+ const data = financialSeed();+ data.tables.invoices.records[0][`${CURRENCY_NAV}@odata.bind`] = binding;+ const requests = [];+ const result = await applySeedData({ ...seedFixture(t, data), currencyCode: 'SGD' }, {+ token: 'test-token', makeRequest: currencyRequests(requests),+ });+ assert.equal(result.ok, false);+ assert.equal(result.inserted, 0);+ assert.match(result.errors[0].message, /currency binding disagrees/);+ assert.ok(requests.every((r) => !r.method || r.method === 'GET'));+ });+ }++ test('explicit matching currency binding is preserved and source lookup/exchange rate fields are not forwarded', async (t) => {+ const data = { entitySetName: 'cr123_invoices', records: [{+ cr123_total: 20, _transactioncurrencyid_value: RECORD_ID, exchangerate: 1.23,+ [`${CURRENCY_NAV}@odata.bind`]: `/transactioncurrencies(${CURRENCY_ID})`,+ }] };+ const requests = [];+ const result = await applySeedData({ ...seedFixture(t, data), currencyCode: 'SGD' }, {+ token: 'test-token', makeRequest: currencyRequests(requests),+ });+ assert.equal(result.ok, true);+ assert.deepEqual(JSON.parse(requests.at(-1).body), {+ cr123_total: 20, [`${CURRENCY_NAV}@odata.bind`]: `/transactioncurrencies(${CURRENCY_ID})`,+ });+ });++ for (const invalid of ['missing active currencies', 'duplicate active currencies']) {+ test(`plan fails explicitly with no writes on ${invalid}`, async (t) => {+ const requests = [];+ const result = await planSeedData(seedFixture(t, financialSeed()), {+ token: 'test-token', makeRequest: currencyRequests(requests, (req) => {+ if (!req.url.includes('transactioncurrencies?')) return null;+ const row = { transactioncurrencyid: CURRENCY_ID, isocurrencycode: 'SGD',+ currencyname: 'Singapore Dollar', statecode: 0 };+ return { statusCode: 200, body: JSON.stringify({+ value: invalid === 'missing active currencies' ? [] : [row, { ...row, transactioncurrencyid: RECORD_ID }],+ }) };+ }),+ });+ assert.equal(result.ok, false);+ assert.equal(result.writes, 0);+ assert.match(result.errors[0].message, /active|ambiguous|duplicate/i);+ assert.ok(requests.every((r) => !r.method || r.method === 'GET'));+ });+ }+for (const fileExports of [+ [null],+ [{ fileColumn: 'cr123_file', path: 'files/stored.pdf' }],+ [{ attachmentId: 'missing', fileColumn: 'cr123_file', path: 'files/stored.pdf' }],+ [{ attachmentId: CURRENCY_ID, fileColumn: 'cr123_file', path: 'files/stored.pdf' }],+ [{ attachmentId: RECORD_ID, fileColumn: 'cr123_file' }],+ 'not-an-array',+]) {+ test(`invalid exported upload ${JSON.stringify(fileExports)} fails instead of silently omitting files`, async (t) => {+ const args = seedFixture(t, {+ tables: { attachments: { entitySet: 'cr123_attachments', idColumn: 'cr123_attachmentid',+ records: [{ cr123_attachmentid: RECORD_ID }] } }, fileExports,+ });+ let calls = 0;+ const result = await applySeedData(args, {+ token: 'test-token', makeRequest: async () => { calls++; return { statusCode: 204 }; },+ });+ assert.equal(result.ok, false);+ assert.equal(calls, 0);+ assert.match(result.errors[0].message, /fileExports|upload|attachment/i);+ });+}++for (const failure of ['http', 'transport', 'throw', 'invalid response']) {+ test(`applySeedData reports ok false for ${failure} and continues other rows`, async (t) => {+ const args = seedFixture(t, {+ entitySetName: 'contacts',+ records: [{ firstname: 'Failed' }, { firstname: 'Succeeded' }],+ });+ let calls = 0;+ const result = await applySeedData(args, {+ token: 'test-token',+ makeRequest: async () => {+ if (++calls === 2) return { statusCode: 204 };+ if (failure === 'throw') throw new Error('request exploded');+ if (failure === 'transport') return { error: 'network unavailable' };+ if (failure === 'invalid response') return {};+ return { statusCode: 400, body: 'create rejected' };+ },+ });+ assert.equal(result.ok, false);+ assert.equal(result.inserted, 1);+ assert.equal(result.failed, 1);+ assert.equal(result.errors.length, 1);+ assert.match(result.errors[0].message, /request exploded|network unavailable|create rejected|invalid|HTTP/i);+ });}function withSeedStats(fsImpl, seedDir) {@@ -1001,6 +1588,174 @@ test('createTokenProvider refreshes after the configured request cadence', () =>assert.equal(provider(), 'fresh-2');});+for (const statusCode of ['204', 200.5, null, undefined]) {+ test(`invalid create status ${statusCode} cannot produce success`, async (t) => {+ const result = await applySeedData(seedFixture(t, { entitySetName: 'contacts', records: [{}] }), {+ token: 'test-token', makeRequest: async () => ({ statusCode }),+ });+ assert.equal(result.ok, false);+ assert.equal(result.inserted, 0);+ assert.equal(result.failed, 1);+ });+}++test('missing seed source is an explicit plan/apply failure, never a successful empty fallback', async () => {+ let calls = 0;+ const args = { seedDir: path.resolve('nonexistent-seed-fixture'), envUrl: TEST_ENV };+ const deps = { token: 'test-token', makeRequest: async () => { calls++; return { statusCode: 204 }; } };+ const plan = await planSeedData(args, deps);+ const applied = await applySeedData(args, deps);+ assert.equal(plan.ok, false);+ assert.equal(plan.writes, 0);+ assert.equal(applied.ok, false);+ assert.match(plan.errors[0].message, /seed.*JSON|seed.*source/i);+ assert.match(applied.errors[0].message, /seed.*JSON|seed.*source/i);+ assert.equal(calls, 0);+});++test('empty refreshed/custom tokens fail before authenticated metadata requests', async (t) => {+ for (const entryPoint of [applySeedData, planSeedData]) {+ let calls = 0;+ const result = await entryPoint({ ...seedFixture(t, financialSeed()), currencyCode: 'SGD' }, {+ token: 'initial-token', tokenProvider: () => null,+ makeRequest: async () => { calls++; return { statusCode: 200, body: '{"value":[]}' }; },+ });+ assert.equal(result.ok, false);+ assert.equal(calls, 0);+ assert.match(result.errors[0].message, /token unavailable/);+ }+});++test('same-origin metadata pagination lists all currencies and returns no continuation or auth secrets', async (t) => {+ const requests = [];+ const result = await planSeedData(seedFixture(t, financialSeed()), {+ token: 'private-auth',+ makeRequest: currencyRequests(requests, (req) => {+ if (!req.url.includes('transactioncurrencies?')) return null;+ if (req.url.includes('skiptoken')) {+ return { statusCode: 200, body: JSON.stringify({ value: [{+ transactioncurrencyid: RECORD_ID, currencyname: 'US Dollar', isocurrencycode: 'USD', statecode: 0,+ }] }) };+ }+ return { statusCode: 200, body: JSON.stringify({+ value: [{ transactioncurrencyid: CURRENCY_ID, currencyname: 'Singapore Dollar', isocurrencycode: 'SGD', statecode: 0 }],+ '@odata.nextLink': `${TEST_ENV}/api/data/v9.2/transactioncurrencies?$skiptoken=private-page-token`,+ }) };+ }),+ });+ assert.equal(result.ok, true);+ assert.deepEqual(result.currencies.map((c) => c.code), ['SGD', 'USD']);+ assert.equal(result.writes, 0);+ assert.ok(!JSON.stringify(result).includes('private-'));+});++test('plan validates and counts original exported attachments without opening upload sessions', async (t) => {+ const flat = attachmentSeed();+ const args = seedFixture(t, {+ tables: { attachments: { entitySet: 'cr123_attachments', idColumn: 'cr123_attachmentid',+ records: flat.records.map(({ __files, ...record }) => record) } },+ fileExports: [{ attachmentId: RECORD_ID, fileColumn: 'cr123_file', path: 'files/stored.pdf' }],+ });+ const requests = [];+ const result = await planSeedData(args, {+ token: 'test-token',+ makeRequest: async (req) => {+ requests.push(req);+ const value = req.url.includes('EntityDefinitions?') ? [{+ EntitySetName: 'cr123_attachments', LogicalName: 'cr123_attachment', PrimaryIdAttribute: 'cr123_attachmentid',+ }] : [];+ return { statusCode: 200, body: JSON.stringify({ value }) };+ },+ });+ assert.equal(result.ok, true);+ assert.deepEqual(result.counts, { tables: 1, records: 1, files: 1 });+ assert.equal(result.requiresCurrencySelection, false);+ assert.ok(requests.every((r) => !r.method || r.method === 'GET'));+});++test('explicit currency never creates source currencies', async (t) => {+ const args = seedFixture(t, { entitySetName: 'transactioncurrencies', records: [{+ transactioncurrencyid: RECORD_ID, currencyname: 'Source currency', isocurrencycode: 'SGD',+ }] });+ let calls = 0;+ const result = await applySeedData({ ...args, currencyCode: 'SGD' }, {+ token: 'test-token', makeRequest: async () => { calls++; return { statusCode: 204 }; },+ });+ assert.equal(result.ok, false);+ assert.equal(calls, 0);+ assert.match(result.errors[0].message, /existing target currency/);+});++test('currency bind with a wrong navigation collection fails before writes', async (t) => {+ const data = financialSeed();+ data.tables.invoices.records[0]['[email protected]'] = [`/transactioncurrencies(${CURRENCY_ID})`];+ const requests = [];+ const result = await applySeedData({ ...seedFixture(t, data), currencyCode: 'SGD' }, {+ token: 'test-token', makeRequest: currencyRequests(requests),+ });+ assert.equal(result.ok, false);+ assert.match(result.errors[0].message, /currency binding disagrees/);+ assert.ok(requests.every((r) => !r.method || r.method === 'GET'));+});++test('export normalization rejects malformed record objects rather than posting an empty replacement', async (t) => {+ let calls = 0;+ const result = await applySeedData(seedFixture(t, {+ tables: { contacts: { entitySet: 'contacts', idColumn: 'contactid', records: [null] } },+ }), { token: 'test-token', makeRequest: async () => { calls++; return { statusCode: 204 }; } });+ assert.equal(result.ok, false);+ assert.equal(calls, 0);+ assert.match(result.errors[0].message, /record must be an object/);+});++for (const filename of ['invoice|bad.pdf', 'invoice?.pdf', 'invoice%2fsecret.pdf', 'invoice%5csecret.pdf', 'invoice%00.pdf']) {+ test(`portable upload filename rejects ${filename}`, async (t) => {+ const data = attachmentSeed();+ data.records[0].cr123_file_name = filename;+ let calls = 0;+ const result = await applySeedData(seedFixture(t, data), {+ token: 'test-token', makeRequest: async () => { calls++; return { statusCode: 204 }; },+ });+ assert.equal(result.ok, false);+ assert.equal(calls, 0);+ assert.match(result.errors[0].message, /upload filename/);+ });+}++test('invalid metadata JSON cannot leak an echoed bearer token through parser diagnostics', async (t) => {+ const requests = [];+ const result = await planSeedData(seedFixture(t, financialSeed()), {+ token: 'private-bearer-token',+ makeRequest: currencyRequests(requests, () => ({ statusCode: 200, body: 'private-bearer-token invalid JSON' })),+ });+ assert.equal(result.ok, false);+ assert.match(result.errors[0].message, /invalid JSON/i);+ assert.ok(!JSON.stringify(result).includes('private-'));+});++test('file action invalid JSON reports no continuation secret from parser excerpts', async (t) => {+ const result = await applySeedData(seedFixture(t, attachmentSeed()), {+ token: 'test-token', makeRequest: async (req) => req.url.endsWith('/InitializeFileBlocksUpload')+ ? { statusCode: 200, body: 'private-continuation invalid JSON' } : { statusCode: 204 },+ });+ assert.equal(result.ok, false);+ assert.match(result.errors[0].message, /invalid JSON/i);+ assert.ok(!JSON.stringify(result).includes('private-'));+});++test('actual CLI plan argument failures emit parseable no-write JSON and remain best effort', () => {+ const { spawnSync } = require('child_process');+ const execution = spawnSync(process.execPath, [+ path.resolve(__dirname, '../apply-seed-data.js'), '--plan', '--currencyCode',+ ], { encoding: 'utf8', env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: '1' }, shell: false });+ assert.equal(execution.status, 0);+ assert.equal(execution.stderr, '');+ const result = JSON.parse(execution.stdout);+ assert.equal(result.ok, false);+ assert.equal(result.writes, 0);+ assert.match(result.errors[0].message, /currencyCode.*value/);+});+test('apply-seed-data CLI parser and runner return best-effort summaries', async () => {assert.deepEqual(parseArgs(['--seedDir', '/tmp/seed', '--seedFile', '/tmp/seed/data.json', '--envUrl', 'https://org.crm.dynamics.com']), {seedDir: '/tmp/seed',diff --git a/plugins/power-pages/scripts/tests/create-site-template-telemetry.test.js b/plugins/power-pages/scripts/tests/create-site-template-telemetry.test.jsindex 8e5c662c7..56b06976d 100644--- a/plugins/power-pages/scripts/tests/create-site-template-telemetry.test.js+++ b/plugins/power-pages/scripts/tests/create-site-template-telemetry.test.js@@ -76,7 +76,7 @@ test('buildTemplateOutcomeEvent emits import result details separately from tempframework: 'react',audience: 'internal',outcome: 'failure',- errorClass: 'ImportSolutionAsync',+ errorClass: 'PacSolutionImport',errorDescription: 'https://example.crm.dynamics.com/private/path',correlationId: 'corr',}, {@@ -86,7 +86,7 @@ test('buildTemplateOutcomeEvent emits import result details separately from temp});assert.equal(failure.data.eventName, 'template_import_failure');assert.equal(failure.data.outcome, 'failure');- assert.equal(failure.data.errorClass, 'ImportSolutionAsync');+ assert.equal(failure.data.errorClass, 'PacSolutionImport');assert.equal('errorDescription' in failure.data, false);assert.equal(failure.data.severity, 'Error');});diff --git a/plugins/power-pages/scripts/tests/import-template-solution.test.js b/plugins/power-pages/scripts/tests/import-template-solution.test.jsnew file mode 100644index 000000000..04337ead3--- /dev/null+++ b/plugins/power-pages/scripts/tests/import-template-solution.test.js@@ -0,0 +1,150 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const {+ MAX_ASYNC_WAIT_MINUTES,+ PROCESS_TIMEOUT_MS,+ importTemplateSolution,+ parseArgs,+ run,+} = require('../import-template-solution');++function tempDir() {+ return fs.mkdtempSync(path.join(os.tmpdir(), 'import-template-solution-test-'));+}++function fakeSolutionZip() {+ const name = Buffer.from('solution.xml');+ const header = Buffer.alloc(30);+ header.writeUInt32LE(0x04034b50, 0);+ header.writeUInt16LE(name.length, 26);+ return Buffer.concat([header, name]);+}++function writeSolutionZip(t) {+ const root = tempDir();+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const zipPath = path.join(root, 'solution.zip');+ fs.writeFileSync(zipPath, fakeSolutionZip());+ return zipPath;+}++test('parseArgs reads explicit publish behavior', () => {+ assert.deepEqual(parseArgs([+ '--zipPath', '/tmp/solution.zip',+ '--envUrl', 'https://contoso.crm.dynamics.com',+ '--publishChanges', 'true',+ ]), {+ zipPath: '/tmp/solution.zip',+ envUrl: 'https://contoso.crm.dynamics.com',+ publishChanges: true,+ });+ assert.equal(parseArgs(['--publishChanges', 'invalid']).publishChanges, null);+});++test('flagged template solutions import with publish changes', (t) => {+ const zipPath = writeSolutionZip(t);+ const calls = [];+ const result = importTemplateSolution({+ zipPath,+ envUrl: 'https://contoso.crm.dynamics.com',+ publishChanges: true,+ }, {+ runPac(args, options) {+ calls.push([args, options]);+ return { status: 0, stdout: 'imported', stderr: '' };+ },+ });++ assert.deepEqual(result, { ok: true, imported: true, publishChanges: true });+ assert.deepEqual(calls[0][0], [+ 'solution', 'import',+ '--environment', 'https://contoso.crm.dynamics.com',+ '--path', path.resolve(zipPath),+ '--force-overwrite',+ '--activate-plugins',+ '--async',+ '--max-async-wait-time', String(MAX_ASYNC_WAIT_MINUTES),+ '--publish-changes',+ ]);+ assert.equal(calls[0][1], undefined);+});++test('unflagged template solutions omit publish changes', (t) => {+ const zipPath = writeSolutionZip(t);+ let args;+ const result = importTemplateSolution({+ zipPath,+ envUrl: 'https://contoso.crm.dynamics.com',+ publishChanges: false,+ }, {+ runPac(value) {+ args = value;+ return { status: 0, stdout: 'imported', stderr: '' };+ },+ });++ assert.equal(result.ok, true);+ assert.equal(result.publishChanges, false);+ assert.equal(args.includes('--publish-changes'), false);+});++test('default PAC runner receives a timeout longer than the CLI wait', (t) => {+ const zipPath = writeSolutionZip(t);+ let options;+ const result = importTemplateSolution({+ zipPath,+ envUrl: 'https://contoso.crm.dynamics.com',+ publishChanges: false,+ }, {+ runCommand(command, args, commandOptions) {+ assert.equal(command, process.platform === 'win32' ? 'pac.exe' : 'pac');+ assert.equal(args.includes('--async'), true);+ options = commandOptions;+ return '';+ },+ });++ assert.equal(result.ok, true);+ assert.equal(options.timeout, PROCESS_TIMEOUT_MS);+ assert.ok(PROCESS_TIMEOUT_MS > MAX_ASYNC_WAIT_MINUTES * 60 * 1000);+});++test('PAC failures and invalid inputs stay explicit', (t) => {+ const zipPath = writeSolutionZip(t);+ const failed = importTemplateSolution({+ zipPath,+ envUrl: 'https://contoso.crm.dynamics.com',+ publishChanges: true,+ }, {+ runPac() {+ return { status: 1, stdout: '', stderr: 'Import failed' };+ },+ });+ assert.equal(failed.ok, false);+ assert.equal(failed.phase, 'import');+ assert.match(failed.error, /Import failed/);++ for (const options of [+ { zipPath: '/missing.zip', envUrl: 'https://contoso.crm.dynamics.com', publishChanges: false },+ { zipPath, envUrl: 'https://example.org', publishChanges: false },+ { zipPath, envUrl: 'https://contoso.crm.dynamics.com', publishChanges: 'true' },+ ]) {+ assert.equal(importTemplateSolution(options).ok, false);+ }+});++test('CLI rejects incomplete or malformed arguments', () => {+ for (const argv of [+ [],+ ['--zipPath', '/tmp/a.zip'],+ ['--zipPath', '/tmp/a.zip', '--envUrl', 'https://contoso.crm.dynamics.com', '--publishChanges', 'yes'],+ ['--zipPath', '/tmp/a.zip', '--envUrl', 'https://contoso.crm.dynamics.com', '--unknown'],+ ]) {+ assert.equal(run(argv).ok, false);+ }+});diff --git a/plugins/power-pages/scripts/tests/template-catalog.test.js b/plugins/power-pages/scripts/tests/template-catalog.test.jsindex 8c3eec45d..8082e03b6 100644--- a/plugins/power-pages/scripts/tests/template-catalog.test.js+++ b/plugins/power-pages/scripts/tests/template-catalog.test.js@@ -32,6 +32,7 @@ const {assertValidSha,resolveRefToSha,normalizeCatalogFamilies,+ applySolutionSettings,} = require('../lib/template-catalog');const { parseArgs: parseCatalogArgs } = require('../fetch-template-catalog');const { parseArgs: parseVariantArgs } = require('../fetch-template-variant');@@ -369,6 +370,74 @@ test('validateCatalogShape rejects duplicate framework variants in a family', ()validateCatalogShape({ templates: [family] }),/duplicate framework variant/i);+ assert.match(+ validateCatalogShape({+ templates: [{+ ...VALID_TEMPLATE_FAMILY,+ variants: {+ react: {+ solutions: [{ uniqueName: 'SupplierPortal', publishChanges: true }],+ },+ },+ }],+ }),+ /family level/+ );+});++test('validateCatalogShape accepts strict solution-level publish settings', () => {+ assert.equal(validateCatalogShape({+ templates: [{+ ...VALID_TEMPLATE_FAMILY,+ solutions: [+ { uniqueName: 'SupplierBase', publishChanges: false },+ { uniqueName: 'SupplierPortal', publishChanges: true },+ ],+ }],+ }), null);++ for (const solutions of [+ {},+ [{ uniqueName: 'SupplierPortal' }],+ [{ uniqueName: 'SupplierPortal', publishChanges: 'true' }],+ [{ uniqueName: 'SupplierPortal', publishChanges: true, extra: true }],+ [+ { uniqueName: 'SupplierPortal', publishChanges: true },+ { uniqueName: 'supplierportal', publishChanges: false },+ ],+ ]) {+ assert.notEqual(validateCatalogShape({+ templates: [{ ...VALID_TEMPLATE_FAMILY, solutions }],+ }), null);+ }+});++test('normalization preserves family solution settings for every variant', () => {+ const solutions = [{ uniqueName: 'SupplierPortal', publishChanges: true }];+ const [family] = normalizeCatalogFamilies({+ templates: [{ ...VALID_TEMPLATE_FAMILY, solutions }],+ });+ assert.deepEqual(family.solutions, solutions);+ assert.ok(family.variants.every(variant => variant.solutions === solutions));+});++test('solution settings default to false and reject unknown manifest entries', () => {+ const discovered = [+ { uniqueName: 'SupplierBase', version: '1.0.0.0', solutionPath: '/base' },+ { uniqueName: 'SupplierPortal', version: '2.0.0.0', solutionPath: '/portal' },+ ];+ assert.deepEqual(applySolutionSettings(discovered, [+ { uniqueName: 'SupplierPortal', publishChanges: true },+ ]), [+ { ...discovered[0], publishChanges: false },+ { ...discovered[1], publishChanges: true },+ ]);+ assert.throws(() => applySolutionSettings(discovered, [+ { uniqueName: 'MissingSolution', publishChanges: true },+ ]), /unknown solution/);+ assert.throws(() => applySolutionSettings(discovered, [+ { uniqueName: 'supplierportal', publishChanges: true },+ ]), /unknown solution/);});test('fetchCatalog materializes nested preview and seed artifact paths', async (t) => {@@ -865,6 +934,7 @@ test('downloadTemplateVariant combines variant website code with family solutiontemplateId: 'company',variant: 'react',cacheRoot: dir,+ solutionSettings: [{ uniqueName: 'CompanyPortal', publishChanges: true }],}, {execFileSync(command, args) {calls.push([command, args]);@@ -892,6 +962,7 @@ test('downloadTemplateVariant combines variant website code with family solutiontemplateId: 'company',variant: 'react',cacheRoot: dir,+ solutionSettings: [{ uniqueName: 'CompanyPortal', publishChanges: true }],}, {execFileSync() {throw new Error('cached variant must not run git');@@ -915,11 +986,13 @@ test('downloadTemplateVariant combines variant website code with family solutionuniqueName: 'CompanyBase',version: '1.0.0.0',solutionPath: path.join(localSolutionsPath, 'CompanyBase'),+ publishChanges: false,},{uniqueName: 'CompanyPortal',version: '2.0.0.0',solutionPath: path.join(localSolutionsPath, 'CompanyPortal'),+ publishChanges: true,},]);assert.deepEqual(cached, { ...result, cached: true });@@ -1344,6 +1417,7 @@ test('fetch-template-variant CLI parser accepts derivable variant identity', ()'--kind', 'spa','--templateId', 'company','--variant', 'react',+ '--solutionSettingsJson', '[{"uniqueName":"CompanyPortal","publishChanges":true}]','--catalogPath', 'templates/manifest.json','--cacheRoot', '/tmp/cache',]), {@@ -1353,6 +1427,7 @@ test('fetch-template-variant CLI parser accepts derivable variant identity', ()kind: 'spa',templateId: 'company',variant: 'react',+ solutionSettings: [{ uniqueName: 'CompanyPortal', publishChanges: true }],catalogPath: 'templates/manifest.json',cacheRoot: '/tmp/cache',});diff --git a/plugins/power-pages/scripts/tests/template-publish-manifest-skill.test.js b/plugins/power-pages/scripts/tests/template-publish-manifest-skill.test.jsnew file mode 100644index 000000000..092b7fa4d--- /dev/null+++ b/plugins/power-pages/scripts/tests/template-publish-manifest-skill.test.js@@ -0,0 +1,32 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');++const skill = fs.readFileSync(path.join(__dirname, '../../skills/create-site/SKILL.md'), 'utf8');++test('selected solution publication metadata reaches variant download', () => {+ assert.match(skill, /--solutionSettingsJson '<JSON\.stringify\(SELECTED_TEMPLATE\.solutions \|\| \[\]\)>'/);+ assert.match(skill, /CURRENT_TEMPLATE_SOLUTION\.publishChanges/);+});++test('template import uses the PAC wrapper and manifest publish flag', () => {+ const packing = skill.indexOf('scripts/pack-template-solution.js');+ const importing = skill.indexOf('scripts/import-template-solution.js');+ const provisioning = skill.indexOf('scripts/provision-template-site.js');+ assert.ok(packing !== -1 && importing > packing && provisioning > importing);+ assert.match(skill, /--publishChanges "<CURRENT_TEMPLATE_SOLUTION\.publishChanges>"/);+ assert.match(skill, /pac solution import --publish-changes/);+ assert.match(skill, /run_in_background: true/);+ assert.match(skill, /Importing solution <CURRENT_TEMPLATE_SOLUTION\.uniqueName>/);+ assert.match(skill, /other pending customizations/);+});++test('template install has no second publication phase', () => {+ assert.doesNotMatch(skill, /publish-template-customizations/);+ assert.doesNotMatch(skill, /TEMPLATE_PUBLICATION_/);+ assert.doesNotMatch(skill, /Publish template customizations/);+ assert.doesNotMatch(skill, /publication-scope|publication-failed/);+});diff --git a/plugins/power-pages/scripts/tests/test-site-replay-instructions.test.js b/plugins/power-pages/scripts/tests/test-site-replay-instructions.test.jsnew file mode 100644index 000000000..6b43e28fa--- /dev/null+++ b/plugins/power-pages/scripts/tests/test-site-replay-instructions.test.js@@ -0,0 +1,97 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const vm = require('node:vm');++const skill = fs.readFileSync(path.join(__dirname, '../../skills/test-site/SKILL.md'), 'utf8');+const section = skill.slice(skill.indexOf('#### 5.3b Inspect Server Logic Response Shapes'));+const code = /```javascript\s*([\s\S]*?)```/.exec(section)[1];+const origin = 'https://contoso.powerappsportals.com';++function replay({+ token = 'local-fixture-csrf',+ tokenStatus = 200,+ tokenHtml = null,+ url = `${origin}/_api/serverlogics/example`,+} = {}) {+ const calls = [];+ const window = { location: { origin } };+ const fetch = async (requestUrl, options) => {+ calls.push({ requestUrl, options });+ if (requestUrl === `${origin}/_layout/tokenhtml`) {+ return {+ status: tokenStatus,+ text: async () => tokenHtml === null+ ? `<input name="__RequestVerificationToken" type="hidden" value="${token}" />`+ : tokenHtml,+ };+ }+ return {+ status: 200,+ text: async () => JSON.stringify({+ success: true,+ data: JSON.stringify({ Body: JSON.stringify({ items: [{ id: 'fixture' }] }) }),+ }),+ };+ };+ const serializedUrl = JSON.stringify(url);+ const fn = vm.runInNewContext(`(${code.replace('<serialized-observed-url>', serializedUrl)})`, {+ window, fetch, URL, Promise, Error, JSON, Object, Array,+ });+ return { execute: fn, calls };+}++test('test-site read-only replay uses authenticated same-origin GET with an in-memory verification token', async () => {+ const probe = replay();+ const result = await probe.execute();+ assert.equal(probe.calls.length, 2);+ assert.equal(probe.calls[0].requestUrl, `${origin}/_layout/tokenhtml`);+ assert.equal(probe.calls[0].options.credentials, 'include');+ assert.equal(probe.calls[0].options.redirect, 'error');+ assert.equal(probe.calls[0].options.headers.Accept, 'text/html');+ assert.equal(probe.calls[1].options.credentials, 'include');+ assert.equal(probe.calls[1].options.redirect, 'error');+ assert.equal(probe.calls[1].options.headers.__RequestVerificationToken, 'local-fixture-csrf');+ assert.equal(probe.calls[1].options.method, undefined);+ assert.equal(probe.calls[1].options.body, undefined);+ assert.equal(result.levels.length, 3);+ assert.equal(result.levels[1].parsedFrom, 'data');+ assert.equal(result.levels[2].parsedFrom, 'Body');+ assert.ok(!JSON.stringify(result).includes('local-fixture-csrf'));+});++test('test-site safely serializes observed URLs containing quotes and backslashes', async () => {+ const observedUrl = `${origin}/_api/serverlogics/example?$filter=name eq 'O\\Reilly'`;+ const probe = replay({ url: observedUrl });+ await probe.execute();+ assert.equal(probe.calls.length, 2);+ assert.equal(probe.calls[1].requestUrl, new URL(observedUrl).href);+});++test('test-site cannot replay off-origin requests or redirects carrying credentials', async () => {+ const probe = replay({ url: 'https://example.org/_api/serverlogics/example' });+ await assert.rejects(probe.execute(), /authenticated site/);+ assert.equal(probe.calls.length, 0);+});++test('test-site reports unavailable verification-token endpoints as blocked instead of unauthenticated replay', async () => {+ const probe = replay({ tokenStatus: 404 });+ await assert.rejects(probe.execute(), /replay is blocked/);+ assert.equal(probe.calls.length, 1);+});++test('test-site rejects empty or malformed verification tokens before requesting', async () => {+ for (const tokenHtml of [+ '',+ '<input name="__RequestVerificationToken" type="hidden" />',+ '<input name="__RequestVerificationToken" type="hidden" value="" />',+ '<input name="__RequestVerificationToken" type="hidden" value=" " />',+ ]) {+ const probe = replay({ tokenHtml });+ await assert.rejects(probe.execute(), /verification token is unavailable/);+ assert.equal(probe.calls.length, 1);+ }+});diff --git a/plugins/power-pages/skills/create-site/SKILL.md b/plugins/power-pages/skills/create-site/SKILL.mdindex ddb99d9e5..b62b04c18 100644--- a/plugins/power-pages/skills/create-site/SKILL.md+++ b/plugins/power-pages/skills/create-site/SKILL.md@@ -199,7 +199,8 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read--catalogPath "<catalogPath from fetch-template-catalog.js>" \--kind "<SELECTED_TEMPLATE.kind>" \--templateId "<SELECTED_TEMPLATE.id>" \- --variant "<SELECTED_TEMPLATE_VARIANT.variantKey>"+ --variant "<SELECTED_TEMPLATE_VARIANT.variantKey>" \+ --solutionSettingsJson '<JSON.stringify(SELECTED_TEMPLATE.solutions || [])>'```Use the returned `websiteCodePath` and `solutions`. Process `solutions` in the returned order; do not rediscover, reorder, or revalidate the template assets in the skill.2. If the result is `ok: false`, tell the user the selected framework variant is unavailable or invalid. If the same family has other available framework variants, offer those first; otherwise offer **Start from scratch** or **Stop**. Do not emit `template_used` for a variant whose package did not validate. If the user falls back to from-scratch, recommend the framework they had selected.@@ -239,7 +240,7 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read```bashnode "${PLUGIN_ROOT}/scripts/resolve-template-import-context.js"```- Use the returned `environmentUrl` for the remaining template workflow. Downstream preflight, import, seed, and polling helpers acquire Azure tokens internally so credentials are never returned in JSON or carried between tasks. If `ok: false`, surface the error and stop before import. Do not emit `template_import_failure` because no import was attempted; `template_used` was already emitted when the template path was selected.+ Use the returned `environmentUrl` for the remaining template workflow. The PAC import wrapper uses the current PAC authentication with this explicit target URL; Dataverse preflight and seed helpers acquire Azure tokens internally so credentials are never returned in JSON or carried between tasks. If `ok: false`, surface the error and stop before import. Do not emit `template_import_failure` because no import was attempted; `template_used` was already emitted when the template path was selected.<!-- gate: create-site:1.5.confirm-environment | category=consent | cancel-leaves=template-cache -->@@ -322,9 +323,13 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read7. If the language preflight passed but `.js` was blocked and the user approved/verification passed, mark **Validate JavaScript unblock requirement** as `completed`. Then mark **Confirm template install** as `in_progress`, present the template and environment, and ask:+ List any supporting solution whose manifest metadata has `publishChanges: true`.+ Explain that those solutions use `pac solution import --publish-changes` so imported forms, views, and other customizations become visible immediately after import.+ Disclose that PAC's publication step can also publish other pending customizations in the target environment.+| Question | Header | Options ||----------|--------|---------|- | Install **`<SELECTED_TEMPLATE.displayName>`** into **`<environmentUrl>`**? This imports any required unmanaged supporting solutions, clones and builds the website code, and uploads the new code site. Seed data is applied before activation when available. | Install Template | Yes, install this template (Recommended), No, start from scratch, Cancel |+ | Install **`<SELECTED_TEMPLATE.displayName>`** into **`<environmentUrl>`**? This imports any required unmanaged supporting solutions, runs PAC's publish-changes step for solutions that declare it in the template manifest, clones and builds the website code, and uploads the new code site. The publication step can include other pending customizations in this environment. Seed data is applied before activation when available. | Install Template | Yes, install this template (Recommended), No, start from scratch, Cancel |- **No, start from scratch**: set `CREATION_PATH = "from-scratch"` and continue to the deferred framework/location questions.- **Cancel**: stop; no org mutation has happened. Do not emit `template_import_failure` because no import was attempted; `template_used` was already emitted when the template path was selected.@@ -378,7 +383,9 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read- **Start from scratch**: set `CREATION_PATH = "from-scratch"` and continue to the deferred framework/location questions.- **Stop**: stop before import; no org mutation has happened. Do not emit `template_import_failure` because no import was attempted; `template_used` was already emitted when the template path was selected.- After all solutions are classified, append the full site-install tasks. Include **Import template supporting solutions** only when `TEMPLATE_SOLUTIONS_TO_IMPORT` is non-empty. If every solution was skipped, ask once before creating the site:+ Append the full site-install tasks.+ Include **Import template supporting solutions** only when `TEMPLATE_SOLUTIONS_TO_IMPORT` is non-empty.+ If every solution was skipped, ask once before creating the site:<!-- gate: create-site:1.5.clone-existing | category=consent | cancel-leaves=template-cache -->@@ -445,36 +452,34 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read- **Fall back to from-scratch**: set `CREATION_PATH = "from-scratch"` and continue to the deferred framework/location questions.- **Stop**: stop after showing the local pack error. Do not mark **Import template supporting solutions** as completed.- After packing succeeds, import the temporary ZIP inline. Do not invoke `/import-solution` or write ALM artifacts. After `ImportSolutionAsync` returns the async operation id, immediately clean the packer's work directory, then launch a Task subagent to run `poll-async-operation.js` and write `<temp-import-status-dir>/status.json`:+ After packing succeeds, import the temporary ZIP with the PAC CLI wrapper. Do not invoke `/import-solution` or write ALM artifacts.+ The solution-level `publishChanges` value comes from the pinned template manifest.+ The wrapper adds `pac solution import --publish-changes` only when that value is true:+ ```json+ { "state": "running", "phase": "solution", "message": "Importing solution <CURRENT_TEMPLATE_SOLUTION.uniqueName>" }+ ```+ Write that object to `<temp-import-status-dir>/status.json`, then run the import wrapper in a Task subagent with `run_in_background: true`:+ ```bash+ node "${PLUGIN_ROOT}/scripts/import-template-solution.js" \+ --zipPath "<PACKED_TEMPLATE_SOLUTION_ZIP>" \+ --envUrl "<environmentUrl>" \+ --publishChanges "<CURRENT_TEMPLATE_SOLUTION.publishChanges>"+ ```+ The Task must return the wrapper's complete JSON result.+ When it finishes, clean the owned temporary directory in the main conversation:```bash- node "${PLUGIN_ROOT}/scripts/encode-solution-file.js" --zipPath "<PACKED_TEMPLATE_SOLUTION_ZIP>"- # Write a temp JSON body file containing:- # {- # "CustomizationFile": "<encoded>",- # "OverwriteUnmanagedCustomizations": true,- # "PublishWorkflows": true,- # "ConvertToManaged": false- # }- node "${PLUGIN_ROOT}/scripts/dataverse-request.js" "<environmentUrl>" POST "ImportSolutionAsync" \- --bodyFile "<temp-import-body.json>" \- --include-headersnode "${PLUGIN_ROOT}/scripts/pack-template-solution.js" \--cleanup \--workDirectory "<PACKED_TEMPLATE_SOLUTION_WORK_DIRECTORY>" \--cleanupMarker "<PACKED_TEMPLATE_SOLUTION_CLEANUP_MARKER>" \--cleanupToken "<PACKED_TEMPLATE_SOLUTION_CLEANUP_TOKEN>"- # Run this poll command in a Task subagent, not in the main conversation:- node "${PLUGIN_ROOT}/scripts/poll-async-operation.js" \- --asyncJobId "<AsyncOperationId from ImportSolutionAsync>" \- --envUrl "<environmentUrl>" \- --intervalMs 30000 \- --maxAttempts 75 \- --statusFile "<temp-import-status-dir>/status.json"```- If encoding or `ImportSolutionAsync` fails before returning an async operation id, clean `PACKED_TEMPLATE_SOLUTION_WORK_DIRECTORY` before retrying, falling back, or stopping. Treat a cleanup failure as a local warning and show the work-directory path so the user can remove it manually; do not hide the original failure.-- The subagent must return the poller's final JSON when the command exits. Do not rely only on that notification: read `<temp-import-status-dir>/status.json` every 30 seconds until `state` is `succeeded`, `failed`, `canceled`, or `timeout`. Do not start the next solution import until the current solution succeeds, and do not start site cloning until every solution in `TEMPLATE_SOLUTIONS_TO_IMPORT` succeeds.- If the poll result is not `Succeeded`, query the import job (using the `ImportJobKey` returned by `ImportSolutionAsync`) and parse its component-level error XML, following `/import-solution`'s Phase 6 pattern. Do **not** auto-clean up the unmanaged partial import. Run the `template_import_failure` telemetry command silently before asking the recovery question. Do not mention this telemetry command to the user and do not print its output:+ Always run the owned temporary-directory cleanup after the import command returns.+ Treat a cleanup failure as a local warning and show the work-directory path so the user can remove it manually; do not hide the import result.+ Do not start the next solution import until the current command returns `ok: true`, and do not start site cloning until every solution in `TEMPLATE_SOLUTIONS_TO_IMPORT` succeeds.+ If the import wrapper returns `ok: false`, do **not** auto-clean up the unmanaged partial import.+ Run the `template_import_failure` telemetry command silently before asking the recovery question.+ Do not mention this telemetry command to the user and do not print its output:```bashnode "${PLUGIN_ROOT}/scripts/emit-create-site-template-outcome.js" \--eventName template_import_failure \@@ -483,7 +488,7 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read--framework "<SELECTED_TEMPLATE_VARIANT.framework>" \--audience "<internal|external from Phase 1 discovery>" \--outcome failure \- --errorClass "ImportSolutionAsync"+ --errorClass "PacSolutionImport"````--audience` is the site audience captured in Phase 1 (`internal` or `external`), **not** the template's `audience` persona array from the catalog manifest. Do not add free-form error text to telemetry; it can contain paths, URLs, stack traces, or user data.@@ -491,9 +496,9 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read> 🚦 **Gate (progress · create-site:1.5.import-failed):** Choose how to proceed after template solution import fails.>- > **Trigger:** Phase 1.5 when `ImportSolutionAsync` fails, times out, or reports component-level failures.+ > **Trigger:** Phase 1.5 when `pac solution import` fails or times out.> **Loop behavior:** Fires per failed iteration of `TEMPLATE_SOLUTIONS_TO_IMPORT`; an answer applies only to `CURRENT_TEMPLATE_SOLUTION`.- > **Why we ask:** The environment may contain the current partial unmanaged import plus any earlier solutions imported during this run; retrying or switching paths should be an explicit choice.+ > **Why we ask:** The environment may contain the current partial unmanaged import plus any earlier solutions imported during this run. A local timeout does not cancel an already-started server import, so retrying or switching paths should be an explicit choice.> **Cancel leaves:** `partial-unmanaged-template-import` — downloaded template artifacts remain in the private SHA-keyed template cache; the current partial import and any earlier successful solution imports remain in Dataverse and are explained in the error summary.Use `AskUserQuestion`:@@ -503,16 +508,43 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read| Supporting solution `<CURRENT_TEMPLATE_SOLUTION.uniqueName>` failed or partially completed. How would you like to proceed? | Template Import Failed | Retry import, Fall back to from-scratch (Recommended), Stop |Branch on the answer:- - **Retry import**: return to the pack-and-import command sequence above and poll again.+ - **Retry import**: return to the pack-and-import command sequence above.- **Fall back to from-scratch**: set `CREATION_PATH = "from-scratch"` and continue to the deferred framework/location questions. Tell the user the unmanaged partial import may remain in Dataverse. The eventual from-scratch branch emits the single terminal telemetry event.- **Stop**: stop after showing the error summary. Do not mark **Import template supporting solutions** as completed and do not clone or upload the site. The `template_import_failure` event was already emitted when the import failure was detected.If the error is `AttachmentBlocked`, point to `/import-solution` Phase 5b remediation.- Only continue to the next step when the import poll result is `Succeeded`.- 8. When every required solution import succeeds, mark **Import template supporting solutions** as `completed` and set `EMIT_TEMPLATE_IMPORT_SUCCESS = true`. Defer that telemetry event until the seed-data workstream joins so `seedApplied` reflects this run. If every solution import was skipped, mark the task as skipped and set `EMIT_TEMPLATE_IMPORT_SUCCESS = false`.- 9. Start site provisioning and seed-data application concurrently after all required solution imports finish:+ Only continue to the next step when the import wrapper returns `ok: true`.+ 8. When every required solution import succeeds, continue to seed planning and site provisioning.+ Mark **Import template supporting solutions** as `completed` and set `EMIT_TEMPLATE_IMPORT_SUCCESS = true` only after these checks.+ Defer that telemetry event until the seed-data workstream joins so `seedApplied` reflects this run.+ If every solution import was skipped, mark the task as skipped and set `EMIT_TEMPLATE_IMPORT_SUCCESS = false`.+ 9. Prepare seed data in the main conversation before starting either mutating workstream.+ If seed data is present, fetch it:+ ```bash+ node "${PLUGIN_ROOT}/scripts/fetch-template-seed-data.js" --sha "<catalog-sha>" --seedDataPath "<SELECTED_TEMPLATE_VARIANT.seedDataPath or SELECTED_TEMPLATE.seedDataPath>"+ ```+ Save `localDir` and `seedFile` from a successful result as `TEMPLATE_SEED_DIRECTORY` and `TEMPLATE_SEED_FILE`.+ Inspect the source and target without inserting records:+ ```bash+ node "${PLUGIN_ROOT}/scripts/apply-seed-data.js" \+ --seedDir "<TEMPLATE_SEED_DIRECTORY>" \+ --seedFile "<TEMPLATE_SEED_FILE>" \+ --envUrl "<environmentUrl>" \+ --plan+ ```+ This reports table/record/file counts, financial entity sets, and active target currencies with `writes: 0`.+ <!-- not-a-gate: create-site:1.5.seed-currency — Read-only currency selection prepares already-approved optional seed records; it does not create currencies or mutate records. -->+ If `requiresCurrencySelection` is true, ask in the main conversation which existing active currency the financial sample rows should use.+ Show the available currency codes/names, explain that the numeric amounts are not converted, and offer **Skip sample data**.+ Never create a currency, copy a source-environment currency GUID, or silently assume USD.+ Save the selected ISO code as `TEMPLATE_SEED_CURRENCY_CODE`.+ If the user skips sample data, do not launch seed writes.+ If no financial rows are present, omit currency selection and the `--currencyCode` flag.+ Fetch/plan failures remain best-effort seed failures: show the explicit failure, retain it in the seed summary, and create the site without a seed task rather than pretending records were inserted.++ Start site provisioning and seed-data application concurrently only after successful imports and the main-conversation seed decisions:- Mark **Clone, build, and upload template site** as `in_progress`.- - If seed data is present, mark **Apply template seed data** as `in_progress` and launch the seed-data workstream with `Task` using `run_in_background: true`. The background task must only fetch, apply, and verify seed data. It must not clone, build, upload, activate, update the shared status file, ask the user questions, or retry failed writes.+ - If seed data is ready and was not skipped, mark **Apply template seed data** as `in_progress` and launch the seed-data workstream with `Task` using `run_in_background: true`. The background task must only apply and verify the prepared seed data. It must not clone, build, upload, activate, update the shared status file, ask the user questions, or retry failed writes.- Run the site-provisioning wrapper in the main conversation while the seed-data task runs. These workstreams are independent after the supporting solution import creates the required Dataverse tables.When seed data is present, update the status page:@@ -531,18 +563,24 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read--siteName "<__SITE_NAME__>"```Treat the wrapper as the sole template-site provisioning entry point. Do not rerun its underlying `pac`, `npm`, or build commands directly for diagnosis. Never pipe a mutating command such as `pac pages clone` or `pac pages upload-code-site` through `head`, `tail`, or another consumer that can close the output stream before the command finishes. The wrapper safely captures a bounded diagnostic tail without interrupting the command. On success, save the returned `clonedPath` as both `CLONED_TEMPLATE_SITE_PATH` and `PROJECT_ROOT`, `siteName` as `IMPORTED_SITE_NAME`, and `websiteRecordId` as `IMPORTED_WEBSITE_RECORD_ID`.- 10. In the seed-data background task, run:- ```bash- node "${PLUGIN_ROOT}/scripts/fetch-template-seed-data.js" --sha "<catalog-sha>" --seedDataPath "<SELECTED_TEMPLATE_VARIANT.seedDataPath or SELECTED_TEMPLATE.seedDataPath>"- ```- If the result is `ok: true`, use `localDir` as the attachment base and `seedFile` as the only seed JSON:+ 10. In the seed-data background task, use the main conversation's prepared directory/file and currency decision:```bashnode "${PLUGIN_ROOT}/scripts/apply-seed-data.js" \- --seedDir "<localDir>" \- --seedFile "<seedFile>" \- --envUrl "<environmentUrl>"+ --seedDir "<TEMPLATE_SEED_DIRECTORY>" \+ --seedFile "<TEMPLATE_SEED_FILE>" \+ --envUrl "<environmentUrl>" \+ --currencyCode "<TEMPLATE_SEED_CURRENCY_CODE, only when financial rows were planned>"```- Return the JSON summary (`inserted`, `failed`, `skipped`, `errors`) to the main conversation. Seed records must use the exact table entity-set names, column logical names, and `<NavigationProperty>@odata.bind` lookup names from the template solution metadata. Never derive lookup navigation properties from a primary key, entity set, display name, or app-style alias such as `categoryId`; the seeder rejects ambiguous aliases before its first Dataverse write. For a lightweight read-only verification path, query each seeded `entitySetName` with `dataverse-request.js` using `GET "<entitySetName>?$top=1"` and report whether the seeded table is reachable. Prefer the selected variant's `seedDataPath` when present; otherwise use the family `seedDataPath`.+ Omit the entire currency flag when no financial rows were planned.+ The seeder resolves only an existing active target currency and its exact metadata navigation before any writes.+ It removes declared upload-column values and their generated file-name companions from create payloads; file-upload actions populate those fields.+ Return the complete JSON summary (`ok`, `inserted`, `failed`, `skipped`, `errors`) to the main conversation.+ A partial row, state, validation, or file-upload failure must be reported as `ok: false`; never rely solely on a successful CLI exit.+ Seed records must use the exact table entity-set names, column logical names, and scalar or collection `<NavigationProperty>@odata.bind` lookup names from the template solution metadata.+ Never derive lookup navigation properties from a primary key, entity set, display name, or app-style alias such as `categoryId`; the seeder rejects ambiguous aliases and malformed collection binds before its first Dataverse write.+ For verification, query the planned record IDs—not merely `$top=1`—and compare expected references and native collection memberships.+ Verify each uploaded attachment through its target file metadata/content, rather than counting only created attachment rows.+ Ordinary existing seed-record skips do not reconcile native N:N memberships; disclose that limit and do not silently update existing contacts, businesses, or assignments.11. Wait for both workstreams to finish before showing the inactive-site summary or starting activation. Record the seed summary, then mark **Apply template seed data** as `completed`; if seed data is absent, mark it skipped. Seed fetch and insertion remain best-effort: surface their result, but do not fail site creation or block activation.If `EMIT_TEMPLATE_IMPORT_SUCCESS = true`, emit the import result now:@@ -2025,9 +2063,9 @@ When `TEMPLATE_SOLUTIONS_TO_IMPORT` contains exactly one entry, use the task sub| Task subject | activeForm | Description ||-------------|------------|-------------|-| Import template supporting solutions | Importing supporting solutions | Import each required unmanaged supporting solution in deterministic order and poll every async job to completion |+| Import template supporting solutions | Importing supporting solutions | Import each required unmanaged supporting solution in deterministic order; solutions marked `publishChanges` in the manifest publish changes as part of import || Clone, build, and upload template site | Creating template site | Clone the packaged SPA source into the selected local directory, install dependencies, build and verify the configured compiled output, then upload the resulting code site |-| Apply template seed data | Applying seed data | In parallel with site creation, insert optional template seed records using the deterministic seed-data script; failures do not block activation |+| Apply template seed data | Applying seed data | After read-only planning and any financial currency decision, insert optional template seed records in parallel with site creation; failures do not block activation || Show inactive template site | Showing template site | After site creation and seeding join, use the Website Record ID written by `pac pages clone` to `.powerpages-site/website.yml` and tell the user the uploaded site is not activated yet || Activate template site | Activating template site | Invoke activate-site with the resolved site name and Website Record ID || Show live template site | Showing live site | Open the activated site URL in the browser and invite the user to continue customizing |diff --git a/plugins/power-pages/skills/test-site/SKILL.md b/plugins/power-pages/skills/test-site/SKILL.mdindex c63ee4fbc..06623750d 100644--- a/plugins/power-pages/skills/test-site/SKILL.md+++ b/plugins/power-pages/skills/test-site/SKILL.md@@ -358,11 +358,39 @@ Server logic endpoints (`/_api/serverlogics/<name>`) commonly return a standardFor each `/_api/serverlogics/` request observed on any tested page:1. Record the endpoint name from the URL (`/_api/serverlogics/<endpointName>`), the HTTP method, query string parameters, and HTTP status code.-2. When the request was a GET (no CSRF token required), re-execute it from the browser with `browser_evaluate` so the full response body is captured. Progressively parse the payload — keep parsing string-typed fields until further parsing fails — and record the shape at each level. Use a script of this form, replacing the URL with the observed one:+2. When the request was a GET, re-execute it from the same authenticated site with `browser_evaluate` so its response shape is captured.+ Power Pages API requests require the site's verification token; GET is read-only, not an authentication or CSRF exemption.+ Prefer the site's existing authenticated request wrapper when it is exposed to the browser.+ Otherwise fetch the token from the same-origin `/_layout/tokenhtml` endpoint, keep it in memory, and never include it in logs or reports.+ If the token endpoint is unavailable or the observed URL is not same-origin, report the replay as blocked instead of importing cookies or making an unauthenticated request.+ Progressively parse string-typed payload fields and record the shape at each level.+ Serialize the observed URL with `JSON.stringify(observedUrl)`, then replace+ `<serialized-observed-url>` with that complete serialized value, including+ its quotes. Do not wrap the placeholder in another string literal.+ Use a script of this form:```javascriptasync () => {- const res = await fetch('<observed-url>', { credentials: 'include', headers: { 'Content-Type': 'application/json' } });+ const url = new URL(<serialized-observed-url>, window.location.origin);+ if (url.origin !== window.location.origin) throw new Error('API replay must remain on the authenticated site.');+ const tokenResponse = await fetch(new URL('/_layout/tokenhtml', window.location.origin).href, {+ credentials: 'include',+ redirect: 'error',+ headers: { Accept: 'text/html' },+ });+ if (tokenResponse.status !== 200) throw new Error('The site verification-token endpoint is unavailable; read-only replay is blocked.');+ const tokenHtml = await tokenResponse.text();+ const valueMarker = 'value="';+ const valueStart = tokenHtml.indexOf(valueMarker);+ const valueEnd = valueStart === -1 ? -1 : tokenHtml.indexOf('"', valueStart + valueMarker.length);+ const token = valueStart === -1 || valueEnd === -1+ ? '' : tokenHtml.slice(valueStart + valueMarker.length, valueEnd);+ if (typeof token !== 'string' || !token.trim()) throw new Error('The site verification token is unavailable.');+ const res = await fetch(url.href, {+ credentials: 'include',+ redirect: 'error',+ headers: { Accept: 'application/json', '__RequestVerificationToken': token },+ });const status = res.status;const text = await res.text();const levels = [];