@stacksjs/stx 0.2.183 → 0.2.185
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/cli.js +749 -699
- package/dist/component-library.js +183 -8
- package/dist/craft.js +280 -280
- package/dist/expressions.d.ts +29 -0
- package/dist/expressions.js +5 -2
- package/dist/pwa.js +261 -261
- package/dist/server-components.js +5 -2
- package/dist/ssg.js +272 -272
- package/dist/template-hydrator.js +3 -3
- package/package.json +6 -6
|
@@ -110,6 +110,120 @@ 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
|
+
let body;
|
|
220
|
+
try {
|
|
221
|
+
body = new Bun.Transpiler({ loader: "ts" }).transformSync(code);
|
|
222
|
+
} catch (error) {
|
|
223
|
+
throw Error(`${file}: failed to transpile component script (${error.message})`);
|
|
224
|
+
}
|
|
225
|
+
return { imports, body: body.trim(), propNames, defaults };
|
|
226
|
+
}
|
|
113
227
|
function compileEventDirectives(template) {
|
|
114
228
|
const eventTypes = new Set;
|
|
115
229
|
return { template: template.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi, (_match, eventName, modifiers, _quote, method) => {
|
|
@@ -150,7 +264,17 @@ async function compileComponent(inputDir, entry, defaults) {
|
|
|
150
264
|
throw Error(`${sourcePath}: invalid component class name "${name}"`);
|
|
151
265
|
if (!validCustomElementTag(tag))
|
|
152
266
|
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),
|
|
267
|
+
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);
|
|
268
|
+
for (const propertyName of scope.propNames) {
|
|
269
|
+
if (properties[propertyName])
|
|
270
|
+
continue;
|
|
271
|
+
const fallback = scope.defaults[propertyName];
|
|
272
|
+
properties[propertyName] = normalizeProperty(propertyName, {
|
|
273
|
+
type: inferPropertyType(fallback),
|
|
274
|
+
...fallback === void 0 ? {} : { default: literalValue(fallback) }
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
const metadataMethods = metadata.methods || {}, configuredMethods = entry.methods || {}, extractedMethods = extractClientMethods(source, sourcePath);
|
|
154
278
|
return {
|
|
155
279
|
file: path.relative(inputDir, sourcePath),
|
|
156
280
|
sourcePath,
|
|
@@ -167,7 +291,9 @@ async function compileComponent(inputDir, entry, defaults) {
|
|
|
167
291
|
eventTypes: eventCompilation.eventTypes,
|
|
168
292
|
bindings: bindingCompilation.bindings,
|
|
169
293
|
slots: extractSlots(bindingCompilation.template),
|
|
170
|
-
cssProperties: extractCssProperties(extractStyles(source))
|
|
294
|
+
cssProperties: extractCssProperties(extractStyles(source)),
|
|
295
|
+
scope,
|
|
296
|
+
render
|
|
171
297
|
};
|
|
172
298
|
}
|
|
173
299
|
function runtimeModule() {
|
|
@@ -285,6 +411,17 @@ export class StxElement extends HTMLElementBase {
|
|
|
285
411
|
}
|
|
286
412
|
}
|
|
287
413
|
|
|
414
|
+
/**
|
|
415
|
+
* The props a compiled render reads.
|
|
416
|
+
*
|
|
417
|
+
* Its own method rather than _values directly, so a component that sets a
|
|
418
|
+
* property before upgrade still sees it, and so the generated code has one
|
|
419
|
+
* name to depend on rather than a private field's shape.
|
|
420
|
+
*/
|
|
421
|
+
_props() {
|
|
422
|
+
return this._values;
|
|
423
|
+
}
|
|
424
|
+
|
|
288
425
|
requestUpdate() {
|
|
289
426
|
if (!this._connected || this._initializing || this._updatePending) return this.updateComplete;
|
|
290
427
|
this._updatePending = true;
|
|
@@ -348,9 +485,15 @@ export class StxElement extends HTMLElementBase {
|
|
|
348
485
|
const active = root.activeElement || (root.contains?.(globalThis.document?.activeElement) ? globalThis.document.activeElement : null);
|
|
349
486
|
const focusKey = active && (active.getAttribute?.('data-key') || active.id || active.getAttribute?.('name'));
|
|
350
487
|
const selection = active && 'selectionStart' in active ? [active.selectionStart, active.selectionEnd] : null;
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
488
|
+
// A compiled component renders itself: the control flow and the derived
|
|
489
|
+
// values were turned into JavaScript at build time, so there is nothing to
|
|
490
|
+
// interpret here and nothing that needs an eval the page's CSP forbids.
|
|
491
|
+
// The string template remains for components that carry no logic.
|
|
492
|
+
let html = typeof this.render === 'function'
|
|
493
|
+
? this.render(RENDER_HELPERS)
|
|
494
|
+
: definition.template
|
|
495
|
+
.replace(new RegExp(${rawInterpolation}, 'g'), (_match, expression) => String(valueAt(this, expression) ?? ''))
|
|
496
|
+
.replace(new RegExp(${escapedInterpolation}, 'g'), (_match, expression) => escapeHTML(valueAt(this, expression)));
|
|
354
497
|
if (definition.shadowMode && definition.styles) html = '<style>' + definition.styles + '</style>' + html;
|
|
355
498
|
root.innerHTML = html;
|
|
356
499
|
this._applyBindings();
|
|
@@ -383,6 +526,25 @@ export class StxElement extends HTMLElementBase {
|
|
|
383
526
|
}
|
|
384
527
|
}
|
|
385
528
|
|
|
529
|
+
/**
|
|
530
|
+
* What a compiled render is handed.
|
|
531
|
+
*
|
|
532
|
+
* Passed in rather than closed over so the generated code names no globals, and
|
|
533
|
+
* a component module stays readable on its own: __escape is visibly a
|
|
534
|
+
* parameter, not something the bundler happened to leave in scope.
|
|
535
|
+
*/
|
|
536
|
+
const RENDER_HELPERS = {
|
|
537
|
+
escape: escapeHTML,
|
|
538
|
+
// The raw form is the author declaring the value is markup. Null becomes an
|
|
539
|
+
// empty string rather than the word "null", which is the only sensible
|
|
540
|
+
// reading of a missing fragment.
|
|
541
|
+
raw: (value) => String(value ?? ''),
|
|
542
|
+
// A loop over something absent runs zero times. Throwing here would fail a
|
|
543
|
+
// whole page over one empty list, which is never what the author meant.
|
|
544
|
+
values: (value) => value == null ? [] : (value[Symbol.iterator] ? value : Object.values(value)),
|
|
545
|
+
entries: (value) => value == null ? [] : (Array.isArray(value) ? value.entries() : Object.entries(value)),
|
|
546
|
+
};
|
|
547
|
+
|
|
386
548
|
export function defineComponent(Component, definition) {
|
|
387
549
|
const properties = definition.properties || {};
|
|
388
550
|
const attributeToProperty = {};
|
|
@@ -444,12 +606,25 @@ ${body}
|
|
|
444
606
|
}`;
|
|
445
607
|
}).join(`
|
|
446
608
|
|
|
447
|
-
`)
|
|
609
|
+
`), 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(`
|
|
610
|
+
`).map((line) => line.trim() === "" ? line : ` ${line}`).join(`
|
|
611
|
+
`), renderMethod = component.render.trim() === "" && scope.body === "" && destructured === "" ? "" : `
|
|
612
|
+
render(__helpers) {
|
|
613
|
+
const { escape: __escape, raw: __raw, values: __values, entries: __entries } = __helpers;
|
|
614
|
+
${destructured ? ` const { ${destructured} } = this._props();
|
|
615
|
+
` : ""}${scope.body ? `${indent(scope.body)}
|
|
616
|
+
` : ""} let out = '';
|
|
617
|
+
${indent(component.render)}
|
|
618
|
+
return out;
|
|
619
|
+
}
|
|
620
|
+
`;
|
|
448
621
|
return `import { StxElement, defineComponent } from './runtime.js';
|
|
449
|
-
|
|
622
|
+
${scope.imports.length ? `${scope.imports.join(`
|
|
623
|
+
`)}
|
|
624
|
+
` : ""}
|
|
450
625
|
/** ${component.description || `${component.name} web component generated from ${component.file}.`} */
|
|
451
626
|
export class ${component.name} extends StxElement {
|
|
452
|
-
${methodCode}
|
|
627
|
+
${methodCode}${renderMethod}
|
|
453
628
|
}
|
|
454
629
|
|
|
455
630
|
defineComponent(${component.name}, ${definition});
|