forked from rethinkdb/horizon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.js
319 lines (281 loc) · 9.39 KB
/
init.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
/* global require, module */
'use strict';
const fs = require('fs');
const crypto = require('crypto');
const process = require('process');
const argparse = require('argparse');
const checkProjectName = require('./utils/check-project-name');
const rethrow = require('./utils/rethrow');
const makeIndexHTML = (projectName) => `\
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="/horizon/horizon.js"></script>
<script>
var horizon = Horizon();
horizon.onReady(function() {
document.querySelector('h1').innerHTML = '${projectName} works!'
});
horizon.connect();
</script>
</head>
<body>
<marquee direction="left"><h1></h1></marquee>
</body>
</html>
`;
const makeDefaultConfig = (projectName) => `\
# This is a TOML file
###############################################################################
# IP options
# 'bind' controls which local interfaces will be listened on
# 'port' controls which port will be listened on
#------------------------------------------------------------------------------
# bind = [ "localhost" ]
# port = 8181
###############################################################################
# HTTPS Options
# 'secure' will disable HTTPS and use HTTP instead when set to 'false'
# 'key_file' and 'cert_file' are required for serving HTTPS
#------------------------------------------------------------------------------
# secure = true
# key_file = "horizon-key.pem"
# cert_file = "horizon-cert.pem"
###############################################################################
# App Options
# 'project_name' sets the name of the RethinkDB database used to store the
# application state
# 'serve_static' will serve files from the given directory over HTTP/HTTPS
#------------------------------------------------------------------------------
project_name = "${projectName}"
# serve_static = "dist"
###############################################################################
# Data Options
# WARNING: these should probably not be enabled on a publically accessible
# service. Tables and indexes are not lightweight objects, and allowing them
# to be created like this could open the service up to denial-of-service
# attacks.
# 'auto_create_collection' creates a collection when one is needed but does not exist
# 'auto_create_index' creates an index when one is needed but does not exist
#------------------------------------------------------------------------------
# auto_create_collection = false
# auto_create_index = false
###############################################################################
# RethinkDB Options
# 'connect' and 'start_rethinkdb' are mutually exclusive
# 'connect' will connect to an existing RethinkDB instance
# 'start_rethinkdb' will run an internal RethinkDB instance
# 'rdb_timeout' is the number of seconds to wait when connecting to RethinkDB
#------------------------------------------------------------------------------
# connect = "localhost:28015"
# start_rethinkdb = false
# rdb_timeout = 30
###############################################################################
# Debug Options
# 'debug' enables debug log statements
#------------------------------------------------------------------------------
# debug = false
###############################################################################
# Authentication Options
# Each auth subsection will add an endpoint for authenticating through the
# specified provider.
# 'token_secret' is the key used to sign jwts
# 'allow_anonymous' issues new accounts to users without an auth provider
# 'allow_unauthenticated' allows connections that are not tied to a user id
# 'auth_redirect' specifies where users will be redirected to after login
# 'access_control_allow_origin' sets a host that can access auth settings
# (typically your frontend host)
#------------------------------------------------------------------------------
# allow_anonymous = false
# allow_unauthenticated = false
# auth_redirect = "/"
# access_control_allow_origin = ""
#
`;
const makeDefaultSchema = () => `\
[groups.admin]
[groups.admin.rules.carte_blanche]
template = "any()"
`;
const makeDefaultSecrets = () => `\
token_secret = "${crypto.randomBytes(64).toString('base64')}"
###############################################################################
# RethinkDB Options
# 'rdb_user' is the user account to log in with when connecting to RethinkDB
# 'rdb_password' is the password for the user account specified by 'rdb_user'
#------------------------------------------------------------------------------
# rdb_user = 'admin'
# rdb_password = ''
# [auth.auth0]
# host = "0000.00.auth0.com"
# id = "0000000000000000000000000"
# secret = "00000000000000000000000000000000000000000000000000"
#
# [auth.facebook]
# id = "000000000000000"
# secret = "00000000000000000000000000000000"
#
# [auth.google]
# id = "00000000000-00000000000000000000000000000000.apps.googleusercontent.com"
# secret = "000000000000000000000000"
#
# [auth.twitter]
# id = "0000000000000000000000000"
# secret = "00000000000000000000000000000000000000000000000000"
#
# [auth.github]
# id = "00000000000000000000"
# secret = "0000000000000000000000000000000000000000"
#
# [auth.twitch]
# id = "0000000000000000000000000000000"
# secret = "0000000000000000000000000000000"
#
# [auth.slack]
# id = "0000000000000000000000000000000"
# secret = "0000000000000000000000000000000"
`;
const gitignore = () => `\
rethinkdb_data
**/*.log
.hz/secrets.toml
node_modules
`;
const parseArguments = (args) => {
const parser = new argparse.ArgumentParser({ prog: 'hz init' });
parser.addArgument([ 'projectName' ],
{ action: 'store',
help: 'Name of directory to create. Defaults to current directory',
nargs: '?',
}
);
return parser.parseArgs(args);
};
const fileExists = (pathName) => {
try {
fs.statSync(pathName);
return true;
} catch (e) {
return false;
}
};
const maybeMakeDir = (createDir, dirName) => {
if (createDir) {
try {
fs.mkdirSync(dirName);
console.info(`Created new project directory ${dirName}`);
} catch (e) {
throw rethrow(e,
`Couldn't make directory ${dirName}: ${e.message}`);
}
} else {
console.info(`Initializing in existing directory ${dirName}`);
}
};
const maybeChdir = (chdirTo) => {
if (chdirTo) {
try {
process.chdir(chdirTo);
} catch (e) {
if (e.code === 'ENOTDIR') {
throw rethrow(e, `${chdirTo} is not a directory`);
} else {
throw rethrow(e, `Couldn't chdir to ${chdirTo}: ${e.message}`);
}
}
}
};
const populateDir = (projectName, dirWasPopulated, chdirTo, dirName) => {
const niceDir = chdirTo ? `${dirName}/` : '';
if (!dirWasPopulated && !fileExists('src')) {
fs.mkdirSync('src');
console.info(`Created ${niceDir}src directory`);
}
if (!dirWasPopulated && !fileExists('dist')) {
fs.mkdirSync('dist');
console.info(`Created ${niceDir}dist directory`);
fs.appendFileSync('./dist/index.html', makeIndexHTML(projectName));
console.info(`Created ${niceDir}dist/index.html example`);
}
if (!fileExists('.hz')) {
fs.mkdirSync('.hz');
console.info(`Created ${niceDir}.hz directory`);
}
// Default permissions
const permissionGeneral = {
encoding: 'utf8',
mode: 0o666,
};
const permissionSecret = {
encoding: 'utf8',
mode: 0o600, // Secrets are put in this config, so set it user, read/write only
};
// Create .gitignore if it doesn't exist
if (!fileExists('.gitignore')) {
fs.appendFileSync(
'.gitignore',
gitignore(),
permissionGeneral
);
console.info(`Created ${niceDir}.gitignore`);
} else {
console.info('.gitignore already exists, not touching it.');
}
// Create .hz/config.toml if it doesn't exist
if (!fileExists('.hz/config.toml')) {
fs.appendFileSync(
'.hz/config.toml',
makeDefaultConfig(projectName),
permissionGeneral
);
console.info(`Created ${niceDir}.hz/config.toml`);
} else {
console.info('.hz/config.toml already exists, not touching it.');
}
// Create .hz/schema.toml if it doesn't exist
if (!fileExists('.hz/schema.toml')) {
fs.appendFileSync(
'.hz/schema.toml',
makeDefaultSchema(),
permissionGeneral
);
console.info(`Created ${niceDir}.hz/schema.toml`);
} else {
console.info('.hz/schema.toml already exists, not touching it.');
}
// Create .hz/secrets.toml if it doesn't exist
if (!fileExists('.hz/secrets.toml')) {
fs.appendFileSync(
'.hz/secrets.toml',
makeDefaultSecrets(),
permissionSecret
);
console.info(`Created ${niceDir}.hz/secrets.toml`);
} else {
console.info('.hz/secrets.toml already exists, not touching it.');
}
};
const run = (args) =>
Promise.resolve(args)
.then(parseArguments)
.then((parsed) => {
const check = checkProjectName(
parsed.projectName,
process.cwd(),
fs.readdirSync('.')
);
const projectName = check.projectName;
const dirName = check.dirName;
const chdirTo = check.chdirTo;
const createDir = check.createDir;
maybeMakeDir(createDir, dirName);
maybeChdir(chdirTo);
// Before we create things, check if the directory is empty
const dirWasPopulated = fs.readdirSync(process.cwd()).length !== 0;
populateDir(projectName, dirWasPopulated, chdirTo, dirName);
});
module.exports = {
run,
description: 'Initialize a horizon app directory',
};