-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
Copy pathindex.ts
108 lines (90 loc) · 2.41 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import { assign } from '../internal';
import Stats from '../Stats';
import parse from '../parse/index';
import render_dom from './render-dom/index';
import render_ssr from './render-ssr/index';
import { CompileOptions, Ast, Warning } from '../interfaces';
import Component from './Component';
import fuzzymatch from '../utils/fuzzymatch';
const valid_options = [
'format',
'name',
'filename',
'generate',
'outputFilename',
'cssOutputFilename',
'sveltePath',
'dev',
'accessors',
'immutable',
'hydratable',
'legacy',
'customElement',
'tag',
'css',
'preserveComments',
'preserveWhitespace'
];
function validate_options(options: CompileOptions, warnings: Warning[]) {
const { name, filename } = options;
Object.keys(options).forEach(key => {
if (valid_options.indexOf(key) === -1) {
const match = fuzzymatch(key, valid_options);
let message = `Unrecognized option '${key}'`;
if (match) message += ` (did you mean '${match}'?)`;
throw new Error(message);
}
});
if (name && !/^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(name)) {
throw new Error(`options.name must be a valid identifier (got '${name}')`);
}
if (name && /^[a-z]/.test(name)) {
const message = `options.name should be capitalised`;
warnings.push({
code: `options-lowercase-name`,
message,
filename,
toString: () => message,
});
}
}
function get_name(filename) {
if (!filename) return null;
const parts = filename.split(/[\/\\]/);
if (parts.length > 1 && /^index\.\w+/.test(parts[parts.length - 1])) {
parts.pop();
}
const base = parts.pop()
.replace(/\..+/, "")
.replace(/[^a-zA-Z_$0-9]+/g, '_')
.replace(/^_/, '')
.replace(/_$/, '')
.replace(/^(\d)/, '_$1');
return base[0].toUpperCase() + base.slice(1);
}
export default function compile(source: string, options: CompileOptions = {}) {
options = assign({ generate: 'dom', dev: false }, options);
const stats = new Stats();
const warnings = [];
let ast: Ast;
validate_options(options, warnings);
stats.start('parse');
ast = parse(source, options);
stats.stop('parse');
stats.start('create component');
const component = new Component(
ast,
source,
options.name || get_name(options.filename) || 'Component',
options,
stats,
warnings
);
stats.stop('create component');
const js = options.generate === false
? null
: options.generate === 'ssr'
? render_ssr(component, options)
: render_dom(component, options);
return component.generate(js);
}