@lucidkiln/core 1.3.0 → 1.4.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
@@ -1947,7 +1962,8 @@ const effectsOf = (statements, env) => {
1947
1962
  switch (node.type) {
1948
1963
  case "Macro":
1949
1964
  case "Import":
1950
- case "FromImport": continue;
1965
+ case "FromImport":
1966
+ case "Export": continue;
1951
1967
  case "Name":
1952
1968
  reads.add(node.name);
1953
1969
  break;
@@ -2325,6 +2341,7 @@ var Compiler = class {
2325
2341
  blocks: /* @__PURE__ */ new Map(),
2326
2342
  blockList: void 0,
2327
2343
  macros: /* @__PURE__ */ new Map(),
2344
+ exports: /* @__PURE__ */ new Map(),
2328
2345
  imports: [],
2329
2346
  resolved: /* @__PURE__ */ new Map(),
2330
2347
  keyed: void 0,
@@ -2340,6 +2357,7 @@ var Compiler = class {
2340
2357
  const body = this.#ast.body;
2341
2358
  this.#collectNames(body);
2342
2359
  this.#collectMacros(body);
2360
+ this.#collectExports(body);
2343
2361
  const first = body.find((statement) => !isBlank$1(statement));
2344
2362
  const extendsNode = first?.type === "Extends" ? first : null;
2345
2363
  this.#checkPlacement(body, extendsNode !== null);
@@ -2501,6 +2519,73 @@ var Compiler = class {
2501
2519
  this.#inMacro = saved.inMacro;
2502
2520
  }
2503
2521
  }
2522
+ /** Compiles top-level exports on their own, since they never run with the template. */
2523
+ #collectExports(body) {
2524
+ const exports = this.#template.exports;
2525
+ for (const statement of body) {
2526
+ if (statement.type !== "Export") continue;
2527
+ if (exports.has(statement.name)) {
2528
+ this.#error("duplicate-export", `"${statement.name}" is exported more than once`, statement.span);
2529
+ continue;
2530
+ }
2531
+ this.#checkExportReads(statement.value, /* @__PURE__ */ new Set());
2532
+ exports.set(statement.name, this.#expr(statement.value));
2533
+ }
2534
+ }
2535
+ /** Reports variables an export reads that only a render has, since `evaluate` runs it with globals alone. */
2536
+ #checkExportReads(node, params) {
2537
+ const visit = (child) => this.#checkExportReads(child, params);
2538
+ switch (node.type) {
2539
+ case "Literal":
2540
+ case "Invalid": return;
2541
+ case "Name":
2542
+ 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);
2543
+ return;
2544
+ case "Arrow":
2545
+ this.#checkExportReads(node.body, /* @__PURE__ */ new Set([...params, ...node.params]));
2546
+ return;
2547
+ case "Interpolation":
2548
+ node.parts.forEach(visit);
2549
+ return;
2550
+ case "Array":
2551
+ for (const element of node.elements) visit(element.type === "Spread" ? element.value : element);
2552
+ return;
2553
+ case "Hash":
2554
+ for (const entry of node.entries) {
2555
+ if (entry.type === "Property" && entry.key.type !== "Literal") visit(entry.key);
2556
+ visit(entry.value);
2557
+ }
2558
+ return;
2559
+ case "Unary":
2560
+ visit(node.operand);
2561
+ return;
2562
+ case "Binary":
2563
+ visit(node.left);
2564
+ visit(node.right);
2565
+ return;
2566
+ case "Conditional":
2567
+ visit(node.test);
2568
+ visit(node.consequent);
2569
+ if (node.alternate) visit(node.alternate);
2570
+ return;
2571
+ case "Member":
2572
+ visit(node.object);
2573
+ if (node.property.type !== "Literal") visit(node.property);
2574
+ return;
2575
+ case "OptionalChain":
2576
+ visit(node.expression);
2577
+ return;
2578
+ case "Call":
2579
+ if (node.callee.type !== "Name") visit(node.callee);
2580
+ for (const arg of node.args) visit(arg.value);
2581
+ return;
2582
+ case "Filter":
2583
+ case "Test":
2584
+ visit(node.input);
2585
+ for (const arg of node.args) visit(arg.value);
2586
+ return;
2587
+ }
2588
+ }
2504
2589
  /** Checks where tags may appear: `extends` first, child templates' top level, `props` and macros. */
2505
2590
  #checkPlacement(body, isChild) {
2506
2591
  let seenContent = false;
@@ -2523,19 +2608,21 @@ var Compiler = class {
2523
2608
  break;
2524
2609
  case "Set":
2525
2610
  case "SetBlock":
2611
+ case "Export":
2526
2612
  case "Import":
2527
2613
  case "FromImport":
2528
2614
  case "Macro": break;
2529
2615
  default: seenContent = true;
2530
2616
  }
2531
2617
  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);
2618
+ 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
2619
  }
2534
2620
  }
