Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ maps each payload to an SPO text web part.
- Optional image manifest produced by extract-page-images.ps1
- Optional -LibraryPathMapPath (inventory/library-path-map.csv) with -SourceHost: rewrites
SP2016 links to their planned SPO location (assume-migrated link policy)
- Optional -NoBcDesignTokens: skips the BC design-token wrapper on text web parts
- Optional -LeadingImageWebPartIds: web parts whose leading banner image becomes an
Image web part reusing the already-migrated image (ExistingImageUrl, no upload)
- -ConfigPath: config-spo-<env>.psd1; Connection.Environment is the target environment
Expand Down Expand Up @@ -66,7 +67,9 @@ param(
[int]$PageHeaderZoneThemeIndex = 3,
[string]$PageTitle,
[string]$BreadcrumbSection,
[string]$BreadcrumbSectionUrl
[string]$BreadcrumbSectionUrl,
# Leaves the BC design-token wrapper (font, colour, 16px) off the text web parts.
[switch]$NoBcDesignTokens
)

Set-StrictMode -Version Latest
Expand Down Expand Up @@ -584,7 +587,9 @@ function ConvertTo-SpPageMappedLinks {
[AllowEmptyString()][string]$PageUrl,
[Parameter(Mandatory = $true)][string]$SourceHost,
[string]$TargetSitePath,
[string]$RelativeBase
[string]$RelativeBase,
# Values already pointing at their final location (e.g. uploaded image assets) are left untouched.
[string[]]$PreservedValues = @()
)

