UNPKG

@jss-rule-engine/edge

Version:

185 lines (184 loc) 10.7 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) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); 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 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["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 }; } }; import { NextResponse, userAgent } from 'next/server'; import { GraphQLSCPersonalizeService } from './ScPersonalizeService'; import { MiddlewareBase } from './middleware'; import { getScPersonalizedRewrite } from '../../lib/personalizationUtils'; /** * Middleware / handler to support Sitecore Personalize */ var ScPersonalizeMiddleware = /** @class */ (function (_super) { __extends(ScPersonalizeMiddleware, _super); /** * @param {ScPersonalizeMiddlewareConfig} [config] Personalize middleware config */ function ScPersonalizeMiddleware(config) { var _this = _super.call(this, config) || this; _this.config = config; _this.handler = function (req, res) { return __awaiter(_this, void 0, void 0, function () { var pathname, language, hostname, queryString, startTimestamp, response, site, personalizeInfo, ua, params, variantId, basePath, rewritePath, rewriteUrl; return __generator(this, function (_a) { switch (_a.label) { case 0: pathname = req.nextUrl.pathname; language = this.getLanguage(req); hostname = this.getHostHeader(req) || this.defaultHostname; queryString = req.nextUrl.search; startTimestamp = Date.now(); console.log('scPersonalizeHandler', hostname, startTimestamp, queryString); response = res || NextResponse.next(); if (this.config.disabled && this.config.disabled(req, response)) { console.log('skipped (personalize middleware is disabled)'); return [2 /*return*/, response]; } if (response.redirected || // Don't attempt to personalize a redirect this.isPreview(req) || // No need to personalize for preview (layout data is already prepared for preview) this.excludeRoute(pathname)) { console.log('skipped (%s)', response.redirected ? 'redirected' : this.isPreview(req) ? 'preview' : 'route excluded'); return [2 /*return*/, response]; } site = this.getSite(req, res); console.log('getPersonalizeInfo', pathname, language, site.name); // Get personalization info from Experience Edge this._personalizeService.setPersonalizeContext({ url: req.url, hostname: req.headers.get('hostname') }); return [4 /*yield*/, this._personalizeService.getPersonalizeInfo(pathname, language, site.name)]; case 1: personalizeInfo = _a.sent(); if (!personalizeInfo) { // Likely an invalid route / language console.log('skipped (personalize info not found)'); return [2 /*return*/, response]; } ua = userAgent(req).ua; params = this.getExperienceParams(req); console.log('params', ua, params); variantId = personalizeInfo.activeVariantid; if (!variantId) { console.log('skipped (no variant identified)'); return [2 /*return*/, response]; } basePath = (res === null || res === void 0 ? void 0 : res.headers.get('x-sc-rewrite')) || pathname; rewritePath = getScPersonalizedRewrite(basePath, variantId); console.log('Rewritten path - ', rewritePath); rewriteUrl = req.nextUrl.clone(); rewriteUrl.pathname = rewritePath; response = NextResponse.rewrite(rewriteUrl); // Disable preflight caching to force revalidation on client-side navigation (personalization may be influenced) // See https://github.com/vercel/next.js/issues/32727 response.headers.set('x-middleware-cache', 'no-cache'); // Share rewrite path with following executed middlewares response.headers.set('x-sc-rewrite', rewritePath); // Share site name with the following executed middlewares response.cookies.set(this.SITE_SYMBOL, site.name); return [2 /*return*/, response]; } }); }); }; _this._personalizeService = new GraphQLSCPersonalizeService(__assign(__assign({}, config.edgeConfig), { fetch: fetch })); return _this; } /** * Gets the Next.js middleware handler with error handling * @returns middleware handler */ ScPersonalizeMiddleware.prototype.getHandler = function () { var _this = this; return function (req, res) { return __awaiter(_this, void 0, void 0, function () { var error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.handler(req, res)]; case 1: return [2 /*return*/, _a.sent()]; case 2: error_1 = _a.sent(); console.log('Personalize middleware failed:'); console.log(error_1); return [2 /*return*/, res || NextResponse.next()]; case 3: return [2 /*return*/]; } }); }); }; }; ScPersonalizeMiddleware.prototype.getExperienceParams = function (req) { return { // It's expected that the header name "referer" is actually a misspelling of the word "referrer" // req.referrer is used during fetching to determine the value of the Referer header of the request being made, // used as a fallback referrer: req.headers.get('referer') || req.referrer, utm: { campaign: req.nextUrl.searchParams.get('utm_campaign'), content: req.nextUrl.searchParams.get('utm_content'), medium: req.nextUrl.searchParams.get('utm_medium'), source: req.nextUrl.searchParams.get('utm_source'), }, }; }; ScPersonalizeMiddleware.prototype.excludeRoute = function (pathname) { // ignore files return pathname.includes('.') || _super.prototype.excludeRoute.call(this, pathname); }; return ScPersonalizeMiddleware; }(MiddlewareBase)); export { ScPersonalizeMiddleware };