@blamejs/core 0.4.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 (160) hide show
  1. package/CHANGELOG.md +230 -0
  2. package/LICENSE +201 -0
  3. package/LTS-CALENDAR.md +29 -0
  4. package/MIGRATING.md +7 -0
  5. package/NOTICE +59 -0
  6. package/README.md +100 -0
  7. package/bin/blamejs.js +13 -0
  8. package/index.js +253 -0
  9. package/lib/api-key.js +705 -0
  10. package/lib/api-snapshot.js +335 -0
  11. package/lib/app-shutdown.js +381 -0
  12. package/lib/app.js +364 -0
  13. package/lib/atomic-file.js +525 -0
  14. package/lib/audit-chain.js +168 -0
  15. package/lib/audit-sign.js +319 -0
  16. package/lib/audit-tools.js +682 -0
  17. package/lib/audit.js +753 -0
  18. package/lib/auth/jwt.js +280 -0
  19. package/lib/auth/oauth.js +691 -0
  20. package/lib/auth/passkey.js +185 -0
  21. package/lib/auth/password.js +139 -0
  22. package/lib/auth/totp.js +17 -0
  23. package/lib/auth-header.js +81 -0
  24. package/lib/backup/bundle.js +219 -0
  25. package/lib/backup/crypto.js +174 -0
  26. package/lib/backup/index.js +490 -0
  27. package/lib/backup/manifest.js +275 -0
  28. package/lib/bundler.js +295 -0
  29. package/lib/cache.js +819 -0
  30. package/lib/chain-writer.js +234 -0
  31. package/lib/cli-helpers.js +201 -0
  32. package/lib/cli.js +1377 -0
  33. package/lib/cluster-provider-db.js +245 -0
  34. package/lib/cluster-storage.js +166 -0
  35. package/lib/cluster.js +691 -0
  36. package/lib/consent.js +222 -0
  37. package/lib/constants.js +186 -0
  38. package/lib/cookies.js +293 -0
  39. package/lib/credential-hash.js +303 -0
  40. package/lib/crypto-field.js +159 -0
  41. package/lib/crypto.js +250 -0
  42. package/lib/db-query.js +297 -0
  43. package/lib/db-schema.js +250 -0
  44. package/lib/db.js +1054 -0
  45. package/lib/deprecate.js +226 -0
  46. package/lib/dev.js +324 -0
  47. package/lib/error-page.js +424 -0
  48. package/lib/events.js +135 -0
  49. package/lib/external-db.js +422 -0
  50. package/lib/forms.js +378 -0
  51. package/lib/framework-error.js +189 -0
  52. package/lib/framework-schema.js +604 -0
  53. package/lib/handlers.js +350 -0
  54. package/lib/html-balance.js +227 -0
  55. package/lib/http-client.js +615 -0
  56. package/lib/i18n.js +780 -0
  57. package/lib/jobs.js +181 -0
  58. package/lib/lazy-require.js +48 -0
  59. package/lib/log-stream-local.js +137 -0
  60. package/lib/log-stream-webhook.js +170 -0
  61. package/lib/log-stream.js +211 -0
  62. package/lib/log.js +355 -0
  63. package/lib/mail-bounce.js +507 -0
  64. package/lib/mail.js +701 -0
  65. package/lib/metrics.js +647 -0
  66. package/lib/middleware/api-encrypt.js +553 -0
  67. package/lib/middleware/attach-user.js +156 -0
  68. package/lib/middleware/body-parser.js +883 -0
  69. package/lib/middleware/bot-guard.js +148 -0
  70. package/lib/middleware/compression.js +436 -0
  71. package/lib/middleware/cors.js +236 -0
  72. package/lib/middleware/csp-nonce.js +332 -0
  73. package/lib/middleware/csrf-protect.js +275 -0
  74. package/lib/middleware/error-handler.js +46 -0
  75. package/lib/middleware/health.js +358 -0
  76. package/lib/middleware/index.js +52 -0
  77. package/lib/middleware/rate-limit.js +319 -0
  78. package/lib/middleware/request-id.js +53 -0
  79. package/lib/middleware/require-auth.js +95 -0
  80. package/lib/middleware/security-headers.js +91 -0
  81. package/lib/migrations.js +353 -0
  82. package/lib/mtls-ca.js +333 -0
  83. package/lib/mtls-engine-default.js +285 -0
  84. package/lib/nonce-store.js +177 -0
  85. package/lib/notify.js +643 -0
  86. package/lib/ntp-check.js +178 -0
  87. package/lib/object-store/azure-blob.js +467 -0
  88. package/lib/object-store/gcs.js +469 -0
  89. package/lib/object-store/http-put.js +153 -0
  90. package/lib/object-store/index.js +140 -0
  91. package/lib/object-store/local.js +163 -0
  92. package/lib/object-store/retry.js +15 -0
  93. package/lib/object-store/sigv4.js +535 -0
  94. package/lib/observability.js +114 -0
  95. package/lib/pagination.js +371 -0
  96. package/lib/parsers/index.js +64 -0
  97. package/lib/parsers/safe-csv.js +224 -0
  98. package/lib/parsers/safe-env.js +614 -0
  99. package/lib/parsers/safe-toml.js +745 -0
  100. package/lib/parsers/safe-xml.js +379 -0
  101. package/lib/parsers/safe-yaml.js +977 -0
  102. package/lib/permissions.js +430 -0
  103. package/lib/pqc-agent.js +85 -0
  104. package/lib/pqc-gate.js +266 -0
  105. package/lib/protocol-dispatcher.js +144 -0
  106. package/lib/queue-local.js +327 -0
  107. package/lib/queue.js +430 -0
  108. package/lib/redact.js +192 -0
  109. package/lib/render.js +193 -0
  110. package/lib/request-helpers.js +178 -0
  111. package/lib/restore-bundle.js +239 -0
  112. package/lib/restore-rollback.js +254 -0
  113. package/lib/restore.js +301 -0
  114. package/lib/retry.js +329 -0
  115. package/lib/router.js +437 -0
  116. package/lib/safe-async.js +520 -0
  117. package/lib/safe-buffer.js +162 -0
  118. package/lib/safe-json.js +532 -0
  119. package/lib/safe-schema.js +1176 -0
  120. package/lib/safe-sql.js +157 -0
  121. package/lib/safe-url.js +109 -0
  122. package/lib/scheduler.js +680 -0
  123. package/lib/seeders.js +622 -0
  124. package/lib/session.js +304 -0
  125. package/lib/slug.js +243 -0
  126. package/lib/static.js +268 -0
  127. package/lib/storage.js +470 -0
  128. package/lib/subject.js +281 -0
  129. package/lib/template.js +781 -0
  130. package/lib/testing.js +621 -0
  131. package/lib/totp.js +285 -0
  132. package/lib/tracing.js +484 -0
  133. package/lib/validate-opts.js +56 -0
  134. package/lib/vault/index.js +299 -0
  135. package/lib/vault/passphrase-ops.js +311 -0
  136. package/lib/vault/passphrase-source.js +198 -0
  137. package/lib/vault/rotate.js +761 -0
  138. package/lib/vault/wrap.js +289 -0
  139. package/lib/vendor/MANIFEST.json +84 -0
  140. package/lib/vendor/argon2/argon2.cjs +466 -0
  141. package/lib/vendor/argon2/argon2.d.cts +62 -0
  142. package/lib/vendor/argon2/package.json +1 -0
  143. package/lib/vendor/argon2/prebuilds/darwin-arm64/argon2.armv8.glibc.node +0 -0
  144. package/lib/vendor/argon2/prebuilds/darwin-x64/argon2.glibc.node +0 -0
  145. package/lib/vendor/argon2/prebuilds/freebsd-arm64/argon2.armv8.glibc.node +0 -0
  146. package/lib/vendor/argon2/prebuilds/freebsd-x64/argon2.glibc.node +0 -0
  147. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.glibc.node +0 -0
  148. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.musl.node +0 -0
  149. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.glibc.node +0 -0
  150. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.musl.node +0 -0
  151. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.glibc.node +0 -0
  152. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.musl.node +0 -0
  153. package/lib/vendor/argon2/prebuilds/win32-x64/argon2.glibc.node +0 -0
  154. package/lib/vendor/noble-ciphers.cjs +9 -0
  155. package/lib/vendor/pki.cjs +181 -0
  156. package/lib/vendor/simplewebauthn-server.cjs +328 -0
  157. package/lib/webhook.js +632 -0
  158. package/lib/websocket-channels.js +413 -0
  159. package/lib/websocket.js +833 -0
  160. package/package.json +39 -0
