UNPKG

sitecore-jss-rule-engine-nextjs

Version:

263 lines (262 loc) 15.1 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; 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 (g && (g = 0, op[0] && (_ = 0)), _) 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 }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.BasePersonalizeGraphQLSitemapService = exports.getSiteEmptyError = exports.siteError = exports.languageError = void 0; var graphql_1 = require("@sitecore-jss/sitecore-jss/graphql"); var sitecore_jss_1 = require("@sitecore-jss/sitecore-jss"); var personalizationUtils_1 = require("../../lib/personalizationUtils"); //@ts-ignore var sitecore_jss_rule_engine_1 = require("sitecore-jss-rule-engine"); /** @private */ exports.languageError = 'The list of languages cannot be empty'; exports.siteError = 'The service needs a site name'; /** * @param {string} siteName to inject into error text * @private */ function getSiteEmptyError(siteName) { return "Site \"".concat(siteName, "\" does not exist or site item tree is missing"); } exports.getSiteEmptyError = getSiteEmptyError; var languageEmptyError = 'The language must be a non-empty string'; /** * GQL query made dynamic based on schema differences between SXP and XM Cloud * @param {boolean} usesPersonalize flag to detrmine which variation of a query to run * @returns GraphQL query to fetch site paths with */ var defaultQuery = function () { /* GraphQL */ return "\nquery SitecorePersonalizeSitemapQuery(\n $siteName: String!\n $language: String!\n $includedPaths: [String]\n $excludedPaths: [String]\n $pageSize: Int = 100\n $after: String\n) {\n site {\n siteInfo(site: $siteName) {\n routes(\n language: $language\n includedPaths: $includedPaths\n excludedPaths: $excludedPaths\n first: $pageSize\n after: $after\n ){\n total\n pageInfo {\n endCursor\n hasNext\n }\n results {\n path: routePath\n route: route{\n personalizationRule:field(name:\"PersonalizationRules\"){\n value\n },\n personalizeOnEdge:field(name:\"PersonalizeOnEdge\"){\n value\n },\n isStaticRender:field(name:\"IsStaticRender\"){\n value\n }\n }\n }\n }\n }\n }\n}"; }; /** * Service that fetches the list of site pages using Sitecore's GraphQL API. * Used to handle a single site * This list is used for SSG and Export functionality. * @mixes SearchQueryService<PageListQueryResult> */ var BasePersonalizeGraphQLSitemapService = /** @class */ (function () { /** * Creates an instance of graphQL sitemap service with the provided options * @param {GraphQLSitemapServiceConfig} options instance */ function BasePersonalizeGraphQLSitemapService(options) { this.options = options; this._graphQLClient = this.getGraphQLClient(); } Object.defineProperty(BasePersonalizeGraphQLSitemapService.prototype, "graphQLClient", { /** * GraphQL client accessible by descendant classes when needed */ get: function () { return this._graphQLClient; }, enumerable: false, configurable: true }); Object.defineProperty(BasePersonalizeGraphQLSitemapService.prototype, "query", { /** * Gets the default query used for fetching the list of site pages */ get: function () { return defaultQuery(); }, enumerable: false, configurable: true }); /** * Fetch sitemap which could be used for generation of static pages during `next export`. * The `locale` parameter will be used in the item query, but since i18n is not supported, * the output paths will not include a `language` property. * @param {string} locale which application supports * @returns an array of @see StaticPath objects */ BasePersonalizeGraphQLSitemapService.prototype.fetchExportSitemap = function (locale) { return __awaiter(this, void 0, void 0, function () { var formatPath; return __generator(this, function (_a) { formatPath = function (path, _language, isStaticRender) { return ({ params: { path: path, isStaticRender: isStaticRender } }); }; return [2 /*return*/, this.fetchSitemap([locale], formatPath)]; }); }); }; /** * Fetch sitemap which could be used for generation of static pages using SSG mode * @param {string[]} locales locales which application supports * @returns an array of @see StaticPath objects */ BasePersonalizeGraphQLSitemapService.prototype.fetchSSGSitemap = function (locales) { return __awaiter(this, void 0, void 0, function () { var formatPath; return __generator(this, function (_a) { formatPath = function (path, locale, isStaticRender) { return ({ params: { path: path, isStaticRender: isStaticRender }, locale: locale }); }; return [2 /*return*/, this.fetchSitemap(locales, formatPath)]; }); }); }; BasePersonalizeGraphQLSitemapService.prototype.getTranformedPaths = function (siteName, languages, formatStaticPath) { return __awaiter(this, void 0, void 0, function () { var paths, _i, languages_1, language, results, transformedPaths; return __generator(this, function (_a) { switch (_a.label) { case 0: paths = new Array(); _i = 0, languages_1 = languages; _a.label = 1; case 1: if (!(_i < languages_1.length)) return [3 /*break*/, 5]; language = languages_1[_i]; if (language === '') { throw new RangeError(languageEmptyError); } sitecore_jss_1.debug.sitemap('fetching sitemap data for %s %s', language, siteName); return [4 /*yield*/, this.fetchLanguageSitePaths(language, siteName)]; case 2: results = _a.sent(); return [4 /*yield*/, this.transformLanguageSitePaths(results, formatStaticPath, language)]; case 3: transformedPaths = _a.sent(); paths.push.apply(paths, transformedPaths); _a.label = 4; case 4: _i++; return [3 /*break*/, 1]; case 5: return [2 /*return*/, paths]; } }); }); }; BasePersonalizeGraphQLSitemapService.prototype.transformLanguageSitePaths = function (sitePaths, formatStaticPath, language) { return __awaiter(this, void 0, void 0, function () { var formatPath, aggregatedPaths; return __generator(this, function (_a) { formatPath = function (path, isStaticRender) { return formatStaticPath(path.replace(/^\/|\/$/g, '').split('/'), language, isStaticRender); }; aggregatedPaths = []; sitePaths.forEach(function (item) { var _a, _b, _c, _d, _e, _f, _g, _h, _j; if (!item) return; aggregatedPaths.push(formatPath(item.path, ((_b = (_a = item.route) === null || _a === void 0 ? void 0 : _a.isStaticRender) === null || _b === void 0 ? void 0 : _b.value) == "1")); // check for type safety's sake - personalize may be empty depending on query type if (((_e = (_d = (_c = item.route) === null || _c === void 0 ? void 0 : _c.personalizationRule) === null || _d === void 0 ? void 0 : _d.value) === null || _e === void 0 ? void 0 : _e.length) && ((_g = (_f = item.route) === null || _f === void 0 ? void 0 : _f.personalizeOnEdge) === null || _g === void 0 ? void 0 : _g.value) == "1") { var ruleEngineInstance = (0, sitecore_jss_rule_engine_1.getRuleEngineInstance)(); var ruleEngineContext = ruleEngineInstance.getRuleEngineContext(); var parsedRule = ruleEngineInstance.parseRuleXml((_j = (_h = item.route) === null || _h === void 0 ? void 0 : _h.personalizationRule) === null || _j === void 0 ? void 0 : _j.value, ruleEngineContext); var personalizationVariationIds = (0, personalizationUtils_1.getScPersonalizedVariantIds)(parsedRule); if (personalizationVariationIds) { aggregatedPaths.push.apply(aggregatedPaths, (personalizationVariationIds.map(function (varId) { var _a, _b; return formatPath((0, personalizationUtils_1.getScPersonalizedRewrite)(item.path, varId), ((_b = (_a = item === null || item === void 0 ? void 0 : item.route) === null || _a === void 0 ? void 0 : _a.isStaticRender) === null || _b === void 0 ? void 0 : _b.value) == "1"); }) || {})); } } }); return [2 /*return*/, aggregatedPaths]; }); }); }; BasePersonalizeGraphQLSitemapService.prototype.fetchLanguageSitePaths = function (language, siteName) { var _a, _b, _c, _d; return __awaiter(this, void 0, void 0, function () { var args, results, hasNext, after, fetchResponse; return __generator(this, function (_e) { switch (_e.label) { case 0: args = { siteName: siteName, language: language, pageSize: this.options.pageSize, includedPaths: this.options.includedPaths, excludedPaths: this.options.excludedPaths, }; results = []; hasNext = true; after = ''; _e.label = 1; case 1: if (!hasNext) return [3 /*break*/, 3]; return [4 /*yield*/, this.graphQLClient.request(this.query, __assign(__assign({}, args), { after: after }))]; case 2: fetchResponse = _e.sent(); if (!((_a = fetchResponse === null || fetchResponse === void 0 ? void 0 : fetchResponse.site) === null || _a === void 0 ? void 0 : _a.siteInfo)) { throw new RangeError(getSiteEmptyError(siteName)); } else { results = results.concat((_b = fetchResponse.site.siteInfo.routes) === null || _b === void 0 ? void 0 : _b.results); hasNext = (_c = fetchResponse.site.siteInfo.routes) === null || _c === void 0 ? void 0 : _c.pageInfo.hasNext; after = (_d = fetchResponse.site.siteInfo.routes) === null || _d === void 0 ? void 0 : _d.pageInfo.endCursor; } return [3 /*break*/, 1]; case 3: return [2 /*return*/, results]; } }); }); }; /** * Gets a GraphQL client that can make requests to the API. Uses graphql-request as the default * library for fetching graphql data (@see GraphQLRequestClient). Override this method if you * want to use something else. * @returns {GraphQLClient} implementation */ BasePersonalizeGraphQLSitemapService.prototype.getGraphQLClient = function () { return new graphql_1.GraphQLRequestClient(this.options.endpoint, { apiKey: this.options.apiKey, debugger: sitecore_jss_1.debug.sitemap, }); }; return BasePersonalizeGraphQLSitemapService; }()); exports.BasePersonalizeGraphQLSitemapService = BasePersonalizeGraphQLSitemapService;