@joystick.js/node-canary 0.0.0-canary.3 → 0.0.0-canary.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,7 @@ import compression from "compression";
3
3
  import cookieParser from "cookie-parser";
4
4
  import favicon from "serve-favicon";
5
5
  import fs from "fs";
6
+ import { __package } from "../../index.js";
6
7
  import insecure from "./insecure.js";
7
8
  import requestMethods from "./requestMethods.js";
8
9
  import bodyParser from "./bodyParser.js";
@@ -14,7 +15,7 @@ import runUserQuery from "../accounts/runUserQuery.js";
14
15
  import replaceBackslashesWithForwardSlashes from "../../lib/replaceBackslashesWithForwardSlashes.js";
15
16
  import replaceFileProtocol from "../../lib/replaceFileProtocol.js";
16
17
  import getBuildPath from "../../lib/getBuildPath.js";
17
- import sanitizeQueryParameters from "./sanitizeQueryParameters.js";
18
+ import sanitizeRequestParameters from "./sanitizeRequestParameters.js";
18
19
  import session from "./session.js";
19
20
  import csp from "./csp.js";
20
21
  const cwd = replaceFileProtocol(replaceBackslashesWithForwardSlashes(process.cwd()));
@@ -41,7 +42,7 @@ var middleware_default = ({
41
42
  }
42
43
  next();
43
44
  });
44
- app.use(sanitizeQueryParameters);
45
+ app.use(sanitizeRequestParameters);
45
46
  app.use(requestMethods);
