@stacksjs/stx 0.2.184 → 0.2.186

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.
@@ -110,6 +110,114 @@ function extractStyles(source) {
110
110
 
111
111
  `);
112
112
  }
113
+ function inferPropertyType(fallback) {
114
+ if (fallback === void 0)
115
+ return "object";
116
+ if (fallback === "true" || fallback === "false")
117
+ return "boolean";
118
+ if (/^-?\d+(?:\.\d+)?$/.test(fallback))
119
+ return "number";
120
+ if (/^['"`]/.test(fallback))
121
+ return "string";
122
+ return "object";
123
+ }
124
+ function literalValue(fallback) {
125
+ if (fallback === "true")
126
+ return !0;
127
+ if (fallback === "false")
128
+ return !1;
129
+ if (/^-?\d+(?:\.\d+)?$/.test(fallback))
130
+ return Number(fallback);
131
+ if (/^['"`]/.test(fallback))
132
+ return fallback.slice(1, -1);
133
+ try {
134
+ return JSON.parse(fallback);
135
+ } catch {
136
+ return;
137
+ }
138
+ }
139
+ function compileTemplateToRender(template) {
140
+ const parts = [];
141
+ let cursor = 0;
142
+ const source = template.replace(/\{\{--[\s\S]*?--\}\}/g, ""), directive = /@(if|elseif|else|endif|foreach|endforeach)\s*(?:\(([\s\S]*?)\))?/g;
143
+ let match;
144
+ const text = (raw) => {
145
+ if (raw === "")
146
+ return;
147
+ let index = 0;
148
+ const interpolation = /\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g;
149
+ let hit;
150
+ while (hit = interpolation.exec(raw)) {
151
+ if (hit.index > index)
152
+ parts.push(`out += ${JSON.stringify(raw.slice(index, hit.index))};`);
153
+ parts.push(hit[1] !== void 0 ? `out += __raw(${hit[1]});` : `out += __escape(${hit[2]});`);
154
+ index = hit.index + hit[0].length;
155
+ }
156
+ if (index < raw.length)
157
+ parts.push(`out += ${JSON.stringify(raw.slice(index))};`);
158
+ };
159
+ while (match = directive.exec(source)) {
160
+ text(source.slice(cursor, match.index));
161
+ cursor = match.index + match[0].length;
162
+ switch (match[1]) {
163
+ case "if":
164
+ parts.push(`if (${match[2]}) {`);
165
+ break;
166
+ case "elseif":
167
+ parts.push(`} else if (${match[2]}) {`);
168
+ break;
169
+ case "else":
170
+ parts.push("} else {");
171
+ break;
172
+ case "endif":
173
+ case "endforeach":
174
+ parts.push("}");
175
+ break;
176
+ case "foreach": {
177
+ const pair = /^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((match[2] || "").trim());
178
+ if (!pair) {
179
+ parts.push(`out += ${JSON.stringify(match[0])};`);
180
+ break;
181
+ }
182
+ const [, iterable, key, value] = pair;
183
+ parts.push(key ? `for (const [${key}, ${value}] of __entries(${iterable})) {` : `for (const ${value} of __values(${iterable})) {`);
184
+ break;
185
+ }
186
+ }
187
+ }
188
+ text(source.slice(cursor));
189
+ return parts.join(`
190
+ `);
191
+ }
192
+ function compileScriptScope(source, file, outputDir) {
193
+ const block = [...source.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((script) => !/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(script[1]));
194
+ if (!block)
195
+ return { imports: [], body: "", propNames: [], defaults: {} };
196
+ let code = block[2];
197
+ const imports = [], propNames = [], defaults = {};
198
+ code = code.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm, (statement) => {
199
+ if (/from\s*['"]stx['"]/.test(statement))
200
+ return "";
201
+ imports.push(statement.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/, (_all, open, specifier, close) => {
202
+ const target = path.resolve(path.dirname(file), specifier), rewritten = path.relative(outputDir, target);
203
+ return `${open}${rewritten.startsWith(".") ? rewritten : `./${rewritten}`}${close}`;
204
+ }));
205
+ return "";
206
+ });
207
+ const propMatch = /const\s*\{([^}]*)\}\s*=\s*(?:withDefaults\s*\(\s*)?defineProps\s*<[^>]*>\s*\(\s*\)\s*(?:,\s*(\{[\s\S]*?\})\s*,?\s*\))?[\s\S]*?$/m.exec(code);
208
+ if (propMatch) {
209
+ for (const name of propMatch[1].split(",")) {
210
+ const clean = name.split(":")[0].trim();
211
+ if (clean)
212
+ propNames.push(clean);
213
+ }
214
+ for (const pair of (propMatch[2] || "").matchAll(/([A-Za-z_$][\w$]*)\s*:\s*([^,}]+)/g))
215
+ defaults[pair[1]] = pair[2].trim();
216
+ code = code.replace(propMatch[0], "");
217
+ }
218
+ code = code.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g, "");
219
+ return { imports, body: code.trim(), propNames, defaults };
220
+ }
113
221
  function compileEventDirectives(template) {
114
222
  const eventTypes = new Set;
115
223
  return { template: template.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi, (_match, eventName, modifiers, _quote, method) => {
@@ -150,7 +258,17 @@ async function compileComponent(inputDir, entry, defaults) {
150
258
  throw Error(`${sourcePath}: invalid component class name "${name}"`);
151
259
  if (!validCustomElementTag(tag))
152
260
  throw Error(`${sourcePath}: invalid custom-element tag "${tag}"; tags must be lowercase and contain a hyphen`);
153
- const propertyInput = entry.properties || metadata.properties || metadata.props || {}, properties = Object.fromEntries(Object.entries(propertyInput).map(([propertyName, property]) => [propertyName, normalizeProperty(propertyName, property)])), eventCompilation = compileEventDirectives(extractTemplate(source)), bindingCompilation = compileDynamicBindings(eventCompilation.template), metadataMethods = metadata.methods || {}, configuredMethods = entry.methods || {}, extractedMethods = extractClientMethods(source, sourcePath);
261
+ const propertyInput = entry.properties || metadata.properties || metadata.props || {}, properties = Object.fromEntries(Object.entries(propertyInput).map(([propertyName, property]) => [propertyName, normalizeProperty(propertyName, property)])), eventCompilation = compileEventDirectives(extractTemplate(source)), bindingCompilation = compileDynamicBindings(eventCompilation.template), scope = compileScriptScope(source, sourcePath, path.resolve(defaults.outputDir)), render = compileTemplateToRender(bindingCompilation.template);
262
+ for (const propertyName of scope.propNames) {
263
+ if (properties[propertyName])
264
+ continue;
265
+ const fallback = scope.defaults[propertyName];
266
+ properties[propertyName] = normalizeProperty(propertyName, {
267
+ type: inferPropertyType(fallback),
268
+ ...fallback === void 0 ? {} : { default: literalValue(fallback) }
269
+ });
270
+ }
271
+ const metadataMethods = metadata.methods || {}, configuredMethods = entry.methods || {}, extractedMethods = extractClientMethods(source, sourcePath);
154
272
  return {
155
273
  file: path.relative(inputDir, sourcePath),
156
274
  sourcePath,
@@ -167,7 +285,9 @@ async function compileComponent(inputDir, entry, defaults) {
167
285
  eventTypes: eventCompilation.eventTypes,
168
286
  bindings: bindingCompilation.bindings,
169
287
  slots: extractSlots(bindingCompilation.template),
170
- cssProperties: extractCssProperties(extractStyles(source))
288
+ cssProperties: extractCssProperties(extractStyles(source)),
289
+ scope,
290
+ render
171
291
  };
172
292
  }
173
293
  function runtimeModule() {
@@ -285,6 +405,17 @@ export class StxElement extends HTMLElementBase {
285
405
  }
286
406
  }
287
407
 
408
+ /**
409
+ * The props a compiled render reads.
410
+ *
411
+ * Its own method rather than _values directly, so a component that sets a
412
+ * property before upgrade still sees it, and so the generated code has one
413
+ * name to depend on rather than a private field's shape.
414
+ */
415
+ _props() {
416
+ return this._values;
417
+ }
418
+
288
419
  requestUpdate() {
289
420
  if (!this._connected || this._initializing || this._updatePending) return this.updateComplete;
290
421
  this._updatePending = true;
@@ -348,9 +479,15 @@ export class StxElement extends HTMLElementBase {
348
479
  const active = root.activeElement || (root.contains?.(globalThis.document?.activeElement) ? globalThis.document.activeElement : null);
349
480
  const focusKey = active && (active.getAttribute?.('data-key') || active.id || active.getAttribute?.('name'));
350
481
  const selection = active && 'selectionStart' in active ? [active.selectionStart, active.selectionEnd] : null;
351
- let html = definition.template
352
- .replace(new RegExp(${rawInterpolation}, 'g'), (_match, expression) => String(valueAt(this, expression) ?? ''))
353
- .replace(new RegExp(${escapedInterpolation}, 'g'), (_match, expression) => escapeHTML(valueAt(this, expression)));
482
+ // A compiled component renders itself: the control flow and the derived
483
+ // values were turned into JavaScript at build time, so there is nothing to
484
+ // interpret here and nothing that needs an eval the page's CSP forbids.
485
+ // The string template remains for components that carry no logic.
486
+ let html = typeof this.render === 'function'
487
+ ? this.render(RENDER_HELPERS)
488
+ : definition.template
489
+ .replace(new RegExp(${rawInterpolation}, 'g'), (_match, expression) => String(valueAt(this, expression) ?? ''))
490
+ .replace(new RegExp(${escapedInterpolation}, 'g'), (_match, expression) => escapeHTML(valueAt(this, expression)));
354
491
  if (definition.shadowMode && definition.styles) html = '<style>' + definition.styles + '</style>' + html;
355
492
  root.innerHTML = html;
356
493
  this._applyBindings();
@@ -383,6 +520,25 @@ export class StxElement extends HTMLElementBase {
383
520
  }
384
521
  }
385
522
 
523
+ /**
524
+ * What a compiled render is handed.
525
+ *
526
+ * Passed in rather than closed over so the generated code names no globals, and
527
+ * a component module stays readable on its own: __escape is visibly a
528
+ * parameter, not something the bundler happened to leave in scope.
529
+ */
530
+ const RENDER_HELPERS = {
531
+ escape: escapeHTML,
532
+ // The raw form is the author declaring the value is markup. Null becomes an
533
+ // empty string rather than the word "null", which is the only sensible
534
+ // reading of a missing fragment.
535
+ raw: (value) => String(value ?? ''),
536
+ // A loop over something absent runs zero times. Throwing here would fail a
537
+ // whole page over one empty list, which is never what the author meant.
538
+ values: (value) => value == null ? [] : (value[Symbol.iterator] ? value : Object.values(value)),
539
+ entries: (value) => value == null ? [] : (Array.isArray(value) ? value.entries() : Object.entries(value)),
540
+ };
541
+
386
542
  export function defineComponent(Component, definition) {
387
543
  const properties = definition.properties || {};
388
544
  const attributeToProperty = {};
@@ -444,12 +600,42 @@ ${body}
444
600
  }`;
445
601
  }).join(`
446
602
 
603
+ `), scope = component.scope, destructured = [...new Set([...Object.keys(component.properties), ...scope.propNames])].map((name) => scope.defaults[name] === void 0 ? name : `${name} = ${scope.defaults[name]}`).join(", "), indent = (code) => code.split(`
604
+ `).map((line) => line.trim() === "" ? line : ` ${line}`).join(`
447
605
  `);
606
+ let renderMethod = "";
607
+ if (component.render.trim() !== "" || scope.body !== "" || destructured !== "") {
608
+ const inner = [
609
+ destructured ? `const { ${destructured} } = this._props();` : "",
610
+ scope.body,
611
+ "let out = '';",
612
+ component.render,
613
+ "return out;"
614
+ ].filter(Boolean).join(`
615
+ `);
616
+ let compiled;
617
+ try {
618
+ const wrapped = new Bun.Transpiler({ loader: "ts" }).transformSync(`export function __render(__helpers) {
619
+ ${inner}
620
+ }`), opening = wrapped.indexOf("{"), closing = wrapped.lastIndexOf("}");
621
+ compiled = wrapped.slice(opening + 1, closing).trim();
622
+ } catch (error) {
623
+ throw Error(`${component.sourcePath}: failed to compile render (${error.message})`);
624
+ }
625
+ renderMethod = `
626
+ render(__helpers) {
627
+ const { escape: __escape, raw: __raw, values: __values, entries: __entries } = __helpers;
628
+ ${indent(compiled.trim())}
629
+ }
630
+ `;
631
+ }
448
632
  return `import { StxElement, defineComponent } from './runtime.js';
449
-
633
+ ${scope.imports.length ? `${scope.imports.join(`
634
+ `)}
635
+ ` : ""}
450
636
  /** ${component.description || `${component.name} web component generated from ${component.file}.`} */
451
637
  export class ${component.name} extends StxElement {
452
- ${methodCode}
638
+ ${methodCode}${renderMethod}
453
639
  }
454
640
 
455
641
  defineComponent(${component.name}, ${definition});