@lucidkiln/core 1.3.0 → 1.5.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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { $ as compare, $t as escapeUrl, A as consume, At as additionsIn, B as loadTemplate, Bt as fillScope, C as getAttr, Ct as contentSets, D as after, Dt as passesFrom, E as addSlotFlags, Et as passesAhead, F as fail, Ft as RenderState, G as renderTemplate, Gt as sectionCopy, H as locating, Ht as childScope, I as hold, It as Run, J as unhold, Jt as suggest, K as silence, Kt as sectionScope, L as holdData, Lt as blockScope, M as embed, Mt as closeOutlets, N as embedKeyed, Nt as recordAddition, O as all, Ot as runAhead, P as embedScope, Pt as takeOutput, Q as MISSING, Qt as escapeHtml, R as importsFor, Rt as emptyOut, S as toTime, St as atFront, T as readableNames, Tt as mayRunAhead, U as markCaller, Ut as lookup$1, V as locate, Vt as startCapture, W as passData, Wt as ownerOf, X as write, Xt as isSafe, Y as withCaller, Yt as Markup, Z as FORMATTERS, Zt as safe, _ as markupText, _t as unwrap, a as operatorFunction, an as KilnSyntaxError, at as isHashLike, b as toPieces, bt as expose, c as checkDepth, ct as mapKeys, d as functionArgument, dt as templateFunctions, en as escapeWith, et as describeType, f as insertedPiece, ft as toNumber, g as mapContents, gt as typeName, h as listOf$1, ht as truthy, i as contains, in as KilnRenderError, it as isEmpty, j as consumeAt, jt as checkLate, k as checkLength, kt as runSequence, l as entriesOf, lt as matchesType, m as isHtmlStrategy, mt as toStringArgument, n as builtinFunctions, nn as resolveTemplateName, nt as equals, o as rangeOperator, on as createDiagnostic, ot as isPlainObject, p as integerArgument, pt as toStr, q as step, qt as variableNames, r as builtinTests, rn as KilnIssue, rt as hashKeys, s as Kept, sn as issue, st as literalOptions, t as Source, tn as TEMPLATE_EXTENSION, tt as describeValue, u as fromPieces, ut as setOwn, v as readProperty, vt as valueLabel, w as getMethod, wt as isRoot, x as toPlainData, xt as lookup, y as scanHtml, yt as BLOCKED_NAMES, z as isPromise, zt as endCapture } from "./source-BbikGqIb.js";
2
- import { a as ESCAPE_STRATEGIES, i as DEFAULT_SLOT, r as scanParts, t as parse } from "./parser-isboTef0.js";
1
+ import { $ as compare, $t as escapeUrl, A as consume, At as additionsIn, B as loadTemplate, Bt as fillScope, C as getAttr, Ct as contentSets, D as after, Dt as passesFrom, E as addSlotFlags, Et as passesAhead, F as fail, Ft as RenderState, G as renderTemplate, Gt as sectionCopy, H as locating, Ht as childScope, I as hold, It as Run, J as unhold, Jt as suggest, K as silence, Kt as sectionScope, L as holdData, Lt as blockScope, M as embed, Mt as closeOutlets, N as embedKeyed, Nt as recordAddition, O as all, Ot as runAhead, P as embedScope, Pt as takeOutput, Q as MISSING, Qt as escapeHtml, R as importsFor, Rt as emptyOut, S as toTime, St as atFront, T as readableNames, Tt as mayRunAhead, U as markCaller, Ut as lookup$1, V as locate, Vt as startCapture, W as passData, Wt as ownerOf, X as write, Xt as isSafe, Y as withCaller, Yt as Markup, Z as FORMATTERS, Zt as safe, _ as markupText, _t as unwrap, a as operatorFunction, an as KilnSyntaxError, at as isHashLike, b as toPieces, bt as expose, c as checkDepth, ct as mapKeys, d as functionArgument, dt as templateFunctions, en as escapeWith, et as describeType, f as insertedPiece, ft as toNumber, g as mapContents, gt as typeName, h as listOf$1, ht as truthy, i as contains, in as KilnRenderError, it as isEmpty, j as consumeAt, jt as checkLate, k as checkLength, kt as runSequence, l as entriesOf, lt as matchesType, m as isHtmlStrategy, mt as toStringArgument, n as builtinFunctions, nn as resolveTemplateName, nt as equals, o as rangeOperator, on as createDiagnostic, ot as isPlainObject, p as integerArgument, pt as toStr, q as step, qt as variableNames, r as builtinTests, rn as KilnIssue, rt as hashKeys, s as Kept, sn as issue, st as literalOptions, t as Source, tn as TEMPLATE_EXTENSION, tt as describeValue, u as fromPieces, ut as setOwn, v as readProperty, vt as valueLabel, w as getMethod, wt as isRoot, x as toPlainData, xt as lookup, y as scanHtml, yt as BLOCKED_NAMES, z as isPromise, zt as endCapture } from "./source-C2pjTx-Y.js";
2
+ import { a as ESCAPE_STRATEGIES, i as DEFAULT_SLOT, r as scanParts, t as parse } from "./parser-BZpRlGWi.js";
3
3
  //#region src/analyzer.ts
