bajo-template 1.2.5 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/.github/FUNDING.yml +13 -0
  2. package/.github/workflows/repo-lockdown.yml +24 -0
  3. package/.jsdoc.conf.json +42 -0
  4. package/README.md +49 -1
  5. package/docs/BajoTemplate.html +3 -0
  6. package/docs/data/search.json +1 -0
  7. package/docs/fonts/Inconsolata-Regular.ttf +0 -0
  8. package/docs/fonts/OpenSans-Regular.ttf +0 -0
  9. package/docs/fonts/WorkSans-Bold.ttf +0 -0
  10. package/docs/global.html +3 -0
  11. package/docs/index.html +3 -0
  12. package/docs/index.js.html +375 -0
  13. package/docs/scripts/core.js +726 -0
  14. package/docs/scripts/core.min.js +23 -0
  15. package/docs/scripts/resize.js +90 -0
  16. package/docs/scripts/search.js +265 -0
  17. package/docs/scripts/search.min.js +6 -0
  18. package/docs/scripts/third-party/Apache-License-2.0.txt +202 -0
  19. package/docs/scripts/third-party/fuse.js +9 -0
  20. package/docs/scripts/third-party/hljs-line-num-original.js +369 -0
  21. package/docs/scripts/third-party/hljs-line-num.js +1 -0
  22. package/docs/scripts/third-party/hljs-original.js +5171 -0
  23. package/docs/scripts/third-party/hljs.js +1 -0
  24. package/docs/scripts/third-party/popper.js +5 -0
  25. package/docs/scripts/third-party/tippy.js +1 -0
  26. package/docs/scripts/third-party/tocbot.js +672 -0
  27. package/docs/scripts/third-party/tocbot.min.js +1 -0
  28. package/docs/static/bitcoin.jpeg +0 -0
  29. package/docs/static/home.md +23 -0
  30. package/docs/static/logo-ecosystem.png +0 -0
  31. package/docs/static/logo.png +0 -0
  32. package/docs/styles/clean-jsdoc-theme-base.css +1159 -0
  33. package/docs/styles/clean-jsdoc-theme-dark.css +412 -0
  34. package/docs/styles/clean-jsdoc-theme-light.css +482 -0
  35. package/docs/styles/clean-jsdoc-theme-scrollbar.css +30 -0
  36. package/docs/styles/clean-jsdoc-theme-without-scrollbar.min.css +1 -0
  37. package/docs/styles/clean-jsdoc-theme.min.css +1 -0
  38. package/index.js +42 -28
  39. package/lib/resolve-resource.js +8 -8
  40. package/package.json +34 -29
  41. package/wiki/CONFIG.md +3 -0
  42. package/wiki/CONTRIBUTING.md +5 -0
  43. /package/{bajo → extend/bajo}/intl/en-US.json +0 -0
  44. /package/{bajo → extend/bajo}/intl/id.json +0 -0
  45. /package/{bajoTemplate → extend/bajoTemplate}/layout/default.html +0 -0
  46. /package/{bajoTemplate → extend/bajoTemplate}/layout/email.html +0 -0
  47. /package/{bajoTemplate → extend/bajoTemplate}/layout/email.id.html +0 -0
  48. /package/{bajoTemplate → extend/bajoTemplate}/partial/script-block.html +0 -0
  49. /package/{bajoTemplate → extend/bajoTemplate}/partial/style-block.html +0 -0
