镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Commit d903ce5

Browse files
committed
fix(components): preserve source imports and server boundary
1 parent 1ebda4f commit d903ce5

6 files changed

Lines changed: 164 additions & 35 deletions

‎docs/api/component-library.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,8 @@ Client functions become element methods. Event directives accept a method name a
8282

8383
Client methods can explicitly import browser helpers from relative TypeScript modules or installed packages. Named, aliased, default, namespace and side-effect imports are resolved during the build, including their transitive dependencies. Type-only imports have no runtime effect. Helpers declare their own imports; no STX page globals are supplied by the custom-element host. Use `this` for per-element state, and `onConnect` / `onDisconnect` for setup and cleanup. Authored browser modules retain ordinary shared module identity across elements.
8484

85+
Imports resolve from the authored component's package, including browser export conditions and package import maps, even when `outputDir` is outside that package. Comments and import attributes retain their ordinary module meaning. `<script server>` blocks are excluded from the browser component graph and are not executed by the component-library compiler. Supply browser render values through properties or the component's default client script; server-only declarations are unavailable to the generated browser render.
86+
8587
Distribute the complete emitted directory, including any `chunks/` files. Both individual ESM entries and `bundle.js` work without the author's source tree. `bundle: false` disables only the standalone bundle; browser dependencies are still compiled into the ESM distribution. Server-only modules such as `node:fs` fail the browser build. Component metadata and SSR helper generation do not execute these browser dependencies.
8688

8789
Property types are `string`, `number`, `boolean`, `object`, and `array`. Properties reflect to kebab-case attributes by default. Use `"attribute": false` for property-only values, a string for a custom attribute name, or `"reflect": false` to accept attribute input without reflecting later property writes.

‎packages/stx/src/component-library.ts‎

Lines changed: 53 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { builtinModules } from 'node:module'
1212
import { scriptAttributes, scriptContainsCode } from './script-attributes'
1313
import { topLevelDeclarationSites } from './client-parameter-bindings'
1414
import { bracketDepths, stripCommentsAndLiterals } from './strip-literals'
15+
import { Tokenizer } from './parser/tokenizer'
1516

