-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirebase-cli.js
More file actions
executable file
·292 lines (264 loc) · 7.51 KB
/
Copy pathfirebase-cli.js
File metadata and controls
executable file
·292 lines (264 loc) · 7.51 KB
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
#!/usr/bin/env node
"use strict";
const process = require("process");
const { createInterface } = require("readline");
const admin = require("firebase-admin");
const { initializeApp, cert } = require("firebase-admin/app");
const { getAuth } = require("firebase-admin/auth");
const { getDatabase } = require("firebase-admin/database");
const { getFirestore } = require("firebase-admin/firestore");
const { getStorage } = require("firebase-admin/storage");
const firestoreNs = require("firebase-admin/firestore");
const { writeFileSync, existsSync, readFileSync } = require("fs");
const { join, normalize } = require("path");
const { getProjectInfo } = require("../utils/getProjectInfo");
const { strHandler } = require("../utils/strHandler");
/**
* Terminal type definition
* @typedef {Object} Terminal
* @property {string} command - current command
* @property {Array<string>} commandsHistory - history of the commands
* @property {number} delayForWrite - delay for write command
* @property {number} lastWriteTime - the time in ms when the last symbol was write
* @property {number} lastEnterTime - the time in ms when the enter key was pressed on the keyboard
*/
/**
* @type {Terminal}
*/
const terminal = {
command: "",
commandsHistory: [],
delayForWrite: 100,
lastWriteTime: 0,
lastEnterTime: 0,
};
/**
* Path to command history file
*/
const commandsHistoryFilePath = join(__dirname, "..", "./commands.json");
/**
* History size
*/
const historySize = 100;
/**
* Saved path to service account key
*
* @type {string|undefined}
*/
let savedServiceAccountKeyPath = undefined;
// load history of commands from file
if (existsSync(commandsHistoryFilePath)) {
try {
const commandsHistoryFileTxt = readFileSync(commandsHistoryFilePath);
const commandsHistoryFile = JSON.parse(commandsHistoryFileTxt);
if (Array.isArray(commandsHistoryFile.commandsHistory)) {
terminal.commandsHistory = commandsHistoryFile.commandsHistory.slice(
commandsHistoryFile.commandsHistory.length - historySize - 1
);
}
savedServiceAccountKeyPath = commandsHistoryFile.serviceAccountKeyPath;
} catch (err) {}
}
// error handle
process.on("uncaughtException", (err, origin) => {
console.log(err.message);
process.exit(1);
});
const projectInfo = getProjectInfo(savedServiceAccountKeyPath);
const servicename = `Firebase Admin CLI (${projectInfo.serviceAccount.project_id})`;
// save history of commands and service account path to file
process.on("exit", (code) => {
writeFileSync(
commandsHistoryFilePath,
JSON.stringify({
commandsHistory: terminal.commandsHistory,
serviceAccountKeyPath: projectInfo.serviceAccountKeyPath,
})
);
process.exit(code);
});
/**
* FastCommand type definition
* @typedef {Object} FastCommand
* @property {string} command
* @property {string} title
* @property {string} alias
*/
/**
* @type {Array<FastCommand>}
*/
const fastcommands = [];
const app = initializeApp({
authDomain: `${projectInfo.serviceAccount.project_id}.firebaseapp.com`,
databaseURL: `https://${projectInfo.serviceAccount.project_id}.firebaseio.com`,
storageBucket: `${projectInfo.serviceAccount.project_id}.appspot.com`,
credential: cert(projectInfo.serviceAccount),
});
function help() {
console.table(fastcommands, ["command", "title", "alias"]);
}
fastcommands.push({
command: "help()",
title: "Сall current help",
alias: "help()",
});
const auth = getAuth(app);
fastcommands.push({
command: "auth",
title: "Сall firebase authorization interface",
alias: "admin.auth()",
});
const rtdb = getDatabase(app);
fastcommands.push({
command: "rtdb",
title: "Сall firebase database interface",
alias: "admin.database()",
});
const db = getFirestore(app);
fastcommands.push({
command: "db",
title: "Сall firebase firestore interface",
alias: "admin.firestore()",
});
const storage = getStorage(app);
fastcommands.push({
command: "storage",
title: "Сall firebase storage interface",
alias: `admin.storage()`,
});
const bucket = getStorage(app).bucket();
fastcommands.push({
command: "bucket",
title: "Сall firebase storage/bucket interface",
alias: `admin.storage().bucket()`,
});
const types = firestoreNs;
fastcommands.push({
command: "types",
title: "Сall firebase firestore types interface",
alias: "admin.firestore",
});
const tools = Object.freeze({
projectInfo,
admin,
app,
auth,
rtdb,
db,
storage,
bucket,
types,
});
global.tools = tools;
global.ext = {};
if (process.argv?.length > 2) {
const extRegSource = "^--with=";
const extRegCheck = new RegExp(`${extRegSource}.+`);
const extRegRepl = new RegExp(`${extRegSource}`);
const extensions =
process.argv
.filter((e) => extRegCheck.test(e))
.map((e) => normalize(e.replace(extRegRepl, "").replace(/'"/g, "")))
.filter((e) => !!e) ?? [];
extensions.forEach((path) => {
try {
Object.assign(global.ext, require(path));
console.log(`Extension is loaded: ${path}`);
} catch (err) {
console.error(`Extension isn't loaded: ${path}`, err);
}
});
if (extensions.length) {
console.log(
`The following methods are now available to you: ${Object.keys(global.ext)
.map((k) => `ext.${k}`)
.join(", ")}`
);
}
}
const terminalInterface = createInterface({
input: process.stdin,
output: process.stdout,
prompt: servicename + ">",
historySize,
terminal: true,
history: JSON.parse(JSON.stringify(terminal.commandsHistory)),
});
const exit = () => {
terminalInterface.close();
};
fastcommands.push({
command: "exit()",
title: "Exit console",
alias: "terminalInterface.close()",
});
/**
* @type {Array<string>}
*/
const constants = [];
/**
* @type {Object}
*/
const globalKeys = Object.keys(global);
/**
* Eval async code in the context
*
* @param {string} str - string of the code
* @returns
*/
async function evalInContext(str) {
if (str && str !== "") {
str = strHandler.call(this, str, constants, globalKeys);
const _match = str.match(/^this\.[a-zA-Z]+\d*/);
if (_match && _match[0])
return await eval(
"(async()=>{\n" + str + ";\nreturn " + _match[0] + ";\n})()"
);
else
return await eval(
"(async()=>{\n const _result = " + str + ";\nreturn _result;\n})()"
);
} else return;
}
help();
process.stdin.on("keypress", (code, key) => {
if (code === "\r") terminal.lastEnterTime = Date.now();
else terminal.lastWriteTime = Date.now();
});
terminalInterface.prompt();
terminalInterface
.on("line", (line) => {
setTimeout(
async (l) => {
terminal.command += `${l}\n`;
if (
terminal.lastEnterTime - terminal.lastWriteTime >
terminal.delayForWrite
) {
terminal.command = terminal.command.replace(/\n$/gi, "");
if (terminal.command !== "") {
terminal.commandsHistory = terminal.commandsHistory.slice(
terminal.commandsHistory.length - historySize - 1
);
terminal.commandsHistory.unshift(terminal.command);
}
try {
const _result = await evalInContext.call(global, terminal.command);
// if (typeof _result !== "undefined") console.log(_result);
} catch (err) {
if (err instanceof TypeError) console.error(err.message);
else console.error(err);
}
terminal.command = "";
}
terminalInterface.prompt();
},
0,
line
);
return;
})
.on("close", () => {
console.log(servicename + " disconnected!");
process.exit(0);
});