@lucidkiln/core 1.2.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. */
@@ -30,6 +30,7 @@ const analyzeTemplate = (template, globals, reads) => {
30
30
  const source = template.source;
31
31
  const variables = /* @__PURE__ */ new Set();
32
32
  const functions = /* @__PURE__ */ new Set();
33
+ const calls = [];
33
34
  const filters = /* @__PURE__ */ new Set();
34
35
  const tests = /* @__PURE__ */ new Set();
35
36
  const templates = [];
@@ -73,6 +74,18 @@ const analyzeTemplate = (template, globals, reads) => {
73
74
  scopes.pop();
74
75
  if (isolated) scopes.pop();
75
76
  };
77
+ const callArgument = (arg) => {
78
+ const name = arg.type === "Named" ? arg.name : null;
79
+ return arg.type !== "Spread" && arg.value.type === "Literal" ? {
80
+ name,
81
+ literal: true,
82
+ value: arg.value.value
83
+ } : {
84
+ name,
85
+ literal: false,
86
+ value: null
87
+ };
88
+ };
76
89
  const visitArguments = (args) => {
77
90
  for (const arg of args) expression(arg.value);
78
91
  };
@@ -95,8 +108,9 @@ const analyzeTemplate = (template, globals, reads) => {
95
108
  else expression(node);
96
109
  };
97
110
  if (template.slotNames.length > 0 || template.parent) scopes[0]?.add("slots");
111
+ let inExport = false;
98
112
  const read = (name, span, isGuarded) => {
99
- if (declared(name) || importAliases.has(name) || importedNames.has(name)) return;
113
+ if (inExport || declared(name) || importAliases.has(name) || importedNames.has(name)) return;
100
114
  const inMacro = scopes.includes(null);
101
115
  if (!inMacro) variables.add(name);
102
116
  const found = inMacro ? reads?.macros : reads?.context;
@@ -145,7 +159,15 @@ const analyzeTemplate = (template, globals, reads) => {
145
159
  const callee = node.callee;
146
160
  if (callee.type === "Name") {
147
161
  const name = callee.name;
148
- if (name !== "parent" && name !== "block" && !macroNames.has(name) && !importedNames.has(name)) functions.add(name);
162
+ if (name !== "parent" && name !== "block" && !macroNames.has(name) && !importedNames.has(name)) {
163
+ functions.add(name);
164
+ calls.push({
165
+ name,
166
+ args: node.args.map(callArgument),
167
+ start: source.position(node.span.start),
168
+ end: source.position(node.span.end)
169
+ });
170
+ }
149
171
  } else if (!(callee.type === "Member" && callee.object.type === "Name" && importAliases.has(callee.object.name))) expression(callee);
150
172
  visitArguments(node.args);
151
173
  return;
@@ -196,6 +218,11 @@ const analyzeTemplate = (template, globals, reads) => {
196
218
  expression(node.value);
197
219
  declare(node.name);
198
220
  return;
221
+ case "Export":
222
+ inExport = true;
223
+ withScope([], () => expression(node.value), true);
224
+ inExport = false;
225
+ return;
199
226
  case "SetBlock":
200
227
  statements(node.body);
201
228
  declare(node.name);
@@ -302,11 +329,21 @@ const analyzeTemplate = (template, globals, reads) => {
302
329
  rest,
303
330
  sets: template.ast.body.flatMap((node) => node.type === "Set" || node.type === "SetBlock" ? [node.name] : []),
304
331
  functions: [...functions],
332
+ calls,
305
333
  filters: [...filters],
306
334
  tests: [...tests],
307
335
  templates,
308
336
  blocks,
309
- 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
+ }] : [])
310
347
  };
311
348
  };
312
349
  //#endregion
