UNPKG

6.07 kBJavaScriptView Raw
1/* eslint-disable no-process-env */
2
3const fs = require('fs');
4const path = require('path');
5const dotenv = require('dotenv');
6const config = require('./slate-env.config');
7
8const SLATE_ENV_VARS = [
9 config.envNameVar,
10 config.envStoreVar,
11 config.envPasswordVar,
12 config.envThemeIdVar,
13 config.envIgnoreFilesVar,
14 config.envUserEmail,
15];
16
17const DEFAULT_ENV_VARS = [
18 config.envStoreVar,
19 config.envPasswordVar,
20 config.envThemeIdVar,
21 config.envIgnoreFilesVar,
22];
23
24// Creates a new env file with optional name and values
25function create({values, name, root} = {}) {
26 const envName = _getFileName(name);
27 const envPath = path.resolve(root || config.envRootDir, envName);
28 const envContents = _getFileContents(values);
29
30 fs.writeFileSync(envPath, envContents);
31}
32
33// Return the default env file name, with optional name appended
34function _getFileName(name) {
35 if (typeof name === 'undefined' || name.trim() === '') {
36 return config.envDefaultFileName;
37 }
38
39 return `${config.envDefaultFileName}.${name}`;
40}
41
42// Return default list of env variables with their assigned value, if any.
43function _getFileContents(values) {
44 const env = getDefaultSlateEnv();
45
46 for (const key in values) {
47 if (values.hasOwnProperty(key) && env.hasOwnProperty(key)) {
48 env[key] = values[key];
49 }
50 }
51
52 return Object.entries(env)
53 .map((keyValues) => {
54 const envVar = keyValues[0];
55
56 // Search through config for the key which has a value of the env variable
57 // e.g. find the key which has the value of 'SLATE_STORE'
58 for (const key in config) {
59 if (config.hasOwnProperty(key) && config[key] === envVar) {
60 // Once we find the key, we can search the config.__schema for the
61 // schema item. We need to schema item so we can print the description
62 // comment.
63 const schemaItem = config.__schema.items.find(
64 (item) => item.id === key,
65 );
66 return `# ${schemaItem.description || ''} \r\n${keyValues.join('=')}`;
67 }
68 }
69
70 return true;
71 })
72 .join('\r\n\r\n');
73}
74
75// Reads an .env file and assigns their values to environment variables
76function assign(name) {
77 const envFileName = _getFileName(name);
78 const envPath = path.resolve(config.envRootDir, envFileName);
79 const result = dotenv.config({path: envPath});
80
81 if (typeof name !== 'undefined' && result.error) {
82 throw result.error;
83 }
84
85 _setEnvName(name);
86}
87
88function _setEnvName(name) {
89 let envName = name;
90 const envFileName = _getFileName(name);
91 const envPath = path.resolve(config.envRootDir, envFileName);
92
93 if (typeof name === 'undefined') {
94 if (fs.existsSync(envPath)) {
95 envName = config.envDefaultEnvName;
96 } else {
97 envName = config.envExternalEnvName;
98 }
99 }
100
101 process.env[config.envNameVar] = envName;
102}
103
104// Checks if Slate env variables are the required value types and format
105function validate() {
106 const errors = [].concat(
107 _validateStore(),
108 _validatePassword(),
109 _validateThemeId(),
110 );
111
112 return {
113 errors,
114 isValid: errors.length === 0,
115 };
116}
117
118function _validateStore() {
119 const errors = [];
120 const store = getStoreValue();
121
122 if (store.length === 0) {
123 errors.push(new Error(`${config.envStoreVar} must not be empty`));
124 } else if (
125 store.indexOf('.myshopify.com') < 1 &&
126 store.indexOf('.myshopify.io') < 1
127 ) {
128 errors.push(
129 new Error(`${config.envStoreVar} must be a valid .myshopify.com URL`),
130 );
131 }
132
133 return errors;
134}
135
136function _validatePassword() {
137 const errors = [];
138 const password = getPasswordValue();
139
140 if (password.length === 0) {
141 errors.push(new Error(`${config.envPasswordVar} must not be empty`));
142 } else if (!/^\w+$/.test(password)) {
143 errors.push(
144 new Error(
145 `${config.envPasswordVar} can only contain numbers and letters`,
146 ),
147 );
148 }
149
150 return errors;
151}
152
153function _validateThemeId() {
154 const errors = [];
155 const themeId = getThemeIdValue();
156
157 if (themeId.length === 0) {
158 errors.push(new Error(`${config.envThemeIdVar} must not be empty`));
159 } else if (themeId !== 'live' && !/^\d+$/.test(themeId)) {
160 errors.push(
161 new Error(
162 `${
163 config.envThemeIdVar
164 } can be set to 'live' or a valid theme ID containing only numbers`,
165 ),
166 );
167 }
168
169 return errors;
170}
171
172// Clears the values of environment variables used by Slate
173function clear() {
174 SLATE_ENV_VARS.forEach((key) => (process.env[key] = ''));
175}
176
177// Get the values of Slate's required environment variables
178function getSlateEnv() {
179 const env = {};
180
181 SLATE_ENV_VARS.forEach((key) => {
182 env[key] = process.env[key];
183 });
184
185 return env;
186}
187
188// Returns the Slate's required environment variables with empty values
189function getEmptySlateEnv() {
190 const env = {};
191
192 SLATE_ENV_VARS.forEach((key) => {
193 env[key] = '';
194 });
195
196 return env;
197}
198
199function getDefaultSlateEnv() {
200 const env = {};
201
202 DEFAULT_ENV_VARS.forEach((key) => {
203 env[key] = '';
204 });
205
206 return env;
207}
208
209function getEnvNameValue() {
210 return process.env[config.envNameVar];
211}
212
213// Returns the configurable environment varible that reference the store URL
214function getStoreValue() {
215 const value = process.env[config.envStoreVar];
216 return typeof value === 'undefined' ? '' : value;
217}
218
219function getPasswordValue() {
220 const value = process.env[config.envPasswordVar];
221 return typeof value === 'undefined' ? '' : value;
222}
223
224function getThemeIdValue() {
225 const value = process.env[config.envThemeIdVar];
226 return typeof value === 'undefined' ? '' : value;
227}
228
229function getIgnoreFilesValue() {
230 const value = process.env[config.envIgnoreFilesVar];
231 return typeof value === 'undefined' ? '' : value;
232}
233
234function getUserEmail() {
235 const value = process.env[config.envUserEmail];
236 return typeof value === 'undefined' ? '' : value;
237}
238
239module.exports = {
240 create,
241 assign,
242 validate,
243 clear,
244 getSlateEnv,
245 getDefaultSlateEnv,
246 getEmptySlateEnv,
247 getEnvNameValue,
248 getStoreValue,
249 getPasswordValue,
250 getThemeIdValue,
251 getIgnoreFilesValue,
252 getUserEmail,
253};