@@ -0,0 +1,375 @@
1
+ <!DOCTYPE html><html lang="en" style="font-size:16px"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Source: index.js</title><!--[if lt IE 9]>
2
+ <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
3
+ <![endif]--><script src="scripts/third-party/hljs.js" defer="defer"></script><script src="scripts/third-party/hljs-line-num.js" defer="defer"></script><script src="scripts/third-party/popper.js" defer="defer"></script><script src="scripts/third-party/tippy.js" defer="defer"></script><script src="scripts/third-party/tocbot.min.js"></script><script>var baseURL="/",locationPathname="";baseURL=(locationPathname=document.location.pathname).substr(0,locationPathname.lastIndexOf("/")+1)</script><link rel="stylesheet" href="styles/clean-jsdoc-theme.min.css"><svg aria-hidden="true" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="display:none"><defs><symbol id="copy-icon" viewbox="0 0 488.3 488.3"><g><path d="M314.25,85.4h-227c-21.3,0-38.6,17.3-38.6,38.6v325.7c0,21.3,17.3,38.6,38.6,38.6h227c21.3,0,38.6-17.3,38.6-38.6V124 C352.75,102.7,335.45,85.4,314.25,85.4z M325.75,449.6c0,6.4-5.2,11.6-11.6,11.6h-227c-6.4,0-11.6-5.2-11.6-11.6V124 c0-6.4,5.2-11.6,11.6-11.6h227c6.4,0,11.6,5.2,11.6,11.6V449.6z"/><path d="M401.05,0h-227c-21.3,0-38.6,17.3-38.6,38.6c0,7.5,6,13.5,13.5,13.5s13.5-6,13.5-13.5c0-6.4,5.2-11.6,11.6-11.6h227 c6.4,0,11.6,5.2,11.6,11.6v325.7c0,6.4-5.2,11.6-11.6,11.6c-7.5,0-13.5,6-13.5,13.5s6,13.5,13.5,13.5c21.3,0,38.6-17.3,38.6-38.6 V38.6C439.65,17.3,422.35,0,401.05,0z"/></g></symbol><symbol id="search-icon" viewBox="0 0 512 512"><g><g><path d="M225.474,0C101.151,0,0,101.151,0,225.474c0,124.33,101.151,225.474,225.474,225.474 c124.33,0,225.474-101.144,225.474-225.474C450.948,101.151,349.804,0,225.474,0z M225.474,409.323 c-101.373,0-183.848-82.475-183.848-183.848S124.101,41.626,225.474,41.626s183.848,82.475,183.848,183.848 S326.847,409.323,225.474,409.323z"/></g></g><g><g><path d="M505.902,476.472L386.574,357.144c-8.131-8.131-21.299-8.131-29.43,0c-8.131,8.124-8.131,21.306,0,29.43l119.328,119.328 c4.065,4.065,9.387,6.098,14.715,6.098c5.321,0,10.649-2.033,14.715-6.098C514.033,497.778,514.033,484.596,505.902,476.472z"/></g></g></symbol><symbol id="font-size-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M11.246 15H4.754l-2 5H.6L7 4h2l6.4 16h-2.154l-2-5zm-.8-2L8 6.885 5.554 13h4.892zM21 12.535V12h2v8h-2v-.535a4 4 0 1 1 0-6.93zM19 18a2 2 0 1 0 0-4 2 2 0 0 0 0 4z"/></symbol><symbol id="add-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M11 11V5h2v6h6v2h-6v6h-2v-6H5v-2z"/></symbol><symbol id="minus-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M5 11h14v2H5z"/></symbol><symbol id="dark-theme-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M10 7a7 7 0 0 0 12 4.9v.1c0 5.523-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2h.1A6.979 6.979 0 0 0 10 7zm-6 5a8 8 0 0 0 15.062 3.762A9 9 0 0 1 8.238 4.938 7.999 7.999 0 0 0 4 12z"/></symbol><symbol id="light-theme-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M12 18a6 6 0 1 1 0-12 6 6 0 0 1 0 12zm0-2a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM11 1h2v3h-2V1zm0 19h2v3h-2v-3zM3.515 4.929l1.414-1.414L7.05 5.636 5.636 7.05 3.515 4.93zM16.95 18.364l1.414-1.414 2.121 2.121-1.414 1.414-2.121-2.121zm2.121-14.85l1.414 1.415-2.121 2.121-1.414-1.414 2.121-2.121zM5.636 16.95l1.414 1.414-2.121 2.121-1.414-1.414 2.121-2.121zM23 11v2h-3v-2h3zM4 11v2H1v-2h3z"/></symbol><symbol id="reset-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M18.537 19.567A9.961 9.961 0 0 1 12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10c0 2.136-.67 4.116-1.81 5.74L17 12h3a8 8 0 1 0-2.46 5.772l.997 1.795z"/></symbol><symbol id="down-icon" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M12.7803 6.21967C13.0732 6.51256 13.0732 6.98744 12.7803 7.28033L8.53033 11.5303C8.23744 11.8232 7.76256 11.8232 7.46967 11.5303L3.21967 7.28033C2.92678 6.98744 2.92678 6.51256 3.21967 6.21967C3.51256 5.92678 3.98744 5.92678 4.28033 6.21967L8 9.93934L11.7197 6.21967C12.0126 5.92678 12.4874 5.92678 12.7803 6.21967Z"></path></symbol><symbol id="codepen-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M16.5 13.202L13 15.535v3.596L19.197 15 16.5 13.202zM14.697 12L12 10.202 9.303 12 12 13.798 14.697 12zM20 10.869L18.303 12 20 13.131V10.87zM19.197 9L13 4.869v3.596l3.5 2.333L19.197 9zM7.5 10.798L11 8.465V4.869L4.803 9 7.5 10.798zM4.803 15L11 19.131v-3.596l-3.5-2.333L4.803 15zM4 13.131L5.697 12 4 10.869v2.262zM2 9a1 1 0 0 1 .445-.832l9-6a1 1 0 0 1 1.11 0l9 6A1 1 0 0 1 22 9v6a1 1 0 0 1-.445.832l-9 6a1 1 0 0 1-1.11 0l-9-6A1 1 0 0 1 2 15V9z"/></symbol><symbol id="close-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M12 10.586l4.95-4.95 1.414 1.414-4.95 4.95 4.95 4.95-1.414 1.414-4.95-4.95-4.95 4.95-1.414-1.414 4.95-4.95-4.95-4.95L7.05 5.636z"/></symbol><symbol id="menu-icon" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"/><path d="M3 4h18v2H3V4zm0 7h18v2H3v-2zm0 7h18v2H3v-2z"/></symbol></defs></svg></head><body data-theme="light"><div class="sidebar-container"><div class="sidebar" id="sidebar"><a href="/" class="sidebar-title sidebar-title-anchor">BajoTemplate API</a><div class="sidebar-items-container"><div class="sidebar-section-title with-arrow" data-isopen="false" id="sidebar-classes"><div>Classes</div><svg><use xlink:href="#down-icon"></use></svg></div><div class="sidebar-section-children-container"><div class="sidebar-section-children"><a href="BajoTemplate.html">BajoTemplate</a></div></div><div class="sidebar-section-title with-arrow" data-isopen="false" id="sidebar-global"><div>Global</div><svg><use xlink:href="#down-icon"></use></svg></div><div class="sidebar-section-children-container"><div class="sidebar-section-children"><a href="global.html#factory">factory</a></div></div></div></div></div><div class="navbar-container" id="VuAckcnZhf"><nav class="navbar"><div class="navbar-left-items"><div class="navbar-item"><a id="" href="https://www.npmjs.com/package/bajo-template" target="">NPM</a></div><div class="navbar-item"><a id="" href="https://github.com/ardhi/bajo-template" target="">Github</a></div><div class="navbar-item"><a id="" href="https://bajo.app" target="">Bajo</a></div></div><div class="navbar-right-items"><div class="navbar-right-item"><button class="icon-button search-button" aria-label="open-search"><svg><use xlink:href="#search-icon"></use></svg></button></div><div class="navbar-right-item"><button class="icon-button theme-toggle" aria-label="toggle-theme"><svg><use class="theme-svg-use" xlink:href="#dark-theme-icon"></use></svg></button></div><div class="navbar-right-item"><button class="icon-button font-size" aria-label="change-font-size"><svg><use xlink:href="#font-size-icon"></use></svg></button></div></div><nav></nav></nav></div><div class="toc-container"><div class="toc-content"><span class="bold">On this page</span><div id="eed4d2a0bfd64539bb9df78095dec881"></div></div></div><div class="body-wrapper"><div class="main-content"><div class="main-wrapper"><section id="source-page" class="source-page"><header><h1 id="title" class="has-anchor">index.js</h1></header><article><pre class="prettyprint source lang-js"><code>import resolveResource, { filecheck } from './lib/resolve-resource.js'
4
+ import crypto from 'crypto'
5
+ import path from 'path'
6
+
7
+ /**
8
+ * Plugin factory
9
+ *
10
+ * @param {string} pkgName - NPM package name
11
+ * @returns {class}
12
+ */
13
+ async function factory (pkgName) {
14
+ const me = this
15
+
16
+ /**
17
+ * BajoTemplate class
18
+ *
19
+ * @class
20
+ */
21
+ class BajoTemplate extends this.app.pluginClass.base {
22
+ static alias = 'tpl'
23
+
24
+ constructor () {
25
+ super(pkgName, me.app)
26
+ this.config = {
27
+ layout: {
28
+ fallback: true
29
+ },
30
+ loopDetectorDur: '1m',
31
+ cache: {
32
+ maxAgeDur: '1s'
33
+ }
34
+ }
35
+ this.loopDetector = {}
36
+ }
37
+
38
+ buildCompileImports = (lang) => {
39
+ const _ = this.app.lib._
40
+ return {
41
+ _,
42
+ _t: (text, ...args) => {
43
+ const params = [...args, { lang }]
44
+ return this.t(text, ...params)
45
+ },
46
+ _format: (val, type, opts = {}) => {
47
+ opts.lang = opts.lang ?? lang
48
+ return this.app.bajo.format(val, type, opts)
49
+ },
50
+ _findRoute: (input) => {
51
+ if (!this.app.waibu) return false
52
+ return this.app.waibu.findRoute(input)
53
+ },
54
+ _routePath: (input, opts) => {
55
+ if (!this.app.waibu) return input
56
+ return this.app.waibu.routePath(input, opts)
57
+ },
58
+ _titleize: this.app.lib.aneka.titleize,
59
+ _hasPlugin: name => this.app.getAllNs().includes(name),
60
+ _jsonStringify: this.app.waibuMpa.jsonStringify,
61
+ _parseMarkdown: content => {
62
+ if (!this.app.bajoMarkdown) return content
63
+ return this.app.bajoMarkdown.parseContent(content)
64
+ },
65
+ _excerpt: (content, words) => {
66
+ return this.getExcerpt(content, words)
67
+ },
68
+ _dump: (value, noPre) => {
69
+ return (noPre ? '' : '&lt;pre>') + JSON.stringify(value, null, 2) + (noPre ? '' : '&lt;/pre>')
70
+ }
71
+ }
72
+ }
73
+
74
+ _clearLoopDetector = () => {
75
+ const { omit } = this.app.lib._
76
+ const now = Date.now()
77
+ const omitted = []
78
+ for (const groupId in this.loopDetector) {
79
+ const history = this.loopDetector[groupId]
80
+ if ((history.ts + this.config.loopDetectorDur) &lt; now) omitted.push(groupId)
81
+ }
82
+ this.loopDetector = omit(this.loopDetector, omitted)
83
+ }
84
+
85
+ _detectLoop = (tpl, file, opts) => {
86
+ const { last } = this.app.lib._
87
+ if (opts.groupId) {
88
+ if (this.loopDetector[opts.groupId]) {
89
+ if (last(this.loopDetector[opts.groupId].file) === file &amp;&amp; path.basename(file)[0] !== '~') {
90
+ throw this.error('loopDetected%s%s', tpl, file)
91
+ }
92
+ this.loopDetector[opts.groupId].file.push(file)
93
+ } else {
94
+ this.loopDetector[opts.groupId] = {
95
+ ts: Date.now(),
96
+ file: [file]
97
+ }
98
+ }
99
+ }
100
+ }
101
+
102
+ _render = async (tpl, locals = {}, opts = {}) => {
103
+ this._clearLoopDetector()
104
+ const { trim, isEmpty, last } = this.app.lib._
105
+ const { fs } = this.app.lib
106
+ const { breakNsPath } = this.app.bajo
107
+
108
+ let resp
109
+ let subNs
110
+ if (path.isAbsolute(tpl)) resp = { file: tpl }
111
+ else {
112
+ subNs = breakNsPath(tpl).subNs
113
+ if (subNs === 'template') {
114
+ resp = this.resolveTemplate(tpl, opts)
115
+ } else if (subNs === 'partial') {
116
+ resp = this.resolvePartial(tpl, opts)
117
+ }
118
+ }
119
+ if (!resp) throw this.error('resourceNotFound%s', tpl)
120
+ const { file } = resp
121
+ this._detectLoop(tpl, file, opts)
122
+ const fileContent = trim(fs.readFileSync(file, 'utf8'))
123
+ let { content, frontMatter } = this.splitContent(fileContent)
124
+ if (isEmpty(content)) {
125
+ const sep = '/waibuMpa/route/'
126
+ if (path.isAbsolute(tpl) &amp;&amp; tpl.includes(sep)) { // for direct waibuMpa's route
127
+ const parts = tpl.split(sep)
128
+ const ns = last(parts[0].split('/'))
129
+ content = `&lt;!-- include ${ns}.partial:/${parts[1]} -->`
130
+ } else content = '&lt;!-- include ' + tpl.replace('.template', '.partial') + ' -->'
131
+ }
132
+ opts.ext = path.extname(file)
133
+ opts.frontMatter = frontMatter
134
+ opts.partial = opts.partial ?? subNs === 'partial'
135
+ return await this._renderString(content, locals, opts)
136
+ }
137
+
138
+ _handleInclude = async (content, locals = {}, opts = {}) => {
139
+ const { isEmpty, omit, template, merge } = this.app.lib._
140
+ const { extractText } = this.app.lib.aneka
141
+ const { breakNsPath } = this.app.bajo
142
+ const start = '&lt;!-- include '
143
+ const end = ' -->'
144
+ const imports = this.buildCompileImports(opts.lang)
145
+ while (content.includes(start) &amp;&amp; content.includes(end)) {
146
+ const { pattern, result: rsc } = extractText(content, start, end)
147
+ if (!isEmpty(rsc)) {
148
+ let attr = {}
149
+ let [resource, sattr] = rsc.split('|')
150
+ if (!isEmpty(sattr)) {
151
+ try {
152
+ attr = JSON.parse(sattr)
153
+ } catch (err) {}
154
+ }
155
+ const fn = template(resource, { imports })
156
+ resource = fn(locals)
157
+ const { subNs } = breakNsPath(resource)
158
+ let result = ''
159
+ if (subNs === 'partial') {
160
+ const { req, reply } = opts
161
+ const nopts = omit(opts, ['req', 'reply', 'postProcessor'])
162
+ nopts.partial = true
163
+ nopts.req = req
164
+ nopts.reply = reply
165
+ const nlocals = merge({}, locals, { attr })
166
+ result = await this.render(resource, nlocals, nopts)
167
+ }
168
+ content = content.replace(pattern, result)
169
+ }
170
+ }
171
+ return content
172
+ }
173
+
174
+ _renderString = async (content, locals = {}, opts = {}) => {
175
+ const { merge, without, isString, omit, kebabCase } = this.app.lib._
176
+ if (opts.ext === '.md' &amp;&amp; this.app.bajoMarkdown) {
177
+ content = await this.compile(content, locals, { lang: opts.lang, ttl: -1 }) // markdown can't process template tags, hence preprocess here
178
+ content = this.app.bajoMarkdown.parse(content)
179
+ }
180
+ let layout
181
+ if (!opts.partial) {
182
+ const pageFm = await this.parseFrontMatter(opts.frontMatter, opts.lang)
183
+ if (pageFm.layout) opts.layout = pageFm.layout
184
+ if (pageFm.scriptBlock) opts.scriptBlock = pageFm.scriptBlock
185
+ if (pageFm.styleBlock) opts.styleBlock = pageFm.styleBlock
186
+ locals.page = merge({}, locals.page, omit(pageFm, ['layout']))
187
+ layout = opts.layout ?? locals.page.layout ?? (locals.page.ns ? `${locals.page.ns}.layout:/default.html` : 'main.layout:/default.html')
188
+ for (const b of ['scriptBlock', 'styleBlock']) {
189
+ locals.page[b] = pageFm[b] ?? opts[b] ?? (locals.page.ns ? `${locals.page.ns}.partial:/${kebabCase(b)}.html` : `bajoTemplate.partial:/${kebabCase(b)}.html`)
190
+ }
191
+ const ext = path.extname(layout)
192
+ const { file } = this.resolveLayout(layout, opts)
193
+ let { content: layoutContent, frontMatter: layoutFm } = this.splitContent(file, true)
194
+ layoutFm = await this.parseFrontMatter(layoutFm, opts.lang)
195
+ const keys = without(Object.keys(layoutFm), 'css', 'scripts')
196
+ if (['.html'].includes(ext)) {
197
+ for (const item of ['css', 'scripts']) {
198
+ locals.page[item] = locals.page[item] ?? []
199
+ if (isString(locals.page[item])) locals.page[item] = [locals.page[item]]
200
+ layoutFm[item] = layoutFm[item] ?? []
201
+ if (isString(layoutFm[item])) layoutFm[item] = [layoutFm[item]]
202
+ locals.page[item].unshift(...layoutFm[item])
203
+ }
204
+ }
205
+ for (const key of keys) {
206
+ locals.page[key] = locals.page[key] ?? layoutFm[key]
207
+ }
208
+ if (layoutFm.title &amp;&amp; !locals.page.title) locals.page.title = layoutFm.title
209
+ content = layoutContent.replace('&lt;!-- body -->', content)
210
+ const appTitle = this.t(locals.page.appTitle, { lang: opts.lang })
211
+ const fullTitle = locals.page.title ? `${locals.page.title} - ${appTitle}` : appTitle
212
+ locals.page.fullTitle = locals.fullTitle ?? fullTitle
213
+ }
214
+ content = await this.compile(content, locals, { lang: opts.lang, ttl: this.config.cache.maxAgeDur })
215
+ return await this._handleInclude(content, locals, opts)
216
+ }
217
+
218
+ getResource = (name) => {
219
+ const subNses = ['layout', 'template', 'partial']
220
+ const { ns, path, subNs, subSubNs, qs } = this.app.bajo.breakNsPath(name)
221
+ const plugin = this.app.bajo.getPlugin(ns)
222
+ const dir = `${plugin.dir.pkg}/extend/bajoTemplate`
223
+ if (!subNses.includes(subNs)) throw this.error('unknownResource%s', name)
224
+ const fullPath = subSubNs ? `${dir}/${subSubNs}/${subNs}${path}` : `${dir}/${subNs}${path}`
225
+ return { ns, subNs, subSubNs, path, qs, fullPath }
226
+ }
227
+
228
+ parseFrontMatter = async (input = '', lang) => {
229
+ const { isEmpty, isPlainObject, isArray, filter, map } = this.app.lib._
230
+ const { parseObject } = this.app.bajo
231
+ const handlers = map(filter(this.app.configHandlers, h => !['.js'].includes(h.ext)), h => h.readHandler)
232
+ let success
233
+ for (const handler of handlers) {
234
+ if (success) break
235
+ try {
236
+ const result = await handler(input, true)
237
+ if (isPlainObject(result) || isArray(result)) success = result
238
+ } catch (err) {
239
+ }
240
+ }
241
+ if (isEmpty(success)) return {}
242
+ return parseObject(success, { parseValue: true, lang }) ?? {}
243
+ }
244
+
245
+ compile = async (content, locals, { lang, ttl = 0 } = {}) => {
246
+ locals.attr = locals.attr ?? {}
247
+ const _ = this.app.lib._
248
+ const { template } = _
249
+ const cache = this.app.bajoCache
250
+ let canCache = this.config.cache !== false &amp;&amp; cache &amp;&amp; this.app.bajo.config.env !== 'dev'
251
+ if (ttl === -1) canCache = false
252
+ const opts = {
253
+ imports: this.buildCompileImports(lang)
254
+ }
255
+
256
+ let item
257
+ if (canCache) {
258
+ const key = 'fn:' + crypto.createHash('md5').update(content).digest('hex')
259
+ const value = template(content, opts)
260
+ item = await cache.sync({ key, value, ttl })
261
+ } else {
262
+ item = template(content, opts)
263
+ }
264
+ return item(locals)
265
+ }
266
+
267
+ renderString = async (content, locals = {}, opts = {}) => {
268
+ let text = await this._renderString(content, locals, opts)
269
+ if (opts.postProcessor) text = await opts.postProcessor({ text, locals, opts })
270
+ return text
271
+ }
272
+
273
+ render = async (tpl, locals = {}, opts = {}) => {
274
+ const { runHook, breakNsPath } = this.app.bajo
275
+ const { upperFirst } = this.app.lib._
276
+ const cache = this.app.bajoCache
277
+ const key = crypto.createHash('md5').update(`${tpl}:${JSON.stringify(locals)}`).digest('hex')
278
+ let subNs
279
+ const isAbsolute = path.isAbsolute(tpl)
280
+ if (!isAbsolute) subNs = breakNsPath(tpl).subNs
281
+ const canCache = (isAbsolute || subNs === 'template') &amp;&amp; this.config.cache !== false &amp;&amp; cache &amp;&amp; this.app.bajo.config.env !== 'dev'
282
+ if (canCache) {
283
+ const item = await cache.get({ key })
284
+ if (item) return item
285
+ }
286
+ if (subNs) await runHook(`${this.ns}:beforeRender${upperFirst(subNs)}`, { tpl, locals, opts })
287
+ let text = await this._render(tpl, locals, opts)
288
+ if (opts.postProcessor) text = await opts.postProcessor({ text, locals, opts })
289
+ if (subNs) await runHook(`${this.ns}:afterRender${upperFirst(subNs)}`, { tpl, locals, opts, text })
290
+ if (canCache) await cache.set({ key, value: text, ttl: opts.cacheMaxAge ?? this.config.cache.maxAgeDur })
291
+ return text
292
+ }
293
+
294
+ resolveLayout = (item = '', opts = {}) => {
295
+ const { find } = this.app.lib._
296
+ const fallbackHandler = ({ file, exts, ns, subSubNs, type, theme }) => {
297
+ const dir = ''
298
+ const base = 'default'
299
+ if (!this.config.layout.fallback) return false
300
+ // check main: theme specific
301
+ if (theme &amp;&amp; !file) {
302
+ const check = `${this.app.main.dir.pkg}/extend/${this.ns}/${type}/_${theme}`
303
+ file = filecheck.call(this, { dir, base, exts, check })
304
+ }
305
+ // check main: common
306
+ if (!file) {
307
+ const check = `${this.app.main.dir.pkg}/extend/${this.ns}/${type}`
308
+ file = filecheck.call(this, { dir, base, exts, check })
309
+ }
310
+ if (theme &amp;&amp; !file) {
311
+ const otheme = find(this.app.waibuMpa.themes, { name: theme })
312
+ const check = `${otheme.plugin.dir.pkg}/extend/${this.ns}/extend/${this.ns}/${type}`
313
+ file = filecheck.call(this, { dir, base, exts, check })
314
+ }
315
+ // check fallback: common
316
+ if (!file) {
317
+ const check = `${this.app[ns].dir.pkg}/extend/${this.ns}/${subSubNs ? (subSubNs + '/') : ''}${type}`
318
+ file = filecheck.call(this, { dir, base, exts, check })
319
+ }
320
+ // check general fallback
321
+ if (!file) {
322
+ const check = `${this.dir.pkg}/extend/${this.ns}/${subSubNs ? (subSubNs + '/') : ''}${type}`
323
+ file = filecheck.call(this, { dir, base, exts, check })
324
+ }
325
+ return file
326
+ }
327
+
328
+ return resolveResource.call(this, 'layout', item, opts, fallbackHandler)
329
+ }
330
+
331
+ resolvePartial = (item = '', opts = {}) => {
332
+ return resolveResource.call(this, 'partial', item, opts)
333
+ }
334
+
335
+ resolveTemplate = (item = '', opts = {}) => {
336
+ return resolveResource.call(this, 'template', item, opts)
337
+ }
338
+
339
+ splitContent = (input, readFile) => {
340
+ const { fs } = this.app.lib
341
+ const start = '---\n'
342
+ const end = '\n---'
343
+
344
+ let content = readFile ? fs.readFileSync(input, 'utf8') : input
345
+ let text = content.replaceAll('\r\n', '\n')
346
+ const open = text.indexOf(start)
347
+ let frontMatter
348
+ if (open > -1) {
349
+ text = text.slice(open + start.length)
350
+ const close = text.indexOf(end)
351
+ if (close > -1) {
352
+ frontMatter = text.slice(0, close)
353
+ content = text.slice(close + end.length)
354
+ }
355
+ }
356
+ frontMatter = frontMatter ?? ''
357
+ content = content ?? ''
358
+ return { frontMatter, content }
359
+ }
360
+
361
+ // based on: https://medium.com/@paulohfev/problem-solving-how-to-create-an-excerpt-fdb048687928
362
+ getExcerpt = (content, maxWords = 50, trailChars = '...') => {
363
+ const listOfWords = content.trim().split(' ')
364
+ const truncatedContent = listOfWords.slice(0, maxWords).join(' ')
365
+ const excerpt = truncatedContent + trailChars
366
+ const output = listOfWords.length > maxWords ? excerpt : content
367
+ return output
368
+ }
369
+ }
370
+
371
+ return BajoTemplate
372
+ }
373
+
374
+ export default factory
375
+ </code></pre></article></section></div></div></div><div class="search-container" id="PkfLWpAbet" style="display:none"><div class="wrapper" id="iCxFxjkHbP"><button class="icon-button search-close-button" id="VjLlGakifb" aria-label="close search"><svg><use xlink:href="#close-icon"></use></svg></button><div class="search-box-c"><svg><use xlink:href="#search-icon"></use></svg> <input type="text" id="vpcKVYIppa" class="search-input" placeholder="Search..." autofocus></div><div class="search-result-c" id="fWwVHRuDuN"><span class="search-result-c-text">Type anything to view search result</span></div></div></div><div class="mobile-menu-icon-container"><button class="icon-button" id="mobile-menu" data-isopen="false" aria-label="menu"><svg><use xlink:href="#menu-icon"></use></svg></button></div><div id="mobile-sidebar" class="mobile-sidebar-container"><div class="mobile-sidebar-wrapper"><a href="/" class="sidebar-title sidebar-title-anchor">BajoTemplate API</a><div class="mobile-nav-links"><div class="navbar-item"><a id="" href="https://www.npmjs.com/package/bajo-template" target="">NPM</a></div><div class="navbar-item"><a id="" href="https://github.com/ardhi/bajo-template" target="">Github</a></div><div class="navbar-item"><a id="" href="https://bajo.app" target="">Bajo</a></div></div><div class="mobile-sidebar-items-c"><div class="sidebar-section-title with-arrow" data-isopen="false" id="sidebar-classes"><div>Classes</div><svg><use xlink:href="#down-icon"></use></svg></div><div class="sidebar-section-children-container"><div class="sidebar-section-children"><a href="BajoTemplate.html">BajoTemplate</a></div></div><div class="sidebar-section-title with-arrow" data-isopen="false" id="sidebar-global"><div>Global</div><svg><use xlink:href="#down-icon"></use></svg></div><div class="sidebar-section-children-container"><div class="sidebar-section-children"><a href="global.html#factory">factory</a></div></div></div><div class="mobile-navbar-actions"><div class="navbar-right-item"><button class="icon-button search-button" aria-label="open-search"><svg><use xlink:href="#search-icon"></use></svg></button></div><div class="navbar-right-item"><button class="icon-button theme-toggle" aria-label="toggle-theme"><svg><use class="theme-svg-use" xlink:href="#dark-theme-icon"></use></svg></button></div><div class="navbar-right-item"><button class="icon-button font-size" aria-label="change-font-size"><svg><use xlink:href="#font-size-icon"></use></svg></button></div></div></div></div><script type="text/javascript" src="scripts/core.min.js"></script><script src="scripts/search.min.js" defer="defer"></script><script src="scripts/third-party/fuse.js" defer="defer"></script><script type="text/javascript">var tocbotInstance=tocbot.init({tocSelector:"#eed4d2a0bfd64539bb9df78095dec881",contentSelector:".main-content",headingSelector:"h1, h2, h3",hasInnerContainers:!0,scrollContainer:".main-content",headingsOffset:130,onClick:bringLinkToView})</script></body></html>