@@ -1925,7 +1962,8 @@ const effectsOf = (statements, env) => {
1925
1962
  switch (node.type) {
1926
1963
  case "Macro":
1927
1964
  case "Import":
1928
- case "FromImport": continue;
1965
+ case "FromImport":
1966
+ case "Export": continue;
1929
1967
  case "Name":
1930
1968
  reads.add(node.name);
1931
1969
  break;
@@ -2303,6 +2341,7 @@ var Compiler = class {
2303
2341
  blocks: /* @__PURE__ */ new Map(),
2304
2342
  blockList: void 0,
2305
2343
  macros: /* @__PURE__ */ new Map(),
2344
+ exports: /* @__PURE__ */ new Map(),
2306
2345
  imports: [],
2307
2346
  resolved: /* @__PURE__ */ new Map(),
2308
2347
  keyed: void 0,
@@ -2318,6 +2357,7 @@ var Compiler = class {
2318
2357
  const body = this.#ast.body;
2319
2358
  this.#collectNames(body);
2320
2359
  this.#collectMacros(body);
2360
+ this.#collectExports(body);
2321
2361
  const first = body.find((statement) => !isBlank$1(statement));
2322
2362
  const extendsNode = first?.type === "Extends" ? first : null;
2323
2363
  this.#checkPlacement(body, extendsNode !== null);
@@ -2479,6 +2519,73 @@ var Compiler = class {
2479
2519
  this.#inMacro = saved.inMacro;
2480
2520
  }
2481
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
+ }
2482
2589
  /** Checks where tags may appear: `extends` first, child templates' top level, `props` and macros. */
2483
2590
  #checkPlacement(body, isChild) {
2484
2591
  let seenContent = false;
@@ -2501,19 +2608,21 @@ var Compiler = class {
2501
2608
  break;
2502
2609
  case "Set":
2503
2610
  case "SetBlock":
2611
+ case "Export":
2504
2612
  case "Import":
2505
2613
  case "FromImport":
2506
2614
  case "Macro": break;
2507
2615
  default: seenContent = true;
2508
2616
  }
2509
2617
  if (isChild) {
2510
- 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);
2511
2619
  }
2512
2620
  }
2513
2621
  const checkNested = (statements, depth, inMacro) => {
2514
2622
  for (const statement of statements) {
2515
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);
2516
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);
2517
2626
  if (depth > 0 && statement.type === "Props") this.#error("props-not-first", "\"props\" must be at the top level of a template", statement.span);
2518
2627
  if (inMacro && statement.type === "Block") this.#error("invalid-block-placement", "Blocks cannot be defined inside macros", statement.span);
2519
2628
  const nestedMacro = inMacro || statement.type === "Macro";
@@ -2694,7 +2803,8 @@ var Compiler = class {
2694
2803
  case "Slot": return this.#slot(node);
2695
2804
  case "Macro":
2696
2805
  case "Import":
2697
- case "FromImport": return NOOP;
2806
+ case "FromImport":
2807
+ case "Export": return NOOP;
2698
2808
  case "With": return this.#with(node);
2699
2809
  case "Cache": return this.#cache(node);
2700
2810
  case "Outlet": return this.#outlet(node);
@@ -5139,6 +5249,7 @@ var Generator = class {
5139
5249
  case "Component": return this.#component(statement, context);
5140
5250
  case "Slot": return this.#slot(statement, context);
5141
5251
  case "Block": return this.#block(statement, context);
5252
+ case "Export": return [];
5142
5253
  default: return unsupported();
5143
5254
  }
5144
5255
  }
@@ -8084,6 +8195,12 @@ const RESERVED = {
8084
8195
  ]),
8085
8196
  test: /* @__PURE__ */ new Set(["defined"])
8086
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
+ };
8087
8204
  const builtinMaps = /* @__PURE__ */ new WeakMap();
8088
8205
  /** Built-ins of one kind as a map, made once and shared by environments that add none of their own. */
8089
8206
  const builtinMap = (builtins) => {
@@ -8319,6 +8436,22 @@ var Environment = class {
8319
8436
  }
8320
8437
  });
8321
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
+ }
8322
8455
  /** Finds the template and makes the state, scope and output for one render. */
8323
8456
  #prepare(name, context, options) {
8324
8457
  let resolved = this.#names.get(name);
@@ -8417,10 +8550,15 @@ const createApi = (env) => {
8417
8550
  return env.render(name, context, renderOptions ?? {}, block);
8418
8551
  };
8419
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
+ };
8420
8557
  return {
8421
8558
  render,
8422
8559
  renderBlock,
8423
8560
  renderStream,
8561
+ evaluate,
8424
8562
  check: async (name, source) => {
8425
8563
  const template = await env.compileFor(name, source);
8426
8564
  if (!template) {
@@ -8673,6 +8811,6 @@ const generateTypes = async (kiln, names) => {
8673
8811
  ].join("\n");
8674
8812
  };
8675
8813
  //#endregion
8676
- 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 };
8677
8815
 
8678
8816
  //# sourceMappingURL=index.js.map