1617
export interface SourceMetadata {
1718
name?: string
@@ -976,32 +977,51 @@ export function parseDefaults(object: string): Array<[string, string]> {
976977
}
977978

978979
/** Keep real module imports from every authored script, including method blocks. */
979-
function hoistScriptImports(code: string, file: string, outputDir: string): { imports: string[], body: string } {
980+
function hoistScriptImports(code: string): { imports: string[], body: string } {
980981
const masked = stripCommentsAndLiterals(code)
981982
const depths = bracketDepths(masked).depths
982983
const imports: string[] = []
983984
const spans: Array<{ start: number, end: number }> = []
984985
for (const match of masked.matchAll(/\bimport\b/g)) {
985986
const start = match.index!
986987
if (depths[start] !== 0) continue
988+
// Use source tokens, keeping the declaration verbatim. Comment punctuation
989+
// is not syntax, and a string-named binding is not the module specifier.
990+
const tokens = new Tokenizer(code.slice(start)).tokenize().filter(token => !['COMMENT', 'WHITESPACE'].includes(token.type))
987991
// Dynamic import() and import.meta are expressions, not declarations.
988-
const declaration = /^import\s*(?:[^'";]*?\bfrom\s*)?(['"])([^'"\r\n]+)\1(?:\s+with\s*\{[^}]*\})?\s*;?/.exec(code.slice(start))
989-
if (!declaration) continue
990-
const statement = declaration[0]
991-
spans.push({ start, end: start + statement.length })
992-
if (declaration[2] === 'stx') continue
993-
const specifier = declaration[2]!
994-
const target = specifier.startsWith('.') ? path.resolve(path.dirname(file), specifier) : undefined
995-
const rewritten = target ? path.relative(outputDir, target).split(path.sep).join('/') : specifier
996-
const offset = statement.indexOf(declaration[1]! + specifier + declaration[1]!) + 1
997-
imports.push(statement.slice(0, offset) + (target && !rewritten.startsWith('.') ? `./${rewritten}` : rewritten) + statement.slice(offset + specifier.length))
992+
if (tokens[1]?.value === '(' || tokens[1]?.value === '.') continue
993+
let specifierIndex = tokens[1]?.type === 'STRING' ? 1 : -1
994+
let depth = 0
995+
for (let index = 1; specifierIndex === -1 && index < tokens.length; index++) {
996+
const token = tokens[index]!
997+
if (token.value === ';' || token.type === 'EOF') break
998+
if (token.value === '{') depth++
999+
else if (token.value === '}') depth--
1000+
else if (depth === 0 && token.value === 'from' && tokens[index + 1]?.type === 'STRING') specifierIndex = index + 1
1001+
}
1002+
if (specifierIndex === -1) continue
1003+
const specifier = tokens[specifierIndex]!
1004+
let last = specifierIndex
1005+
if (tokens[last + 1]?.value === 'with' && tokens[last + 2]?.value === '{') {
1006+
last += 2
1007+
let attributesDepth = 1
1008+
while (attributesDepth && tokens[last + 1]?.type !== 'EOF') {
1009+
last++
1010+
if (tokens[last]?.value === '{') attributesDepth++
1011+
else if (tokens[last]?.value === '}') attributesDepth--
1012+
}
1013+
}
1014+
if (tokens[last + 1]?.value === ';') last++
1015+
const end = start + tokens[last]!.end
1016+
spans.push({ start, end })
1017+
if (specifier.value.slice(1, -1) !== 'stx') imports.push(code.slice(start, end))
9981018
}
9991019
let body = code
10001020
for (const span of spans.reverse()) body = body.slice(0, span.start) + body.slice(span.end)
10011021
return { imports, body }
10021022
}
10031023

1004-
function compileScriptScope(source: string, file: string, outputDir: string): {
1024+
function compileScriptScope(source: string): {
10051025
imports: string[]
10061026
body: string
10071027
propNames: string[]
@@ -1010,7 +1030,7 @@ function compileScriptScope(source: string, file: string, outputDir: string): {
10101030
declared: Record<string, string>
10111031
} {
10121032
const scripts = scanHtmlScriptElements(componentScriptSource(source))
1013-
const block = scripts.find(script => { const attrs = scriptAttributes(script.attrs); return scriptContainsCode(attrs) && !['component','stx:component','client','src'].some(name => attrs.has(name)) })
1033+
const block = scripts.find(script => { const attrs = scriptAttributes(script.attrs); return scriptContainsCode(attrs) && !['component','stx:component','client','server','src'].some(name => attrs.has(name)) })
10141034

10151035
if (!block) return { imports: [], body: '', propNames: [], propBindings: {}, defaults: {}, declared: {} }
10161036

@@ -1022,7 +1042,7 @@ function compileScriptScope(source: string, file: string, outputDir: string): {
10221042
/** Prop name to the TypeScript type the component declared for it. */
10231043
const declared: Record<string, string> = {}
10241044

1025-
const hoisted = hoistScriptImports(code, file, outputDir)
1045+
const hoisted = hoistScriptImports(code)
10261046
imports.push(...hoisted.imports)
10271047
code = hoisted.body
10281048

@@ -1162,11 +1182,11 @@ async function compileComponent(
11621182
)
11631183
const eventCompilation = compileEventDirectives(extractTemplate(source))
11641184
const bindingCompilation = compileDynamicBindings(eventCompilation.template)
1165-
const scope = compileScriptScope(source, sourcePath, path.resolve(defaults.outputDir))
1185+
const scope = compileScriptScope(source)
11661186
for (const script of scanHtmlScriptElements(componentScriptSource(source))) {
11671187
const attrs = scriptAttributes(script.attrs)
11681188
if (!attrs.has('client') || ['server', 'component', 'stx:component', 'src'].some(name => attrs.has(name)) || !scriptContainsCode(attrs)) continue
1169-
scope.imports.push(...hoistScriptImports(source.slice(script.bodyStart, script.bodyEnd), sourcePath, path.resolve(defaults.outputDir)).imports)
1189+
scope.imports.push(...hoistScriptImports(source.slice(script.bodyStart, script.bodyEnd)).imports)
11701190
}
11711191
scope.imports = [...new Set(scope.imports)]
11721192
const render = compileTemplateToRender(bindingCompilation.template)
@@ -1541,7 +1561,7 @@ export function defineComponent(Component, definition) {
15411561
`
15421562
}
15431563

1544-
function componentModule(component: CompiledComponent): string {
1564+
function componentModule(component: CompiledComponent, runtimeImport = './runtime.js'): string {
15451565
const definition = JSON.stringify({
15461566
tag: component.tag,
15471567
template: component.template,
@@ -1615,7 +1635,7 @@ ${indent(compiled.trim())}
16151635
`
16161636
}
16171637

1618-
return `import { StxElement, defineComponent } from './runtime.js';
1638+
return `import { StxElement, defineComponent } from ${runtimeImport === './runtime.js' ? "'./runtime.js'" : JSON.stringify(runtimeImport)};
16191639
${scope.imports.length ? `${scope.imports.join('\n')}\n` : ''}
16201640
/** ${component.description || `${component.name} web component generated from ${component.file}.`} */
16211641
export class ${component.name} extends StxElement {
@@ -1850,7 +1870,14 @@ export async function buildComponentLibrary(config: ComponentLibraryConfig): Pro
18501870
// single split build preserves shared module identity between elements;
18511871
// separately bundling each entry would duplicate imported stores/effects.
18521872
const entrypoints = components.map(component => path.join(outputDir, `${component.tag}.js`))
1853-
const canonicalEntries = new Set(await Promise.all(entrypoints.map(file => realpath(file))))
1873+
const canonicalEntries = new Map(await Promise.all(entrypoints.map(async (file, index) => [await realpath(file), components[index]!] as const)))
1874+
for (const [index, file] of entrypoints.entries()) canonicalEntries.set(file, components[index]!)
1875+
const sourceEntries = new Map(components.map(component => [path.join(path.dirname(component.sourcePath), `.stx-library-${component.tag}.ts`), component]))
1876+
const runtimePath = path.join(outputDir, 'runtime.js')
1877+
// Bun resolves from its module identity (onLoad has no resolveDir option).
1878+
// Give each generated entry an identity beside its authored component,
1879+
// without writing there. Bun then applies the source package's browser
1880+
// exports/import maps and nested dependencies through its native resolver.
18541881
const built = await Bun.build({
18551882
entrypoints, outdir: outputDir, root: outputDir,
18561883
target: 'browser', format: 'esm', splitting: true,
@@ -1859,7 +1886,13 @@ export async function buildComponentLibrary(config: ComponentLibraryConfig): Pro
18591886
plugins: [{ name: 'stx-element-runtime', setup(builder) {
18601887
builder.onResolve({ filter: /.*/ }, args => {
18611888
if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || SERVER_MODULES.has(args.path)) throw new Error(`Server-only import ${JSON.stringify(args.path)} is not available in a browser component (${args.importer})`)
1862-
if (args.path === './runtime.js' && canonicalEntries.has(args.importer)) return { path: './runtime.js', external: true }
1889+
const entry = canonicalEntries.get(args.path)
1890+
if (!args.importer && entry) return { path: path.join(path.dirname(entry.sourcePath), `.stx-library-${entry.tag}.ts`) }
1891+
if (args.path === runtimePath && sourceEntries.has(args.importer)) return { path: './runtime.js', external: true }
1892+
})
1893+
builder.onLoad({ filter: /\.ts$/ }, args => {
1894+
const component = sourceEntries.get(args.path)
1895+
if (component) return { contents: componentModule(component, runtimePath), loader: 'ts' }
18631896
})
18641897
} }],
18651898
}).catch(error => {

‎packages/stx/test/web-components/component-library-alias-browser.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ it('renders aliased public props and their defaults from emitted JavaScript modu
99
const root = createTempDir('stx-library-alias-')
1010
const input = join(root, 'source')
1111
const output = join(root, 'dist')
12-
await Bun.write(join(input, 'Field.stx'), `<script server>
12+
await Bun.write(join(input, 'Field.stx'), `<script>
1313
const { class: classList, label: caption = 'Default label' } = withDefaults(
1414
defineProps<{ class?: string, label?: string }>(), { class: 'default-class' }
1515
)

0 commit comments

Comments
 (0)