$sourceHostName = ($SourceHost -replace "^[a-z]+://", "").Trim("/")
Expand All @@ -594,7 +599,8 @@ function ConvertTo-SpPageMappedLinks {
param($match)
$raw = $match.Groups["value"].Value
$value = [System.Net.WebUtility]::HtmlDecode($raw).Trim()
if ($value -eq "" -or $value -match "^(#|mailto:|tel:|javascript:|data:)" -or $value -match "^/sites/") {
if ($value -eq "" -or $value -match "^(#|mailto:|tel:|javascript:|data:)" -or $value -match "^/sites/" -or
$PreservedValues -contains $value) {
return $match.Value
}
$uri = $null
Expand Down Expand Up @@ -901,7 +907,8 @@ function New-SpPageWave1DryRun {
[int]$PageHeaderZoneThemeIndex = 3,
[string]$PageTitle,
[string]$BreadcrumbSection,
[string]$BreadcrumbSectionUrl
[string]$BreadcrumbSectionUrl,
[switch]$NoBcDesignTokens
)

$useSpfx = $AccordionOutput -eq "Spfx"
Expand Down Expand Up @@ -1081,7 +1088,8 @@ function New-SpPageWave1DryRun {
if ($pathMap.Count -gt 0) {
$mapped = ConvertTo-SpPageMappedLinks -Html $html -PathMap $pathMap -PageUrl $pageUrl `
-SourceHost $SourceHost -TargetSitePath $TargetSitePath `
-RelativeBase $(if ($TargetSitePath) { if ([string]$page.SiteName -eq "Main") { "../" } else { "../../" } } else { "" })
-RelativeBase $(if ($TargetSitePath) { if ([string]$page.SiteName -eq "Main") { "../" } else { "../../" } } else { "" }) `
-PreservedValues @($webpartImages | ForEach-Object { [string]$_.DestinationRelativePath })
foreach ($link in @($mapped.Links)) {
$link | Add-Member -NotePropertyName SourceWebPartId -NotePropertyValue $webpartId
$linkRewrites.Add($link)
Expand Down Expand Up @@ -1213,7 +1221,8 @@ function New-SpPageWave1DryRun {
}
$isFirstPiece = $false
if ([string]::IsNullOrWhiteSpace($html)) { continue }
$components.Add((& $newComponent "TextWebPart" (Set-SpPageBcDesignTokenStyles -Html (ConvertTo-SpPageBcAlert -Html $html)) $section))
$alerted = ConvertTo-SpPageBcAlert -Html $html
$components.Add((& $newComponent "TextWebPart" $(if ($NoBcDesignTokens) { $alerted } else { Set-SpPageBcDesignTokenStyles -Html $alerted }) $section))
}
}
if ($hasAccordion -and -not $useSpfx -and $pageLayout -notin @("", "One-Column")) {
Expand Down Expand Up @@ -1338,5 +1347,6 @@ if ($MyInvocation.InvocationName -ne ".") {
-PageHeaderZoneThemeIndex $PageHeaderZoneThemeIndex `
-PageTitle $PageTitle `
-BreadcrumbSection $BreadcrumbSection `
-BreadcrumbSectionUrl $BreadcrumbSectionUrl
-BreadcrumbSectionUrl $BreadcrumbSectionUrl `
-NoBcDesignTokens:$NoBcDesignTokens
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,10 @@ asset through PnP read operations.

Dry-run is the default and performs no tenant I/O. Real writes require both
`-Execute` and the exact `PUBLISH-SPO-PAGE` confirmation token, plus an
explicit target configuration. Execution also requires ClientId, TenantId,
and a durable `-OutputPath` for the publication receipt.
explicit target configuration. Execution also requires ClientId and TenantId.
The wave publisher additionally requires a durable `-OutputPath` for the
publication receipt; the single-page `publish-spo-page.ps1` has no
`-OutputPath` parameter, so check the published page itself.

## Single-page and wave workflows

Expand Down Expand Up @@ -165,8 +167,11 @@ position inside each Content Editor HTML payload are preserved.

For the currently observed partial DEV page only, recovery requires the
additional `-RecoverPartialPage` switch. Recovery refuses unless the existing
page has exactly one component; it then adds the remaining package components
in order before publishing and validating.
page has exactly one component and that component is a text web part with
visible content (when the package's first component is a text web part). An
empty draft shell is refused; republish it with `-Force` (backup, then
overwrite). Otherwise it adds the remaining package components in order before
publishing and validating.

This capability does not update inventory. After independent publication
validation, hand the verified destination URL to `sp-page-inventory-agent`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ maps each payload to an SPO text web part.
- Optional image manifest produced by extract-page-images.ps1
- Optional -LibraryPathMapPath (inventory/library-path-map.csv) with -SourceHost: rewrites
SP2016 links to their planned SPO location (assume-migrated link policy)
- Optional -NoBcDesignTokens: skips the BC design-token wrapper on text web parts
- Optional -LeadingImageWebPartIds: web parts whose leading banner image becomes an
Image web part reusing the already-migrated image (ExistingImageUrl, no upload)
- -ConfigPath: config-spo-<env>.psd1; Connection.Environment is the target environment
Expand Down Expand Up @@ -66,7 +67,9 @@ param(
[int]$PageHeaderZoneThemeIndex = 3,
[string]$PageTitle,
[string]$BreadcrumbSection,
[string]$BreadcrumbSectionUrl
[string]$BreadcrumbSectionUrl,
# Leaves the BC design-token wrapper (font, colour, 16px) off the text web parts.
[switch]$NoBcDesignTokens
)

Set-StrictMode -Version Latest
Expand Down Expand Up @@ -584,7 +587,9 @@ function ConvertTo-SpPageMappedLinks {
[AllowEmptyString()][string]$PageUrl,
[Parameter(Mandatory = $true)][string]$SourceHost,
[string]$TargetSitePath,
[string]$RelativeBase
[string]$RelativeBase,
# Values already pointing at their final location (e.g. uploaded image assets) are left untouched.
[string[]]$PreservedValues = @()
)

$sourceHostName = ($SourceHost -replace "^[a-z]+://", "").Trim("/")
Expand All @@ -594,7 +599,8 @@ function ConvertTo-SpPageMappedLinks {
param($match)
$raw = $match.Groups["value"].Value
$value = [System.Net.WebUtility]::HtmlDecode($raw).Trim()
if ($value -eq "" -or $value -match "^(#|mailto:|tel:|javascript:|data:)" -or $value -match "^/sites/") {
if ($value -eq "" -or $value -match "^(#|mailto:|tel:|javascript:|data:)" -or $value -match "^/sites/" -or
$PreservedValues -contains $value) {
return $match.Value
}
$uri = $null
Expand Down Expand Up @@ -901,7 +907,8 @@ function New-SpPageWave1DryRun {
[int]$PageHeaderZoneThemeIndex = 3,
[string]$PageTitle,
[string]$BreadcrumbSection,
[string]$BreadcrumbSectionUrl
[string]$BreadcrumbSectionUrl,
[switch]$NoBcDesignTokens
)

$useSpfx = $AccordionOutput -eq "Spfx"
Expand Down Expand Up @@ -1081,7 +1088,8 @@ function New-SpPageWave1DryRun {
if ($pathMap.Count -gt 0) {
$mapped = ConvertTo-SpPageMappedLinks -Html $html -PathMap $pathMap -PageUrl $pageUrl `
-SourceHost $SourceHost -TargetSitePath $TargetSitePath `
-RelativeBase $(if ($TargetSitePath) { if ([string]$page.SiteName -eq "Main") { "../" } else { "../../" } } else { "" })
-RelativeBase $(if ($TargetSitePath) { if ([string]$page.SiteName -eq "Main") { "../" } else { "../../" } } else { "" }) `
-PreservedValues @($webpartImages | ForEach-Object { [string]$_.DestinationRelativePath })
foreach ($link in @($mapped.Links)) {
$link | Add-Member -NotePropertyName SourceWebPartId -NotePropertyValue $webpartId
$linkRewrites.Add($link)
Expand Down Expand Up @@ -1213,7 +1221,8 @@ function New-SpPageWave1DryRun {
}
$isFirstPiece = $false
if ([string]::IsNullOrWhiteSpace($html)) { continue }
$components.Add((& $newComponent "TextWebPart" (Set-SpPageBcDesignTokenStyles -Html (ConvertTo-SpPageBcAlert -Html $html)) $section))
$alerted = ConvertTo-SpPageBcAlert -Html $html
$components.Add((& $newComponent "TextWebPart" $(if ($NoBcDesignTokens) { $alerted } else { Set-SpPageBcDesignTokenStyles -Html $alerted }) $section))
}
}
if ($hasAccordion -and -not $useSpfx -and $pageLayout -notin @("", "One-Column")) {
Expand Down Expand Up @@ -1338,5 +1347,6 @@ if ($MyInvocation.InvocationName -ne ".") {
-PageHeaderZoneThemeIndex $PageHeaderZoneThemeIndex `
-PageTitle $PageTitle `
-BreadcrumbSection $BreadcrumbSection `
-BreadcrumbSectionUrl $BreadcrumbSectionUrl
-BreadcrumbSectionUrl $BreadcrumbSectionUrl `
-NoBcDesignTokens:$NoBcDesignTokens
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Get-SpoImageProportionalHeight, Get-SpoImageComponentUrl,
ConvertTo-SpoPageHtml,
New-SpoInlineImageHtml, Get-SpoInlineImageAlignment,
Get-SpoInlineImageTableCellWidth, ConvertTo-SpoPageInlineImages,
Test-SpoPublicationPackageAssets, Read-SpoConfiguration, Publish-SpoPage.
Test-SpoPublicationPackageAssets, Assert-SpoRecoverableComponent, Read-SpoConfiguration, Publish-SpoPage.

.EXAMPLE
pwsh -File .\plugins\sp-migration\scripts\publication\publish-spo-page.ps1 `
Expand Down Expand Up @@ -482,7 +482,8 @@ function Get-SpoInlineImageAlignment {
[Parameter(Mandatory = $true)][int]$ImageIndex
)

$prefix = $Html.Substring(0, $ImageIndex)
# SharePoint stores ':' in rich-text styles as '&#58;'.
$prefix = $Html.Substring(0, $ImageIndex).Replace('&#58;', ':')
$openElements = [System.Collections.Generic.List[object]]::new()
$alignment = "Left"
$tagMatches = [regex]::Matches(
Expand Down Expand Up @@ -547,7 +548,7 @@ function Get-SpoInlineImageDimensions {
)

$styleMatch = [regex]::Match($ImageTag, '(?i)\bstyle\s*=\s*["'']([^"'']*)["'']')
$style = if ($styleMatch.Success) { $styleMatch.Groups[1].Value } else { "" }
$style = if ($styleMatch.Success) { $styleMatch.Groups[1].Value.Replace('&#58;', ':') } else { "" }
$getDimension = {
param([string]$Name)
$match = [regex]::Match($style, "(?i)\b$Name\s*:\s*(\d+)\s*px")
Expand Down Expand Up @@ -1091,6 +1092,29 @@ function Backup-SpoExistingPage {
}
}

# Refuses partial-page recovery unless the page holds exactly one component that is the package's first one
# with real content; an empty shell would otherwise be "recovered" and published as a blank page.
function Assert-SpoRecoverableComponent {
[CmdletBinding()]
param(
[AllowEmptyCollection()][object[]]$ExistingComponents = @(),
[Parameter(Mandatory = $true)]$FirstPackageComponent
)

$existing = @($ExistingComponents | Where-Object { $null -ne $_ })
if ($existing.Count -ne 1) {
throw "Partial-page recovery requires exactly one existing component; found $($existing.Count)."
}
if ([string]$FirstPackageComponent.OutputType -ne "TextWebPart") { return }
$text = if ($existing[0].PSObject.Properties["Text"]) { [string]$existing[0].Text } else { $null }
$visible = if ($null -ne $text) {
[System.Net.WebUtility]::HtmlDecode([regex]::Replace($text, '(?s)<[^>]*>', '')).Replace([string][char]0xA0, ' ').Trim()
}
if ([string]::IsNullOrWhiteSpace($visible)) {
throw "Partial-page recovery refused: the existing component is not a text web part with content (empty shell). Republish with -Force to back up and overwrite."
}
}

function Publish-SpoPage {
[CmdletBinding()]
param(
Expand Down Expand Up @@ -1423,9 +1447,8 @@ function Publish-SpoPage {

if ($RecoverPartialPage) {
$existingComponents = @(Get-PnPPageComponent -Page $identity.CreateName -ErrorAction Stop)
if ($existingComponents.Count -ne 1) {
throw "Partial-page recovery requires exactly one existing component; found $($existingComponents.Count)."
}
Assert-SpoRecoverableComponent -ExistingComponents $existingComponents `
-FirstPackageComponent @($package.Components)[0]
$page = $identity.CreateName
} else {
$pageLayout = if ($package.Target.PSObject.Properties["PageLayout"] -and
Expand Down
102 changes: 102 additions & 0 deletions plugins/sharepoint-workbench/tests/test_publish_page_fixes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
"""Tests for the page planner and publisher fixes found in the CSB news-message pilot.

Purpose: planner must not re-map image sources it already pointed at an uploaded asset, and must let a caller drop the
BC design-token wrapper; the publisher must read SharePoint's `&#58;` style colons and must refuse to "recover" a page
whose only component is an empty shell.

Key Input Dependencies: pwsh, scripts/new-page-migration-dry-run.ps1 (modernizing and publishing copies) and
scripts/publish-spo-page.ps1 in publishing-sharepoint-pages (real scripts, no tenant access).
Usage: python -m pytest plugins/sharepoint-workbench/tests/test_publish_page_fixes.py

Function index: run_planner_with_images, run_publisher_snippet, test_* cases.
"""
import json
import subprocess
from pathlib import Path

import pytest

from test_planner_numbered_titles import IDS, PLANNERS, PWSH, SKILLS, run_planner

PUBLISHER = SKILLS / "publishing-sharepoint-pages" / "scripts" / "publish-spo-page.ps1"
pytestmark = pytest.mark.skipif(PWSH is None, reason="pwsh is required")

BODY = '<p>Hello</p><img src="/PublishingImages/a.png" alt="a" />'
DESTINATION = "SiteAssets/Sheriff/a.png"


def run_planner_with_images(planner: Path, tmp_path: Path, **params) -> dict:
"""Plan a page whose image is in the manifest and whose library map also covers the page folder."""
(tmp_path / "images.json").write_text(json.dumps([{
"SourceWebPartId": "wp1", "SourceUrl": "https://csb.jag.gov.bc.ca/PublishingImages/a.png",
"DestinationRelativePath": DESTINATION, "OutputFileName": "a.png"}]), encoding="utf-8")
(tmp_path / "map.csv").write_text(
"source_prefix,dest_prefix,status\n/Sheriff/Pages/,/sites/AG-CSB-INTRANET-DEV/SitePages/Sheriff/,planned\n",
encoding="utf-8")
return run_planner(
planner, tmp_path, [("wp1", "Body", BODY)],
ImageManifestPath=tmp_path / "images.json", LibraryPathMapPath=tmp_path / "map.csv",
SourceHost="csb.jag.gov.bc.ca", TargetSitePath="/sites/AG-CSB-INTRANET-DEV", **params)


def run_publisher_snippet(snippet: str) -> subprocess.CompletedProcess:
script = f". '{PUBLISHER}'\n{snippet}\n"
return subprocess.run([PWSH, "-NoProfile", "-Command", script], capture_output=True, text=True)


@pytest.mark.parametrize("planner", PLANNERS, ids=IDS)
def test_manifest_image_destination_is_not_link_mapped(planner, tmp_path):
plan = run_planner_with_images(planner, tmp_path)
html = " ".join(c["Html"] for c in plan["Components"])
assert f'src="{DESTINATION}"' in html, html


@pytest.mark.parametrize("planner", PLANNERS, ids=IDS)
def test_design_token_wrapper_is_on_by_default(planner, tmp_path):
plan = run_planner_with_images(planner, tmp_path)
assert "data-sp-bc-tokens" in " ".join(c["Html"] for c in plan["Components"])


@pytest.mark.parametrize("planner", PLANNERS, ids=IDS)
def test_design_token_wrapper_can_be_disabled(planner, tmp_path):
plan = run_planner_with_images(planner, tmp_path, NoBcDesignTokens="true")
html = " ".join(c["Html"] for c in plan["Components"])
assert "data-sp-bc-tokens" not in html and "BC Sans" not in html, html


def test_inline_image_dimensions_read_encoded_colon():
done = run_publisher_snippet(
"$d = Get-SpoInlineImageDimensions -ImageTag '<img src=\"a.png\" style=\"width&#58; 120px; height&#58; 60px;\" />'\n"
"\"$($d.Width)x$($d.Height)\"")
assert done.returncode == 0, done.stderr
assert done.stdout.strip() == "120x60"


def test_inline_image_alignment_reads_encoded_colon():
html = '<div style="text-align&#58;center;"><img src="a.png" /></div>'
done = run_publisher_snippet(
f"$h = '{html}'\nGet-SpoInlineImageAlignment -Html $h -ImageIndex $h.IndexOf('<img')")
assert done.returncode == 0, done.stderr
assert done.stdout.strip() == "Center"


@pytest.mark.parametrize("existing, ok", [
("[pscustomobject]@{ Text = '' }", False),
("[pscustomobject]@{ Text = '<p>&#160;</p>' }", False),
("[pscustomobject]@{ Text = '<div><h2>Title</h2></div>' }", True),
])
def test_recovery_requires_existing_text_part_with_content(existing, ok):
done = run_publisher_snippet(
f"Assert-SpoRecoverableComponent -ExistingComponents @({existing}) "
"-FirstPackageComponent ([pscustomobject]@{ OutputType = 'TextWebPart' })\n'passed'")
if ok:
assert done.returncode == 0 and done.stdout.strip() == "passed", done.stderr
else:
assert done.returncode != 0 and "empty" in (done.stdout + done.stderr).lower()


def test_recovery_refuses_wrong_component_count():
done = run_publisher_snippet(
"Assert-SpoRecoverableComponent -ExistingComponents @() "
"-FirstPackageComponent ([pscustomobject]@{ OutputType = 'TextWebPart' })")
assert done.returncode != 0 and "exactly one" in (done.stdout + done.stderr)
Loading
Loading