Skip to content
Open
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
63 changes: 63 additions & 0 deletions docs/docs/cmd/spo/page/page-unpublish.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import Global from '../../_global.mdx';
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

# spo page unpublish

Unpublishes a modern page

## Usage

```sh
m365 spo page unpublish [options]
```

## Options

```md definition-list
`-u, --webUrl <webUrl>`
: URL of the site where the page is located.

`-n, --name <name>`
: Name of the page.
```

<Global />


## Permissions

<Tabs>
<TabItem value="Delegated">

| Resource | Permissions |
|------------|----------------|
| SharePoint | AllSites.Write |

</TabItem>
<TabItem value="Application">

| Resource | Permissions |
|------------|---------------------|
| SharePoint | Sites.ReadWrite.All |

</TabItem>
</Tabs>

## Examples

Unpublish a modern page

```sh
m365 spo page unpublish --webUrl https://contoso.sharepoint.com/sites/Marketing --name "Style guide.aspx"
```

Unpublish a modern page in a subfolder

```sh
m365 spo page unpublish --webUrl https://contoso.sharepoint.com/sites/Marketing --name "/Styles/Guide.aspx"
```

## Response

The command won't return a response on success.
5 changes: 5 additions & 0 deletions docs/src/config/sidebars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3573,6 +3573,11 @@ const sidebars: SidebarsConfig = {
label: 'page set',
id: 'cmd/spo/page/page-set'
},
{
type: 'doc',
label: 'page unpublish',
id: 'cmd/spo/page/page-unpublish'
},
{
type: 'doc',
label: 'page clientsidewebpart add',
Expand Down
1 change: 1 addition & 0 deletions src/m365/spo/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ export default {
PAGE_PUBLISH: `${prefix} page publish`,
PAGE_REMOVE: `${prefix} page remove`,
PAGE_SET: `${prefix} page set`,
PAGE_UNPUBLISH: `${prefix} page unpublish`,
PAGE_CLIENTSIDEWEBPART_ADD: `${prefix} page clientsidewebpart add`,
PAGE_COLUMN_GET: `${prefix} page column get`,
PAGE_COLUMN_LIST: `${prefix} page column list`,
Expand Down
177 changes: 177 additions & 0 deletions src/m365/spo/commands/page/page-unpublish.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import assert from 'assert';
import sinon from 'sinon';
import auth from '../../../../Auth.js';
import { cli } from '../../../../cli/cli.js';
import { CommandInfo } from '../../../../cli/CommandInfo.js';
import { Logger } from '../../../../cli/Logger.js';
import { CommandError } from '../../../../Command.js';
import request from '../../../../request.js';
import { telemetry } from '../../../../telemetry.js';
import { formatting } from '../../../../utils/formatting.js';
import { pid } from '../../../../utils/pid.js';
import { session } from '../../../../utils/session.js';
import { sinonUtil } from '../../../../utils/sinonUtil.js';
import { urlUtil } from '../../../../utils/urlUtil.js';
import commands from '../../commands.js';
import command, { options } from './page-unpublish.js';

describe(commands.PAGE_UNPUBLISH, () => {
let log: string[];
let logger: Logger;
let loggerLogSpy: sinon.SinonSpy;
let commandInfo: CommandInfo;
let postStub: sinon.SinonStub;
let commandOptionsSchema: typeof options;

const webUrl = 'https://contoso.sharepoint.com/sites/Marketing';
const serverRelativeUrl = urlUtil.getServerRelativeSiteUrl(webUrl);
const pageName = 'HR.aspx';

before(() => {
sinon.stub(auth, 'restoreAuth').resolves();
sinon.stub(telemetry, 'trackEvent').resolves();
sinon.stub(pid, 'getProcessName').returns('');
sinon.stub(session, 'getId').returns('');
auth.connection.active = true;
commandInfo = cli.getCommandInfo(command);
commandOptionsSchema = commandInfo.command.getSchemaToParse() as typeof options;
});

beforeEach(() => {
log = [];
logger = {
log: async (msg: string) => {
log.push(msg);
},
logRaw: async (msg: string) => {
log.push(msg);
},
logToStderr: async (msg: string) => {
log.push(msg);
}
};
loggerLogSpy = sinon.spy(logger, 'log');

const serverRelativePageUrl = `${serverRelativeUrl}/SitePages/${pageName}`;
postStub = sinon.stub(request, 'post').callsFake(async (opts) => {
if (opts.url === `${webUrl}/_api/web/GetFileByServerRelativePath(DecodedUrl='${formatting.encodeQueryParameter(serverRelativePageUrl)}')/UnPublish`) {
return;
}

throw 'Invalid request: ' + opts.url;
});
});

afterEach(() => {
sinonUtil.restore([
request.post
]);
});

after(() => {
sinon.restore();
auth.connection.active = false;
});

it('has correct name', () => {
assert.strictEqual(command.name, commands.PAGE_UNPUBLISH);
});

it('has a description', () => {
assert.notStrictEqual(command.description, null);
});

it('logs no command output', async () => {
await command.action(logger,
{
options: {
webUrl: webUrl,
name: pageName
}
});

assert(loggerLogSpy.notCalled);
});

it('correctly unpublishes page', async () => {
await command.action(logger,
{
options: {
webUrl: webUrl,
name: pageName
}
});

assert(postStub.calledOnce);
});

it('correctly unpublishes a page when extension is not specified', async () => {
await command.action(logger,
{
options: {
webUrl: webUrl,
name: pageName.substring(0, pageName.lastIndexOf('.')),
verbose: true
}
});

assert(postStub.calledOnce);
});

it('correctly unpublishes a nested page', async () => {
const pageUrl = '/folder1/folder2/' + pageName;
postStub.restore();

postStub = sinon.stub(request, 'post').callsFake(async (opts) => {
if (opts.url === `${webUrl}/_api/web/GetFileByServerRelativePath(DecodedUrl='${formatting.encodeQueryParameter(serverRelativeUrl + '/SitePages' + pageUrl)}')/UnPublish`) {
return;
}

throw 'Invalid request: ' + opts.url;
});

await command.action(logger,
{
options: {
webUrl: webUrl,
name: pageUrl
}
});

assert(postStub.calledOnce);
});

it('correctly handles API error', async () => {
postStub.restore();
const errorMessage = 'The file /sites/Marketing/SitePages/My-new-page.aspx does not exist.';

sinon.stub(request, 'post').rejects({
error: {
'odata.error': {
message: {
lang: 'en-US',
value: errorMessage
}
}
}
});

await assert.rejects(command.action(logger, { options: { webUrl: webUrl, name: pageName } }),
new CommandError(errorMessage));
});

it('fails validation if webUrl is not a valid SharePoint URL', async () => {
const actual = commandOptionsSchema.safeParse({ webUrl: 'foo' });
assert.strictEqual(actual.success, false);
});

it('passes validation when the webUrl is a valid SharePoint URL and name is specified', async () => {
const actual = commandOptionsSchema.safeParse({ webUrl: webUrl, name: pageName });
assert.strictEqual(actual.success, true);
});

it('passes validation when name has no extension', async () => {
const actual = commandOptionsSchema.safeParse({ webUrl: webUrl, name: 'page' });
assert.strictEqual(actual.success, true);
});
});
67 changes: 67 additions & 0 deletions src/m365/spo/commands/page/page-unpublish.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { z } from 'zod';
import { Logger } from '../../../../cli/Logger.js';
import { globalOptionsZod } from '../../../../Command.js';
import request, { CliRequestOptions } from '../../../../request.js';
import { formatting } from '../../../../utils/formatting.js';
import { urlUtil } from '../../../../utils/urlUtil.js';
import { validation } from '../../../../utils/validation.js';
import SpoCommand from '../../../base/SpoCommand.js';
import commands from '../../commands.js';

export const options = z.strictObject({
...globalOptionsZod.shape,
webUrl: z.string()
.refine(url => validation.isValidSharePointUrl(url) === true, {
error: e => `'${e.input}' is not a valid SharePoint Online site URL.`
})
.alias('u'),
name: z.string().alias('n')
});
declare type Options = z.infer<typeof options>;

interface CommandArgs {
options: Options;
}

class SpoPageUnpublishCommand extends SpoCommand {
public get name(): string {
return commands.PAGE_UNPUBLISH;
}

public get description(): string {
return 'Unpublishes a modern page';
}

public get schema(): z.ZodType {
return options;
}

public async commandAction(logger: Logger, args: CommandArgs): Promise<void> {
try {
let pageName: string = urlUtil.removeLeadingSlashes(args.options.name);
if (!pageName.toLowerCase().endsWith('.aspx')) {
pageName += '.aspx';
}

if (this.verbose) {
await logger.logToStderr(`Unpublishing page ${pageName}...`);
}

const filePath = `${urlUtil.getServerRelativeSiteUrl(args.options.webUrl)}/SitePages/${pageName}`;
const requestOptions: CliRequestOptions = {
url: `${args.options.webUrl}/_api/web/GetFileByServerRelativePath(DecodedUrl='${formatting.encodeQueryParameter(filePath)}')/UnPublish`,
headers: {
accept: 'application/json;odata=nometadata'
},
responseType: 'json'
};

await request.post(requestOptions);
}
catch (err: any) {
this.handleRejectedODataJsonPromise(err);
}
}
}

export default new SpoPageUnpublishCommand();