UNPKG

tanam

Version:

Pluggable CMS for Firebase

165 lines 8.15 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const cheerio = require("cheerio"); const dust = require("dustjs-helpers"); const documentContextService = require("./services/page-context.service"); const documentService = require("./services/document.service"); const siteInfoService = require("./services/site-info.service"); const templateService = require("./services/template.service"); dust.isDebug = true; // ---------------------------------------------------------------------------- // DUST HELPERS // Implements Tanam helper extensions for the template engine // dust.helpers.debugDump = (chunk, context, bodies, params) => { const data = context.stack.head; console.log(`[dust.helpers.debugDump] ${JSON.stringify(data)}`); const prefix = !!params.prefix ? `${params.prefix}: ` : ''; const outputData = JSON.stringify(data, null, 2); if (params.to === 'console') { console.log(prefix + outputData); return chunk; } return chunk.write(outputData.replace(/</g, '\\u003c')); }; dust.helpers.document = (chunk, context, bodies, params) => __awaiter(this, void 0, void 0, function* () { console.log(`[dust.helpers.document] Getting document id: ${JSON.stringify(params.id)}`); if (!params.document) { console.error(`[dust.helpers.document] Missing reference parameter "document"`); throw new Error(`Dust helper must declare referencing context ID.`); } const pageContext = yield documentContextService.getPageContextById(params.id); yield documentService.addDependency(params.document.id, pageContext.document.id); return pageContext; }); dust.helpers.documents = (chunk, context, bodies, params) => __awaiter(this, void 0, void 0, function* () { console.log(`[dust.helpers.documents] Getting documents: ${JSON.stringify({ limit: params.limit, documentType: params.documentType, orderBy: params.orderBy, sortOrder: params.sortOrder })}`); if (!params.document) { console.error(`[dust.helpers.document] Missing reference parameter "document"`); throw new Error(`Dust helper must declare referencing context ID.`); } const pageContexts = yield documentContextService.queryPageContext(params.documentType, { limit: params.limit, orderBy: { field: params.orderBy, sortOrder: params.sortOrder, }, }); try { yield documentService.addDependency(params.document.id, pageContexts.map(pageContext => pageContext.document.id)); console.log(`[addDependencySuccess] Success`); } catch (error) { console.warn(`[addDependencyError] ${JSON.stringify(error)}`); } console.log(`[pageContextsResult] ${JSON.stringify(pageContexts)}`); return pageContexts; }); function compileTemplate(context) { return __awaiter(this, void 0, void 0, function* () { const templates = yield templateService.getTemplates(); console.log(`[renderTemplate] Theme has ${templates.length} templates.`); for (const template of templates) { console.log(`[renderTemplate] Compiling template: ${template.id}`); const source = dust.compile(template.template, template.id); dust.register(template.id, dust.loadSource(source)); } const currentThemeTemplate = context.document.documentType; console.log(`[renderTemplate] ${JSON.stringify({ currentThemeTemplate, context })}`); return new Promise((resolve, reject) => { dust.render(currentThemeTemplate, context, (err, out) => { if (err) { console.log(`[renderDocument] Error rendering: ${JSON.stringify({ err, out })}`); reject(JSON.stringify(err)); return; } console.log(`[renderDocument] Finished rendering`); console.log(`[renderDocument-Result] ${JSON.stringify(out)}`); resolve(out); }); }); }); } exports.compileTemplate = compileTemplate; function renderPage404() { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { const template = yield templateService.getTemplate404(); if (!template) { console.log(`[compileTemplate404] template http404 not found`); reject(); } const source = dust.compile(template.template, template.id); dust.register(template.id, dust.loadSource(source)); dust.render('http404', {}, (err, out) => { if (err) { console.log(`[renderDocument] Error rendering: ${JSON.stringify({ err, out })}`); reject(); } console.log(`[renderDocument] Finished rendering`); console.log(`[renderDocument-Result] ${JSON.stringify(out)}`); const $ = cheerio.load(out); resolve($.html()); }); })); }); } exports.renderPage404 = renderPage404; function renderPage(context) { return __awaiter(this, void 0, void 0, function* () { const siteInfo = yield siteInfoService.getSiteInfo(); const template = yield compileTemplate(context); if (!template) { console.error(`No template rendered for document ${context.document.id}`); return null; } const $ = cheerio.load(template); const $head = $('head'); const $body = $('body'); // Add canonical link if ($head.find('link[rel="canonical"]').length === 0) { // Ony add canonical link data if not already present in document $head.append(`<link rel="canonical" href="${context.document.canonicalUrl || context.document.permalink}">`); } // Add Google Analytics tracking if (siteInfo.analytics && siteInfo.analytics.startsWith('UA')) { $head.prepend(`<!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=${siteInfo.analytics}"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '${siteInfo.analytics}'); </script>`); } else if (siteInfo.analytics && siteInfo.analytics.startsWith('GTM')) { $head.prepend(`<!-- Google Tag Manager --> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','${siteInfo.analytics}');</script> <!-- End Google Tag Manager -->`); $body.prepend(`<!-- Google Tag Manager (noscript) --> <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=${siteInfo.analytics}" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <!-- End Google Tag Manager (noscript) -->`); } return $.html(); }); } exports.renderPage = renderPage; //# sourceMappingURL=render.js.map