-
Notifications
You must be signed in to change notification settings - Fork 67
/
meteor.js
360 lines (318 loc) · 11 KB
/
meteor.js
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// MODULES
const { print } = require('./helpers.js');
const fs = require('fs-extra');
const path = require('path');
const _ = require('underscore');
const Q = require('bluebird');
const spawn = require('buffered-spawn');
Q.promisifyAll(fs);
// VARIABLES
const argPath = process.argv[2];
const basePath = './';
const outputPath = path.resolve(argPath);
let buildPath = path.resolve(argPath);
// const bundleName = path.basename(path.resolve(basePath));
const RE = {
scripts: {
template: /{{ *> *scripts *}}/,
tag: /<meteor-bundled-js *\/>/
},
styles: {
template: /{{ *> *css *}}/,
tag: /<meteor-bundled-css *\/>/,
url: /{{ *url-to-meteor-bundled-css *}}/
},
templates: {
head: /{{ *> *head *}}/,
body: /{{ *> *body *}}/
},
fileName: {
js: /^[a-z0-9]{40}\.js$/,
css: /^[a-z0-9]{40}\.css$/
},
path: {
app: /^app\//
}
};
// execute shell scripts
const execute = (command) => {
return new Q(function(resolve, reject) {
const cmd = spawn(command[0], command.slice(1), {
cwd: basePath
}, function(err, stdout, stderr) {
if (err){
print('[execute] ERROR:', err.message);
reject(err);
} else {
resolve({
stdout: stdout,
stderr: stderr,
});
}
});
cmd.stdout.pipe(process.stdout);
cmd.stderr.pipe(process.stderr);
});
};
const deleteFolderRecursive = (_path) => {
let files = [];
if(fs.existsSync(_path)) {
files = fs.readdirSync(_path);
files.forEach((file) => {
try {
const curPath = `${_path}/${file}`;
if (fs.lstatSync(curPath).isDirectory()) { // recurse
deleteFolderRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
} catch (_e) {
// silence here
}
});
fs.rmdirSync(_path);
}
};
module.exports = {
build(program){
return Q.try(function() {
deleteFolderRecursive(buildPath);
const command = ['meteor', 'build', argPath, '--directory'];
if (program.debug) {
command.push('--debug');
}
if (program.verbose) {
command.push('--verbose');
}
if (program.url) {
command.push('--server');
command.push(program.url);
}
if (program.debug) {
print('[build()] DEBUG:', command.join(' '));
}
return execute(command, 'build the app, are you in your meteor apps folder?');
});
},
move(_path){
buildPath = _path;
return Q.try(function() {
try {
const modernDirs = ['/bundle/programs/web.browser', '/bundle/programs/web.browser/app'];
const legacyDirs = ['/bundle/programs/web.browser.legacy', '/bundle/programs/web.browser.legacy/app'];
const isModern = fs.lstatSync(path.join(buildPath, legacyDirs[0])).isDirectory() ? false : true;
const dataPaths = isModern ? modernDirs : legacyDirs;
dataPaths.forEach((givenPath) => {
const clientPath = path.join(buildPath, givenPath);
if (fs.lstatSync(clientPath).isDirectory()) {
let rootFolder = fs.readdirSync(clientPath);
rootFolder = _.without(rootFolder, 'app');
rootFolder.forEach((file) => {
fs.copySync(path.join(clientPath, file), path.join(outputPath, file));
});
}
});
} catch(e) {
print('[move()] Exception:', e);
// do nothing
}
});
},
addIndexFile(program) {
return Q.try(function() {
const starJson = require(`${path.resolve(buildPath)}/bundle/star.json`);
const settingsJson = program.settings ? require(path.resolve(program.settings)) : {};
let content = fs.readFileSync(program.template || path.resolve(__dirname, 'index.html'), {encoding: 'utf-8'});
let body = '';
let head = '<meta charset="UTF-8">';
try{
head = fs.readFileSync(path.join(outputPath, 'head.html'), {encoding: 'utf8'});
} catch(e) {
if (program.debug) {
print('FYI: No <head> found in Meteor app...');
}
}
try{
body = fs.readFileSync(path.join(outputPath, 'body.html'), {encoding: 'utf8'});
} catch(e) {
if (program.debug) {
print('FYI: No <body> found in Meteor app...');
}
}
// Add head and body
// if no head.html then put in the styles.template
// if no body.html then put in the scripts.template
//
// This will allow meteor-build-client to work without a user specified template.
// Required for blaze projects that do not produce a body.html file
content = !program.template && !head
? content.replace(RE.templates.head, '{{> css}}')
: content.replace(RE.templates.head, head);
content = !program.template && !body
? content.replace(RE.templates.body, '{{> scripts}}')
: content.replace(RE.templates.body, body);
// get the css and js files
const files = {
css: [],
js: []
};
_.each(fs.readdirSync(outputPath), (file) => {
if (RE.fileName.js.test(file)) {
files.js.push(file);
} else if (RE.fileName.css.test(file)) {
files.css.push(file);
}
});
let primaryCSSfile = files.css[0];
const json = fs.readFileSync(path.resolve(path.join(outputPath, 'program.json')), {encoding: 'utf-8'});
const prog = JSON.parse(json);
_.each(prog.manifest, (item) => {
if (item.type === 'js' && item.url) {
const file = item.path.replace(RE.path.app, '');
if (!files.js.includes(file)) {
files.js.push(`${file}?hash=${item.hash}`);
}
} else if (item.type === 'css' && item.url) {
const file = item.path.replace(RE.path.app, '');
if (!files.css.includes(file)) {
// for css file cases, do not append hash.
files.css.push(file);
}
if (item.url.includes('meteor_css_resource=true')) {
primaryCSSfile = item.path.replace(RE.path.app, '');
}
}
});
// --debug case
if (program.debug) {
print('[DEBUG] Files:', files, {primaryCSSfile});
}
// MAKE PATHS ABSOLUTE
if(_.isString(program.path)) {
// fix paths in the CSS file
if(!_.isEmpty(files.css)) {
_.each(files.css, (css, i) => {
let cssFile = fs.readFileSync(path.join(outputPath, css), { encoding: 'utf8' });
cssFile = cssFile.replace(/url\(\'\//g, `url('${program.path}`).replace(/url\(\//g, `url(${program.path}`);
fs.unlinkSync(path.join(outputPath, css));
fs.writeFileSync(path.join(outputPath, css), cssFile, { encoding: 'utf8' });
files.css[i] = `${program.path}${css}`;
});
}
if(!_.isEmpty(files.js)) {
_.each(files.js, (jsFile, i) => {
files.js[i] = `${program.path}${jsFile}`;
});
}
if (primaryCSSfile) {
primaryCSSfile = `${program.path}${primaryCSSfile}`;
}
} else {
if(!_.isEmpty(files.css)) {
_.each(files.css, (cssFile, i) => {
files.css[i] = `/${cssFile}`;
});
}
if(!_.isEmpty(files.js)) {
_.each(files.js, (jsFile, i) => {
files.js[i] = `/${jsFile}`;
});
}
if (primaryCSSfile) {
primaryCSSfile = `/${primaryCSSfile}`;
}
}
// ADD CSS
let css = [];
_.each(files.css, (cssFile) => {
css.push(`<link rel="stylesheet" type="text/css" href="${cssFile}">`);
});
css = css.join('');
if (RE.styles.template.test(content)) {
content = content.replace(RE.styles.template, css);
} else if (RE.styles.tag.test(content)) {
content = content.replace(RE.styles.tag, css);
}
if (RE.styles.url.test(content) && primaryCSSfile) {
content = content.replace(RE.styles.url, primaryCSSfile);
}
// ADD the SCRIPT files
let scripts = ['__meteor_runtime_config__'];
_.each(files.js, (jsFile) => {
scripts.push(`<script type="text/javascript" src="${jsFile}"></script>`);
});
scripts = scripts.join('');
// add the meteor runtime config
const settings = {
'meteorRelease': starJson.meteorRelease,
'ROOT_URL_PATH_PREFIX': process.env.ROOT_URL_PATH_PREFIX || '',
meteorEnv: {
NODE_ENV: 'production'
},
autoupdate: { versions: {}},
// 'DDP_DEFAULT_CONNECTION_URL': program.url || '', // will reload infinite if Meteor.disconnect is not called
// 'appId': process.env.APP_ID || null,
// 'autoupdateVersion': null, // "ecf7fcc2e3d4696ea099fdd287dfa56068a692ec"
// 'autoupdateVersionRefreshable': null, // "c5600e68d4f2f5b920340f777e3bfc4297127d6e"
// 'autoupdateVersionCordova': null
};
// on url = "default", we dont set the ROOT_URL, so Meteor chooses the app serving url for its DDP connection
if (program.url !== 'default') {
settings.ROOT_URL = program.url || '';
}
if (settingsJson.public) {
settings.PUBLIC_SETTINGS = settingsJson.public;
}
scripts = scripts.replace('__meteor_runtime_config__', `<script type="text/javascript">__meteor_runtime_config__ = JSON.parse(decodeURIComponent("${encodeURIComponent(JSON.stringify(settings))}"));</script>`);
// add Meteor.disconnect() when no server is given
if (!program.url) {
scripts += '<script type="text/javascript">Meteor && Meteor.disconnect && Meteor.disconnect();</script>';
}
if (RE.scripts.template.test(content)) {
content = content.replace(RE.scripts.template, scripts);
} else if (RE.scripts.tag.test(content)) {
content = content.replace(RE.scripts.tag, scripts);
}
// write the index.html
return fs.writeFileAsync(path.join(outputPath, 'index.html'), content).then(() => {
if (!program.url) {
return fs.mkdirAsync(path.join(outputPath, 'sockjs'))
.then(() => fs.writeFileAsync(path.join(outputPath, 'sockjs/info'), '{"websocket": false}', { encoding: 'utf8' })).catch(() => {
print('sockjs/info not created or already exists');
return true;
});
}
return true;
});
});
},
cleanUp(program) {
return Q.try(function() {
// remove files
if (!program.usebuild) {
deleteFolderRecursive(path.join(buildPath, 'bundle'));
}
try {
fs.unlinkSync(path.join(outputPath, 'program.json'));
} catch (e){
if (program.debug) {
print('FYI: Didn\'t unlink program.json; doesn\'t exist.');
}
}
try{
fs.unlinkSync(path.join(outputPath, 'head.html'));
} catch (e){
if (program.debug) {
print('FYI: Didn\'t unlink head.html; doesn\'t exist.');
}
}
try{
fs.unlinkSync(path.join(outputPath, 'body.html'));
} catch (e){
if (program.debug) {
print('FYI: Didn\'t unlink body.html; doesn\'t exist.');
}
}
});
}
};