import { walk, childKeys } from 'estree-walker'; import { getLocator } from 'locate-character'; import Stats from '../Stats'; import { globals, reserved, is_valid } from '../utils/names'; import { namespaces, valid_namespaces } from '../utils/namespaces'; import create_module from './create_module'; import { create_scopes, extract_names, Scope, extract_identifiers, } from './utils/scope'; import Stylesheet from './css/Stylesheet'; import { test } from '../config'; import Fragment from './nodes/Fragment'; import internal_exports from './internal_exports'; import { Ast, CompileOptions, Var, Warning } from '../interfaces'; import error from '../utils/error'; import get_code_frame from '../utils/get_code_frame'; import flatten_reference from './utils/flatten_reference'; import is_used_as_reference from './utils/is_used_as_reference'; import is_reference from 'is-reference'; import TemplateScope from './nodes/shared/TemplateScope'; import fuzzymatch from '../utils/fuzzymatch'; import get_object from './utils/get_object'; import Slot from './nodes/Slot'; import { Node, ImportDeclaration, Identifier, Program, ExpressionStatement, AssignmentExpression, Literal } from 'estree'; import add_to_set from './utils/add_to_set'; import check_graph_for_cycles from './utils/check_graph_for_cycles'; import { print, x } from 'code-red'; interface ComponentOptions { namespace?: string; tag?: string; immutable?: boolean; accessors?: boolean; preserveWhitespace?: boolean; } // We need to tell estree-walker that it should always // look for an `else` block, otherwise it might get // the wrong idea about the shape of each/if blocks childKeys.EachBlock = childKeys.IfBlock = ['children', 'else']; childKeys.Attribute = ['value']; childKeys.ExportNamedDeclaration = ['declaration', 'specifiers']; export default class Component { stats: Stats; warnings: Warning[]; ignores: Set; ignore_stack: Array> = []; ast: Ast; original_ast: Ast; source: string; name: Identifier; compile_options: CompileOptions; fragment: Fragment; module_scope: Scope; instance_scope: Scope; instance_scope_map: WeakMap; component_options: ComponentOptions; namespace: string; tag: string; accessors: boolean; vars: Var[] = []; var_lookup: Map = new Map(); imports: ImportDeclaration[] = []; hoistable_nodes: Set = new Set(); node_for_declaration: Map = new Map(); partly_hoisted: Array<(Node | Node[])> = []; fully_hoisted: Array<(Node | Node[])> = []; reactive_declarations: Array<{ assignees: Set; dependencies: Set; node: Node; declaration: Node; }> = []; reactive_declaration_nodes: Set = new Set(); has_reactive_assignments = false; injected_reactive_declaration_vars: Set = new Set(); helpers: Map = new Map(); globals: Map = new Map(); indirect_dependencies: Map> = new Map(); file: string; locate: (c: number) => { line: number; column: number }; stylesheet: Stylesheet; aliases: Map = new Map(); used_names: Set = new Set(); globally_used_names: Set = new Set(); slots: Map = new Map(); slot_outlets: Set = new Set(); constructor( ast: Ast, source: string, name: string, compile_options: CompileOptions, stats: Stats, warnings: Warning[] ) { this.name = { type: 'Identifier', name }; this.stats = stats; this.warnings = warnings; this.ast = ast; this.source = source; this.compile_options = compile_options; // the instance JS gets mutated, so we park // a copy here for later. TODO this feels gross this.original_ast = { html: ast.html, css: ast.css, instance: ast.instance && JSON.parse(JSON.stringify(ast.instance)), module: ast.module }; this.file = compile_options.filename && (typeof process !== 'undefined' ? compile_options.filename .replace(process.cwd(), '') .replace(/^[/\\]/, '') : compile_options.filename); this.locate = getLocator(this.source, { offsetLine: 1 }); // styles this.stylesheet = new Stylesheet( source, ast, compile_options.filename, compile_options.dev ); this.stylesheet.validate(this); this.component_options = process_component_options( this, this.ast.html.children ); this.namespace = namespaces[this.component_options.namespace] || this.component_options.namespace; if (compile_options.customElement) { if ( this.component_options.tag === undefined && compile_options.tag === undefined ) { const svelteOptions = ast.html.children.find( child => child.name === 'svelte:options' ) || { start: 0, end: 0 }; this.warn(svelteOptions, { code: 'custom-element-no-tag', message: `No custom element 'tag' option was specified. To automatically register a custom element, specify a name with a hyphen in it, e.g. . To hide this warning, use `, }); } this.tag = this.component_options.tag || compile_options.tag; } else { this.tag = this.name.name; } this.walk_module_js_pre_template(); this.walk_instance_js_pre_template(); this.fragment = new Fragment(this, ast.html); this.name = this.get_unique_name(name); this.walk_module_js_post_template(); this.walk_instance_js_post_template(); if (!compile_options.customElement) this.stylesheet.reify(); this.stylesheet.warn_on_unused_selectors(this); } add_var(variable: Var) { this.vars.push(variable); this.var_lookup.set(variable.name, variable); } add_reference(name: string) { const variable = this.var_lookup.get(name); if (variable) { variable.referenced = true; } else if (name === '$$props') { this.add_var({ name, injected: true, referenced: true, }); } else if (name[0] === '$') { this.add_var({ name, injected: true, referenced: true, mutated: true, writable: true, }); const subscribable_name = name.slice(1); this.add_reference(subscribable_name); const variable = this.var_lookup.get(subscribable_name); if (variable) variable.subscribable = true; } else { this.used_names.add(name); } } alias(name: string) { if (!this.aliases.has(name)) { this.aliases.set(name, this.get_unique_name(name)); } return this.aliases.get(name); } global(name: string) { const alias = this.alias(name); this.globals.set(name, alias); return alias; } generate(result?: Node[]) { let js = null; let css = null; if (result) { const { compile_options, name } = this; const { format = 'esm' } = compile_options; const banner = `${this.file ? `${this.file} ` : ``}generated by Svelte v${'__VERSION__'}`; const program: any = { type: 'Program', body: result }; walk(program, { enter: (node, parent, key) => { if (node.type === 'Identifier') { if (node.name[0] === '@') { if (node.name[1] === '_') { const alias = this.global(node.name.slice(2)); node.name = alias.name; } else { let name = node.name.slice(1); if (compile_options.dev) { if (internal_exports.has(`${name}_dev`)) { name += '_dev'; } else if (internal_exports.has(`${name}Dev`)) { name += 'Dev'; } } const alias = this.alias(name); this.helpers.set(name, alias); node.name = alias.name; } } else if (node.name[0] !== '#' && !is_valid(node.name)) { // this hack allows x`foo.${bar}` where bar could be invalid const literal: Literal = { type: 'Literal', value: node.name }; if (parent.type === 'Property' && key === 'key') { parent.key = literal; } else if (parent.type === 'MemberExpression' && key === 'property') { parent.property = literal; parent.computed = true; } } } } }); const referenced_globals = Array.from( this.globals, ([name, alias]) => name !== alias.name && { name, alias } ).filter(Boolean); if (referenced_globals.length) { this.helpers.set('globals', this.alias('globals')); } const imported_helpers = Array.from(this.helpers, ([name, alias]) => ({ name, alias, })); create_module( program, format, name, banner, compile_options.sveltePath, imported_helpers, referenced_globals, this.imports, this.vars .filter(variable => variable.module && variable.export_name) .map(variable => ({ name: variable.name, as: variable.export_name, })) ); css = compile_options.customElement ? { code: null, map: null } : this.stylesheet.render(compile_options.cssOutputFilename, true); js = print(program, { sourceMapSource: compile_options.filename }); js.map.sources = [ compile_options.filename ? get_relative_path(compile_options.outputFilename || '', compile_options.filename) : null ]; js.map.sourcesContent = [ this.source ]; } return { js, css, ast: this.original_ast, warnings: this.warnings, vars: this.vars .filter(v => !v.global && !v.internal) .map(v => ({ name: v.name, export_name: v.export_name || null, injected: v.injected || false, module: v.module || false, mutated: v.mutated || false, reassigned: v.reassigned || false, referenced: v.referenced || false, writable: v.writable || false, referenced_from_script: v.referenced_from_script || false, })), stats: this.stats.render(), }; } get_unique_name(name: string): Identifier { if (test) name = `${name}$`; let alias = name; for ( let i = 1; reserved.has(alias) || this.var_lookup.has(alias) || this.used_names.has(alias) || this.globally_used_names.has(alias); alias = `${name}_${i++}` ); this.used_names.add(alias); return { type: 'Identifier', name: alias }; } get_unique_name_maker() { const local_used_names = new Set(); function add(name: string) { local_used_names.add(name); } reserved.forEach(add); internal_exports.forEach(add); this.var_lookup.forEach((_value, key) => add(key)); return (name: string): Identifier => { if (test) name = `${name}$`; let alias = name; for ( let i = 1; this.used_names.has(alias) || local_used_names.has(alias); alias = `${name}_${i++}` ); local_used_names.add(alias); this.globally_used_names.add(alias); return { type: 'Identifier', name: alias }; }; } error( pos: { start: number; end: number; }, e: { code: string; message: string; } ) { error(e.message, { name: 'ValidationError', code: e.code, source: this.source, start: pos.start, end: pos.end, filename: this.compile_options.filename, }); } warn( pos: { start: number; end: number; }, warning: { code: string; message: string; } ) { if (this.ignores && this.ignores.has(warning.code)) { return; } const start = this.locate(pos.start); const end = this.locate(pos.end); const frame = get_code_frame(this.source, start.line - 1, start.column); this.warnings.push({ code: warning.code, message: warning.message, frame, start, end, pos: pos.start, filename: this.compile_options.filename, toString: () => `${warning.message} (${start.line}:${start.column})\n${frame}`, }); } extract_imports(node) { this.imports.push(node); } extract_exports(node) { if (node.type === 'ExportDefaultDeclaration') { this.error(node, { code: `default-export`, message: `A component cannot have a default export`, }); } if (node.type === 'ExportNamedDeclaration') { if (node.source) { this.error(node, { code: `not-implemented`, message: `A component currently cannot have an export ... from`, }); } if (node.declaration) { if (node.declaration.type === 'VariableDeclaration') { node.declaration.declarations.forEach(declarator => { extract_names(declarator.id).forEach(name => { const variable = this.var_lookup.get(name); variable.export_name = name; if (variable.writable && !(variable.referenced || variable.referenced_from_script)) { this.warn(declarator, { code: `unused-export-let`, message: `${this.name.name} has unused export property '${name}'. If it is for external reference only, please consider using \`export const '${name}'\`` }); } }); }); } else { const { name } = node.declaration.id; const variable = this.var_lookup.get(name); variable.export_name = name; } return node.declaration; } else { node.specifiers.forEach(specifier => { const variable = this.var_lookup.get(specifier.local.name); if (variable) { variable.export_name = specifier.exported.name; if (variable.writable && !(variable.referenced || variable.referenced_from_script)) { this.warn(specifier, { code: `unused-export-let`, message: `${this.name.name} has unused export property '${specifier.exported.name}'. If it is for external reference only, please consider using \`export const '${specifier.exported.name}'\`` }); } } }); return null; } } } extract_javascript(script) { if (!script) return null; return script.content.body.filter(node => { if (!node) return false; if (this.hoistable_nodes.has(node)) return false; if (this.reactive_declaration_nodes.has(node)) return false; if (node.type === 'ImportDeclaration') return false; if (node.type === 'ExportDeclaration' && node.specifiers.length > 0) return false; return true; }); } walk_module_js_pre_template() { const component = this; const script = this.ast.module; if (!script) return; walk(script.content, { enter(node) { if (node.type === 'LabeledStatement' && node.label.name === '$') { component.warn(node as any, { code: 'module-script-reactive-declaration', message: '$: has no effect in a module script', }); } }, }); const { scope, globals } = create_scopes(script.content); this.module_scope = scope; scope.declarations.forEach((node, name) => { if (name[0] === '$') { this.error(node as any, { code: 'illegal-declaration', message: `The $ prefix is reserved, and cannot be used for variable and import names`, }); } const writable = node.type === 'VariableDeclaration' && (node.kind === 'var' || node.kind === 'let'); this.add_var({ name, module: true, hoistable: true, writable }); }); globals.forEach((node, name) => { if (name[0] === '$') { this.error(node as any, { code: 'illegal-subscription', message: `Cannot reference store value inside