@lucidkiln/core 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
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";
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-DxHQeBEo.js";
2
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;
@@ -1755,19 +1755,33 @@ const hashId = (text) => {
1755
1755
  return (a >>> 0).toString(16).padStart(8, "0") + (b >>> 0).toString(16).padStart(8, "0");
1756
1756
  };
1757
1757
  /**
1758
- * Records an island in the manifest and returns its id. The id comes from the template and props, so it is the same
1759
- * 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.
1760
1761
  */
1761
1762
  const recordIsland = (run, span, islands, template, props) => {
1762
- 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
+ ]);
1763
1770
  const id = hashId(key);
1764
1771
  const { manifest } = islands;
1765
1772
  const existing = Object.hasOwn(manifest, id) ? manifest[id] : void 0;
1766
1773
  if (existing === void 0) manifest[id] = {
1767
1774
  template,
1768
- props
1775
+ props,
1776
+ locale,
1777
+ timeZone
1769
1778
  };
1770
- 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`);
1771
1785
  run.capture?.section?.deferred.push(id);
1772
1786
  return id;
1773
1787
  };
@@ -3989,7 +4003,7 @@ const readingLabel = (key) => `Reading "${key}"`;
3989
4003
  /** `set`: assigns where the variable already exists, or declares it in the current scope. */
3990
4004
  const assign = (run, scope, name, value, span) => {
3991
4005
  let owner = ownerOf(scope, name);
3992
- 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}"`);
3993
4007
  if (owner !== null && run.capture?.section) owner = sectionCopy(scope, owner);
3994
4008
  (owner ?? scope)[name] = value ?? null;
3995
4009
  };
@@ -6196,6 +6210,68 @@ var Generator = class {
6196
6210
  }
6197
6211
  };
6198
6212
  //#endregion
6213
+ //#region src/compiler/host.ts
6214
+ const hostMark = Symbol("kiln.hostComponent");
6215
+ /**
6216
+ * Wraps a function that renders a component, such as one made with a UI library, so a loader can return it for a
6217
+ * name. It should return markup made with `safe`, or a promise of it. A plain string is escaped.
6218
+ *
6219
+ * ```ts
6220
+ * load: (name) => name.endsWith(".tsx") ? hostComponent((props, slots) => safe(renderReact(name, props, slots))) : null
6221
+ * ```
6222
+ */
6223
+ const hostComponent = (render) => ({
6224
+ [hostMark]: true,
6225
+ render
6226
+ });
6227
+ const isHostComponent = (value) => typeof value === "object" && value !== null && hostMark in value;
6228
+ const SPAN = {
6229
+ start: 0,
6230
+ end: 0
6231
+ };
6232
+ /**
6233
+ * A template whose content is the host component: it renders the caller's fills, then calls the component with the
6234
+ * variables passed in and writes what it returns. Everything that renders templates renders it unchanged.
6235
+ */
6236
+ const compileHost = (env, name, component) => {
6237
+ const emit = emitter(env.autoescape);
6238
+ const label = `Component "${name}"`;
6239
+ const body = (run, scope, out) => {
6240
+ step(run, SPAN);
6241
+ const props = {};
6242
+ for (const key of run.passed ?? []) setOwn(props, key, scope[key]);
6243
+ return after(renderFills(run), (slots) => after(locating(run, SPAN, () => component.render(props, slots, run.info), label), (html) => write(run, out, emit(html), SPAN)));
6244
+ };
6245
+ return Object.assign(compileTemplate(env, name, ""), {
6246
+ body,
6247
+ host: true
6248
+ });
6249
+ };
6250
+ /**
6251
+ * Renders each fill the caller passed where the component is, as a slot would: the content outside fills first, then
6252
+ * each fill in order.
6253
+ */
6254
+ const renderFills = (run) => {
6255
+ const slots = {};
6256
+ if (run.slots === null) return slots;
6257
+ const fills = [...run.slots].sort(([a], [b]) => Number(b === DEFAULT_SLOT) - Number(a === DEFAULT_SLOT));
6258
+ const from = (index) => {
6259
+ for (let i = index; i < fills.length; i++) {
6260
+ const [name, fill] = fills[i];
6261
+ const out = emptyOut();
6262
+ const done = () => setOwn(slots, name, new Markup(out.s, "html"));
6263
+ const result = fill.body(fill.run.within(run.capture, run.blockDepth), fillScope(fill, run), out);
6264
+ if (result instanceof Promise) return result.then(() => {
6265
+ done();
6266
+ return from(i + 1);
6267
+ });
6268
+ done();
6269
+ }
6270
+ return slots;
6271
+ };
6272
+ return from(0);
6273
+ };
6274
+ //#endregion
6199
6275
  //#region src/html/data.ts
6200
6276
  /** Obsolete elements in the HTML standard, by what to use instead. */