2535
2621
  const checkNested = (statements, depth, inMacro) => {
2536
2622
  for (const statement of statements) {
2537
2623
  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
2624
  if (depth > 0 && statement.type === "Extends") this.#error("extends-not-first", "\"extends\" must be the first tag in the template", statement.span);
2625
+ if (depth > 0 && statement.type === "Export") this.#error("misplaced-export", "Exports must be at the top level of a template", statement.span);
2539
2626
  if (depth > 0 && statement.type === "Props") this.#error("props-not-first", "\"props\" must be at the top level of a template", statement.span);
2540
2627
  if (inMacro && statement.type === "Block") this.#error("invalid-block-placement", "Blocks cannot be defined inside macros", statement.span);
2541
2628
  const nestedMacro = inMacro || statement.type === "Macro";
@@ -2716,7 +2803,8 @@ var Compiler = class {
2716
2803
  case "Slot": return this.#slot(node);
2717
2804
  case "Macro":
2718
2805
  case "Import":
2719
- case "FromImport": return NOOP;
2806
+ case "FromImport":
2807
+ case "Export": return NOOP;
2720
2808
  case "With": return this.#with(node);
2721
2809
  case "Cache": return this.#cache(node);
2722
2810
  case "Outlet": return this.#outlet(node);
@@ -5161,6 +5249,7 @@ var Generator = class {
5161
5249
  case "Component": return this.#component(statement, context);
5162
5250
  case "Slot": return this.#slot(statement, context);
5163
5251
  case "Block": return this.#block(statement, context);
5252
+ case "Export": return [];
5164
5253
  default: return unsupported();
5165
5254
  }
5166
5255
  }
@@ -8106,6 +8195,12 @@ const RESERVED = {
8106
8195
  ]),
8107
8196
  test: /* @__PURE__ */ new Set(["defined"])
8108
8197
  };
8198
+ /** Kiln's own function, filter and test names, sorted and including reserved ones, for hosts that stop a name replacing one. */
8199
+ const builtins = {
8200
+ functions: [...Object.keys(builtinFunctions), ...RESERVED.function].sort(),
8201
+ filters: [...Object.keys(builtinFilters), ...RESERVED.filter].sort(),
8202
+ tests: [...Object.keys(builtinTests), ...RESERVED.test].sort()
8203
+ };
8109
8204
  const builtinMaps = /* @__PURE__ */ new WeakMap();
8110
8205
  /** Built-ins of one kind as a map, made once and shared by environments that add none of their own. */
8111
8206
  const builtinMap = (builtins) => {
@@ -8341,6 +8436,22 @@ var Environment = class {
8341
8436
  }
8342
8437
  });
8343
8438
  }
8439
+ /** Runs one export with only the globals in scope, for `evaluate`. */
8440
+ async evaluate(name, exportName, options) {
8441
+ let render = this.#prepare(name, {}, options);
8442
+ if (isPromise(render)) render = await render;
8443
+ const { template, state, resolved } = render;
8444
+ const compiled = template.exports.get(exportName);
8445
+ if (!compiled) return void 0;
8446
+ const run = new Run(state, template, 0, null, null);
8447
+ const imports = importsFor(run, template);
8448
+ run.imports = isPromise(imports) ? await imports : imports;
8449
+ const value = compiled.ev(run, childScope(this.globals));
8450
+ if (!isPromise(value)) return value;
8451
+ const result = unhold(await untilAborted(value, state.signal, resolved));
8452
+ if (state.signal?.aborted) throw aborted(resolved);
8453
+ return result;
8454
+ }
8344
8455
  /** Finds the template and makes the state, scope and output for one render. */
8345
8456
  #prepare(name, context, options) {
8346
8457
  let resolved = this.#names.get(name);
@@ -8439,10 +8550,15 @@ const createApi = (env) => {
8439
8550
  return env.render(name, context, renderOptions ?? {}, block);
8440
8551
  };
8441
8552
  const renderStream = (name, context, renderOptions) => env.renderStream(name, context, renderOptions ?? {});
8553
+ const evaluate = (name, exportName, options) => {
8554
+ if (typeof exportName !== "string") throw new TypeError("evaluate needs an export name");
8555
+ return env.evaluate(name, exportName, options ?? {});
8556
+ };
8442
8557
  return {
8443
8558
  render,
8444
8559
  renderBlock,
8445
8560
  renderStream,
8561
+ evaluate,
8446
8562
  check: async (name, source) => {
8447
8563
  const template = await env.compileFor(name, source);
8448
8564
  if (!template) {
@@ -8695,6 +8811,6 @@ const generateTypes = async (kiln, names) => {
8695
8811
  ].join("\n");
8696
8812
  };
8697
8813
  //#endregion
8698
- export { KilnRenderError, KilnSyntaxError, Markup, createKiln, deferIslands, expose, generateManifest, generateTypes, isSafe, islandScript, lookup, memoryCache, memoryLoader, safe, streamIslands, templateText, withRender };
8814
+ export { KilnRenderError, KilnSyntaxError, Markup, builtins, createKiln, deferIslands, expose, generateManifest, generateTypes, isSafe, islandScript, lookup, memoryCache, memoryLoader, safe, streamIslands, templateText, withRender };
8699
8815
 
8700
8816
  //# sourceMappingURL=index.js.map