sjabloon 0.5.1 → 0.6.0
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.
- package/LICENSE +201 -21
- package/README.md +24 -5
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/index.d.ts +15 -1
- package/package.json +4 -4
- package/src/index.js +21 -4
package/LICENSE
CHANGED
|
@@ -1,21 +1,201 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
A tiny, CSP-safe template engine for JavaScript. **~1.8KB min+gzip (~3.6KB with [xprsn](https://www.npmjs.com/package/xprsn)), one dependency.**
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/sjabloon)
|
|
6
|
-
[](https://github.com/getquario/sjabloon/actions/workflows/test.yml)
|
|
7
7
|
[](https://www.npmjs.com/package/sjabloon)
|
|
8
|
-
[](https://github.com/getquario/sjabloon/blob/main/LICENSE)
|
|
9
9
|
|
|
10
10
|
<a href="https://webstronauts.com?utm_source=github&utm_medium=readme&utm_campaign=sjabloon">
|
|
11
11
|
<picture>
|
|
@@ -13,7 +13,7 @@ A tiny, CSP-safe template engine for JavaScript. **~1.8KB min+gzip (~3.6KB with
|
|
|
13
13
|
</picture>
|
|
14
14
|
</a>
|
|
15
15
|
|
|
16
|
-
*Sjabloon* is Dutch for "template". It renders text templates with full [xprsn](https://github.com/
|
|
16
|
+
*Sjabloon* is Dutch for "template". It renders text templates with full [xprsn](https://github.com/getquario/xprsn) expressions inside every tag, without turning template text into JavaScript. There is no `eval` and no `new Function`, so it runs under a strict Content Security Policy where engines that compile templates to code cannot.
|
|
17
17
|
|
|
18
18
|
```js
|
|
19
19
|
import { template, render } from 'sjabloon';
|
|
@@ -47,6 +47,13 @@ tpl(base, { root: reportRoot, item: currentRow }); // $ = reportRoot, @ = curren
|
|
|
47
47
|
tpl(base, { root: reportRoot }); // no item → @.x throws
|
|
48
48
|
```
|
|
49
49
|
|
|
50
|
+
The renderer's `withRaw(values?, scope?)` method renders once and returns both channels: `{ text, raws }` — the rendered string plus each interpolation's pre-escape, pre-stringify value, whatever the expression evaluated to before it became output text. A `{{ total }}` holding `1000` yields the number `1000`, not the string `"1000"` — the whole point for typed consumers like spreadsheet cells. Both `{{ }}` and `{{{ }}}` are captured, nullish included, in render order (loop bodies once per iteration, untaken branches never). Block expressions — `#if` conditions, `#each` collections — are not interpolations and are never captured.
|
|
51
|
+
|
|
52
|
+
```js
|
|
53
|
+
const cell = template('{{ total * 1.21 }}');
|
|
54
|
+
cell.withRaw({ total: 1000 }); // => { text: '1210', raws: [1210] } — still a number
|
|
55
|
+
```
|
|
56
|
+
|
|
50
57
|
The renderer also carries `names` (every variable the template reads from your values, loop variables excluded) and `functions` (the registry functions it calls, methods excluded), both deduplicated. Check a stored template against your data model and its allowed functions before you render it, or fetch only the fields it needs.
|
|
51
58
|
|
|
52
59
|
```js
|
|
@@ -88,7 +95,7 @@ Use `isDiagnostic(error)` when a host needs to distinguish those errors. It retu
|
|
|
88
95
|
| `{{! anything }}` | Comment, removed from output |
|
|
89
96
|
| `{{- expr -}}` | A dash hugging either brace trims the whitespace on that side, newlines included; works on every tag form |
|
|
90
97
|
|
|
91
|
-
Every `expr` is an [xprsn expression](https://github.com/
|
|
98
|
+
Every `expr` is an [xprsn expression](https://github.com/getquario/xprsn#syntax): literals, arithmetic, string concatenation with `~` (`{{ first ~ " " ~ last }}`), comparisons, `and`/`or`/`not`/`in`, ternaries, property and method access, and functions from the registry you pass in. `null` and `undefined` render as empty strings.
|
|
92
99
|
|
|
93
100
|
A loop body sees its loop variable plus the outer scope; reusing an outer name shadows it only inside that body. The engine keeps loop variables on a child scope, so the values you pass are never mutated.
|
|
94
101
|
|
|
@@ -130,4 +137,16 @@ Node.js 22 and newer are supported through the ESM and CommonJS builds. Browser
|
|
|
130
137
|
|
|
131
138
|
## License
|
|
132
139
|
|
|
133
|
-
|
|
140
|
+
Copyright 2026 Robin van der Vleuten
|
|
141
|
+
|
|
142
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
143
|
+
you may not use this file except in compliance with the License.
|
|
144
|
+
You may obtain a copy of the License at
|
|
145
|
+
|
|
146
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
147
|
+
|
|
148
|
+
Unless required by applicable law or agreed to in writing, software
|
|
149
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
150
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
151
|
+
See the License for the specific language governing permissions and
|
|
152
|
+
limitations under the License.
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("xprsn");const t={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},n=e=>String(e).replace(/[&<>"']/g,e=>t[e]),r=/^(?:__proto__|constructor|prototype)$/,i=new WeakSet,a=i.add.bind(i),o=i.has.bind(i),s=e=>o(e);let c=e=>{let t=[];for(let n=0,r=1;n<e.length;){let i=e.indexOf(`{{`,n);if(i<0){t.push([0,e.slice(n)]);break}i>n&&t.push([0,e.slice(n,i)]);let a=e[i+2]===`{`,o=i+2+a,s=e[o]===`-`,c=-1;if(s&&o++,a&&r&&(c=e.indexOf(`}}}`,o),c<0&&(r=0)),c<0&&(a&&(a=!1,o=i+2,s=e[o]===`-`,s&&o++),c=e.indexOf(`}}`,o)),c<0){t.push([0,e.slice(i)]);break}let l=c>o&&e[c-1]===`-`,u=l?c-1:c,d=e.slice(o,u),f=d.trim(),p=o+d.length-d.trimStart().length,m=c+2+a,h=[a?1:2,f,i,m,p],g=t.at(-1);if(s&&g?.[0]===0&&g[1]&&(g[1]=g[1].trimEnd()),t.push(h),n=m,l)for(;/\s/.test(e[n]);)n++}return t},l,u,d,f,p,m,h,g,_
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("xprsn");const t={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},n=e=>String(e).replace(/[&<>"']/g,e=>t[e]),r=/^(?:__proto__|constructor|prototype)$/,i=new WeakSet,a=i.add.bind(i),o=i.has.bind(i),s=e=>o(e);let c=e=>{let t=[];for(let n=0,r=1;n<e.length;){let i=e.indexOf(`{{`,n);if(i<0){t.push([0,e.slice(n)]);break}i>n&&t.push([0,e.slice(n,i)]);let a=e[i+2]===`{`,o=i+2+a,s=e[o]===`-`,c=-1;if(s&&o++,a&&r&&(c=e.indexOf(`}}}`,o),c<0&&(r=0)),c<0&&(a&&(a=!1,o=i+2,s=e[o]===`-`,s&&o++),c=e.indexOf(`}}`,o)),c<0){t.push([0,e.slice(i)]);break}let l=c>o&&e[c-1]===`-`,u=l?c-1:c,d=e.slice(o,u),f=d.trim(),p=o+d.length-d.trimStart().length,m=c+2+a,h=[a?1:2,f,i,m,p],g=t.at(-1);if(s&&g?.[0]===0&&g[1]&&(g[1]=g[1].trimEnd()),t.push(h),n=m,l)for(;/\s/.test(e[n]);)n++}return t},l,u,d,f,p,m,h,g,_;const v=Symbol();let y=()=>Object.freeze(_.slice()),b=(e,t)=>(_.length<256||S(`Template too deeply nested`,`SJABLOON_TOO_DEEP`,t),Object.freeze({type:e,start:t[2],end:t[3]})),x=(e,t)=>(Object.defineProperty(e,"blocks",{value:t,enumerable:!0}),a(e),e),S=(e,t,n,r=n?.[2]??g.length,i=n?.[3]??g.length)=>{let a=SyntaxError(e);throw a.code=t,a.start=r,a.end=i,x(a,y())},C=(t,n,r,i=e.isDiagnostic)=>{throw i(t)?(t.start+=n,t.end+=n,x(t,r)):t},w=e=>S(`Unexpected {{`+e[1]+`}}`,`SJABLOON_UNEXPECTED_TAG`,e),T=(e,t)=>e.map(e=>e(t)).join(``),E=(e,t)=>(e=>(n,r)=>(r=e(n),n[v]?.push(r),t(r??``)))(D(e[1],e[4],y())),D=(t,n,r)=>{let i;try{i=(0,e.compile)(t,d)}catch(e){C(e,n,r)}for(let e of i.names)p.includes(e)||m.add(e);for(let e of i.functions)h.add(e);return e=>{try{return i(e)}catch(e){C(e,n,r,i.isDiagnostic)}}},O=e=>{let t=k([`#elif`,`#else`,`/if`]),n=f[1],r=[];return n.startsWith(`#elif `)?r=[O(D(n.slice(6),f[4]+6,y()))]:n===`#else`?(r=k([`/if`]),f[1]===`/if`||w(f)):n!==`/if`&&w(f),n=>T(e(n)?t:r,n)},k=e=>{let t=[];for(let i;i=l[u++];){let a=i[1];if(!i[0])t.push((e=>()=>e)(a));else if(i[0]===1)t.push(E(i,String));else if(e.includes(a.split(` `)[0]))return f=i,t;else if(a[0]!==`!`)if(a.startsWith(`#if `))_.push(b(`if`,i)),t.push(O(D(a.slice(4),i[4]+4,y()))),_.pop();else if(/^#each(?:\s|$)/.test(a)){_.push(b(`each`,i));let e=/^#each ([\s\S]+) as ((\w+)(?:\s*,\s*(\w+))?)$/.exec(a);e||S(`Bad {{`+a+`}}`,`SJABLOON_EACH_SYNTAX`,i);let n=e[3],o=e[4],s=i[4]+a.length-e[2].length;if(r.test(n)&&S(`Bad {{`+a+`}}`,`SJABLOON_BLOCKED_BINDING`,i,s,s+n.length),o&&r.test(o)){let e=i[4]+a.length-o.length;S(`Bad {{`+a+`}}`,`SJABLOON_BLOCKED_BINDING`,i,e,e+o.length)}let c=D(e[1],i[4]+6,y()),l=p.length;p.push(n),o&&p.push(o),p.push(`loop`);let u=k([`#else`,`/each`]);p.length=l;let d=[];f[1]===`#else`?(d=k([`/each`]),f[1]===`/each`||w(f)):f[1]!==`/each`&&w(f),_.pop(),t.push(e=>{let t=c(e),r=Array.isArray(t),i=r?t.slice():t&&typeof t==`object`?Object.keys(t).map(e=>[t[e],e]):[];return i.length?i.map((t,a)=>{let s=r?t:t[0],c=r?a:t[1],l=Object.create(e);return l[n]=s,o&&(l[o]=c),l[`@`]=s,l.loop={index:a+1,index0:a,first:!a,last:a===i.length-1,length:i.length},T(u,l)}).join(``):T(d,e)})}else/^#(?:if|elif|else)(?:\s|$)/.test(a)||a[0]===`/`?w(i):a[0]===`#`?S(`Unknown {{`+a+`}}`,`SJABLOON_UNKNOWN_BLOCK`,i):t.push(E(i,n))}return e.length&&S(`Missing {{`+e[e.length-1]+`}}`,`SJABLOON_UNCLOSED_BLOCK`),t};function A(e,t){d=t,p=[`$`,`@`],m=new Set,h=new Set,g=String(e),_=[],l=c(g),u=0;let n;try{n=k([])}catch(e){throw e instanceof RangeError&&S(`Template too deeply nested`,`SJABLOON_TOO_DEEP`),e}let r=(e,t,r)=>{e||={};let i=Object.create(e);return i.$=t?t.root:e,t?`item`in t&&(i[`@`]=t.item):i[`@`]=e,i[v]=r,T(n,i)},i=(e,t)=>r(e,t);return i.withRaw=(e,t,n=[])=>({text:r(e,t,n),raws:n}),i.names=Array.from(m),i.functions=Array.from(h),i}function j(e,t,n){return A(e,n)(t)}exports.isDiagnostic=s,exports.render=j,exports.template=A;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{compile as e,isDiagnostic as t}from"xprsn";const n={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},r=e=>String(e).replace(/[&<>"']/g,e=>n[e]),i=/^(?:__proto__|constructor|prototype)$/,a=new WeakSet,o=a.add.bind(a),s=a.has.bind(a),c=e=>s(e);let l=e=>{let t=[];for(let n=0,r=1;n<e.length;){let i=e.indexOf(`{{`,n);if(i<0){t.push([0,e.slice(n)]);break}i>n&&t.push([0,e.slice(n,i)]);let a=e[i+2]===`{`,o=i+2+a,s=e[o]===`-`,c=-1;if(s&&o++,a&&r&&(c=e.indexOf(`}}}`,o),c<0&&(r=0)),c<0&&(a&&(a=!1,o=i+2,s=e[o]===`-`,s&&o++),c=e.indexOf(`}}`,o)),c<0){t.push([0,e.slice(i)]);break}let l=c>o&&e[c-1]===`-`,u=l?c-1:c,d=e.slice(o,u),f=d.trim(),p=o+d.length-d.trimStart().length,m=c+2+a,h=[a?1:2,f,i,m,p],g=t.at(-1);if(s&&g?.[0]===0&&g[1]&&(g[1]=g[1].trimEnd()),t.push(h),n=m,l)for(;/\s/.test(e[n]);)n++}return t},u,d,f,p,m,h,g,_,v
|
|
1
|
+
import{compile as e,isDiagnostic as t}from"xprsn";const n={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},r=e=>String(e).replace(/[&<>"']/g,e=>n[e]),i=/^(?:__proto__|constructor|prototype)$/,a=new WeakSet,o=a.add.bind(a),s=a.has.bind(a),c=e=>s(e);let l=e=>{let t=[];for(let n=0,r=1;n<e.length;){let i=e.indexOf(`{{`,n);if(i<0){t.push([0,e.slice(n)]);break}i>n&&t.push([0,e.slice(n,i)]);let a=e[i+2]===`{`,o=i+2+a,s=e[o]===`-`,c=-1;if(s&&o++,a&&r&&(c=e.indexOf(`}}}`,o),c<0&&(r=0)),c<0&&(a&&(a=!1,o=i+2,s=e[o]===`-`,s&&o++),c=e.indexOf(`}}`,o)),c<0){t.push([0,e.slice(i)]);break}let l=c>o&&e[c-1]===`-`,u=l?c-1:c,d=e.slice(o,u),f=d.trim(),p=o+d.length-d.trimStart().length,m=c+2+a,h=[a?1:2,f,i,m,p],g=t.at(-1);if(s&&g?.[0]===0&&g[1]&&(g[1]=g[1].trimEnd()),t.push(h),n=m,l)for(;/\s/.test(e[n]);)n++}return t},u,d,f,p,m,h,g,_,v;const y=Symbol();let b=()=>Object.freeze(v.slice()),x=(e,t)=>(v.length<256||C(`Template too deeply nested`,`SJABLOON_TOO_DEEP`,t),Object.freeze({type:e,start:t[2],end:t[3]})),S=(e,t)=>(Object.defineProperty(e,"blocks",{value:t,enumerable:!0}),o(e),e),C=(e,t,n,r=n?.[2]??_.length,i=n?.[3]??_.length)=>{let a=SyntaxError(e);throw a.code=t,a.start=r,a.end=i,S(a,b())},w=(e,n,r,i=t)=>{throw i(e)?(e.start+=n,e.end+=n,S(e,r)):e},T=e=>C(`Unexpected {{`+e[1]+`}}`,`SJABLOON_UNEXPECTED_TAG`,e),E=(e,t)=>e.map(e=>e(t)).join(``),D=(e,t)=>(e=>(n,r)=>(r=e(n),n[y]?.push(r),t(r??``)))(O(e[1],e[4],b())),O=(t,n,r)=>{let i;try{i=e(t,f)}catch(e){w(e,n,r)}for(let e of i.names)m.includes(e)||h.add(e);for(let e of i.functions)g.add(e);return e=>{try{return i(e)}catch(e){w(e,n,r,i.isDiagnostic)}}},k=e=>{let t=A([`#elif`,`#else`,`/if`]),n=p[1],r=[];return n.startsWith(`#elif `)?r=[k(O(n.slice(6),p[4]+6,b()))]:n===`#else`?(r=A([`/if`]),p[1]===`/if`||T(p)):n!==`/if`&&T(p),n=>E(e(n)?t:r,n)},A=e=>{let t=[];for(let n;n=u[d++];){let a=n[1];if(!n[0])t.push((e=>()=>e)(a));else if(n[0]===1)t.push(D(n,String));else if(e.includes(a.split(` `)[0]))return p=n,t;else if(a[0]!==`!`)if(a.startsWith(`#if `))v.push(x(`if`,n)),t.push(k(O(a.slice(4),n[4]+4,b()))),v.pop();else if(/^#each(?:\s|$)/.test(a)){v.push(x(`each`,n));let e=/^#each ([\s\S]+) as ((\w+)(?:\s*,\s*(\w+))?)$/.exec(a);e||C(`Bad {{`+a+`}}`,`SJABLOON_EACH_SYNTAX`,n);let r=e[3],o=e[4],s=n[4]+a.length-e[2].length;if(i.test(r)&&C(`Bad {{`+a+`}}`,`SJABLOON_BLOCKED_BINDING`,n,s,s+r.length),o&&i.test(o)){let e=n[4]+a.length-o.length;C(`Bad {{`+a+`}}`,`SJABLOON_BLOCKED_BINDING`,n,e,e+o.length)}let c=O(e[1],n[4]+6,b()),l=m.length;m.push(r),o&&m.push(o),m.push(`loop`);let u=A([`#else`,`/each`]);m.length=l;let d=[];p[1]===`#else`?(d=A([`/each`]),p[1]===`/each`||T(p)):p[1]!==`/each`&&T(p),v.pop(),t.push(e=>{let t=c(e),n=Array.isArray(t),i=n?t.slice():t&&typeof t==`object`?Object.keys(t).map(e=>[t[e],e]):[];return i.length?i.map((t,a)=>{let s=n?t:t[0],c=n?a:t[1],l=Object.create(e);return l[r]=s,o&&(l[o]=c),l[`@`]=s,l.loop={index:a+1,index0:a,first:!a,last:a===i.length-1,length:i.length},E(u,l)}).join(``):E(d,e)})}else/^#(?:if|elif|else)(?:\s|$)/.test(a)||a[0]===`/`?T(n):a[0]===`#`?C(`Unknown {{`+a+`}}`,`SJABLOON_UNKNOWN_BLOCK`,n):t.push(D(n,r))}return e.length&&C(`Missing {{`+e[e.length-1]+`}}`,`SJABLOON_UNCLOSED_BLOCK`),t};function j(e,t){f=t,m=[`$`,`@`],h=new Set,g=new Set,_=String(e),v=[],u=l(_),d=0;let n;try{n=A([])}catch(e){throw e instanceof RangeError&&C(`Template too deeply nested`,`SJABLOON_TOO_DEEP`),e}let r=(e,t,r)=>{e||={};let i=Object.create(e);return i.$=t?t.root:e,t?`item`in t&&(i[`@`]=t.item):i[`@`]=e,i[y]=r,E(n,i)},i=(e,t)=>r(e,t);return i.withRaw=(e,t,n=[])=>({text:r(e,t,n),raws:n}),i.names=Array.from(h),i.functions=Array.from(g),i}function M(e,t,n){return j(e,n)(t)}export{c as isDiagnostic,M as render,j as template};
|
package/index.d.ts
CHANGED
|
@@ -44,9 +44,16 @@ export function isDiagnostic(error: unknown): error is SjabloonDiagnostic;
|
|
|
44
44
|
* `root` and `@` becomes `item` (two distinct objects). Omit `item` to leave
|
|
45
45
|
* `@` unbound, so reading `@.x` throws through xprsn's guard.
|
|
46
46
|
*
|
|
47
|
+
* The renderer also exposes `withRaw(values, scope)`: one render, both channels.
|
|
48
|
+
* It returns `{ text, raws }` — the rendered string plus each interpolation's
|
|
49
|
+
* pre-escape, pre-stringify value (`{{ }}` and `{{{ }}}` alike, nullish
|
|
50
|
+
* included), in render order: loop bodies push once per iteration, untaken
|
|
51
|
+
* branches push nothing. Block expressions (`#if` conditions, `#each`
|
|
52
|
+
* collections) are never captured.
|
|
53
|
+
*
|
|
47
54
|
* @param {string} str The template, e.g. `'Hello {{ user.name }}!'`.
|
|
48
55
|
* @param {Record<string, Function>} [funcs] Functions callable inside expressions.
|
|
49
|
-
* @returns {{(values?: Record<string, any>, scope?: { root?: any, item?: any }): string, names: string[], functions: string[]}} Renderer for the compiled template.
|
|
56
|
+
* @returns {{(values?: Record<string, any>, scope?: { root?: any, item?: any }): string, withRaw: (values?: Record<string, any>, scope?: { root?: any, item?: any }) => { text: string, raws: unknown[] }, names: string[], functions: string[]}} Renderer for the compiled template.
|
|
50
57
|
* @throws {SyntaxError} On malformed tags, unclosed blocks, or bad expressions.
|
|
51
58
|
*/
|
|
52
59
|
export function template(str: string, funcs?: Record<string, Function>): {
|
|
@@ -54,6 +61,13 @@ export function template(str: string, funcs?: Record<string, Function>): {
|
|
|
54
61
|
root?: any;
|
|
55
62
|
item?: any;
|
|
56
63
|
}): string;
|
|
64
|
+
withRaw(values?: Record<string, any>, scope?: {
|
|
65
|
+
root?: any;
|
|
66
|
+
item?: any;
|
|
67
|
+
}): {
|
|
68
|
+
text: string;
|
|
69
|
+
raws: unknown[];
|
|
70
|
+
};
|
|
57
71
|
names: string[];
|
|
58
72
|
functions: string[];
|
|
59
73
|
};
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sjabloon",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Tiny, CSP-safe template engine for JavaScript, powered by xprsn expressions. No eval, no new Function.",
|
|
5
5
|
"repository": "getquario/sjabloon",
|
|
6
|
-
"license": "
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
7
|
"author": {
|
|
8
8
|
"name": "Robin van der Vleuten",
|
|
9
9
|
"email": "robin@webstronauts.com",
|
|
@@ -32,11 +32,11 @@
|
|
|
32
32
|
"size-limit": [
|
|
33
33
|
{
|
|
34
34
|
"path": "dist/index.js",
|
|
35
|
-
"limit": "1.
|
|
35
|
+
"limit": "1.76 kB"
|
|
36
36
|
},
|
|
37
37
|
{
|
|
38
38
|
"path": "dist/index.cjs",
|
|
39
|
-
"limit": "1.
|
|
39
|
+
"limit": "1.78 kB"
|
|
40
40
|
}
|
|
41
41
|
],
|
|
42
42
|
"scripts": {
|
package/src/index.js
CHANGED
|
@@ -54,6 +54,11 @@ let lex = s => {
|
|
|
54
54
|
// `nms` collects free variables, `fnms` the registry functions called.
|
|
55
55
|
let toks, i, fns, last, bound, nms, fnms, src, blocks;
|
|
56
56
|
|
|
57
|
+
// The opt-in raw-value collector rides the render's root scope under a
|
|
58
|
+
// symbol: invisible to expressions, inherited by `#each` child scopes, and
|
|
59
|
+
// naturally per render, so re-entrant renders each collect into their own.
|
|
60
|
+
const RAWS = Symbol();
|
|
61
|
+
|
|
57
62
|
let snap = () => Object.freeze(blocks.slice());
|
|
58
63
|
// Block nesting is capped so a pathological template fails as a deterministic
|
|
59
64
|
// SyntaxError at the offending opener, far below the native stack limit.
|
|
@@ -86,8 +91,9 @@ let unexpected = t => fault('Unexpected {{' + t[1] + '}}', 'SJABLOON_UNEXPECTED_
|
|
|
86
91
|
let run = (nodes, v) => nodes.map(n => n(v)).join('');
|
|
87
92
|
|
|
88
93
|
// A leaf interpolation node: compile `src`, render nullish as '', apply `wrap`
|
|
89
|
-
// (`esc` for `{{ }}`, `String` for the raw `{{{ }}}` form).
|
|
90
|
-
|
|
94
|
+
// (`esc` for `{{ }}`, `String` for the raw `{{{ }}}` form). The pre-stringify
|
|
95
|
+
// result feeds the opt-in `raws` collector; block expressions never do.
|
|
96
|
+
let interp = (t, wrap) => (e => (v, x) => (x = e(v), v[RAWS]?.push(x), wrap(x ?? '')))(cp(t[1], t[4], snap()));
|
|
91
97
|
|
|
92
98
|
// Compile one expression and collect its free variables (minus the loop
|
|
93
99
|
// variables currently in scope, which belong to the template) and the registry
|
|
@@ -213,9 +219,16 @@ let parse = stops => {
|
|
|
213
219
|
* `root` and `@` becomes `item` (two distinct objects). Omit `item` to leave
|
|
214
220
|
* `@` unbound, so reading `@.x` throws through xprsn's guard.
|
|
215
221
|
*
|
|
222
|
+
* The renderer also exposes `withRaw(values, scope)`: one render, both channels.
|
|
223
|
+
* It returns `{ text, raws }` — the rendered string plus each interpolation's
|
|
224
|
+
* pre-escape, pre-stringify value (`{{ }}` and `{{{ }}}` alike, nullish
|
|
225
|
+
* included), in render order: loop bodies push once per iteration, untaken
|
|
226
|
+
* branches push nothing. Block expressions (`#if` conditions, `#each`
|
|
227
|
+
* collections) are never captured.
|
|
228
|
+
*
|
|
216
229
|
* @param {string} str The template, e.g. `'Hello {{ user.name }}!'`.
|
|
217
230
|
* @param {Record<string, Function>} [funcs] Functions callable inside expressions.
|
|
218
|
-
* @returns {{(values?: Record<string, any>, scope?: { root?: any, item?: any }): string, names: string[], functions: string[]}} Renderer for the compiled template.
|
|
231
|
+
* @returns {{(values?: Record<string, any>, scope?: { root?: any, item?: any }): string, withRaw: (values?: Record<string, any>, scope?: { root?: any, item?: any }) => { text: string, raws: unknown[] }, names: string[], functions: string[]}} Renderer for the compiled template.
|
|
219
232
|
* @throws {SyntaxError} On malformed tags, unclosed blocks, or bad expressions.
|
|
220
233
|
*/
|
|
221
234
|
export function template(str, funcs) {
|
|
@@ -246,14 +259,18 @@ export function template(str, funcs) {
|
|
|
246
259
|
// `$` = root, `@` = item (distinct objects). Omitting `item` leaves `@`
|
|
247
260
|
// unbound, so `@.x` throws through xprsn's guard — a group-header band that
|
|
248
261
|
// has no current row wants exactly that.
|
|
249
|
-
const
|
|
262
|
+
const g = (v, o, w) => {
|
|
250
263
|
v = v || {};
|
|
251
264
|
const r = Object.create(v);
|
|
252
265
|
r['$'] = o ? o.root : v;
|
|
253
266
|
if (!o) r['@'] = v;
|
|
254
267
|
else if ('item' in o) r['@'] = o.item;
|
|
268
|
+
r[RAWS] = w;
|
|
255
269
|
return run(nodes, r);
|
|
256
270
|
};
|
|
271
|
+
const f = (v, o) => g(v, o);
|
|
272
|
+
// One render, both channels: the rendered string plus the ordered raws.
|
|
273
|
+
f.withRaw = (v, o, w = []) => ({ text: g(v, o, w), raws: w });
|
|
257
274
|
// Array.from, not a spread: the bundler's transpile turns `[...set]` into
|
|
258
275
|
// `[].concat(set)`, which wraps the Set instead of unpacking it.
|
|
259
276
|
f.names = Array.from(nms);
|