6201
6277
  const OBSOLETE = new Map(Object.entries({
@@ -8280,11 +8356,7 @@ var Environment = class {
8280
8356
  if (typeof check !== "function") throw new TypeError(`type "${name}" must be a function`);
8281
8357
  this.types.set(name, check);
8282
8358
  }
8283
- const globals = childScope(null);
8284
- const provided = options.globals ?? {};
8285
- if (!isPlainObject(provided)) throw new TypeError("globals must be a plain object");
8286
- for (const key of hashKeys(provided)) globals[key] = provided[key] ?? null;
8287
- this.globals = globals;
8359
+ this.globals = globalScope(null, options.globals ?? {});
8288
8360
  }
8289
8361
  load(name) {
8290
8362
  const cached = this.#cache.get(name);
@@ -8294,7 +8366,8 @@ var Environment = class {
8294
8366
  if (source === null) return null;
8295
8367
  if (typeof source === "string") return compileTemplate(this, name, source);
8296
8368
  if (isPrecompiled(source)) return compilePrecompiled(this, name, source);
8297
- throw new TypeError(`Loader returned a ${typeName(source)} for "${name}", not a string, a precompiled template or null`);
8369
+ if (isHostComponent(source)) return compileHost(this, name, source);
8370
+ throw new TypeError(`Loader returned a ${typeName(source)} for "${name}", not a string, a precompiled template, a host component or null`);
8298
8371
  };
8299
8372
  const keep = (template) => {
8300
8373
  if (template !== null) this.#cache.set(name, template);
@@ -8446,7 +8519,7 @@ var Environment = class {
8446
8519
  const run = new Run(state, template, 0, null, null);
8447
8520
  const imports = importsFor(run, template);
8448
8521
  run.imports = isPromise(imports) ? await imports : imports;
8449
- const value = compiled.ev(run, childScope(this.globals));
8522
+ const value = compiled.ev(run, childScope(state.globals));
8450
8523
  if (!isPromise(value)) return value;
8451
8524
  const result = unhold(await untilAborted(value, state.signal, resolved));
8452
8525
  if (state.signal?.aborted) throw aborted(resolved);
@@ -8478,9 +8551,10 @@ var Environment = class {
8478
8551
  if (!template) throw new KilnRenderError("missing-template", `Template "${resolved}" was not found`, resolved);
8479
8552
  if (template.hasErrors) throw template.syntaxError();
8480
8553
  if (!isPlainObject(context)) throw new TypeError("render context must be a plain object");
8481
- 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);
8554
+ const globals = options.globals === void 0 ? this.globals : globalScope(this.globals, options.globals);
8555
+ 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);
8482
8556
  if (options.signal?.aborted) throw aborted(resolved);
8483
- const scope = childScope(this.globals);
8557
+ const scope = childScope(globals);
8484
8558
  const passed = hashKeys(context);
8485
8559
  for (const key of passed) scope[key] = context[key] ?? null;
8486
8560
  addSlotFlags(scope, template, null);
@@ -8501,6 +8575,13 @@ var Environment = class {
8501
8575
  return renderTemplate(render.state, template, render.scope, render.out, 0, null, render.passed, null, null, template.parentSpan, block);
8502
8576
  }
8503
8577
  };
8578
+ /** A scope inside `parent` holding `values`: the environment's globals, or one render's over them. */
8579
+ const globalScope = (parent, values) => {
8580
+ if (!isPlainObject(values)) throw new TypeError("globals must be a plain object");
8581
+ const scope = childScope(parent);
8582
+ for (const key of hashKeys(values)) scope[key] = values[key] ?? null;
8583
+ return scope;
8584
+ };
8504
8585
  const aborted = (resolved) => new KilnRenderError("aborted", "Render was aborted", resolved);
8505
8586
  /**
8506
8587
  * Waits for `work`, or rejects as soon as `signal` aborts, when the signal can say so, as a real `AbortSignal` can.
@@ -8600,7 +8681,7 @@ const createApi = (env) => {
8600
8681
  };
8601
8682
  /**
8602
8683
  * A loader for templates held in memory, keyed by name. Keys without an extension get `.kiln`. Each template is its
8603
- * source or a precompiled module's default export.
8684
+ * source, a precompiled module's default export or a host component.
8604
8685
  *
8605
8686
  * Works on every runtime, including Cloudflare Workers.
8606
8687
  */
@@ -8652,7 +8733,7 @@ const memoryCache = ({ max = 1e3 } = {}) => {
8652
8733
  //#region src/manifest.ts
8653
8734
  const hostNames = (registry) => [...registry].filter(([, entry]) => entry.kind === "host").map(([name]) => name).sort();
8654
8735
  /**
8655
- * Writes `kiln.json` for an environment: the names of its functions, filters, tests, globals and prop types, and its HTML check levels, so editors can check templates without running your code. `root` is the template folder, relative to where you write the file.
8736
+ * Writes `kiln.json` for an environment: the names of its functions, filters, tests, globals and prop types, and its HTML check levels, so editors can check templates without running your code. `root` is the template folder, relative to where you write the file, and `components` the files your loader returns as host components.
8656
8737
  *
8657
8738
  * ```ts
8658
8739
  * await writeFile("kiln.json", generateManifest(kiln, { root: "src/templates" }));
@@ -8668,7 +8749,8 @@ const generateManifest = (kiln, options) => {
8668
8749
  tests: hostNames(env.tests),
8669
8750
  globals: variableNames(env.globals).sort(),
8670
8751
  types: [...env.types.keys()].sort(),
8671
- htmlChecks: htmlChecksOption(env.htmlChecks)
8752
+ htmlChecks: htmlChecksOption(env.htmlChecks),
8753
+ components: options.components ?? []
8672
8754
  };
8673
8755
  return `${JSON.stringify(manifest, null, " ")}\n`;
8674
8756
  };
@@ -8811,6 +8893,6 @@ const generateTypes = async (kiln, names) => {
8811
8893
  ].join("\n");
8812
8894
  };
8813
8895
  //#endregion
8814
- export { KilnRenderError, KilnSyntaxError, Markup, builtins, createKiln, deferIslands, expose, generateManifest, generateTypes, isSafe, islandScript, lookup, memoryCache, memoryLoader, safe, streamIslands, templateText, withRender };
8896
+ export { KilnRenderError, KilnSyntaxError, Markup, builtins, createKiln, deferIslands, expose, generateManifest, generateTypes, hostComponent, isSafe, islandScript, lookup, memoryCache, memoryLoader, safe, streamIslands, templateText, withRender };
8815
8897
 
8816
8898
  //# sourceMappingURL=index.js.map