4
4
  const MAX_DEPTH$1 = 1e3;
5
5
  /** The statement lists nested inside a statement. */
@@ -108,8 +108,9 @@ const analyzeTemplate = (template, globals, reads) => {
108
108
  else expression(node);
109
109
  };
110
110
  if (template.slotNames.length > 0 || template.parent) scopes[0]?.add("slots");
111
+ let inExport = false;
111
112
  const read = (name, span, isGuarded) => {
112
- if (declared(name) || importAliases.has(name) || importedNames.has(name)) return;
113
+ if (inExport || declared(name) || importAliases.has(name) || importedNames.has(name)) return;
113
114
  const inMacro = scopes.includes(null);
114
115
  if (!inMacro) variables.add(name);
115
116
  const found = inMacro ? reads?.macros : reads?.context;
@@ -217,6 +218,11 @@ const analyzeTemplate = (template, globals, reads) => {
217
218
  expression(node.value);
218
219
  declare(node.name);
219
220
  return;
221
+ case "Export":
222
+ inExport = true;
223
+ withScope([], () => expression(node.value), true);
224
+ inExport = false;
225
+ return;
220
226
  case "SetBlock":
221
227
  statements(node.body);
222
228
  declare(node.name);
@@ -328,7 +334,16 @@ const analyzeTemplate = (template, globals, reads) => {
328
334
  tests: [...tests],
329
335
  templates,
330
336
  blocks,
331
- macros: [...macroNames]
337
+ macros: [...macroNames],
338
+ exports: template.ast.body.flatMap((node) => node.type === "Export" ? [node.value.type === "Literal" ? {
339
+ name: node.name,
340
+ literal: true,
341
+ value: node.value.value
342
+ } : {
343
+ name: node.name,
344
+ literal: false,
345
+ value: null
346
+ }] : [])
332
347
  };
333
348
  };
334
349
  //#endregion
@@ -1740,19 +1755,33 @@ const hashId = (text) => {
1740
1755
  return (a >>> 0).toString(16).padStart(8, "0") + (b >>> 0).toString(16).padStart(8, "0");
1741
1756
  };
1742
1757
  /**
1743
- * Records an island in the manifest and returns its id. The id comes from the template and props, so it is the same
1744
- * on every page and in every build, and a page cached from an earlier build never asks for a different island.
1758
+ * Records an island in the manifest and returns its id. The id comes from the template, props, locale and time zone,
1759
+ * so it is the same on every page and in every build, and a page cached from an earlier build never asks for a
1760
+ * different island.
1745
1761
  */
1746
1762
  const recordIsland = (run, span, islands, template, props) => {
1747
- const key = JSON.stringify([template, props]);
1763
+ const { locale, timeZone } = run.state;
1764
+ const key = JSON.stringify([
1765
+ template,
1766
+ props,
1767
+ locale,
1768
+ timeZone
1769
+ ]);
1748
1770
  const id = hashId(key);
1749
1771
  const { manifest } = islands;
1750
1772
  const existing = Object.hasOwn(manifest, id) ? manifest[id] : void 0;
1751
1773
  if (existing === void 0) manifest[id] = {
1752
1774
  template,
1753
- props
1775
+ props,
1776
+ locale,
1777
+ timeZone
1754
1778
  };
1755
- else if (JSON.stringify([existing.template, existing.props]) !== key) throw fail(run, span, "island-collision", `Two different islands have the id "${id}". Change one island's props slightly`);
1779
+ else if (JSON.stringify([
1780
+ existing.template,
1781
+ existing.props,
1782
+ existing.locale,
1783
+ existing.timeZone
1784
+ ]) !== key) throw fail(run, span, "island-collision", `Two different islands have the id "${id}". Change one island's props slightly`);
1756
1785
  run.capture?.section?.deferred.push(id);
1757
1786
  return id;
1758
1787
  };
@@ -1947,7 +1976,8 @@ const effectsOf = (statements, env) => {
1947
1976
  switch (node.type) {
1948
1977
  case "Macro":
1949
1978
  case "Import":
1950
- case "FromImport": continue;
1979
+ case "FromImport":
1980
+ case "Export": continue;
1951
1981
  case "Name":
1952
1982
  reads.add(node.name);
1953
1983
  break;
@@ -2325,6 +2355,7 @@ var Compiler = class {
2325
2355
  blocks: /* @__PURE__ */ new Map(),
2326
2356
  blockList: void 0,
2327
2357
  macros: /* @__PURE__ */ new Map(),
2358
+ exports: /* @__PURE__ */ new Map(),
2328
2359
  imports: [],
2329
2360
  resolved: /* @__PURE__ */ new Map(),
2330
2361
  keyed: void 0,
@@ -2340,6 +2371,7 @@ var Compiler = class {
2340
2371
  const body = this.#ast.body;
2341
2372
  this.#collectNames(body);
2342
2373
  this.#collectMacros(body);
2374
+ this.#collectExports(body);
2343
2375
  const first = body.find((statement) => !isBlank$1(statement));
2344
2376
  const extendsNode = first?.type === "Extends" ? first : null;
2345
2377
  this.#checkPlacement(body, extendsNode !== null);
@@ -2501,6 +2533,73 @@ var Compiler = class {
2501
2533
  this.#inMacro = saved.inMacro;
2502
2534
  }
2503
2535
  }
2536
+ /** Compiles top-level exports on their own, since they never run with the template. */
2537
+ #collectExports(body) {
2538
+ const exports = this.#template.exports;
2539
+ for (const statement of body) {
2540
+ if (statement.type !== "Export") continue;
2541
+ if (exports.has(statement.name)) {
2542
+ this.#error("duplicate-export", `"${statement.name}" is exported more than once`, statement.span);
2543
+ continue;
2544
+ }
2545
+ this.#checkExportReads(statement.value, /* @__PURE__ */ new Set());
2546
+ exports.set(statement.name, this.#expr(statement.value));
2547
+ }
2548
+ }
2549
+ /** Reports variables an export reads that only a render has, since `evaluate` runs it with globals alone. */
2550
+ #checkExportReads(node, params) {
2551
+ const visit = (child) => this.#checkExportReads(child, params);
2552
+ switch (node.type) {
2553
+ case "Literal":
2554
+ case "Invalid": return;
2555
+ case "Name":
2556
+ if (!params.has(node.name) && !(node.name in this.#env.globals) && !this.#importAliases.has(node.name)) this.#error("export-scope", `"${node.name}" isn't available to an export, which can only read globals, its arrow functions' parameters and imported macros`, node.span);
2557
+ return;
2558
+ case "Arrow":
2559
+ this.#checkExportReads(node.body, /* @__PURE__ */ new Set([...params, ...node.params]));
2560
+ return;
2561
+ case "Interpolation":
2562
+ node.parts.forEach(visit);
2563
+ return;
2564
+ case "Array":
2565
+ for (const element of node.elements) visit(element.type === "Spread" ? element.value : element);
2566
+ return;
2567
+ case "Hash":
2568
+ for (const entry of node.entries) {
2569
+ if (entry.type === "Property" && entry.key.type !== "Literal") visit(entry.key);
2570
+ visit(entry.value);
2571
+ }
2572
+ return;
2573
+ case "Unary":
2574
+ visit(node.operand);
2575
+ return;
2576
+ case "Binary":
2577
+ visit(node.left);
2578
+ visit(node.right);
2579
+ return;
2580
+ case "Conditional":
2581
+ visit(node.test);
2582
+ visit(node.consequent);
2583
+ if (node.alternate) visit(node.alternate);
2584
+ return;
2585
+ case "Member":
2586
+ visit(node.object);
2587
+ if (node.property.type !== "Literal") visit(node.property);
2588
+ return;
2589
+ case "OptionalChain":
2590
+ visit(node.expression);
2591
+ return;
2592
+ case "Call":
2593
+ if (node.callee.type !== "Name") visit(node.callee);
2594
+ for (const arg of node.args) visit(arg.value);
2595
+ return;
2596
+ case "Filter":
2597
+ case "Test":
2598
+ visit(node.input);
2599
+ for (const arg of node.args) visit(arg.value);
2600
+ return;
2601
+ }
2602
+ }
2504
2603
  /** Checks where tags may appear: `extends` first, child templates' top level, `props` and macros. */
2505
2604
  #checkPlacement(body, isChild) {
2506
2605
  let seenContent = false;
@@ -2523,19 +2622,21 @@ var Compiler = class {
2523
2622
  break;
2524
2623
  case "Set":
2525
2624
  case "SetBlock":
2625
+ case "Export":
2526
2626
  case "Import":
2527
2627
  case "FromImport":
2528
2628
  case "Macro": break;
2529
2629
  default: seenContent = true;
2530
2630
  }
2531
2631
  if (isChild) {
2532
- if (!(statement.type === "Extends" || statement.type === "Block" || statement.type === "Set" || statement.type === "SetBlock" || statement.type === "Props" || statement.type === "Import" || statement.type === "FromImport" || statement.type === "Macro" || isBlank$1(statement))) this.#error("invalid-child-content", "A template that uses \"extends\" can only contain blocks, \"set\", \"props\", \"import\", \"from\" and \"macro\" at its top level", statement.span);
2632
+ if (!(statement.type === "Extends" || statement.type === "Block" || statement.type === "Set" || statement.type === "SetBlock" || statement.type === "Props" || statement.type === "Export" || statement.type === "Import" || statement.type === "FromImport" || statement.type === "Macro" || isBlank$1(statement))) this.#error("invalid-child-content", "A template that uses \"extends\" can only contain blocks, \"set\", \"props\", \"export\", \"import\", \"from\" and \"macro\" at its top level", statement.span);
2533
2633
  }
2534
2634
  }
2535
2635
  const checkNested = (statements, depth, inMacro) => {
2536
2636
  for (const statement of statements) {
2537
2637
  if (depth > 0 && statement.type === "Macro") this.#error("invalid-macro-placement", "Macros must be defined at the top level of a template", statement.span);
2538
2638
  if (depth > 0 && statement.type === "Extends") this.#error("extends-not-first", "\"extends\" must be the first tag in the template", statement.span);
2639
+ if (depth > 0 && statement.type === "Export") this.#error("misplaced-export", "Exports must be at the top level of a template", statement.span);
2539
2640
  if (depth > 0 && statement.type === "Props") this.#error("props-not-first", "\"props\" must be at the top level of a template", statement.span);
2540
2641
  if (inMacro && statement.type === "Block") this.#error("invalid-block-placement", "Blocks cannot be defined inside macros", statement.span);
2541
2642
  const nestedMacro = inMacro || statement.type === "Macro";
@@ -2716,7 +2817,8 @@ var Compiler = class {
2716
2817
  case "Slot": return this.#slot(node);
2717
2818
  case "Macro":
2718
2819
  case "Import":
2719
- case "FromImport": return NOOP;
2820
+ case "FromImport":
2821
+ case "Export": return NOOP;
2720
2822
  case "With": return this.#with(node);
2721
2823
  case "Cache": return this.#cache(node);
2722
2824
  case "Outlet": return this.#outlet(node);
@@ -3901,7 +4003,7 @@ const readingLabel = (key) => `Reading "${key}"`;
3901
4003
  /** `set`: assigns where the variable already exists, or declares it in the current scope. */
3902
4004
  const assign = (run, scope, name, value, span) => {
3903
4005
  let owner = ownerOf(scope, name);
3904
- if (owner === run.state.globals) throw fail(run, span, "assign-global", `Cannot assign to global "${name}"`);
4006
+ if (owner === run.state.globals || owner === run.state.env.globals) throw fail(run, span, "assign-global", `Cannot assign to global "${name}"`);
3905
4007
  if (owner !== null && run.capture?.section) owner = sectionCopy(scope, owner);
3906
4008
  (owner ?? scope)[name] = value ?? null;
3907
4009
  };
@@ -5161,6 +5263,7 @@ var Generator = class {
5161
5263
  case "Component": return this.#component(statement, context);
5162
5264
  case "Slot": return this.#slot(statement, context);
5163
5265
  case "Block": return this.#block(statement, context);
5266
+ case "Export": return [];
5164
5267
  default: return unsupported();
5165
5268
  }
5166
5269
  }
@@ -8106,6 +8209,12 @@ const RESERVED = {
8106
8209
  ]),
8107
8210
  test: /* @__PURE__ */ new Set(["defined"])
8108
8211
  };
8212
+ /** Kiln's own function, filter and test names, sorted and including reserved ones, for hosts that stop a name replacing one. */
8213
+ const builtins = {
8214
+ functions: [...Object.keys(builtinFunctions), ...RESERVED.function].sort(),
8215
+ filters: [...Object.keys(builtinFilters), ...RESERVED.filter].sort(),
8216
+ tests: [...Object.keys(builtinTests), ...RESERVED.test].sort()
8217
+ };
8109
8218
  const builtinMaps = /* @__PURE__ */ new WeakMap();
8110
8219
  /** Built-ins of one kind as a map, made once and shared by environments that add none of their own. */
8111
8220
  const builtinMap = (builtins) => {
@@ -8185,11 +8294,7 @@ var Environment = class {
8185
8294
  if (typeof check !== "function") throw new TypeError(`type "${name}" must be a function`);
8186
8295
  this.types.set(name, check);
8187
8296
  }
8188
- const globals = childScope(null);
8189
- const provided = options.globals ?? {};
8190
- if (!isPlainObject(provided)) throw new TypeError("globals must be a plain object");
8191
- for (const key of hashKeys(provided)) globals[key] = provided[key] ?? null;
8192
- this.globals = globals;
8297
+ this.globals = globalScope(null, options.globals ?? {});
8193
8298
  }
8194
8299
  load(name) {
8195
8300
  const cached = this.#cache.get(name);
@@ -8341,6 +8446,22 @@ var Environment = class {
8341
8446
  }
8342
8447
  });
8343
8448
  }
8449
+ /** Runs one export with only the globals in scope, for `evaluate`. */
8450
+ async evaluate(name, exportName, options) {
8451
+ let render = this.#prepare(name, {}, options);
8452
+ if (isPromise(render)) render = await render;
8453
+ const { template, state, resolved } = render;
8454
+ const compiled = template.exports.get(exportName);
8455
+ if (!compiled) return void 0;
8456
+ const run = new Run(state, template, 0, null, null);
8457
+ const imports = importsFor(run, template);
8458
+ run.imports = isPromise(imports) ? await imports : imports;
8459
+ const value = compiled.ev(run, childScope(state.globals));
8460
+ if (!isPromise(value)) return value;
8461
+ const result = unhold(await untilAborted(value, state.signal, resolved));
8462
+ if (state.signal?.aborted) throw aborted(resolved);
8463
+ return result;
8464
+ }
8344
8465
  /** Finds the template and makes the state, scope and output for one render. */
8345
8466
  #prepare(name, context, options) {
8346
8467
  let resolved = this.#names.get(name);
@@ -8367,9 +8488,10 @@ var Environment = class {
8367
8488
  if (!template) throw new KilnRenderError("missing-template", `Template "${resolved}" was not found`, resolved);
8368
8489
  if (template.hasErrors) throw template.syntaxError();
8369
8490
  if (!isPlainObject(context)) throw new TypeError("render context must be a plain object");
8370
- const state = new RenderState(this, this.globals, this.limits.maxSteps, this.limits.maxOutputLength, this.limits.maxDepth, options.locale ?? this.locale, options.timeZone ?? this.timeZone, options.state, options.signal);
8491
+ const globals = options.globals === void 0 ? this.globals : globalScope(this.globals, options.globals);
8492
+ const state = new RenderState(this, globals, this.limits.maxSteps, this.limits.maxOutputLength, this.limits.maxDepth, options.locale ?? this.locale, options.timeZone ?? this.timeZone, options.state, options.signal);
8371
8493
  if (options.signal?.aborted) throw aborted(resolved);
8372
- const scope = childScope(this.globals);
8494
+ const scope = childScope(globals);
8373
8495
  const passed = hashKeys(context);
8374
8496
  for (const key of passed) scope[key] = context[key] ?? null;
8375
8497
  addSlotFlags(scope, template, null);
@@ -8390,6 +8512,13 @@ var Environment = class {
8390
8512
  return renderTemplate(render.state, template, render.scope, render.out, 0, null, render.passed, null, null, template.parentSpan, block);
8391
8513
  }
8392
8514
  };
8515
+ /** A scope inside `parent` holding `values`: the environment's globals, or one render's over them. */
8516
+ const globalScope = (parent, values) => {
8517
+ if (!isPlainObject(values)) throw new TypeError("globals must be a plain object");
8518
+ const scope = childScope(parent);
8519
+ for (const key of hashKeys(values)) scope[key] = values[key] ?? null;
8520
+ return scope;
8521
+ };
8393
8522
  const aborted = (resolved) => new KilnRenderError("aborted", "Render was aborted", resolved);
8394
8523
  /**
8395
8524
  * Waits for `work`, or rejects as soon as `signal` aborts, when the signal can say so, as a real `AbortSignal` can.
@@ -8439,10 +8568,15 @@ const createApi = (env) => {
8439
8568
  return env.render(name, context, renderOptions ?? {}, block);
8440
8569
  };
8441
8570
  const renderStream = (name, context, renderOptions) => env.renderStream(name, context, renderOptions ?? {});
8571
+ const evaluate = (name, exportName, options) => {
8572
+ if (typeof exportName !== "string") throw new TypeError("evaluate needs an export name");
8573
+ return env.evaluate(name, exportName, options ?? {});
8574
+ };
8442
8575
  return {
8443
8576
  render,
8444
8577
  renderBlock,
8445
8578
  renderStream,
8579
+ evaluate,
8446
8580
  check: async (name, source) => {
8447
8581
  const template = await env.compileFor(name, source);
8448
8582
  if (!template) {
@@ -8695,6 +8829,6 @@ const generateTypes = async (kiln, names) => {
8695
8829
  ].join("\n");
8696
8830
  };
8697
8831
  //#endregion
8698
- export { KilnRenderError, KilnSyntaxError, Markup, createKiln, deferIslands, expose, generateManifest, generateTypes, isSafe, islandScript, lookup, memoryCache, memoryLoader, safe, streamIslands, templateText, withRender };
8832
+ export { KilnRenderError, KilnSyntaxError, Markup, builtins, createKiln, deferIslands, expose, generateManifest, generateTypes, isSafe, islandScript, lookup, memoryCache, memoryLoader, safe, streamIslands, templateText, withRender };
8699
8833
 
8700
8834
  //# sourceMappingURL=index.js.map