46
47
  if (cspConfig) {
47
48
  app.use((req, res, next) => csp(req, res, next, cspConfig));
@@ -54,7 +55,7 @@ var middleware_default = ({
54
55
  });
55
56
  app.use("/_joystick/utils/process.js", (_req, res) => {
56
57
  res.set("Content-Type", "text/javascript");
57
- const processPolyfill = fs.readFileSync(`${cwd}/node_modules/@joystick.js/node/dist/app/utils/process.js`, "utf-8");
58
+ const processPolyfill = fs.readFileSync(`${__package}/app/utils/process.js`, "utf-8");
58
59
  res.send(processPolyfill.replace("${NODE_ENV}", process.env.NODE_ENV));
59
60
  });
60
61
  app.use("/_joystick/index.client.js", express.static(`${buildPath}index.client.js`, {
@@ -65,7 +66,7 @@ var middleware_default = ({
65
66
  app.use("/_joystick/ui", express.static(`${buildPath}ui`, { eTag: false, maxAge: "0" }));
66
67
  app.use("/_joystick/hmr/client.js", (_req, res) => {
67
68
  res.set("Content-Type", "text/javascript");
68
- const hmrClient = fs.readFileSync(`${cwd}/node_modules/@joystick.js/node/dist/app/middleware/hmr/client.js`, "utf-8");
69
+ const hmrClient = fs.readFileSync(`${__package}/app/middleware/hmr/client.js`, "utf-8");
69
70
  res.send(hmrClient.replace("${process.env.PORT}", parseInt(process.env.PORT, 10) + 1));
70
71
  });
71
72
  app.use(favicon(faviconPath));
@@ -0,0 +1,21 @@
1
+ import escapeHTML from "../../lib/escapeHTML.js";
2
+ const sanitizeParameterSet = (parameters = [], target = {}) => {
3
+ for (let i = 0; i < parameters?.length; i += 1) {
4
+ const [key, value] = parameters[i];
5
+ delete target[key];
6
+ target[escapeHTML(key)] = escapeHTML(value);
7
+ }
8
+ };
9
+ var sanitizeRequestParameters_default = (req, res, next) => {
10
+ const parameters = Object.entries(req?.params);
11
+ const queryParameters = Object.entries(req?.query);
12
+ sanitizeParameterSet(parameters, req?.params);
13
+ sanitizeParameterSet(queryParameters, req?.query);
14
+ if (req?.route?.path) {
15
+ req.route.path = escapeHTML(req?.route?.path);
16
+ }
17
+ next();
18
+ };
19
+ export {
20
+ sanitizeRequestParameters_default as default
21
+ };
@@ -1,10 +1,5 @@
1
1
  import util from "util";
2
- import { HTML_ENTITY_MAP } from "../lib/constants.js";
3
- const escapeHTML = (string = "") => {
4
- return String(string).replace(/[&<>"'`=\/]/g, function(match) {
5
- return HTML_ENTITY_MAP[match];
6
- });
7
- };
2
+ import escapeHTML from "../lib/escapeHTML.js";
8
3
  const sanitizeAPIResponse = (data = null) => {
9
4
  let sanitizedData = data;
10
5
  if (!util.isString(sanitizedData) && !util.isObject(sanitizedData) && !Array.isArray(sanitizedData)) {
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ import fs from "fs";
2
+ import { fileURLToPath } from "url";
3
+ import { dirname } from "path";
1
4
  import sanitizeHTML from "sanitize-html";
2
5
  import _accounts from "./app/accounts";
3
6
  import _action from "./action/index.js";
@@ -26,16 +29,18 @@ const sanitize = {
26
29
  allowedTags: sanitizeHTML.defaults.allowedTags
27
30
  }
28
31
  };
32
+ const currentFilePath = fileURLToPath(import.meta.url);
33
+ const __package = dirname(currentFilePath);
29
34
  const __filename = nodeUrlPolyfills.__filename;
30
35
  const __dirname = nodeUrlPolyfills.__dirname;
31
36
  const id = generateId;
32
37
  const origin = getOrigin();
33
38
  const settings = loadSettings();
34
- console.log("HERE", fs.readFileSync(__dirname("/dist/app/utils/process.js"), "utf-8"));
35
39
  global.joystick = {
36
40
  id: generateId,
37
41
  emitters: {},
38
42
  settings,
43
+ __package,
39
44
  __dirname,
40
45
  __filename
41
46
  };
@@ -57,6 +62,7 @@ var src_default = {
57
62
  export {
58
63
  __dirname,
59
64
  __filename,
65
+ __package,
60
66
  accounts,
61
67
  action,
62
68
  src_default as default,
@@ -0,0 +1,9 @@
1
+ import { HTML_ENTITY_MAP } from "./constants.js";
2
+ var escapeHTML_default = (string = "") => {
3
+ return String(string).replace(/[&<>"'`=]/g, function(match) {
4
+ return HTML_ENTITY_MAP[match];
5
+ });
6
+ };
7
+ export {
8
+ escapeHTML_default as default
9
+ };
@@ -1,16 +1,12 @@
1
- import { URL } from "url";
1
+ import { fileURLToPath } from "url";
2
+ import { dirname } from "path";
2
3
  var nodeUrlPolyfills_default = {
3
- __filename: (url = null) => {
4
- if (!url) {
5
- return "";
6
- }
7
- return new URL("", url).pathname;
4
+ __filename: (url = "") => {
5
+ return fileURLToPath(url);
8
6
  },
9
- __dirname: (url = null) => {
10
- if (!url) {
11
- return "";
12
- }
13
- return new URL(".", url).pathname;
7
+ __dirname: (url = "") => {
8
+ const currentFilePath = fileURLToPath(url);
9
+ return dirname(currentFilePath);
14
10
  }
15
11
  };
16
12
  export {
package/dist/ssr/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import fs from "fs";
2
+ import { __package } from "../index.js";
2
3
  import get from "../api/get";
3
4
  import set from "../api/set";
4
5
  import getBrowserSafeRequest from "../app/getBrowserSafeRequest";
@@ -184,7 +185,7 @@ const getBaseCSS = (baseHTMLName = "") => {
184
185
  try {
185
186
  const customBaseCSSPathForEmail = baseHTMLName ? `${process.cwd()}/email/base_${baseHTMLName}.css` : null;
186
187
  const customDefaultBaseCSSPathForEmail = `${process.cwd()}/email/base.css`;
187
- const defaultBaseCSSPathForEmail = process.env.NODE_ENV === "test" ? `${process.cwd()}/src/email/templates/base.css` : `${process.cwd()}/node_modules/@joystick.js/node/dist/email/templates/base.css`;
188
+ const defaultBaseCSSPathForEmail = process.env.NODE_ENV === "test" ? `${process.cwd()}/src/email/templates/base.css` : `${__package}/email/templates/base.css`;
188
189
  let baseCSSPathToFetch = defaultBaseCSSPathForEmail;
189
190
  if (fs.existsSync(customDefaultBaseCSSPathForEmail)) {
190
191
  baseCSSPathToFetch = customDefaultBaseCSSPathForEmail;
@@ -242,7 +243,7 @@ const getBaseHTML = (isEmailRender = false, baseEmailHTMLName = "") => {
242
243
  if (isEmailRender) {
243
244
  const customBaseHTMLPathForEmail = baseEmailHTMLName ? `${process.cwd()}/email/base_${baseEmailHTMLName}.html` : null;
244
245
  const customDefaultBaseHTMLPathForEmail = `${process.cwd()}/email/base.html`;
245
- const defaultBaseHTMLPathForEmail = process.env.NODE_ENV === "test" ? `${process.cwd()}/src/email/templates/base.html` : `${process.cwd()}/node_modules/@joystick.js/node/dist/email/templates/base.html`;
246
+ const defaultBaseHTMLPathForEmail = process.env.NODE_ENV === "test" ? `${process.cwd()}/src/email/templates/base.html` : `${__package}/email/templates/base.html`;
246
247
  baseHTMLPathToFetch = defaultBaseHTMLPathForEmail;
247
248
  if (fs.existsSync(customDefaultBaseHTMLPathForEmail)) {
248
249
  baseHTMLPathToFetch = customDefaultBaseHTMLPathForEmail;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joystick.js/node-canary",
3
- "version": "0.0.0-canary.3",
3
+ "version": "0.0.0-canary.30",
4
4
  "type": "module",
5
5
  "description": "A Node.js framework for building web apps.",
6
6
  "main": "./dist/index.js",
@@ -1,211 +0,0 @@
1
- import fs from "fs";
2
- import dayjs from "dayjs";
3
- import crypto from "crypto";
4
- import ssr from "../../ssr/index.js";
5
- import { isObject } from "../../validation/lib/typeValidators";
6
- import settings from "../../settings";
7
- import generateErrorPage from "../../lib/generateErrorPage.js";
8
- import replaceFileProtocol from "../../lib/replaceFileProtocol.js";
9
- import replaceBackslashesWithForwardSlashes from "../../lib/replaceBackslashesWithForwardSlashes.js";
10
- import getBuildPath from "../../lib/getBuildPath.js";
11
- const generateHash = (input = "") => {
12
- return crypto.createHash("sha256").update(input).digest("hex");
13
- };
14
- const getCacheDiff = async (diffFunction = null) => {
15
- if (diffFunction) {
16
- const diff = await diffFunction();
17
- const diffHash = typeof diff === "string" ? generateHash(diff) : null;
18
- return diffHash;
19
- }
20
- return null;
21
- };
22
- const writeCacheFileToDisk = ({
23
- expiresAfterMinutes = "",
24
- cachePath = "",
25
- cacheFileName = "index",
26
- currentDiff = null,
27
- html = ""
28
- }) => {
29
- const expiresAt = dayjs().add(expiresAfterMinutes, "minutes").unix();
30
- fs.mkdir(`${cachePath}/_cache`, { recursive: true }, () => {
31
- fs.writeFile(`${cachePath}/_cache/${cacheFileName}_${expiresAt}.html`, html, (error) => {
32
- if (error) {
33
- console.warn(error);
34
- }
35
- });
36
- if (currentDiff) {
37
- fs.writeFile(`${cachePath}/_cache/diff_${expiresAt}`, currentDiff, (error) => {
38
- if (error) {
39
- console.warn(error);
40
- }
41
- });
42
- }
43
- });
44
- };
45
- const getCachedHTML = ({ cachePath, cacheFileName, currentDiff }) => {
46
- const files = fs.existsSync(`${cachePath}/_cache`) ? fs.readdirSync(`${cachePath}/_cache`) : [];
47
- const cacheFile = files?.find((file) => file?.includes(cacheFileName));
48
- const cacheFileExpiresAtUnix = cacheFile?.replace(`${cacheFileName}_`, "").replace(".html", "");
49
- const existingDiff = fs.existsSync(`${cachePath}/_cache/diff_${cacheFileExpiresAtUnix}`) ? fs.readFileSync(`${cachePath}/_cache/diff_${cacheFileExpiresAtUnix}`, "utf-8") : null;
50
- const cacheFileDiffHasChanged = existingDiff !== currentDiff;
51
- const cacheFileExpiresAtHasPassed = dayjs().isAfter(dayjs.unix(parseInt(cacheFileExpiresAtUnix)));
52
- const cacheFileHasExpired = cacheFileDiffHasChanged || cacheFileExpiresAtHasPassed;
53
- if (cacheFileDiffHasChanged || cacheFileExpiresAtHasPassed) {
54
- fs.unlink(`${cachePath}/_cache/${cacheFile}`, (error) => {
55
- if (error)
56
- return;
57
- });
58
- fs.unlink(`${cachePath}/_cache/diff_${cacheFileExpiresAtUnix}`, (error) => {
59
- if (error)
60
- return;
61
- });
62
- }
63
- return cacheFile && !cacheFileHasExpired ? fs.readFileSync(`${cachePath}/_cache/${cacheFile}`, "utf-8") : null;
64
- };
65
- const getUrl = (request = {}) => {
66
- const [path = null] = request.url?.split("?");
67
- return {
68
- params: request.params,
69
- query: request.query,
70
- route: request.route.path,
71
- path
72
- };
73
- };
74
- const getFile = async (buildPath = "") => {
75
- const file = await import(buildPath);
76
- return file.default;
77
- };
78
- const getTranslationsFile = async (languageFilePath = "", paths = "") => {
79
- const languageFile = await getFile(`${paths.build}/i18n/${languageFilePath}`);
80
- const isValidLanguageFile = languageFile && isObject(languageFile);
81
- if (isValidLanguageFile) {
82
- const translationsForPage = languageFile[paths.page];
83
- return translationsForPage ? translationsForPage : languageFile;
84
- }
85
- return {};
86
- };
87
- const getTranslations = async (paths = {}, languagePreferences = []) => {
88
- const languageFiles = fs.readdirSync(`${paths.build}/i18n`);
89
- let matchingFile = null;
90
- for (let i = 0; i < languagePreferences.length; i += 1) {
91
- const languageRegex = languagePreferences[i];
92
- const match = languageFiles.find((languageFile) => !!languageFile.match(languageRegex));
93
- if (match) {
94
- matchingFile = match;
95
- break;
96
- }
97
- }
98
- const translationsFile = await getTranslationsFile(matchingFile, paths);
99
- return translationsFile;
100
- };
101
- const getLanguagePreferenceRegexes = (userLanguage = "", browserLanguages = []) => {
102
- let languagePreferences = [];
103
- if (userLanguage) {
104
- languagePreferences.push(userLanguage);
105
- }
106
- const filteredBrowserLanguages = browserLanguages?.filter((language) => {
107
- return !language?.includes("*");
108
- });
109
- languagePreferences.push(...filteredBrowserLanguages);
110
- languagePreferences.push(settings?.config?.i18n?.defaultLanguage);
111
- return languagePreferences?.flatMap((language) => {
112
- const variants = [language];
113
- if (language?.length === 2) {
114
- variants.push(`${language.substring(0, 2)}-`);
115
- }
116
- if (language?.length > 2) {
117
- variants.push(`${language?.split("-")[0]}`);
118
- variants.push(`${language?.split("-")[0]}-`);
119
- }
120
- return variants;
121
- })?.map((languageString) => {
122
- const lastCharacter = languageString[languageString.length - 1];
123
- if (lastCharacter === "-") {
124
- return new RegExp(`^${languageString}[A-Z]+.js`, "g");
125
- }
126
- return new RegExp(`^${languageString}.js`, "g");
127
- });
128
- };
129
- const parseBrowserLanguages = (languages = "") => {
130
- const rawLanguages = languages.split(",");
131
- return rawLanguages?.map((rawLanguage) => rawLanguage.split(";")[0]);
132
- };
133
- var render_default = (req, res, next, appInstance = {}) => {
134
- res.render = async function(path = "", options = {}) {
135
- const urlFormattedForCache = req?.url?.split("/")?.filter((part) => !!part)?.join("_");
136
- const buildPathForEnvironment = getBuildPath();
137
- const buildPath = replaceFileProtocol(replaceBackslashesWithForwardSlashes(`${process.cwd().replace(buildPathForEnvironment, "")}/${buildPathForEnvironment}`));
138
- const pagePath = `${buildPath}${path}`;
139
- const layoutPath = options.layout ? `${buildPath}${options.layout}` : null;
140
- const pagePathParts = `${buildPathForEnvironment}${path}`?.split("/")?.filter((part) => !!part);
141
- const cachePath = pagePathParts?.slice(0, pagePathParts.length - 1)?.join("/");
142
- let currentDiff;
143
- if (!fs.existsSync(pagePath)) {
144
- return res.status(404).send(generateErrorPage({
145
- type: "pageNotFound",
146
- path: `res.render('${path}')`,
147
- frame: null,
148
- stack: `A page component at the path ${path} could not be found.`
149
- }));
150
- }
151
- if (layoutPath && !fs.existsSync(layoutPath)) {
152
- return res.status(404).send(generateErrorPage({
153
- type: "layoutNotFound",
154
- path: `res.render('${path}', { layout: '${options.layout}' })`,
155
- frame: null,
156
- stack: `A layout component at the path ${options.layout} could not be found.`
157
- }));
158
- }
159
- if (options?.cache?.expiresAfterMinutes) {
160
- currentDiff = typeof options?.cache?.diff === "function" ? await getCacheDiff(options?.cache?.diff) : null;
161
- const cachedHTML = await getCachedHTML({
162
- cachePath,
163
- cacheFileName: urlFormattedForCache?.trim() === "" ? "index" : urlFormattedForCache,
164
- currentDiff
165
- });
166
- if (cachedHTML) {
167
- return res.send(cachedHTML);
168
- }
169
- }
170
- const pageFile = await getFile(pagePath);
171
- const Page = pageFile;
172
- const layoutFile = layoutPath ? await getFile(layoutPath) : null;
173
- const Layout = layoutFile;
174
- const browserLanguages = parseBrowserLanguages(req?.headers["accept-language"]);
175
- const languagePreferenceRegexes = getLanguagePreferenceRegexes(req?.context?.user?.language, browserLanguages);
176
- const translations = await getTranslations({ build: buildPath, page: path }, languagePreferenceRegexes);
177
- const url = getUrl(req);
178
- const props = { ...options?.props || {} };
179
- if (layoutPath && fs.existsSync(layoutPath)) {
180
- props.page = Page;
181
- }
182
- const html = await ssr({
183
- componentFunction: Layout || Page,
184
- req,
185
- props,
186
- url,
187
- translations,
188
- attributes: options?.attributes,
189
- email: false,
190
- baseHTMLPath: null,
191
- layoutComponentPath: options?.layout,
192
- pageComponentPath: path?.substring(0, 1) === "/" ? path?.replace("/", "") : path,
193
- head: options?.head,
194
- api: appInstance?.options?.api
195
- });
196
- if (options?.cache?.expiresAfterMinutes) {
197
- writeCacheFileToDisk({
198
- expiresAfterMinutes: parseInt(options?.cache?.expiresAfterMinutes),
199
- cachePath,
200
- cacheFileName: urlFormattedForCache?.trim() === "" ? "index" : urlFormattedForCache,
201
- currentDiff,
202
- html
203
- });
204
- }
205
- return res.status(200).send(html);
206
- };
207
- next();
208
- };
209
- export {
210
- render_default as default
211
- };
@@ -1,16 +0,0 @@
1
- var sanitizeQueryParameters_default = (req, res, next) => {
2
- const queryParameters = Object.entries(req?.query);
3
- const htmlRegex = new RegExp(/<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>/g);
4
- for (let i = 0; i < queryParameters?.length; i += 1) {
5
- const [key, value] = queryParameters[i];
6
- const keyHTMLMatches = key?.match(htmlRegex);
7
- const valueHTMLMatches = value?.match(htmlRegex);
8
- if (keyHTMLMatches?.length > 0 || valueHTMLMatches?.length > 0) {
9
- delete req.query[key];
10
- }
11
- }
12
- next();
13
- };
14
- export {
15
- sanitizeQueryParameters_default as default
16
- };