UNPKG

sp-js-provisioning

Version:
593 lines 30.5 kB
var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __values = (this && this.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; /* eslint-disable unicorn/prevent-abbreviations */ import { combine, isArray } from '@pnp/core'; import { Logger } from '@pnp/logging'; import * as xmljs from 'xml-js'; import { replaceUrlTokens } from '../util'; import { TokenHelper } from '../util/tokenhelper'; import { HandlerBase } from './handlerbase'; /** * Describes the Features Object Handler */ var Files = /** @class */ (function (_super) { __extends(Files, _super); /** * Creates a new instance of the Files class * * @param config - Provisioning config */ function Files(config) { var _this = _super.call(this, 'Files', config) || this; /** * Fetches web part contents * * @param webParts - Web parts * @param callbackFunc - Callback function that takes index of the the webpart and the retrieved XML */ _this.fetchWebPartContents = function (webParts, callbackFunction) { return new Promise(function (resolve, reject) { var fileFetchPromises = webParts.map(function (wp, index) { return (function () { return new Promise(function (_res) { return __awaiter(_this, void 0, void 0, function () { var fileSource, response, xml, object, existingProperties, updatedProperties_1, _loop_1, existingProperties_1, existingProperties_1_1, property; var e_1, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!wp.Contents.FileSrc) return [3 /*break*/, 3]; fileSource = replaceUrlTokens(this.tokenHelper.replaceTokens(wp.Contents.FileSrc), this.config); Logger.log({ data: null, level: 1 /* Info */, message: "Retrieving contents from file '" + fileSource + "'." }); return [4 /*yield*/, fetch(fileSource, { credentials: 'include', method: 'GET' })]; case 1: response = _b.sent(); return [4 /*yield*/, response.text()]; case 2: xml = _b.sent(); if (isArray(wp.PropertyOverrides)) { object = xmljs.xml2js(xml); if (object.elements[0].name === 'webParts') { existingProperties = object.elements[0].elements[0].elements[1].elements[0] .elements; updatedProperties_1 = []; _loop_1 = function (property) { var hasOverride = wp.PropertyOverrides.filter(function (po) { return po.name === property.attributes.name; }).length > 0; if (!hasOverride) { updatedProperties_1.push(property); } }; try { for (existingProperties_1 = __values(existingProperties), existingProperties_1_1 = existingProperties_1.next(); !existingProperties_1_1.done; existingProperties_1_1 = existingProperties_1.next()) { property = existingProperties_1_1.value; _loop_1(property); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (existingProperties_1_1 && !existingProperties_1_1.done && (_a = existingProperties_1.return)) _a.call(existingProperties_1); } finally { if (e_1) throw e_1.error; } } // eslint-disable-next-line unicorn/no-array-for-each wp.PropertyOverrides.forEach(function (_a) { var name = _a.name, type = _a.type, value = _a.value; updatedProperties_1.push({ attributes: { name: name, type: type }, elements: [{ text: value, type: 'text' }], name: 'property', type: 'element' }); }); object.elements[0].elements[0].elements[1].elements[0].elements = updatedProperties_1; callbackFunction(index, xmljs.js2xml(object)); _res(true); } else { callbackFunction(index, xml); _res(true); } } else { callbackFunction(index, xml); _res(true); } return [3 /*break*/, 4]; case 3: _res(true); _b.label = 4; case 4: return [2 /*return*/]; } }); }); }); })(); }); Promise.all(fileFetchPromises).then(resolve).catch(reject); }); }; return _this; } /** * Provisioning Files * * @param web - The web * @param files - The files to provision * @param context - Provisioning context */ Files.prototype.ProvisionObjects = function (web, files, context) { return __awaiter(this, void 0, void 0, function () { var ServerRelativeUrl, error_1; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: this.tokenHelper = new TokenHelper(context, this.config); _super.prototype.scope_started.call(this); if (this.config.spfxContext) { throw 'Files Handler not supported in SPFx.'; } return [4 /*yield*/, web.select('ServerRelativeUrl')()]; case 1: ServerRelativeUrl = (_a.sent()).ServerRelativeUrl; _a.label = 2; case 2: _a.trys.push([2, 4, , 5]); return [4 /*yield*/, files.reduce(function (chain, file) { return chain.then(function () { return _this.processFile(web, file, ServerRelativeUrl); }); }, Promise.resolve())]; case 3: _a.sent(); _super.prototype.scope_ended.call(this); return [3 /*break*/, 5]; case 4: error_1 = _a.sent(); _super.prototype.scope_ended.call(this, error_1); return [3 /*break*/, 5]; case 5: return [2 /*return*/]; } }); }); }; /** * Get blob for a file * * @param file - The file */ Files.prototype.getFileBlob = function (file) { return __awaiter(this, void 0, void 0, function () { var fileSourceWithoutTokens, response, fileContents, blob; return __generator(this, function (_a) { switch (_a.label) { case 0: fileSourceWithoutTokens = replaceUrlTokens(this.tokenHelper.replaceTokens(file.Src), this.config); return [4 /*yield*/, fetch(fileSourceWithoutTokens, { credentials: 'include', method: 'GET' })]; case 1: response = _a.sent(); return [4 /*yield*/, response.text()]; case 2: fileContents = _a.sent(); blob = new Blob([fileContents], { type: 'text/plain' }); return [2 /*return*/, blob]; } }); }); }; /** * Procceses a file * * @param web - The web * @param file - The file * @param webServerRelativeUrl - ServerRelativeUrl for the web */ Files.prototype.processFile = function (web, file, webServerRelativeUrl) { var _a; return __awaiter(this, void 0, void 0, function () { var blob, folderServerRelativeUrl, pnpFolder, fileServerRelativeUrl, fileAddResult, pnpFile, _b, error_2; return __generator(this, function (_c) { switch (_c.label) { case 0: Logger.log({ level: 1 /* Info */, message: "Processing file " + file.Folder + "/" + file.Url }); _c.label = 1; case 1: _c.trys.push([1, 10, , 11]); return [4 /*yield*/, this.getFileBlob(file)]; case 2: blob = _c.sent(); folderServerRelativeUrl = combine('/', webServerRelativeUrl, file.Folder); pnpFolder = web.getFolderByServerRelativePath(folderServerRelativeUrl); fileServerRelativeUrl = combine('/', folderServerRelativeUrl, file.Url); fileAddResult = void 0; pnpFile = void 0; _c.label = 3; case 3: _c.trys.push([3, 5, , 6]); return [4 /*yield*/, pnpFolder.files.addUsingPath(file.Url, blob, { Overwrite: (_a = file.Overwrite) !== null && _a !== void 0 ? _a : true })]; case 4: fileAddResult = _c.sent(); pnpFile = fileAddResult.file; fileServerRelativeUrl = fileAddResult.data.ServerRelativeUrl; return [3 /*break*/, 6]; case 5: _b = _c.sent(); pnpFile = web.getFileByServerRelativePath(fileServerRelativeUrl); return [3 /*break*/, 6]; case 6: return [4 /*yield*/, this.processProperties(web, pnpFile, file)]; case 7: _c.sent(); return [4 /*yield*/, this.processWebParts(file, webServerRelativeUrl, fileServerRelativeUrl)]; case 8: _c.sent(); return [4 /*yield*/, this.processPageListViews(web, file.WebParts, fileServerRelativeUrl)]; case 9: _c.sent(); return [3 /*break*/, 11]; case 10: error_2 = _c.sent(); throw error_2; case 11: return [2 /*return*/]; } }); }); }; /** * Remove exisiting webparts if specified * * @param webServerRelativeUrl - ServerRelativeUrl for the web * @param fileServerRelativeUrl - ServerRelativeUrl for the file * @param shouldRemove - Should web parts be removed */ Files.prototype.removeExistingWebParts = function (webServerRelativeUrl, fileServerRelativeUrl, shouldRemove) { return new Promise(function (resolve, reject) { if (shouldRemove) { Logger.log({ level: 1 /* Info */, message: "Deleting existing webpart from file " + fileServerRelativeUrl }); var clientContext_1 = new SP.ClientContext(webServerRelativeUrl); var spFile = clientContext_1 .get_web() .getFileByServerRelativeUrl(fileServerRelativeUrl); var webPartManager = spFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared); var webParts_1 = webPartManager.get_webParts(); clientContext_1.load(webParts_1); clientContext_1.executeQueryAsync(function () { var e_2, _a; try { for (var _b = __values(webParts_1.get_data()), _c = _b.next(); !_c.done; _c = _b.next()) { var wp = _c.value; wp.deleteWebPart(); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_2) throw e_2.error; } } clientContext_1.executeQueryAsync(resolve, reject); }, reject); } else { Logger.log({ level: 1 /* Info */, message: "Web parts should not be removed from file " + fileServerRelativeUrl + "." }); resolve(true); } }); }; /** * Processes web parts * * @param file - The file * @param webServerRelativeUrl - ServerRelativeUrl for the web * @param fileServerRelativeUrl - ServerRelativeUrl for the file */ Files.prototype.processWebParts = function (file, webServerRelativeUrl, fileServerRelativeUrl) { var _this = this; return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { var clientContext, spFile, webPartManager, _a, _b, wp, webPartXml, webPartDef, webPartInstance; var e_3, _c; return __generator(this, function (_d) { switch (_d.label) { case 0: Logger.log({ level: 1 /* Info */, message: "Processing webparts for file " + file.Folder + "/" + file.Url }); return [4 /*yield*/, this.removeExistingWebParts(webServerRelativeUrl, fileServerRelativeUrl, file.RemoveExistingWebParts)]; case 1: _d.sent(); if (!(file.WebParts && file.WebParts.length > 0)) return [3 /*break*/, 3]; clientContext = new SP.ClientContext(webServerRelativeUrl), spFile = clientContext .get_web() .getFileByServerRelativeUrl(fileServerRelativeUrl), webPartManager = spFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared); return [4 /*yield*/, this.fetchWebPartContents(file.WebParts, function (index, xml) { file.WebParts[index].Contents.Xml = xml; })]; case 2: _d.sent(); try { for (_a = __values(file.WebParts), _b = _a.next(); !_b.done; _b = _a.next()) { wp = _b.value; webPartXml = this.tokenHelper.replaceTokens(this.replaceWebPartXmlTokens(wp.Contents.Xml, clientContext)); webPartDef = webPartManager.importWebPart(webPartXml); webPartInstance = webPartDef.get_webPart(); Logger.log({ data: { webPartXml: webPartXml }, level: 1 /* Info */, message: "Processing webpart " + wp.Title + " for file " + file.Folder + "/" + file.Url }); webPartManager.addWebPart(webPartInstance, wp.Zone, wp.Order); clientContext.load(webPartInstance); } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (_b && !_b.done && (_c = _a.return)) _c.call(_a); } finally { if (e_3) throw e_3.error; } } clientContext.executeQueryAsync(resolve, function (sender, args) { Logger.log({ data: { error: args.get_message() }, level: 3 /* Error */, message: "Failed to process webparts for file " + file.Folder + "/" + file.Url }); reject({ sender: sender, args: args }); }); return [3 /*break*/, 4]; case 3: resolve(true); _d.label = 4; case 4: return [2 /*return*/]; } }); }); }); }; /** * Processes page list views * * @param web - The web * @param webParts - Web parts * @param fileServerRelativeUrl - ServerRelativeUrl for the file */ Files.prototype.processPageListViews = function (web, webParts, fileServerRelativeUrl) { var _this = this; return new Promise(function (resolve, reject) { if (webParts) { Logger.log({ data: { webParts: webParts, fileServerRelativeUrl: fileServerRelativeUrl }, level: 1 /* Info */, message: "Processing page list views for file " + fileServerRelativeUrl }); var listViewWebParts = webParts.filter(function (wp) { return wp.ListView; }); if (listViewWebParts.length > 0) { listViewWebParts .reduce(function (chain, wp) { return chain.then(function () { return _this.processPageListView(web, wp.ListView, fileServerRelativeUrl); }); }, Promise.resolve()) .then(function () { Logger.log({ data: {}, level: 1 /* Info */, message: "Successfully processed page list views for file " + fileServerRelativeUrl }); resolve(); }) .catch(function (error) { Logger.log({ data: { err: error, fileServerRelativeUrl: fileServerRelativeUrl }, level: 3 /* Error */, message: "Failed to process page list views for file " + fileServerRelativeUrl }); reject(error); }); } else { resolve(); } } else { resolve(); } }); }; /** * Processes page list view * * @param web - The web * @param listView - List view * @param fileServerRelativeUrl - ServerRelativeUrl for the file */ Files.prototype.processPageListView = function (web, listView, fileServerRelativeUrl) { return new Promise(function (resolve, reject) { var views = web.lists.getByTitle(listView.List).views; views() .then(function (listViews) { var wpView = listViews.filter(function (v) { return v.ServerRelativeUrl === fileServerRelativeUrl; }); if (wpView.length === 1) { var view_1 = views.getById(wpView[0].Id); var settings = listView.View.AdditionalSettings || {}; view_1 .update(settings) .then(function () { view_1.fields .removeAll() .then(function () { listView.View.ViewFields.reduce(function (chain, viewField) { return chain.then(function () { return view_1.fields.add(viewField); }); }, Promise.resolve()) .then(resolve) .catch(function (error) { Logger.log({ data: { fileServerRelativeUrl: fileServerRelativeUrl, listView: listView, err: error }, level: 3 /* Error */, message: "Failed to process page list view for file " + fileServerRelativeUrl }); reject(error); }); }) .catch(function (error) { Logger.log({ data: { fileServerRelativeUrl: fileServerRelativeUrl, listView: listView, err: error }, level: 3 /* Error */, message: "Failed to process page list view for file " + fileServerRelativeUrl }); reject(error); }); }) .catch(function (error) { Logger.log({ data: { fileServerRelativeUrl: fileServerRelativeUrl, listView: listView, err: error }, level: 3 /* Error */, message: "Failed to process page list view for file " + fileServerRelativeUrl }); reject(error); }); } else { resolve(); } }) .catch(function (error) { Logger.log({ data: { fileServerRelativeUrl: fileServerRelativeUrl, listView: listView, err: error }, level: 3 /* Error */, message: "Failed to process page list view for file " + fileServerRelativeUrl }); reject(error); }); }); }; /** * Process list item properties for the file * * @param web - The web * @param pnpFile - The PnP file * @param properties - The properties to set */ Files.prototype.processProperties = function (web, pnpFile, file) { return __awaiter(this, void 0, void 0, function () { var hasProperties, listItemAllFields; return __generator(this, function (_a) { switch (_a.label) { case 0: hasProperties = file.Properties && Object.keys(file.Properties).length > 0; if (!hasProperties) return [3 /*break*/, 3]; Logger.log({ level: 1 /* Info */, message: "Processing properties for " + file.Folder + "/" + file.Url }); return [4 /*yield*/, pnpFile.listItemAllFields .select('ID', 'ParentList/ID', 'ParentList/Title') .expand('ParentList')()]; case 1: listItemAllFields = _a.sent(); return [4 /*yield*/, web.lists .getById(listItemAllFields.ParentList.Id) .items.getById(listItemAllFields.ID) .update(file.Properties)]; case 2: _a.sent(); Logger.log({ level: 1 /* Info */, message: "Successfully processed properties for " + file.Folder + "/" + file.Url }); _a.label = 3; case 3: return [2 /*return*/]; } }); }); }; /** * Replaces tokens in a string, e.g. `{site}` * * @param str - The string * @param ctx - Client context */ Files.prototype.replaceWebPartXmlTokens = function (string, context) { var site = combine(document.location.protocol, '//', document.location.host, context.get_url()); return string.replace(/{site}/g, site); }; return Files; }(HandlerBase)); export { Files }; //# sourceMappingURL=files.js.map