@@ -0,0 +1,781 @@
1
+ "use strict";
2
+ /**
3
+ * Server-side HTML template engine — eval-free.
4
+ *
5
+ * No `new Function()`, no `eval`, no `vm.runInThisContext`. Templates
6
+ * are tokenized + parsed into a small AST and walked at render time
7
+ * against a data scope. The trade-off vs an eval-based engine is
8
+ * 5–50× slower per render and a restricted expression grammar; the
9
+ * win is "an operator who renders req.query.template (or worse) can't
10
+ * RCE the framework, period."
11
+ *
12
+ * Tag syntax:
13
+ *
14
+ * {{ expr }} HTML-escaped expression output
15
+ * {{{ expr }}} Raw output (no escape — operator-trusted HTML)
16
+ * {{> name }} Partial from <viewsDir>/partials/<name>.html
17
+ * {% extends "name" %} Inherit from a layout (must be first non-whitespace)
18
+ * {% block name %}…{% endblock %}
19
+ * Overrideable section
20
+ * {% if expr %}…{% else %}…{% endif %}
21
+ * Conditional
22
+ * {% for ident in expr %}…{% endfor %}
23
+ * Iterate an array; the identifier is bound
24
+ * for the loop body
25
+ *
26
+ * Expression grammar (recursive-descent Pratt-style):
27
+ *
28
+ * expression := ternary
29
+ * ternary := logical-or ('?' logical-or ':' logical-or)?
30
+ * logical-or := logical-and ('||' logical-and)*
31
+ * logical-and := equality ('&&' equality)*
32
+ * equality := comparison (('==' | '!=' | '===' | '!==') comparison)*
33
+ * comparison := unary (('<' | '<=' | '>' | '>=') unary)*
34
+ * unary := '!' unary | postfix
35
+ * postfix := primary postfix-op*
36
+ * postfix-op := '.' identifier | '[' expression ']' | '(' arg-list ')'
37
+ * primary := literal | identifier | '(' expression ')'
38
+ * literal := string-literal | number-literal | 'true' | 'false' | 'null'
39
+ *
40
+ * Function calls invoke functions THE OPERATOR PROVIDED in the data
41
+ * scope (e.g. `{{ helpers.formatDate(d) }}` resolves `helpers` from
42
+ * data, then `formatDate` on it, then calls it with `d`). The
43
+ * interpreter does not invent built-ins; if an operator wants
44
+ * helpers, they pass them under any data key they like.
45
+ *
46
+ * Public API:
47
+ *
48
+ * template.create({ viewsDir, cache?, escapeHtml? })
49
+ * → engine instance with .render(view, data?), .compile(view), .reset()
50
+ * template.render(view, data?)
51
+ * → convenience using a default singleton against <cwd>/views
52
+ * template.escapeHtml(value)
53
+ * → standalone HTML escape (used by forms.js etc.)
54
+ *
55
+ * Containment defenses (templates ARE server-side files; these guard
56
+ * against operator path-joining mistakes that let request input reach
57
+ * a view-name argument):
58
+ *
59
+ * - View names containing ".." or "\0" → reject
60
+ * - Resolved paths outside viewsDir → reject
61
+ * - Layout-extends and partial-inclusion recursion bounded at depth 16
62
+ *
63
+ * If an operator renders a template path derived from user input, the
64
+ * defenses block path traversal. The interpreter's eval-free posture
65
+ * is the second line: even if a template loaded, it can't execute
66
+ * arbitrary JS — only the limited expression grammar above.
67
+ */
68
+ var fs = require("fs");
69
+ var path = require("path");
70
+ var validateOpts = require("./validate-opts");
71
+
72
+ // ============================================================
73
+ // HTML escape (exported)
74
+ // ============================================================
75
+
76
+ var ESCAPE_MAP = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;" };
77
+ var ESCAPE_RE = /[&<>"']/g;
78
+
79
+ function escapeHtml(value) {
80
+ if (value === null || value === undefined) return "";
81
+ var s = typeof value === "string" ? value : String(value);
82
+ return s.replace(ESCAPE_RE, function (c) { return ESCAPE_MAP[c]; });
83
+ }
84
+
85
+ // ============================================================
86
+ // Path resolution + containment
87
+ // ============================================================
88
+
89
+ function _resolveViewPath(viewsDir, viewName) {
90
+ if (typeof viewName !== "string" || viewName.length === 0) {
91
+ throw new Error("template: view name must be a non-empty string");
92
+ }
93
+ if (viewName.indexOf("..") !== -1 || viewName.indexOf("\0") !== -1) {
94
+ throw new Error("template: view name contains forbidden character: " + JSON.stringify(viewName));
95
+ }
96
+ var resolved = path.resolve(viewsDir, viewName + ".html");
97
+ var resolvedDir = path.resolve(viewsDir);
98
+ if (resolved !== resolvedDir &&
99
+ !resolved.startsWith(resolvedDir + path.sep)) {
100
+ throw new Error("template: view path escapes viewsDir: " + viewName);
101
+ }
102
+ if (!fs.existsSync(resolved)) {
103
+ throw new Error("template: view not found: " + viewName);
104
+ }
105
+ return resolved;
106
+ }
107
+
108
+ function _resolvePartialPath(viewsDir, partialName) {
109
+ if (typeof partialName !== "string" || partialName.length === 0) return null;
110
+ if (partialName.indexOf("..") !== -1 || partialName.indexOf("\0") !== -1) return null;
111
+ var resolved = path.resolve(viewsDir, "partials", partialName + ".html");
112
+ var partialsDir = path.resolve(viewsDir, "partials");
113
+ if (resolved !== partialsDir &&
114
+ !resolved.startsWith(partialsDir + path.sep)) return null;
115
+ return fs.existsSync(resolved) ? resolved : null;
116
+ }
117
+
118
+ // ============================================================
119
+ // Layout inheritance: extract blocks, substitute into parent
120
+ // ============================================================
121
+
122
+ var EXTENDS_RE = /^\s*\{%\s*extends\s+"([^"]+)"\s*%\}\s*/;
123
+ var BLOCK_FULL_RE = /\{%\s*block\s+([A-Za-z_][A-Za-z0-9_-]*)\s*%\}([\s\S]*?)\{%\s*endblock\s*%\}/g;
124
+
125
+ function _extractBlocks(source) {
126
+ var blocks = {};
127
+ var rest = source.replace(BLOCK_FULL_RE, function (_match, name, content) {
128
+ blocks[name] = content;
129
+ return "";
130
+ });
131
+ return { rest: rest, blocks: blocks };
132
+ }
133
+
134
+ function _substituteBlocks(parentSource, childBlocks) {
135
+ return parentSource.replace(BLOCK_FULL_RE, function (_match, name, defaultContent) {
136
+ return Object.prototype.hasOwnProperty.call(childBlocks, name)
137
+ ? childBlocks[name]
138
+ : defaultContent;
139
+ });
140
+ }
141
+
142
+ function _resolveExtends(viewsDir, source) {
143
+ // Walk UP the extends chain accumulating block overrides. Closer-to-
144
+ // leaf overrides win; each parent's blocks fill in only the names the
145
+ // chain hasn't already set. When the chain hits a template with no
146
+ // {% extends %}, that's the rootmost source — substitute the
147
+ // accumulated overrides into its block placeholders, with each
148
+ // un-overridden placeholder falling back to its default content.
149
+ //
150
+ // The earlier recursive substitution had a subtle bug: substituting
151
+ // each level's blocks into its parent erased the parent's block
152
+ // placeholders, leaving nothing for the next-level-up to override.
153
+ // The accumulate-then-substitute-once shape side-steps that.
154
+ var allOverrides = {};
155
+ var current = source;
156
+ var depth = 0;
157
+ while (true) {
158
+ if (depth > 16) {
159
+ throw new Error("template: layout inheritance depth exceeded 16 — possible extends cycle");
160
+ }
161
+ var m = current.match(EXTENDS_RE);
162
+ if (!m) break;
163
+ var parentName = m[1];
164
+ var childRest = current.slice(m[0].length);
165
+ var extracted = _extractBlocks(childRest);
166
+ for (var k in extracted.blocks) {
167
+ if (Object.prototype.hasOwnProperty.call(extracted.blocks, k) &&
168
+ !Object.prototype.hasOwnProperty.call(allOverrides, k)) {
169
+ allOverrides[k] = extracted.blocks[k];
170
+ }
171
+ }
172
+ var parentPath = _resolveViewPath(viewsDir, parentName);
173
+ current = fs.readFileSync(parentPath, "utf8");
174
+ depth++;
175
+ }
176
+ return _substituteBlocks(current, allOverrides);
177
+ }
178
+
179
+ // ============================================================
180
+ // Partial inlining (post-extends, pre-tokenize)
181
+ // ============================================================
182
+
183
+ function _inlinePartials(viewsDir, source, depth) {
184
+ if (depth > 16) {
185
+ throw new Error("template: partial recursion depth exceeded 16 — possible cycle");
186
+ }
187
+ return source.replace(/\{\{>\s*([A-Za-z_][A-Za-z0-9_-]*)\s*\}\}/g, function (_, name) {
188
+ var p = _resolvePartialPath(viewsDir, name);
189
+ if (!p) return ""; // missing partial → silent empty (matches hermitstash)
190
+ return _inlinePartials(viewsDir, fs.readFileSync(p, "utf8"), depth + 1);
191
+ });
192
+ }
193
+
194
+ // ============================================================
195
+ // Block tokenizer — emits LITERAL / EXPR_ESCAPED / EXPR_RAW /
196
+ // DIRECTIVE tokens. Partials are already inlined by this point;
197
+ // extends/block already resolved.
198
+ // ============================================================
199
+
200
+ function _tokenize(source) {
201
+ var tokens = [];
202
+ var i = 0;
203
+ var len = source.length;
204
+ while (i < len) {
205
+ var codeStart = source.indexOf("{%", i);
206
+ var rawStart = source.indexOf("{{{", i);
207
+ var exprStart = source.indexOf("{{", i);
208
+ var nextTag = len;
209
+ var tagType = null;
210
+ if (codeStart !== -1 && codeStart < nextTag) { nextTag = codeStart; tagType = "code"; }
211
+ if (rawStart !== -1 && rawStart < nextTag) { nextTag = rawStart; tagType = "raw"; }
212
+ if (exprStart !== -1 && exprStart < nextTag) { nextTag = exprStart; tagType = "expr"; }
213
+ if (rawStart !== -1 && rawStart === nextTag && tagType === "expr") tagType = "raw";
214
+ if (nextTag > i) {
215
+ tokens.push({ kind: "LITERAL", text: source.slice(i, nextTag) });
216
+ }
217
+ if (tagType === null) break;
218
+ if (tagType === "raw") {
219
+ var endRaw = source.indexOf("}}}", nextTag + 3);
220
+ if (endRaw === -1) throw new Error("template: unterminated {{{ raw }}} tag");
221
+ tokens.push({ kind: "EXPR_RAW", expr: source.slice(nextTag + 3, endRaw).trim() });
222
+ i = endRaw + 3;
223
+ } else if (tagType === "expr") {
224
+ var endExpr = source.indexOf("}}", nextTag + 2);
225
+ if (endExpr === -1) throw new Error("template: unterminated {{ expression }} tag");
226
+ tokens.push({ kind: "EXPR_ESCAPED", expr: source.slice(nextTag + 2, endExpr).trim() });
227
+ i = endExpr + 2;
228
+ } else { // code
229
+ var endCode = source.indexOf("%}", nextTag + 2);
230
+ if (endCode === -1) throw new Error("template: unterminated {% directive %} tag");
231
+ tokens.push({ kind: "DIRECTIVE", body: source.slice(nextTag + 2, endCode).trim() });
232
+ i = endCode + 2;
233
+ }
234
+ }
235
+ return tokens;
236
+ }
237
+
238
+ // ============================================================
239
+ // Block parser — tokens → AST
240
+ //
241
+ // Node types:
242
+ // { type: "Template", body: Node[] }
243
+ // { type: "Literal", text: string }
244
+ // { type: "EscExpr", expr: ExprAST }
245
+ // { type: "RawExpr", expr: ExprAST }
246
+ // { type: "If", cond: ExprAST, thenBody: Node[], elseBody: Node[] | null }
247
+ // { type: "For", binding: string, source: ExprAST, body: Node[] }
248
+ //
249
+ // extends and block are resolved BEFORE parsing (during _resolveExtends).
250
+ // Bare `{% block %}` directives that survive into the parser are an
251
+ // error (block outside a child template that doesn't extend anything).
252
+ // ============================================================
253
+
254
+ var DIRECTIVE_HEAD_RE = /^([a-z]+)(?:\s+([\s\S]+))?$/;
255
+
256
+ function _parseTokens(tokens) {
257
+ var pos = 0;
258
+ function peek() { return tokens[pos]; }
259
+ function next() { return tokens[pos++]; }
260
+
261
+ function parseBody(terminators) {
262
+ var body = [];
263
+ while (pos < tokens.length) {
264
+ var t = peek();
265
+ if (t.kind === "LITERAL") { next(); body.push({ type: "Literal", text: t.text }); continue; }
266
+ if (t.kind === "EXPR_ESCAPED"){ next(); body.push({ type: "EscExpr", expr: _parseExpression(t.expr) }); continue; }
267
+ if (t.kind === "EXPR_RAW") { next(); body.push({ type: "RawExpr", expr: _parseExpression(t.expr) }); continue; }
268
+ // DIRECTIVE
269
+ var m = t.body.match(DIRECTIVE_HEAD_RE);
270
+ if (!m) throw new Error("template: malformed directive: {% " + t.body + " %}");
271
+ var head = m[1];
272
+ var tail = m[2] || "";
273
+ if (terminators && terminators.indexOf(head) !== -1) {
274
+ return body;
275
+ }
276
+ next(); // consume directive token
277
+ if (head === "if") {
278
+ var cond = _parseExpression(tail);
279
+ var thenBody = parseBody(["else", "endif"]);
280
+ var elseBody = null;
281
+ var sentinel = peek();
282
+ if (sentinel && sentinel.kind === "DIRECTIVE" && /^else\b/.test(sentinel.body)) {
283
+ next();
284
+ elseBody = parseBody(["endif"]);
285
+ }
286
+ var endTok = next();
287
+ if (!endTok || endTok.kind !== "DIRECTIVE" || !/^endif\b/.test(endTok.body)) {
288
+ throw new Error("template: missing {% endif %}");
289
+ }
290
+ body.push({ type: "If", cond: cond, thenBody: thenBody, elseBody: elseBody });
291
+ continue;
292
+ }
293
+ if (head === "for") {
294
+ var forMatch = tail.match(/^([A-Za-z_][A-Za-z0-9_]*)\s+in\s+([\s\S]+)$/);
295
+ if (!forMatch) throw new Error("template: invalid for syntax: {% for " + tail + " %}");
296
+ var binding = forMatch[1];
297
+ var srcExpr = _parseExpression(forMatch[2]);
298
+ var loopBody = parseBody(["endfor"]);
299
+ var endFor = next();
300
+ if (!endFor || endFor.kind !== "DIRECTIVE" || !/^endfor\b/.test(endFor.body)) {
301
+ throw new Error("template: missing {% endfor %}");
302
+ }
303
+ body.push({ type: "For", binding: binding, source: srcExpr, body: loopBody });
304
+ continue;
305
+ }
306
+ if (head === "block" || head === "endblock") {
307
+ // {% block %} should have been resolved by _resolveExtends. If
308
+ // it's still here, the template uses block syntax without
309
+ // extending anything — pass it through as no-op (the block's
310
+ // default content was already inlined by _substituteBlocks).
311
+ // Hitting this branch usually means the source had a stray
312
+ // block; we accept it silently (matches the spec: child blocks
313
+ // outside an extends are dropped, parent block defaults are
314
+ // already inlined).
315
+ continue;
316
+ }
317
+ if (head === "extends") {
318
+ // Already handled in _resolveExtends. If we see one here it
319
+ // wasn't at the top — error.
320
+ throw new Error("template: {% extends %} must be the first non-whitespace in the file");
321
+ }
322
+ throw new Error("template: unknown directive: {% " + t.body + " %}");
323
+ }
324
+ if (terminators && terminators.length > 0) {
325
+ throw new Error("template: unexpected end of template — expected one of: " + terminators.join(", "));
326
+ }
327
+ return body;
328
+ }
329
+
330
+ return { type: "Template", body: parseBody(null) };
331
+ }
332
+
333
+ // ============================================================
334
+ // Expression tokenizer + parser
335
+ // ============================================================
336
+
337
+ function _tokenizeExpr(src) {
338
+ var tokens = [];
339
+ var i = 0;
340
+ while (i < src.length) {
341
+ var c = src[i];
342
+ if (c === " " || c === "\t" || c === "\n" || c === "\r") { i++; continue; }
343
+ // String literals (single OR double quotes)
344
+ if (c === '"' || c === "'") {
345
+ var quote = c;
346
+ i++; // skip opening quote
347
+ var s = "";
348
+ while (i < src.length && src[i] !== quote) {
349
+ if (src[i] === "\\" && i + 1 < src.length) {
350
+ var esc = src[i + 1];
351
+ if (esc === "n") s += "\n";
352
+ else if (esc === "t") s += "\t";
353
+ else if (esc === "r") s += "\r";
354
+ else if (esc === "\\") s += "\\";
355
+ else s += esc;
356
+ i += 2;
357
+ continue;
358
+ }
359
+ s += src[i++];
360
+ }
361
+ if (i >= src.length) throw new Error("template: unterminated string in expression");
362
+ i++; // closing quote
363
+ tokens.push({ kind: "STRING", value: s });
364
+ continue;
365
+ }
366
+ // Number literals
367
+ if ((c >= "0" && c <= "9") || (c === "." && src[i + 1] >= "0" && src[i + 1] <= "9")) {
368
+ var nstart = i;
369
+ while (i < src.length && ((src[i] >= "0" && src[i] <= "9") || src[i] === ".")) i++;
370
+ tokens.push({ kind: "NUMBER", value: parseFloat(src.slice(nstart, i)) });
371
+ continue;
372
+ }
373
+ // Identifiers + keywords
374
+ if ((c >= "a" && c <= "z") || (c >= "A" && c <= "Z") || c === "_" || c === "$") {
375
+ var istart = i;
376
+ while (i < src.length && (
377
+ (src[i] >= "a" && src[i] <= "z") || (src[i] >= "A" && src[i] <= "Z") ||
378
+ (src[i] >= "0" && src[i] <= "9") || src[i] === "_" || src[i] === "$"
379
+ )) i++;
380
+ var name = src.slice(istart, i);
381
+ if (name === "true") tokens.push({ kind: "BOOL", value: true });
382
+ else if (name === "false") tokens.push({ kind: "BOOL", value: false });
383
+ else if (name === "null") tokens.push({ kind: "NULL" });
384
+ else tokens.push({ kind: "IDENT", name: name });
385
+ continue;
386
+ }
387
+ // Multi-char operators (longest match first)
388
+ var two = src.slice(i, i + 2);
389
+ var three = src.slice(i, i + 3);
390
+ if (three === "===" || three === "!==") { tokens.push({ kind: "OP", op: three }); i += 3; continue; }
391
+ if (two === "==" || two === "!=" || two === "<=" || two === ">=" ||
392
+ two === "&&" || two === "||") {
393
+ tokens.push({ kind: "OP", op: two }); i += 2; continue;
394
+ }
395
+ // Single-char operators / punctuation
396
+ if ("+-*/!<>?:.,()[]".indexOf(c) !== -1) {
397
+ tokens.push({ kind: "OP", op: c });
398
+ i++;
399
+ continue;
400
+ }
401
+ throw new Error("template: unexpected character in expression: '" + c + "' at offset " + i);
402
+ }
403
+ return tokens;
404
+ }
405
+
406
+ function _parseExpression(src) {
407
+ var tokens = _tokenizeExpr(src);
408
+ var pos = 0;
409
+ function peek() { return tokens[pos]; }
410
+ function eat(kind, op) {
411
+ var t = tokens[pos];
412
+ if (!t) return null;
413
+ if (t.kind !== kind) return null;
414
+ if (op !== undefined && t.op !== op) return null;
415
+ pos++;
416
+ return t;
417
+ }
418
+ function expect(kind, op) {
419
+ var t = eat(kind, op);
420
+ if (!t) {
421
+ var got = tokens[pos] ? (tokens[pos].kind + (tokens[pos].op ? ":" + tokens[pos].op : "")) : "EOF";
422
+ throw new Error("template: expected " + kind + (op ? "(" + op + ")" : "") + " got " + got);
423
+ }
424
+ return t;
425
+ }
426
+
427
+ function parseTernary() {
428
+ var cond = parseLogicalOr();
429
+ if (eat("OP", "?")) {
430
+ var thenE = parseLogicalOr();
431
+ expect("OP", ":");
432
+ var elseE = parseLogicalOr();
433
+ return { type: "Ternary", cond: cond, thenE: thenE, elseE: elseE };
434
+ }
435
+ return cond;
436
+ }
437
+ function parseLogicalOr() {
438
+ var left = parseLogicalAnd();
439
+ while (eat("OP", "||")) {
440
+ var right = parseLogicalAnd();
441
+ left = { type: "Binary", op: "||", left: left, right: right };
442
+ }
443
+ return left;
444
+ }
445
+ function parseLogicalAnd() {
446
+ var left = parseEquality();
447
+ while (eat("OP", "&&")) {
448
+ var right = parseEquality();
449
+ left = { type: "Binary", op: "&&", left: left, right: right };
450
+ }
451
+ return left;
452
+ }
453
+ function parseEquality() {
454
+ var left = parseComparison();
455
+ while (true) {
456
+ var op = eat("OP", "===") || eat("OP", "!==") || eat("OP", "==") || eat("OP", "!=");
457
+ if (!op) break;
458
+ var right = parseComparison();
459
+ left = { type: "Binary", op: op.op, left: left, right: right };
460
+ }
461
+ return left;
462
+ }
463
+ function parseComparison() {
464
+ var left = parseAdditive();
465
+ while (true) {
466
+ var op = eat("OP", "<=") || eat("OP", ">=") || eat("OP", "<") || eat("OP", ">");
467
+ if (!op) break;
468
+ var right = parseAdditive();
469
+ left = { type: "Binary", op: op.op, left: left, right: right };
470
+ }
471
+ return left;
472
+ }
473
+ function parseAdditive() {
474
+ var left = parseMultiplicative();
475
+ while (true) {
476
+ var op = eat("OP", "+") || eat("OP", "-");
477
+ if (!op) break;
478
+ var right = parseMultiplicative();
479
+ left = { type: "Binary", op: op.op, left: left, right: right };
480
+ }
481
+ return left;
482
+ }
483
+ function parseMultiplicative() {
484
+ var left = parseUnary();
485
+ while (true) {
486
+ var op = eat("OP", "*") || eat("OP", "/");
487
+ if (!op) break;
488
+ var right = parseUnary();
489
+ left = { type: "Binary", op: op.op, left: left, right: right };
490
+ }
491
+ return left;
492
+ }
493
+ function parseUnary() {
494
+ if (eat("OP", "!")) return { type: "Unary", op: "!", arg: parseUnary() };
495
+ if (eat("OP", "-")) return { type: "Unary", op: "-", arg: parseUnary() };
496
+ return parsePostfix();
497
+ }
498
+ function parsePostfix() {
499
+ var expr = parsePrimary();
500
+ while (true) {
501
+ if (eat("OP", ".")) {
502
+ var ident = expect("IDENT");
503
+ expr = { type: "Member", object: expr, property: ident.name, computed: false };
504
+ } else if (eat("OP", "[")) {
505
+ var idx = parseTernary();
506
+ expect("OP", "]");
507
+ expr = { type: "Member", object: expr, property: idx, computed: true };
508
+ } else if (eat("OP", "(")) {
509
+ var args = [];
510
+ if (peek() && !(peek().kind === "OP" && peek().op === ")")) {
511
+ args.push(parseTernary());
512
+ while (eat("OP", ",")) args.push(parseTernary());
513
+ }
514
+ expect("OP", ")");
515
+ expr = { type: "Call", callee: expr, args: args };
516
+ } else break;
517
+ }
518
+ return expr;
519
+ }
520
+ function parsePrimary() {
521
+ var t = peek();
522
+ if (!t) throw new Error("template: unexpected end of expression");
523
+ if (t.kind === "STRING") { pos++; return { type: "Literal", value: t.value }; }
524
+ if (t.kind === "NUMBER") { pos++; return { type: "Literal", value: t.value }; }
525
+ if (t.kind === "BOOL") { pos++; return { type: "Literal", value: t.value }; }
526
+ if (t.kind === "NULL") { pos++; return { type: "Literal", value: null }; }
527
+ if (t.kind === "IDENT") { pos++; return { type: "Identifier", name: t.name }; }
528
+ if (t.kind === "OP" && t.op === "(") {
529
+ pos++;
530
+ var inner = parseTernary();
531
+ expect("OP", ")");
532
+ return inner;
533
+ }
534
+ throw new Error("template: unexpected token in expression: " +
535
+ (t.kind + (t.op ? ":" + t.op : "")));
536
+ }
537
+
538
+ var ast = parseTernary();
539
+ if (pos < tokens.length) {
540
+ var rest = tokens[pos];
541
+ throw new Error("template: trailing tokens in expression: " +
542
+ (rest.kind + (rest.op ? ":" + rest.op : "")));
543
+ }
544
+ return ast;
545
+ }
546
+
547
+ // ============================================================
548
+ // Expression evaluator — walks expression AST against a scope chain
549
+ // ============================================================
550
+
551
+ function _scopeLookup(scopes, name) {
552
+ // Walk innermost → outermost; returns undefined if not found.
553
+ for (var i = scopes.length - 1; i >= 0; i--) {
554
+ var s = scopes[i];
555
+ if (s !== null && s !== undefined && Object.prototype.hasOwnProperty.call(s, name)) {
556
+ return s[name];
557
+ }
558
+ }
559
+ return undefined;
560
+ }
561
+
562
+ function _evalExpr(node, scopes) {
563
+ switch (node.type) {
564
+ case "Literal": return node.value;
565
+ case "Identifier": return _scopeLookup(scopes, node.name);
566
+ case "Member":
567
+ var obj = _evalExpr(node.object, scopes);
568
+ if (obj === null || obj === undefined) return undefined;
569
+ var key = node.computed ? _evalExpr(node.property, scopes) : node.property;
570
+ // Block prototype-chain access — only own properties resolve.
571
+ // Prevents `{{ foo.constructor }}` / `{{ foo.__proto__ }}` from
572
+ // walking out of the data scope into the runtime.
573
+ if (Object.prototype.hasOwnProperty.call(obj, key) ||
574
+ // Arrays: numeric indices + .length are legitimate even though
575
+ // .length is on the prototype shape (it's an own property via
576
+ // the array's internal slot — hasOwn returns true)
577
+ (Array.isArray(obj) && key === "length")) {
578
+ return obj[key];
579
+ }
580
+ return undefined;
581
+ case "Call":
582
+ var callee = _evalExpr(node.callee, scopes);
583
+ if (typeof callee !== "function") {
584
+ throw new Error("template: cannot call non-function: " +
585
+ (node.callee.type === "Member" ? node.callee.property : node.callee.name || "<expr>"));
586
+ }
587
+ var args = [];
588
+ for (var ai = 0; ai < node.args.length; ai++) {
589
+ args.push(_evalExpr(node.args[ai], scopes));
590
+ }
591
+ // Bind `this` to the receiver when the callee is a member access.
592
+ var thisRef = null;
593
+ if (node.callee.type === "Member") {
594
+ thisRef = _evalExpr(node.callee.object, scopes);
595
+ }
596
+ return callee.apply(thisRef, args);
597
+ case "Unary":
598
+ var v = _evalExpr(node.arg, scopes);
599
+ if (node.op === "!") return !v;
600
+ if (node.op === "-") return -Number(v);
601
+ throw new Error("template: unknown unary op: " + node.op);
602
+ case "Binary":
603
+ if (node.op === "&&") return _evalExpr(node.left, scopes) && _evalExpr(node.right, scopes);
604
+ if (node.op === "||") return _evalExpr(node.left, scopes) || _evalExpr(node.right, scopes);
605
+ var L = _evalExpr(node.left, scopes);
606
+ var R = _evalExpr(node.right, scopes);
607
+ switch (node.op) {
608
+ case "===": return L === R;
609
+ case "!==": return L !== R;
610
+ case "==": return L == R;
611
+ case "!=": return L != R;
612
+ case "<": return L < R;
613
+ case "<=": return L <= R;
614
+ case ">": return L > R;
615
+ case ">=": return L >= R;
616
+ case "+": return L + R;
617
+ case "-": return L - R;
618
+ case "*": return L * R;
619
+ case "/": return L / R;
620
+ }
621
+ throw new Error("template: unknown binary op: " + node.op);
622
+ case "Ternary":
623
+ return _evalExpr(node.cond, scopes) ? _evalExpr(node.thenE, scopes) : _evalExpr(node.elseE, scopes);
624
+ default:
625
+ throw new Error("template: unknown expression node type: " + node.type);
626
+ }
627
+ }
628
+
629
+ // ============================================================
630
+ // Block evaluator — walks block AST, builds output string
631
+ // ============================================================
632
+
633
+ function _evalBlock(nodes, scopes, escFn) {
634
+ var out = "";
635
+ for (var i = 0; i < nodes.length; i++) {
636
+ var n = nodes[i];
637
+ switch (n.type) {
638
+ case "Literal": out += n.text; break;
639
+ case "EscExpr":
640
+ out += escFn(_evalExpr(n.expr, scopes));
641
+ break;
642
+ case "RawExpr":
643
+ var rawV = _evalExpr(n.expr, scopes);
644
+ if (rawV !== null && rawV !== undefined) out += String(rawV);
645
+ break;
646
+ case "If":
647
+ if (_evalExpr(n.cond, scopes)) {
648
+ out += _evalBlock(n.thenBody, scopes, escFn);
649
+ } else if (n.elseBody) {
650
+ out += _evalBlock(n.elseBody, scopes, escFn);
651
+ }
652
+ break;
653
+ case "For":
654
+ var src = _evalExpr(n.source, scopes);
655
+ if (src && typeof src.length === "number") {
656
+ for (var fi = 0; fi < src.length; fi++) {
657
+ var loopScope = {};
658
+ loopScope[n.binding] = src[fi];
659
+ scopes.push(loopScope);
660
+ out += _evalBlock(n.body, scopes, escFn);
661
+ scopes.pop();
662
+ }
663
+ }
664
+ break;
665
+ default:
666
+ throw new Error("template: unknown block node type: " + n.type);
667
+ }
668
+ }
669
+ return out;
670
+ }
671
+
672
+ // ============================================================
673
+ // Engine instance
674
+ // ============================================================
675
+
676
+ function create(opts) {
677
+ opts = opts || {};
678
+ validateOpts(opts, ["viewsDir", "cache", "escapeHtml"], "b.template");
679
+ if (!opts.viewsDir) {
680
+ throw new Error("template.create({ viewsDir }) is required");
681
+ }
682
+ if (!fs.existsSync(opts.viewsDir)) {
683
+ throw new Error("template: viewsDir does not exist: " + opts.viewsDir);
684
+ }
685
+ var viewsDir = path.resolve(opts.viewsDir);
686
+ var cacheOn = opts.cache !== false;
687
+ var customEscape = typeof opts.escapeHtml === "function" ? opts.escapeHtml : escapeHtml;
688
+ var astCache = {};
689
+
690
+ function compile(viewName) {
691
+ if (cacheOn && astCache[viewName]) return astCache[viewName];
692
+ var viewPath = _resolveViewPath(viewsDir, viewName);
693
+ var source = fs.readFileSync(viewPath, "utf8");
694
+ source = _resolveExtends(viewsDir, source);
695
+ source = _inlinePartials(viewsDir, source, 0);
696
+ var tokens = _tokenize(source);
697
+ var ast = _parseTokens(tokens);
698
+ if (cacheOn) astCache[viewName] = ast;
699
+ return ast;
700
+ }
701
+
702
+ function render(viewName, data) {
703
+ var ast = compile(viewName);
704
+ return _evalBlock(ast.body, [data || {}], customEscape);
705
+ }
706
+
707
+ function reset() { astCache = {}; }
708
+
709
+ // Walk viewsDir, compile every .html file. Surfaces parse errors at
710
+ // boot time (with the offending view name in the message) rather than
711
+ // at first request. Operators call this from the bootstrap path so
712
+ // a typo like `{% if not foo %}` fails the deploy, not the user.
713
+ // Returns the list of view names compiled.
714
+ function precompileAll() {
715
+ var compiled = [];
716
+ function walk(dir, prefix) {
717
+ var entries = fs.readdirSync(dir, { withFileTypes: true });
718
+ for (var i = 0; i < entries.length; i++) {
719
+ var e = entries[i];
720
+ var rel = prefix ? prefix + "/" + e.name : e.name;
721
+ if (e.isDirectory()) {
722
+ walk(path.join(dir, e.name), rel);
723
+ } else if (e.isFile() && /\.html$/.test(e.name)) {
724
+ var viewName = rel.replace(/\.html$/, "");
725
+ try {
726
+ compile(viewName);
727
+ } catch (err) {
728
+ // Re-throw with the view name in the message — the parser's
729
+ // own "trailing tokens" / "malformed directive" don't say
730
+ // which file the syntax error lives in.
731
+ var wrapped = new Error("template: precompile failed for view '" +
732
+ viewName + "': " + (err && err.message || String(err)));
733
+ wrapped.cause = err;
734
+ wrapped.viewName = viewName;
735
+ throw wrapped;
736
+ }
737
+ compiled.push(viewName);
738
+ }
739
+ }
740
+ }
741
+ walk(viewsDir, "");
742
+ return compiled;
743
+ }
744
+
745
+ return {
746
+ compile: compile,
747
+ render: render,
748
+ reset: reset,
749
+ precompileAll: precompileAll,
750
+ viewsDir: viewsDir,
751
+ escapeHtml: customEscape,
752
+ };
753
+ }
754
+
755
+ // ---- Default singleton ----
756
+
757
+ var _default = null;
758
+ function _ensureDefault() {
759
+ if (!_default) {
760
+ var defaultDir = path.resolve(process.cwd(), "views");
761
+ if (!fs.existsSync(defaultDir)) {
762
+ throw new Error("template.render() default uses <cwd>/views which doesn't exist; " +
763
+ "call template.create({ viewsDir }) for a custom location");
764
+ }
765
+ _default = create({ viewsDir: defaultDir });
766
+ }
767
+ return _default;
768
+ }
769
+
770
+ function render(viewName, data) {
771
+ return _ensureDefault().render(viewName, data);
772
+ }
773
+
774
+ function _resetDefaultForTest() { _default = null; }
775
+
776
+ module.exports = {
777
+ create: create,
778
+ render: render,
779
+ escapeHtml: escapeHtml,
780
+ _resetDefaultForTest: _resetDefaultForTest,
781
+ };