From eb0992f28d1d83fa8b06a0999538f69f9fbbe552 Mon Sep 17 00:00:00 2001 From: Benjamin Toby Date: Fri, 10 Jan 2025 20:10:28 +0100 Subject: [PATCH] Refactor Code to typescript --- bun.lockb | Bin 0 -> 45396 bytes client/auth/github/getAccessToken.d.ts | 7 - client/auth/github/getAccessToken.js | 36 - client/auth/github/getAccessToken.ts | 24 + client/auth/google/getAccessToken.d.ts | 19 - .../{getAccessToken.js => getAccessToken.ts} | 53 +- client/auth/logout.d.ts | 2 - client/auth/logout.js | 146 -- client/auth/logout.ts | 103 ++ client/fetch/index.d.ts | 5 - client/fetch/index.js | 95 -- client/fetch/index.ts | 113 ++ client/index.d.ts | 38 - client/index.js | 67 - client/index.ts | 62 + client/media/{client.js => client.ts} | 0 client/media/imageInputFileToBase64.d.ts | 8 - ...eToBase64.js => imageInputFileToBase64.ts} | 58 +- client/media/imageInputToBase64.d.ts | 14 - client/media/imageInputToBase64.js | 115 -- client/media/imageInputToBase64.ts | 104 ++ client/media/inputFileToBase64.d.ts | 19 - client/media/inputFileToBase64.js | 96 -- client/media/inputFileToBase64.ts | 68 + client/utils/parseClientCookies.d.ts | 2 - client/utils/parseClientCookies.js | 65 - client/utils/parseClientCookies.ts | 34 + console-colors.js => console-colors.ts | 2 +- engine/{dsql.js => dsql.ts} | 25 +- engine/{dump.js => dump.ts} | 9 +- index.d.ts | 75 - index.js | 104 -- index.ts | 104 ++ package-shared/functions/api/query/get.d.ts | 9 - .../functions/api/query/{get.js => get.ts} | 39 +- package-shared/functions/api/query/post.d.ts | 9 - .../functions/api/query/{post.js => post.ts} | 43 +- .../api/social-login/facebookLogin.js | 128 -- .../api/social-login/facebookLogin.ts | 80 ++ .../api/social-login/githubLogin.d.ts | 135 -- .../functions/api/social-login/githubLogin.js | 160 --- .../functions/api/social-login/githubLogin.ts | 102 ++ .../{googleLogin.js => googleLogin.ts} | 69 +- .../api/social-login/handleSocialDb.d.ts | 2 - .../{handleSocialDb.js => handleSocialDb.ts} | 37 +- .../api/social-login/loginSocialUser.d.ts | 37 - ...{loginSocialUser.js => loginSocialUser.ts} | 49 +- .../functions/api/users/api-create-user.d.ts | 2 - ...{api-create-user.js => api-create-user.ts} | 25 +- .../functions/api/users/api-delete-user.d.ts | 10 - ...{api-delete-user.js => api-delete-user.ts} | 24 +- .../functions/api/users/api-get-user.d.ts | 2 - .../{api-get-user.js => api-get-user.ts} | 18 +- .../functions/api/users/api-login.d.ts | 2 - .../api/users/{api-login.js => api-login.ts} | 32 +- .../functions/api/users/api-reauth-user.d.ts | 9 - ...{api-reauth-user.js => api-reauth-user.ts} | 40 +- .../api/users/api-send-email-code.d.ts | 18 - ...d-email-code.js => api-send-email-code.ts} | 97 +- .../functions/api/users/api-update-user.d.ts | 14 - ...{api-update-user.js => api-update-user.ts} | 35 +- .../api/users/social/api-github-login.d.ts | 12 - ...pi-github-login.js => api-github-login.ts} | 35 +- .../api/users/social/api-google-login.d.ts | 2 - ...pi-google-login.js => api-google-login.ts} | 74 +- .../backend/addAdminUserOnLogin.d.ts | 11 - ...nUserOnLogin.js => addAdminUserOnLogin.ts} | 55 +- .../functions/backend/addMariadbUser.d.ts | 5 - .../{addMariadbUser.js => addMariadbUser.ts} | 34 +- .../functions/backend/addUsersTableToDb.d.ts | 9 - ...UsersTableToDb.js => addUsersTableToDb.ts} | 48 +- .../backend/{api-cred.js => api-cred.ts} | 27 +- .../backend/auth/write-auth-files.d.ts | 26 - ...rite-auth-files.js => write-auth-files.ts} | 38 +- .../cookies/get-auth-cookie-names.d.ts | 9 - ...okie-names.js => get-auth-cookie-names.ts} | 21 +- .../functions/backend/db/addDbEntry.d.ts | 39 - .../db/{addDbEntry.js => addDbEntry.ts} | 49 +- .../functions/backend/db/deleteDbEntry.d.ts | 34 - .../functions/backend/db/deleteDbEntry.js | 104 -- .../functions/backend/db/deleteDbEntry.ts | 68 + .../backend/db/pathTraversalCheck.js | 14 - .../backend/db/pathTraversalCheck.ts | 7 + .../functions/backend/db/runQuery.d.ts | 24 - .../backend/db/{runQuery.js => runQuery.ts} | 71 +- .../db/{sanitizeSql.js => sanitizeSql.ts} | 23 +- .../functions/backend/db/updateDbEntry.d.ts | 37 - .../db/{updateDbEntry.js => updateDbEntry.ts} | 72 +- .../backend/{dbHandler.js => dbHandler.ts} | 39 +- .../backend/defaultFieldsRegexp.d.ts | 7 - ...FieldsRegexp.js => defaultFieldsRegexp.ts} | 4 +- .../backend/fullAccessDbHandler.d.ts | 8 - ...essDbHandler.js => fullAccessDbHandler.ts} | 33 +- .../backend/grabNewUsersTableSchema.d.ts | 6 - ...leSchema.js => grabNewUsersTableSchema.ts} | 26 +- .../backend/grabSchemaFieldsFromData.d.ts | 11 - ...romData.js => grabSchemaFieldsFromData.ts} | 61 +- .../functions/backend/grabUserSchemaData.d.ts | 4 - .../functions/backend/grabUserSchemaData.js | 46 - .../functions/backend/grabUserSchemaData.ts | 31 + .../functions/backend/handleNodemailer.d.ts | 8 - ...andleNodemailer.js => handleNodemailer.ts} | 64 +- .../backend/html/sanitizeHtmlOptions.d.ts | 6 - .../backend/html/sanitizeHtmlOptions.js | 12 - .../backend/html/sanitizeHtmlOptions.ts | 35 + .../functions/backend/httpRequest.d.ts | 6 - .../{httpRequest.js => httpRequest.ts} | 31 +- .../functions/backend/httpsRequest.d.ts | 11 - .../{httpsRequest.js => httpsRequest.ts} | 62 +- ...aseDbHandler.js => noDatabaseDbHandler.ts} | 21 +- .../functions/backend/parseDbResults.d.ts | 5 - .../{parseDbResults.js => parseDbResults.ts} | 23 +- .../functions/backend/serverError.d.ts | 14 - .../{serverError.js => serverError.ts} | 35 +- .../functions/backend/setUserSchemaData.d.ts | 5 - .../functions/backend/setUserSchemaData.js | 49 - .../functions/backend/setUserSchemaData.ts | 45 + .../{suSocketAuth.js => suSocketAuth.ts} | 24 +- .../backend/updateUsersTableSchema.d.ts | 9 - ...bleSchema.js => updateUsersTableSchema.ts} | 33 +- .../backend/varDatabaseDbHandler.d.ts | 8 - ...seDbHandler.js => varDatabaseDbHandler.ts} | 54 +- .../backend/varReadOnlyDatabaseDbHandler.d.ts | 8 - ...ler.js => varReadOnlyDatabaseDbHandler.ts} | 34 +- package-shared/functions/dsql/decrypt.d.ts | 13 - .../functions/dsql/{decrypt.js => decrypt.ts} | 30 +- package-shared/functions/dsql/encrypt.d.ts | 14 - .../functions/dsql/{encrypt.js => encrypt.ts} | 27 +- .../functions/dsql/hashPassword.d.ts | 5 - .../dsql/{hashPassword.js => hashPassword.ts} | 18 +- .../dsql/sql/sql-delete-generator.d.ts | 24 - .../dsql/sql/sql-delete-generator.js | 41 - .../dsql/sql/sql-delete-generator.ts | 36 + .../functions/dsql/sql/sql-generator.d.ts | 8 - .../{sql-generator.js => sql-generator.ts} | 58 +- .../dsql/sql/sql-insert-generator.d.ts | 24 - ...t-generator.js => sql-insert-generator.ts} | 33 +- .../shell/{checkDb.js => checkDb.ts} | 19 +- package-shared/shell/createDbFromSchema.d.ts | 14 - ...eDbFromSchema.js => createDbFromSchema.ts} | 60 +- package-shared/shell/deploy.js | 7 - package-shared/shell/deploy.ts | 5 + .../{encodingUpdate.js => encodingUpdate.ts} | 10 +- .../{jsonToBase64.js => jsonToBase64.ts} | 6 +- package-shared/shell/grantFullPriviledges.js | 79 -- package-shared/shell/grantFullPriviledges.ts | 52 + .../shell/{lessWatch.js => lessWatch.ts} | 22 +- .../{handleGrants.js => handleGrants.ts} | 45 +- ...sAndGrants.js => refreshUsersAndGrants.ts} | 66 +- .../shell/mariadb-users/resetSQLPasswords.js | 105 -- .../shell/mariadb-users/resetSQLPasswords.ts | 72 + .../users/{create-user.js => create-user.ts} | 22 +- .../users/{update-user.js => update-user.ts} | 17 +- package-shared/shell/readImage.js | 24 - package-shared/shell/readImage.ts | 6 + ...JsonFromDb.js => recoverMainJsonFromDb.ts} | 33 +- ...LCredentials.js => resetSQLCredentials.ts} | 41 +- .../shell/resetSQLCredentialsPasswords.js | 90 -- .../shell/resetSQLCredentialsPasswords.ts | 60 + .../shell/scripts/convert-js-to-ts.ts | 46 + ...SQLCredentials.js => setSQLCredentials.ts} | 41 +- package-shared/shell/tailwindWatch.js | 29 - package-shared/shell/tailwindWatch.ts | 36 + ...rnal-server.js => test-external-server.ts} | 19 +- package-shared/shell/test.js | 221 --- .../{testSQLEscape.js => testSQLEscape.ts} | 35 +- ...lesOnDb.js => updateChildrenTablesOnDb.ts} | 30 +- ...eTimestamps.js => updateDateTimestamps.ts} | 18 +- ...rds.js => updateDbSlugsForTableRecords.ts} | 14 +- .../{updateSSLUsers.js => updateSSLUsers.ts} | 8 +- ...melSpace.js => camelJoinedtoCamelSpace.ts} | 10 +- package-shared/shell/utils/createTable.d.ts | 10 - .../utils/{createTable.js => createTable.ts} | 48 +- package-shared/shell/utils/dbHandler.d.ts | 6 - .../utils/{dbHandler.js => dbHandler.ts} | 43 +- .../utils/generateColumnDescription.d.ts | 8 - .../shell/utils/generateColumnDescription.js | 108 -- .../shell/utils/generateColumnDescription.ts | 83 ++ .../shell/utils/noDatabaseDbHandler.d.ts | 2 - ...aseDbHandler.js => noDatabaseDbHandler.ts} | 17 +- ...lugToCamelTitle.js => slugToCamelTitle.ts} | 9 +- .../shell/utils/supplementTable.d.ts | 4 - ...{supplementTable.js => supplementTable.ts} | 22 +- package-shared/shell/utils/updateTable.d.ts | 15 - .../utils/{updateTable.js => updateTable.ts} | 136 +- .../shell/utils/varDatabaseDbHandler.d.ts | 7 - ...seDbHandler.js => varDatabaseDbHandler.ts} | 33 +- package-shared/types/index.d.ts | 1258 ----------------- package-shared/types/index.js | 1166 --------------- package-shared/types/index.ts | 41 +- .../utils/backend/global-db/DB_HANDLER.d.ts | 9 - .../{DB_HANDLER.js => DB_HANDLER.ts} | 21 +- .../global-db/DSQL_USER_DB_HANDLER.d.ts | 18 - ..._DB_HANDLER.js => DSQL_USER_DB_HANDLER.ts} | 34 +- .../backend/global-db/LOCAL_DB_HANDLER.d.ts | 10 - ...OCAL_DB_HANDLER.js => LOCAL_DB_HANDLER.ts} | 23 +- .../backend/global-db/NO_DB_HANDLER.d.ts | 12 - .../{ROOT_DB_HANDLER.js => NO_DB_HANDLER.ts} | 21 +- .../{NO_DB_HANDLER.js => ROOT_DB_HANDLER.ts} | 19 +- package-shared/utils/backend/grabDbSSL.d.ts | 4 - .../backend/{grabDbSSL.js => grabDbSSL.ts} | 15 +- .../utils/backend/parseCookies.d.ts | 10 - .../{parseCookies.js => parseCookies.ts} | 30 +- .../utils/camelJoinedtoCamelSpace.d.ts | 12 - ...melSpace.js => camelJoinedtoCamelSpace.ts} | 21 +- ...erialize-query.js => deserialize-query.ts} | 17 +- package-shared/utils/ejson.d.ts | 19 - package-shared/utils/ejson.js | 38 - package-shared/utils/ejson.ts | 38 + package-shared/utils/empty-dir.ts | 23 + .../{endConnection.js => endConnection.ts} | 8 +- ...iption.js => generateColumnDescription.ts} | 17 +- package-shared/utils/grab-host-names.d.ts | 24 - ...{grab-host-names.js => grab-host-names.ts} | 22 +- package-shared/utils/numberfy.d.ts | 2 - .../utils/{numberfy.js => numberfy.ts} | 11 +- package-shared/utils/serialize-cookies.d.ts | 10 - ...ialize-cookies.js => serialize-cookies.ts} | 19 +- package-shared/utils/serialize-query.d.ts | 2 - ...{serialize-query.js => serialize-query.ts} | 15 +- ...lugToCamelTitle.js => slugToCamelTitle.ts} | 13 +- package-shared/utils/slugify.d.ts | 2 - .../utils/{slugify.js => slugify.ts} | 9 +- package-shared/utils/trim-sql.d.ts | 24 - package-shared/utils/trim-sql.js | 26 - package-shared/utils/trim-sql.ts | 10 + package.json | 16 +- users/add-user.d.ts | 28 - users/{add-user.js => add-user.ts} | 51 +- users/delete-user.d.ts | 21 - users/{delete-user.js => delete-user.ts} | 56 +- users/get-token.d.ts | 35 - users/get-token.js | 116 -- users/get-token.ts | 96 ++ users/get-user.d.ts | 31 - users/{get-user.js => get-user.ts} | 70 +- users/login-user.d.ts | 55 - users/{login-user.js => login-user.ts} | 118 +- users/logout-user.d.ts | 31 - users/{logout-user.js => logout-user.ts} | 60 +- users/reauth-user.d.ts | 42 - users/{reauth-user.js => reauth-user.ts} | 95 +- users/send-email-code.d.ts | 41 - users/send-email-code.js | 172 --- users/send-email-code.ts | 165 +++ users/social/github-auth.d.ts | 80 -- .../social/{github-auth.js => github-auth.ts} | 111 +- users/social/google-auth.d.ts | 36 - .../social/{google-auth.js => google-auth.ts} | 60 +- users/update-user.d.ts | 25 - users/{update-user.js => update-user.ts} | 51 +- users/user-auth.d.ts | 42 - users/{user-auth.js => user-auth.ts} | 55 +- users/validate-temp-email-code.d.ts | 21 - users/validate-temp-email-code.js | 53 - users/validate-temp-email-code.ts | 50 + users/validate-token.d.ts | 22 - .../{validate-token.js => validate-token.ts} | 30 +- utils/delete-file.d.ts | 46 - utils/{delete-file.js => delete-file.ts} | 45 +- utils/get-schema.d.ts | 26 - utils/{get-schema.js => get-schema.ts} | 60 +- utils/get.d.ts | 26 - utils/{get.js => get.ts} | 85 +- utils/post.d.ts | 25 - utils/{post.js => post.ts} | 53 +- utils/upload-file.d.ts | 56 - utils/{upload-file.js => upload-file.ts} | 69 +- utils/upload-image.d.ts | 60 - utils/{upload-image.js => upload-image.ts} | 69 +- 270 files changed, 3535 insertions(+), 9062 deletions(-) create mode 100755 bun.lockb delete mode 100644 client/auth/github/getAccessToken.d.ts delete mode 100644 client/auth/github/getAccessToken.js create mode 100644 client/auth/github/getAccessToken.ts delete mode 100644 client/auth/google/getAccessToken.d.ts rename client/auth/google/{getAccessToken.js => getAccessToken.ts} (56%) delete mode 100644 client/auth/logout.d.ts delete mode 100644 client/auth/logout.js create mode 100644 client/auth/logout.ts delete mode 100644 client/fetch/index.d.ts delete mode 100644 client/fetch/index.js create mode 100644 client/fetch/index.ts delete mode 100644 client/index.d.ts delete mode 100644 client/index.js create mode 100644 client/index.ts rename client/media/{client.js => client.ts} (100%) delete mode 100644 client/media/imageInputFileToBase64.d.ts rename client/media/{imageInputFileToBase64.js => imageInputFileToBase64.ts} (63%) delete mode 100644 client/media/imageInputToBase64.d.ts delete mode 100644 client/media/imageInputToBase64.js create mode 100644 client/media/imageInputToBase64.ts delete mode 100644 client/media/inputFileToBase64.d.ts delete mode 100644 client/media/inputFileToBase64.js create mode 100644 client/media/inputFileToBase64.ts delete mode 100644 client/utils/parseClientCookies.d.ts delete mode 100644 client/utils/parseClientCookies.js create mode 100644 client/utils/parseClientCookies.ts rename console-colors.js => console-colors.ts (91%) rename engine/{dsql.js => dsql.ts} (84%) rename engine/{dump.js => dump.ts} (87%) delete mode 100644 index.d.ts delete mode 100644 index.js create mode 100644 index.ts delete mode 100644 package-shared/functions/api/query/get.d.ts rename package-shared/functions/api/query/{get.js => get.ts} (76%) delete mode 100644 package-shared/functions/api/query/post.d.ts rename package-shared/functions/api/query/{post.js => post.ts} (75%) delete mode 100755 package-shared/functions/api/social-login/facebookLogin.js create mode 100755 package-shared/functions/api/social-login/facebookLogin.ts delete mode 100644 package-shared/functions/api/social-login/githubLogin.d.ts delete mode 100755 package-shared/functions/api/social-login/githubLogin.js create mode 100755 package-shared/functions/api/social-login/githubLogin.ts rename package-shared/functions/api/social-login/{googleLogin.js => googleLogin.ts} (64%) delete mode 100644 package-shared/functions/api/social-login/handleSocialDb.d.ts rename package-shared/functions/api/social-login/{handleSocialDb.js => handleSocialDb.ts} (88%) delete mode 100644 package-shared/functions/api/social-login/loginSocialUser.d.ts rename package-shared/functions/api/social-login/{loginSocialUser.js => loginSocialUser.ts} (64%) delete mode 100644 package-shared/functions/api/users/api-create-user.d.ts rename package-shared/functions/api/users/{api-create-user.js => api-create-user.ts} (87%) delete mode 100644 package-shared/functions/api/users/api-delete-user.d.ts rename package-shared/functions/api/users/{api-delete-user.js => api-delete-user.ts} (66%) delete mode 100644 package-shared/functions/api/users/api-get-user.d.ts rename package-shared/functions/api/users/{api-get-user.js => api-get-user.ts} (66%) delete mode 100644 package-shared/functions/api/users/api-login.d.ts rename package-shared/functions/api/users/{api-login.js => api-login.ts} (86%) delete mode 100644 package-shared/functions/api/users/api-reauth-user.d.ts rename package-shared/functions/api/users/{api-reauth-user.js => api-reauth-user.ts} (64%) delete mode 100644 package-shared/functions/api/users/api-send-email-code.d.ts rename package-shared/functions/api/users/{api-send-email-code.js => api-send-email-code.ts} (64%) delete mode 100644 package-shared/functions/api/users/api-update-user.d.ts rename package-shared/functions/api/users/{api-update-user.js => api-update-user.ts} (74%) delete mode 100644 package-shared/functions/api/users/social/api-github-login.d.ts rename package-shared/functions/api/users/social/{api-github-login.js => api-github-login.ts} (75%) delete mode 100644 package-shared/functions/api/users/social/api-google-login.d.ts rename package-shared/functions/api/users/social/{api-google-login.js => api-google-login.ts} (56%) delete mode 100644 package-shared/functions/backend/addAdminUserOnLogin.d.ts rename package-shared/functions/backend/{addAdminUserOnLogin.js => addAdminUserOnLogin.ts} (75%) delete mode 100644 package-shared/functions/backend/addMariadbUser.d.ts rename package-shared/functions/backend/{addMariadbUser.js => addMariadbUser.ts} (69%) delete mode 100644 package-shared/functions/backend/addUsersTableToDb.d.ts rename package-shared/functions/backend/{addUsersTableToDb.js => addUsersTableToDb.ts} (64%) rename package-shared/functions/backend/{api-cred.js => api-cred.ts} (73%) delete mode 100644 package-shared/functions/backend/auth/write-auth-files.d.ts rename package-shared/functions/backend/auth/{write-auth-files.js => write-auth-files.ts} (67%) delete mode 100644 package-shared/functions/backend/cookies/get-auth-cookie-names.d.ts rename package-shared/functions/backend/cookies/{get-auth-cookie-names.js => get-auth-cookie-names.ts} (82%) delete mode 100644 package-shared/functions/backend/db/addDbEntry.d.ts rename package-shared/functions/backend/db/{addDbEntry.js => addDbEntry.ts} (85%) delete mode 100644 package-shared/functions/backend/db/deleteDbEntry.d.ts delete mode 100644 package-shared/functions/backend/db/deleteDbEntry.js create mode 100644 package-shared/functions/backend/db/deleteDbEntry.ts delete mode 100644 package-shared/functions/backend/db/pathTraversalCheck.js create mode 100644 package-shared/functions/backend/db/pathTraversalCheck.ts delete mode 100644 package-shared/functions/backend/db/runQuery.d.ts rename package-shared/functions/backend/db/{runQuery.js => runQuery.ts} (67%) rename package-shared/functions/backend/db/{sanitizeSql.js => sanitizeSql.ts} (85%) delete mode 100644 package-shared/functions/backend/db/updateDbEntry.d.ts rename package-shared/functions/backend/db/{updateDbEntry.js => updateDbEntry.ts} (67%) rename package-shared/functions/backend/{dbHandler.js => dbHandler.ts} (62%) delete mode 100644 package-shared/functions/backend/defaultFieldsRegexp.d.ts rename package-shared/functions/backend/{defaultFieldsRegexp.js => defaultFieldsRegexp.ts} (81%) delete mode 100644 package-shared/functions/backend/fullAccessDbHandler.d.ts rename package-shared/functions/backend/{fullAccessDbHandler.js => fullAccessDbHandler.ts} (66%) delete mode 100644 package-shared/functions/backend/grabNewUsersTableSchema.d.ts rename package-shared/functions/backend/{grabNewUsersTableSchema.js => grabNewUsersTableSchema.ts} (55%) delete mode 100644 package-shared/functions/backend/grabSchemaFieldsFromData.d.ts rename package-shared/functions/backend/{grabSchemaFieldsFromData.js => grabSchemaFieldsFromData.ts} (51%) delete mode 100644 package-shared/functions/backend/grabUserSchemaData.d.ts delete mode 100755 package-shared/functions/backend/grabUserSchemaData.js create mode 100755 package-shared/functions/backend/grabUserSchemaData.ts delete mode 100644 package-shared/functions/backend/handleNodemailer.d.ts rename package-shared/functions/backend/{handleNodemailer.js => handleNodemailer.ts} (53%) delete mode 100644 package-shared/functions/backend/html/sanitizeHtmlOptions.d.ts delete mode 100644 package-shared/functions/backend/html/sanitizeHtmlOptions.js create mode 100644 package-shared/functions/backend/html/sanitizeHtmlOptions.ts delete mode 100644 package-shared/functions/backend/httpRequest.d.ts rename package-shared/functions/backend/{httpRequest.js => httpRequest.ts} (80%) delete mode 100644 package-shared/functions/backend/httpsRequest.d.ts rename package-shared/functions/backend/{httpsRequest.js => httpsRequest.ts} (61%) rename package-shared/functions/backend/{noDatabaseDbHandler.js => noDatabaseDbHandler.ts} (65%) delete mode 100644 package-shared/functions/backend/parseDbResults.d.ts rename package-shared/functions/backend/{parseDbResults.js => parseDbResults.ts} (75%) delete mode 100644 package-shared/functions/backend/serverError.d.ts rename package-shared/functions/backend/{serverError.js => serverError.ts} (79%) delete mode 100644 package-shared/functions/backend/setUserSchemaData.d.ts delete mode 100755 package-shared/functions/backend/setUserSchemaData.js create mode 100755 package-shared/functions/backend/setUserSchemaData.ts rename package-shared/functions/backend/{suSocketAuth.js => suSocketAuth.ts} (64%) delete mode 100644 package-shared/functions/backend/updateUsersTableSchema.d.ts rename package-shared/functions/backend/{updateUsersTableSchema.js => updateUsersTableSchema.ts} (68%) delete mode 100644 package-shared/functions/backend/varDatabaseDbHandler.d.ts rename package-shared/functions/backend/{varDatabaseDbHandler.js => varDatabaseDbHandler.ts} (58%) delete mode 100644 package-shared/functions/backend/varReadOnlyDatabaseDbHandler.d.ts rename package-shared/functions/backend/{varReadOnlyDatabaseDbHandler.js => varReadOnlyDatabaseDbHandler.ts} (64%) delete mode 100644 package-shared/functions/dsql/decrypt.d.ts rename package-shared/functions/dsql/{decrypt.js => decrypt.ts} (71%) delete mode 100644 package-shared/functions/dsql/encrypt.d.ts rename package-shared/functions/dsql/{encrypt.js => encrypt.ts} (74%) delete mode 100644 package-shared/functions/dsql/hashPassword.d.ts rename package-shared/functions/dsql/{hashPassword.js => hashPassword.ts} (55%) delete mode 100644 package-shared/functions/dsql/sql/sql-delete-generator.d.ts delete mode 100644 package-shared/functions/dsql/sql/sql-delete-generator.js create mode 100644 package-shared/functions/dsql/sql/sql-delete-generator.ts delete mode 100644 package-shared/functions/dsql/sql/sql-generator.d.ts rename package-shared/functions/dsql/sql/{sql-generator.js => sql-generator.ts} (90%) delete mode 100644 package-shared/functions/dsql/sql/sql-insert-generator.d.ts rename package-shared/functions/dsql/sql/{sql-insert-generator.js => sql-insert-generator.ts} (74%) rename package-shared/shell/{checkDb.js => checkDb.ts} (54%) delete mode 100644 package-shared/shell/createDbFromSchema.d.ts rename package-shared/shell/{createDbFromSchema.js => createDbFromSchema.ts} (86%) delete mode 100755 package-shared/shell/deploy.js create mode 100755 package-shared/shell/deploy.ts rename package-shared/shell/{encodingUpdate.js => encodingUpdate.ts} (85%) rename package-shared/shell/functions/{jsonToBase64.js => jsonToBase64.ts} (73%) delete mode 100755 package-shared/shell/grantFullPriviledges.js create mode 100755 package-shared/shell/grantFullPriviledges.ts rename package-shared/shell/{lessWatch.js => lessWatch.ts} (68%) rename package-shared/shell/mariadb-users/{handleGrants.js => handleGrants.ts} (73%) rename package-shared/shell/mariadb-users/{refreshUsersAndGrants.js => refreshUsersAndGrants.ts} (79%) delete mode 100755 package-shared/shell/mariadb-users/resetSQLPasswords.js create mode 100755 package-shared/shell/mariadb-users/resetSQLPasswords.ts rename package-shared/shell/mariadb-users/users/{create-user.js => create-user.ts} (86%) rename package-shared/shell/mariadb-users/users/{update-user.js => update-user.ts} (80%) delete mode 100755 package-shared/shell/readImage.js create mode 100755 package-shared/shell/readImage.ts rename package-shared/shell/{recoverMainJsonFromDb.js => recoverMainJsonFromDb.ts} (67%) rename package-shared/shell/{resetSQLCredentials.js => resetSQLCredentials.ts} (56%) delete mode 100755 package-shared/shell/resetSQLCredentialsPasswords.js create mode 100755 package-shared/shell/resetSQLCredentialsPasswords.ts create mode 100644 package-shared/shell/scripts/convert-js-to-ts.ts rename package-shared/shell/{setSQLCredentials.js => setSQLCredentials.ts} (59%) delete mode 100755 package-shared/shell/tailwindWatch.js create mode 100755 package-shared/shell/tailwindWatch.ts rename package-shared/shell/{test-external-server.js => test-external-server.ts} (54%) delete mode 100755 package-shared/shell/test.js rename package-shared/shell/{testSQLEscape.js => testSQLEscape.ts} (65%) rename package-shared/shell/{updateChildrenTablesOnDb.js => updateChildrenTablesOnDb.ts} (55%) rename package-shared/shell/{updateDateTimestamps.js => updateDateTimestamps.ts} (63%) rename package-shared/shell/{updateDbSlugsForTableRecords.js => updateDbSlugsForTableRecords.ts} (77%) rename package-shared/shell/{updateSSLUsers.js => updateSSLUsers.ts} (88%) rename package-shared/shell/utils/{camelJoinedtoCamelSpace.js => camelJoinedtoCamelSpace.ts} (85%) delete mode 100644 package-shared/shell/utils/createTable.d.ts rename package-shared/shell/utils/{createTable.js => createTable.ts} (79%) delete mode 100644 package-shared/shell/utils/dbHandler.d.ts rename package-shared/shell/utils/{dbHandler.js => dbHandler.ts} (63%) delete mode 100644 package-shared/shell/utils/generateColumnDescription.d.ts delete mode 100755 package-shared/shell/utils/generateColumnDescription.js create mode 100755 package-shared/shell/utils/generateColumnDescription.ts delete mode 100644 package-shared/shell/utils/noDatabaseDbHandler.d.ts rename package-shared/shell/utils/{noDatabaseDbHandler.js => noDatabaseDbHandler.ts} (65%) rename package-shared/shell/utils/{slugToCamelTitle.js => slugToCamelTitle.ts} (77%) delete mode 100644 package-shared/shell/utils/supplementTable.d.ts rename package-shared/shell/utils/{supplementTable.js => supplementTable.ts} (63%) delete mode 100644 package-shared/shell/utils/updateTable.d.ts rename package-shared/shell/utils/{updateTable.js => updateTable.ts} (78%) delete mode 100644 package-shared/shell/utils/varDatabaseDbHandler.d.ts rename package-shared/shell/utils/{varDatabaseDbHandler.js => varDatabaseDbHandler.ts} (56%) delete mode 100644 package-shared/types/index.d.ts delete mode 100644 package-shared/types/index.js delete mode 100644 package-shared/utils/backend/global-db/DB_HANDLER.d.ts rename package-shared/utils/backend/global-db/{DB_HANDLER.js => DB_HANDLER.ts} (62%) delete mode 100644 package-shared/utils/backend/global-db/DSQL_USER_DB_HANDLER.d.ts rename package-shared/utils/backend/global-db/{DSQL_USER_DB_HANDLER.js => DSQL_USER_DB_HANDLER.ts} (84%) delete mode 100644 package-shared/utils/backend/global-db/LOCAL_DB_HANDLER.d.ts rename package-shared/utils/backend/global-db/{LOCAL_DB_HANDLER.js => LOCAL_DB_HANDLER.ts} (64%) delete mode 100644 package-shared/utils/backend/global-db/NO_DB_HANDLER.d.ts rename package-shared/utils/backend/global-db/{ROOT_DB_HANDLER.js => NO_DB_HANDLER.ts} (65%) rename package-shared/utils/backend/global-db/{NO_DB_HANDLER.js => ROOT_DB_HANDLER.ts} (66%) delete mode 100644 package-shared/utils/backend/grabDbSSL.d.ts rename package-shared/utils/backend/{grabDbSSL.js => grabDbSSL.ts} (58%) delete mode 100644 package-shared/utils/backend/parseCookies.d.ts rename package-shared/utils/backend/{parseCookies.js => parseCookies.ts} (63%) delete mode 100644 package-shared/utils/camelJoinedtoCamelSpace.d.ts rename package-shared/utils/{camelJoinedtoCamelSpace.js => camelJoinedtoCamelSpace.ts} (69%) rename package-shared/utils/{deserialize-query.js => deserialize-query.ts} (66%) delete mode 100644 package-shared/utils/ejson.d.ts delete mode 100644 package-shared/utils/ejson.js create mode 100644 package-shared/utils/ejson.ts create mode 100644 package-shared/utils/empty-dir.ts rename package-shared/utils/{endConnection.js => endConnection.ts} (51%) rename package-shared/utils/{generateColumnDescription.js => generateColumnDescription.ts} (81%) delete mode 100644 package-shared/utils/grab-host-names.d.ts rename package-shared/utils/{grab-host-names.js => grab-host-names.ts} (67%) delete mode 100644 package-shared/utils/numberfy.d.ts rename package-shared/utils/{numberfy.js => numberfy.ts} (69%) delete mode 100644 package-shared/utils/serialize-cookies.d.ts rename package-shared/utils/{serialize-cookies.js => serialize-cookies.ts} (80%) delete mode 100644 package-shared/utils/serialize-query.d.ts rename package-shared/utils/{serialize-query.js => serialize-query.ts} (80%) rename package-shared/utils/{slugToCamelTitle.js => slugToCamelTitle.ts} (59%) delete mode 100644 package-shared/utils/slugify.d.ts rename package-shared/utils/{slugify.js => slugify.ts} (76%) delete mode 100644 package-shared/utils/trim-sql.d.ts delete mode 100644 package-shared/utils/trim-sql.js create mode 100644 package-shared/utils/trim-sql.ts delete mode 100644 users/add-user.d.ts rename users/{add-user.js => add-user.ts} (71%) delete mode 100644 users/delete-user.d.ts rename users/{delete-user.js => delete-user.ts} (63%) delete mode 100644 users/get-token.d.ts delete mode 100644 users/get-token.js create mode 100644 users/get-token.ts delete mode 100644 users/get-user.d.ts rename users/{get-user.js => get-user.ts} (60%) delete mode 100644 users/login-user.d.ts rename users/{login-user.js => login-user.ts} (67%) delete mode 100644 users/logout-user.d.ts rename users/{logout-user.js => logout-user.ts} (56%) delete mode 100644 users/reauth-user.d.ts rename users/{reauth-user.js => reauth-user.ts} (60%) delete mode 100644 users/send-email-code.d.ts delete mode 100644 users/send-email-code.js create mode 100644 users/send-email-code.ts delete mode 100644 users/social/github-auth.d.ts rename users/social/{github-auth.js => github-auth.ts} (62%) delete mode 100644 users/social/google-auth.d.ts rename users/social/{google-auth.js => google-auth.ts} (73%) delete mode 100644 users/update-user.d.ts rename users/{update-user.js => update-user.ts} (67%) delete mode 100644 users/user-auth.d.ts rename users/{user-auth.js => user-auth.ts} (72%) delete mode 100644 users/validate-temp-email-code.d.ts delete mode 100644 users/validate-temp-email-code.js create mode 100644 users/validate-temp-email-code.ts delete mode 100644 users/validate-token.d.ts rename users/{validate-token.js => validate-token.ts} (62%) delete mode 100644 utils/delete-file.d.ts rename utils/{delete-file.js => delete-file.ts} (67%) delete mode 100644 utils/get-schema.d.ts rename utils/{get-schema.js => get-schema.ts} (56%) delete mode 100644 utils/get.d.ts rename utils/{get.js => get.ts} (58%) delete mode 100644 utils/post.d.ts rename utils/{post.js => post.ts} (72%) delete mode 100644 utils/upload-file.d.ts rename utils/{upload-file.js => upload-file.ts} (54%) delete mode 100644 utils/upload-image.d.ts rename utils/{upload-image.js => upload-image.ts} (55%) diff --git a/bun.lockb b/bun.lockb new file mode 100755 index 0000000000000000000000000000000000000000..eb4eb6794642a880147deef96dc4aef956bc2f64 GIT binary patch literal 45396 zcmeHwcRbZ!{Qsq^L|GxJWTkoSk%mzjsZ%7kE%=h~`YARYGydW(%4p)oK z4OMmv;fjH0`1-SaJUG5=hKGNUA2XN{sx2l=qtT`nIQP8pz+QI2nP(qMZ$C@di*kKg z*k#+UiS#qy(p;BjpFaSZz=iSyn&?kqj3BNQB6uJI1sW};37(`N^oOt;go_{)hp+A2% z4EFb7b7?eBW;n+mvWA49)HK>55E}7} zppqCyK_~-ZaFD(s()R!z%UutlG=%PKw-8TA_v05wO9J7Mj~yP&<^rM!lm}U3GC&Df z|Cc~S{yg9z`28UtH2*$`W4)h4qoRJbfQaEHNXK?w0U_dm&VwTY*tGXRNB&4iM_eux z2#++L7c(dTLO*%F{+u9`1G*K2n4j5`-yXp{Uyd8((}Hxgr>&4l8A3UTqkiT=Topng zh+{jjAl?VU*APNdj0J>B5Z)HV2MFS4AjJIQ5Mus!5a|oyH3<7bcpO3?#cYQVM2X?C z{X*G6G}=0dV?9{@zWxxUDFHavHyA?HO96yP_l6MlD-9v)XCm;S{CW_g+`R>HI)sS- z3K|{LOCan8VLpUFiphWw>!Af9;?0E0B0g!?YLJfQyM^%F{3B?zg=+k`m>~T-7zNTl zK#1*$x4OEt?>7h8?(k^7!vD#eKez%s7TcI^$nMUp?A=a%DrJH<)&y0BK^`moX+gC8b@j2mP#+~e`x z)Z7JQN^LDOUMD@)-{C$xYTE?=smtfn^dBo073?^4{&w!2By0A!J;VDN&-*Y+)^38~ z!hKsr!=7wjyXvv=NdpV! z-f@4Tl6$Y(JT};JO`lgcyUH)lOTVEIRx(skuD^7w+SJR&AA`GzN32|tpZMNVwmPDq z%+2sgbf)-@*h}xrOzmcEDy_)4yu4|{m+@gjHdE>!NCl*u9F2>7o%ZOA-1h}{y`FNm zZ<9DGBV%EiR-U=7XWr*Ny}u+p(~~S!p-XP5u+Ofnb}C;jVUyd_)!t6wjeVYN>^0#5 zQ|Aju-Olk!KDptgNkf9UTJ+7-ki%!TO35|5E?b6PR=X1?pWXH5P`dRZn$6G*rB@jPq+RQ!u;!fEv?WR@ z#g-E@!7d~8<<;cnE3>PL9oAgAaVu`NWoFavKG~xs_wTBYw_BfmssH4{Dvi9ls0P!0 z(*rxz(|y(-+xxKK*=LwO|H=sqxFrF|8u~xt!4yXL_5hRoj=(qq_%RMs2acKTawLBW z@DBri7~^O#wRX7tQs6fSewf~I-fUi(z+y-Pc_8#y;3w-%rniMb<~u^+M+_3Dz5HK+ zf3iS+W^t1ZNEvtKT^Q|U+gCp`1OGw z^^U%y_J0NV%>?BGdx!g9cPP*j__6tZ%?^o9+Lkx@ZwA7O~fcD zAG#6lFK`dkE=Tga13!-6s6W_;ba?%+9{48#KbDQ_kM=sUd}-KBX$s13FE8dJ`Ar4< zWW2o?Wd3;INBPOV2hnyplD`xfTqyh`PFo-(zbZttpfgkHnmP_K0@jr#6 z{Nm8z$n_`Y?P&QHz;6TPle#0v@jsPIrjzBT0>3Wslj9$WL+1NaNb(m0|4`t^ILhA9 z`hNm`Y(LWWI$D1{7&OTB1IkLuh0m=yGM^{#n?d<#|LrXsaY_Ch;K%vDBfM1p8sNwF zM}BO(_TrG`50>J$Kk|_}MEtfK$sY{-22ef(|7rf)4U9N{p#6|@NLytioh-i|__6)b zZm|B!;M?O!{*f^0ko#A}AjhG$Fi8F|;2#a;|JV8Vn4o;zdt&)8oVCl5<%<9#&Y#GO zZHQre9LYZd_$`1R%!p`z+(Wd-k^C{hkNb!A>W#!E`OgEtj-Y&`p&hixk^F2pB*pa) z@~D9C==c>22M;)Y|5yGiz;F8({Jr7u*YYp;1Aw0#KS&$Ey0qm;{p|;ST__*puoUj_ z`0)t%?f*i4eFYkg1^j5c=sMc|Yk}YCFUqe5e$T%s-vJiQe`7z}fZzEq%KrxZlmDXr z6BTK+*?&>~Uf}4HEAZp^MUF=u<*xvK9KUefK#Y#^4_2bl%zz)qADqL;aR?q; zb)>v;z&{rFF*Bx-=@@U#k@-r1AM1~KQFbyN~o*-NTAv$V^`IdsmFabO|3^AUF5pWn{d>KZ-VTkeN z7y*YN#*;7t4nvG5V+0(A7+--AaK8(Yo&p}jmEh4)L#*d&@EEQIkNMVtM@J1YJ(WoP zyAaFSAi%*8?Paqdjvm;6q4Tz=7i|1aPP(fGJjX!@AWafdGtc;FVddGG2@6I4#?Oi+^y zS-j(+?WcyG)$v=r_HSy;n!716WK!P;XA{kDEYg2=@g%#yX4WN#k=#+;+_NaSs1wrB z^&1$4$*ZGZMqccf$OqcVj8{o-(MsiA6q$4e2RwktBE{=tyqbHvIdXQyy`NGDg_c8+x=ROMyqwGPKxs`)J2V-KC=6H6}_-+{dSL(H9zMVGu|UrV*YByv!#kR_VzmK z-k@%IpfHJoi)&HR(M1YQ#!Xx|!+Up`Rl~}a7Ba7DSl<|7R)ZoAXa>x1Y6^dxC3ai! zjs3l+BBJ59?%Y}uZFK08cx6MbL+Jj-g-YzD6kHsmNJrlmqZj|Z{Cw=OhDVhvU79S) z{ns!|DlQ)MkUltW-{+q6NR=ZyN4drgQnOxr@tIa_q;&7P8s*T$JBha@xqW0`7NX$d zT8wn`UgfLYWyY+CaC+l$>B3if{g>*&7WAo8j?`Z9UHmZFG(CTm>4bFwa~0?K1`bN> zKUk#Z;NtxinqiHShZol!j6L2!!Nq+E>FCl&y=wNWsbrrnh|EqnKJ4zRvY6Rr6YdQ4 zFv%FZch!39@$y;1eG)j|8jmmR%=KV3rOi$KFxj5FS?}7HwROGLnNo1OlAsXMrE0$H zabA1TW!#Rz#Ty40Y>asIu+#b~L-VbtMHeqy$x)7ZJ9)|N(PMOW3142))9`}A+)*>V zvYHq=QuPXpx!G@d6kK?n-t6dU@3(HQsjQlE-_Nmn>2Z@8iz|DM_C}riDJU8i*UegBs*=H%Z;?1Za@56*u!&j*s7Q1h} zFLJ=C{pX*)R56tIVts8C^|G25^Yz=TkC%pAd1;yO$?>wKZvF|bulbxAQ90>_JqD{T zk)8g*n}XYoifeyVMTIq?YV`H1%j?g2Dqk;K>DYg%+lY(d*NlpW2cMC;nL6&Z-u}j@ z&JPAE4o`DkA~kd9)!0)_LtMY;?)154#-QL*_fhnfUkfLoJS^#y}xc8s-ztG zYS$EF zH2;Lj4|Z(sERmkE{6(+3;h#>AIkq$TM*VdMuGNtI2kr;f4>@CYj=g*BM@Ng4v>E3( z9(3JD$ZWLVVK8yY$vsP?>!MCt8kH+=fQ=*)wE?@oQa zH%#NLUCybx#|vuIyPZ60n;~A`t&duXsGZh9DPG>i0}En%Uzl89*=da8Y%_|yxOOBR z{X${ZJ&`_Da=s*JPABf#Bg=9ouQe?hlT`O0 z&!TbQgv7unA2;8dp>*K9Jq1^m1ci_uq0UJ+l2q9&Un(V>BmX|lIyDSlxz;!lDwl^Mq^0tKfg>IDM+m z-mGvl?!e;)-OGncR8k+znEN72Jb2Ke!cBijjYOh(18ZI;VjsN{E^D^e9Slm0crPIQ5^A}8+q`k1NV1nJz!cUUh zN6S)h;q^|lqdQu&`o&wC^fTMOK3I2wQE4_Pv;$-U-3CVyY|-d z@F+&lW0%G+&^f*Lz3}3T=L!rHYU^v`DY(6wQ9<5*r!;ll8EUR7F}kejPc`}pk1NZ$ zCK;Hx?p@iktTK;&!_JO7S@}9zW!$Y0`4dM~*4Ce{bnMHjvY&N3tX4+!ygLOKUWYV0 zdQi9ir@pz#i7wnUY0k`W>EZo!CcfC06XYgw{=r*A;h~OEUq38MUYayXA+f2*F6@H! zez}5)-zFB%$X&E&^)6lW7ZhCb+yTMq!?JsHHaT$pwPH-4zO#7cMpgrKYNNKTob#c` z4 z%p+fJKOHN!Tgq#j#SL7tka<2!m)m{qubtd(cg5Z)5tKztfABUT;e!vx4fe1C}rr{wXeU^^Rgw9 z*J6*)5fSO6Y?QX)t<<7fbH5l*-!D5eXaD%MMaio-#ZYjSno&XChZhF>p6OGa`)cP+ z+c)+>mWxdy{9eXCUf1>L_q|#BS?Uw=#N~=@E-!JOl=igis;&M`O&>-rosphC;CkWV zlt54X2%lU}QqLXfkJu3h0xe6b-_uNbepSzTIeO+p19qvJuYMSZQ$BbBZQLE_fbqdM zJ4Y&Ip54DUW2oVl1#*uQ9#+1zAIMRDdp(MRt4x*G@wD7#)aml8t3t&+ zKaHC=lNJBQWkilG&26G_#LW8l52S)lJsP<0sGQQ2lgvFbF4P4i2=@Wgv*<;gw0{f?evRk|NZx=$T{)u_0qIGv>5MXr9){##ZBY9$dzR*=XIVSC)KNWYN@q;Min5!nnA23g{H*i5TJ!E-_V<|C*TVeuY}J&pHDWXKZwJ~^a5bp7 z%MXW+=@(LEW)hv{BGn~s?6ahaH3t&xcpDz!wt!-F; zHaolAX@Wt(tI7pIMa5DS+yPYFO}qM+%MbCr->{;qlKN7=svFabivx!C`*`v}!^Mi} zmG5o(JTx^=v6eo*Yk}~M`NEqvkJn^H7z^FuJa-zIJwq;#f;*6kdqvTH@yNbSy@u0< zCu!3Q>OPIKZ+IGHd-LYO#f8=bmb;m4jJP?CH@SCYMLvtWBt`vfwawlPvr<)?=)#+h z(!;5CHi(M5V*ve(!pRAl6V^&e8E2mxvw5kHi1d8rey>JYvuuaY-R!6Ot-gD8u~fo_ zATx>D&kY&@I*hV4E3B>*y_|ecbyE+Dyo0H@L-poMF1XB6x-;`$z44Umi4E` zn-mLqZCXBj<;>%I^t()Yu%&2G{^2l<;p!UehF7lKZ|`SKm0K<}iP?;p)VUo*&MvYh+*W!lsV-;s*50xHMzUasrdEF_j^!1zLj*hbztnX_uH{#V@Pgm-GUYm-$V1}xO z`m@&&FB--(`ndWx#W{|8Q&8)%{)tLUmsKM_pQ29gwHB)gfLZ>&*+f zi?2W2G2O#^+b@vz+G>;9soY45a`&mLD7fVN285^g8++s8)G@kC67^RJrCkhonq>v02A7L!$eNYqJBtnVqML_kJCxzT9+%RT9Hj$6d~K<*H#6Tm!1S z(ZlzPr@2TT$Z_7Y#~|pCZ11!cYX>f7p14VWXHs?NMR}httKP1OI@E(L^jND@NX~m< zScS*T1Vj4C*e;Wl7pLPn6gjRNQgJo?5D?^{~C2`*^VtF7e8hnMz`bG7-6c zFIUMsKUZy{e;T^|w6TQCL&Q@Dw{P{9@64u6v+q|f6J{RD&YLD`R#$#{dz_l;_1Vv?N51ploBJuDXx}cE zt-Zn_C*%hgKS139qZUrg$P@u-B6ro1G}Q##G!7xlXLNb2jAW^}1X_AHKH7vuQ{B zfA?egM8(B5d53CPa+4iC9@smzYGS=-#FE}71v>BC#_pqi^EhCg|HQnGYe2yrPQ_Jj zyzoTA)S@EXSJEw2^F(g)43@HkwaT!!Gp8s%8PesU>LtC!J?I|x`Poe|1HSHFV4L!K z;AZA%v$@VoM1(SCsZel7P;qyRG`E`;e#+_5fQL8MgxHQB@M+M5BgWm|JT>A(_Z|QK zDtp#skJ*PV-L1T_ePoDJAI>L-jY=OSokr@FO?s+*#p?nE7v8-#JG%ev`}1OU=NUy*nG?F^r1>Nh^q#2TcOR?naBT@W0h zF!EU35(+N76K!_%Lf!Khw?y0=95?wx*W`pD4h`}Kwf4S?tiSXg#PFG$_uAUIX4aw8 z(+`V;GLk-Sf9=$-a7w=9<}IH-8Qh)R_3Zik6kK@M-t6eNGAhmXbSYh?pHX(qyL+gQ z^!0K17mO!a-M8qmzv{Nl80OKzB}(e@^1JAp^lYB3oSkOqUu&^vQ;4^i>%tG86)GsW z_@0k+bV*+co2>FGQO5nEynU)h%jHJ&PT!Vi%Fx z&!_aRE-AMf@(WnqoE9%AppT*8nvtLo()FB^lP}HPCw%Il_WPlC{r1R6YOYIH^dCB` zkL)|U7hd>d`%SWMXAU{T3lczC?Wn1nqw@udT* zCp=J7adtd;`M@N`%rn#b&wF!9yDvR{tF6yN-Tf5YF;v{mZ%)WYC*GQJXw7)bZKdgE z+G`gnF+FEb+ivZ5tJ7k0@4M;;zkE7>amp^S!*xD$H=FgQ&70x+Dmi`Wf}&|lz7~w6 z;NtsO($N=gzrA6K`uKaUC+1vloO!3X$~EYTTnQ&XzfQUe(O0WB6*??FRUkYafHKffEJAbKzy%DI=b!})9u$9Q%n~G%?&tt@H0o( z&RO!FXO49*B}I|v?w%6n)pec?rK7%04ahC(oOK6i^v$Q9_%}xnI0j3Dqy4Uw4^D14wzcZ-e2Csxk#5Zh3kvnBVvHgB2z z-a%jQ4VphMc-poVh7T3rNKQQKJ&}6;Fpi45Wd-+B>~;Uj)uB&UnVqcJoSM1mOTvLi zrW-})_;2lUleS>XKGSud)=teZI=$s~Jx_i3<7;Ch?Oe94`gB9cNBT8KUN&=m%nJxXXS*rAjh-nLKSyr ztm~BLRA@89P9=3gh0;hFzb>nWd^?oCETYm^=}LuF^fU`S7rF6-e(Cu4M)2F)W=Efu zec4keS+UNwY<87J|9;k8p3H5u{TlOhiNc%=SCPa+dbw;(R>Mf$eM&ka)~xJHx0J6> zP7PG>m~zhH7AF>m6^%rTHmlz4bavF&}pl6<3#?J|;X#ZvA_e*Wc-)ayt2C7d6Gg9gPxQJPooXy{{gM zbQFzxegE*Aw2uJ=YI^IPZGn(Z zl5n7v-qGx(`RH3Gzd1KN&r2lBoLFTdUJI}p;*)i3ye?j(JY6@TdM6j_BO#q~lt z-QE|*$nP^r-eNIr(!h`&^QP|YKWL)NhzW?oq}U~8pTcl&vFXVHBNce@mt8r*hXIijn-vFviW>Zbh8W}Dvz z9~kDkuDdChcic*6XVfX17t8h%xWa^;k>95vJiWhu?i@#Nc23~(y7j^nm>#a)qomUd z#82+BOHqw%T)!w(*!_!}#wY3SF0aJGKLu9r|1fuS7u%T+)+;MMKH+4pL&2R!l{fB_ z@FQBxu=f*%hM8__GSv;OmDTm0*Dxmhr?dBZcNM=iVcRywof&%%XJ_cm`jXFF_AFjVpkKr#zr#Un`pjdt z25%!C_LaClVquhaZ}XU*ch@Hloj>cL+!HSm(v{^R=F& zWc88_wCWQ%nXm3~jm_ z%{WIJICOAYr`uhgrwo@6)gEZR->WfiWBu_qHubweL%7AkZ<~DUFq`%FP(eG%+g=; zPN!)L2P)1!FfweRrs_1&XVt?NPmox2wQSS^k1Lbxt0=h6Bq)S*|89r0*~gw`AH6*z zyKt~=_N`5d+iG0uOrztqV-1C63(D=3&CVYkCF)XevskYz^I*zc)!Erk*IHhey8Eb3 z^-M7Zm;C+-;pwHh506=>DtOnW^otAc$$c81H*BNo#(`2S%Li{jgeR66g)uv} z=zWjcp#5#_9;ssa?;8(h%b#DfLA+6Wn)C4^J^BP3FP!MI?AfdhTcuO=4i-hoP;h6F zpb*m4C7V`=_R7s$S08cmg6Te&R1J-=&N@0%KWlBd*LTIoH}0-W&)*-KpVM`trc}nc z%}vvlzsvN!^eKCil#Zug#5wBw`Po$52zzg_4{Ubcfd}4~U(eApP%{hfZgXe1qE%f9 zt10x{gxWD_A6O%MueNA-;dOM@wJE2CwmaX6D&E;xS0UjgJbOAtURNq^@SBql#MhMX zJ793wO7%&vokq%uJ_%F5#%g`t5V#`BIP~21!iq=Lx(=Jo=UJtVFJ7>9sqvoJz_+EN zhSNLGq75~p;4-PW7Sh5d7r!p8uJvCp#w-@;JD4L|_9p3jsIh&?pp$y0>j%shv8XWc zNFCli;6;J>qZJZsi@w>;eO#|xQDD_|YyUw6E`QzUM#a^4d$7R!oww-R)na3^Dth-h zv8F#S)`mkDs>`n*vrS(?zdhM_je^Uj;(BiC zeM9{25(|S9Cn{(c;}*_V_`2uRB+jPj)z_2`XJ!nZRIS>h%p%HFiplG&UQqR1tad@5 z>}{v2Pg39SI5*0s3G{&SdQfrA=(hERCEv0R%zv^_Jj}A_#x#e|+gzvUF1uEC)%rza zSe9L7;CkiMO{ZJ zR%#3MfaAIs6?f;!Gnd}h-KsJ&nY=G;)UFYU-@oO*?B`!NZi%>WzKWmoO2t8ub3bL& ze|uT1`Xp4nIKVEt$a7Ws5%uRi!ombfy+mM*iB&x@f${m>LHPmNc;k%loA$Uce~Nzrm^4Hd+9prTNjCppP2ZtK`!=%?v(~hSLw86&f;dh z*3a8xHD)#S{g59Omvv;;d^4r}Vl(c~H`;aJSb?7VnxKqDmr^eEyIp^0yyx`y$Ie>I z-XCE?4`qHl#s0pg`qqZd1C$T>PS5gsr(`axOwliwid(BPnJf8zp=4ljNcRbS6=Wj2 zi{z#){9bZ+?n|vhPdlrhv1qvd-o+)&(9V|$+5Jxam# zr{d}q8lMi^no+v;nnU)>!}gb!&xn@f-pl(Ev_tfvyN{cBTwU(r1y>B0`5ah&*toDAFhiJT(eu(XX#g$QoY&_Z#P9J zbiJ~{sH^W*8IFHJUX zS|*%3=W17qyg^i4r(6DqyO!8%f8KIU+0ROv$Gs>lpYZtE^(JqvUPr|@)~?EbFhA=; zUzhJvjWJ__yLc@R_!u!@$i@y1b5Eap55<<_ql&!bDGecEo&SVW;jvx z8%)J@t&JLgq(1%4o`SrS2mD{}8$LZ*bIXo^Nj+!DS17$t*=Z~Ja_B2#1xBX(lL1Qc z(b;oMiXMgP@P>YK*Ed`}qK0~29YV!byB_DYbWV5UnKBa9m&TSQT+4S@rjjuGW}Wya z@oPaVXWXE5s~RNPrOx_PqI_5D8C@C`_Qo7+JZw2(wPc9s(*5T^4>;zaBSU`d-@pG` z8h|FDCBVmk@I6(`|CS8@%Ke|w0Ji1HZv4MX`agsC59R-o2C#jPz=wI=|Mk`XOU?41 zWWly{g^#oTwdH?O-#?}{G=TQ?&;8TDKMnlTz&{QA)4)Fs{L{cc4gAxC5rt`g@3Bx!;@k4xjNm20XhazlS8_M+GG$hG8zab8%#d zo~{W1{T`CYgE;V03gYjd;r9k2;Nev_@%P#B@5$ibenA27Z>qp+Q{rzX!h3My{uBI0 z4F9$Uylx|8!N1pl-<0C_pZJX}{%#9@V}-wm!rw08?~L#_K|R6a-%7y0YoG|;2t5Ag zS{;0U@EYLpH^TUPUi>x_zoW!&9$mpR!Q=ON`0W&a=Y-!R;rB!Mtq*>egWu5L_b&Kt z3Vx4^zqP>MMc{83Y{27h1Ezt;-w^c%-v>OrV#0enY0BVLzz+q_0Ivxif9p92{9y1y zz^8%V3_cY+ey4)EN41B7N41B8j{rXhd?fg};G@7tgP#XJ27D~|IPmkqF95#~{37u2 z;1`3R3?9E(p8(z*yf*li;8%fP0^Sb1EqMG6e;xQW;Mao3?;($(5a33l0N`4)0hAl% z$9kX*j0WEcJnF^-JhmIQAGRa5jT(5g4^{BW;QN6`8xR7I>4<^+bnuek(SEvsM|(n> zf%kZX4WTVzI@%T57e1r@u^oDXM>~=OkG3TXz6W@;F>Eii7qlC+A8b1^4MXx7X)55A z!4CsJ06eyzA$V*{(#Eh{v@xXPGkVO2bOZ1@;8FKz57_o-6W9yUCeSwY!Rvz86NJcX z1Rm>7+B@pf9K0F$G2qcI(LMvfbHStSq78e47j$tVP=+|_7b6@9y})~d_W;iZ?+%^? z-VOX%@Gjt;!Os9c9lR5GNAM2dr-7de9&HM3W+Hg(2ln96mL`KodqR7&0dED~61)X? zYw+X1V}9gAe#AjM#6^58hY240sw?hY#z6Cei#Y~`J|yMk@r)IqTvw^Yb^#8@&-#`p;_9R+L{Ksgr2$sg}mbu zDEgW@Mw&W$C`~t@khjnRMORbDKvP#I5-8$8A@3&ziZP&pNnme93VCBK^5|+BX&MlJ z`x4Q}yH0_kGfYz#&^7^&6i~?9P?5ri+XocrA2H{Yc?>o6 zG<9fsz=JvJ)R!vL-V z%0Z2ichmv}B-7NTS<(Gr?X#xsrhrAOQ zc{B|`p|n5C_H)b81ubXzoAwzD_~?p+_^nOeF)S<;ZKw%y>(a>EyvbXFg@pu-O(X9I zC+{5=7Se?_z@ARtAWq&)EG%T8sRLLocZ`#F7xQ_bd1&PA;pDBvAb}3ws>u7r$$N`| zq6-ulUdS8B$(xN^c*r}-$-9pQJYb{0$`*~nfe7UN=H$J}1R6mhZ$Kw+Ru+^4Jbyrg za>(1r$y<)0<@C|uVO|sA-z!btgG^9}{zKk;PTr^tlwo`wkawe#cP;}3Oc(ncd3!o} zD>G0~Z%__-KQ(#pErA9`r9&fcUMFvK28tfP>Bzg;$vdA3G{A!fg6Rrvl)M$1pg?bc zziSH<1ol(%o@bz-Apj3~V>@{hG*D1#XgTsuck-@ipa2J=k+;5+w@CvbC2nyN( z%w9N`w2UDn+Mg+&%y5oB2>yc(1XBO0KJ4&dHW!u+k;+QPj4$&KfgYdT5U%0S`SI08Bkw>59_aH#5B`M*EJRNe82{V~8It@q zC2vdzG;D5=?blg`TvI%k;*UGz?difogZZM-w4iZtL?Z7~Z=tM!96zo$NS^n=1OLa6 zcdWPYuz0-ShyXT?yoFt$H_#3jOazN0?_qD@`2dPWJ0Ncg2fN0W108$^3Q9oUB`z$4 z4F}Cb6YIgJkhhH^1tuUMxrOlD{3Bq^FSwT+dx;?`ho&arA#W}h7Ltb)toyHH{4f|S z^>ko|205^`$y?C*b1)i>F;GCf80Q0`PHfHsU$80|C$OOLKmm2foZNZvg7v;b)&xZ# zXKrVpz&;{I|M1Q=kNQak$u_sbucKHfz5Du!pJldC!~qKSmobIgzF&8K{%i-I0?Sd_0HDBb zHO88|W9)YydU*?vg@AJS%(fgunP)p&C@cZm?HsS&MHSFo?d=ra*yq`{ zP__a^87L}r$t@N3*_ADnGe7~sW8N)Z{6N$yFs`Mhw}FCI75T=krrZ486dk-4P#O}< z)uL~vhP3bq0Ry7NUK1WLb-r*^3q=knXb06!<*OxZa(lK=w19%P)2H{BglBq^r7aXI zpy0Uk=#1R=1$Vukwosga0z$+Dq?;U#i+r8dLh%C%N-#c5$Yx6Y1F04Y6Pg-^(iqP6 zZ4yUiWGuiApp#+`4(9oCaPMoGR-U=7XWnPRc8Jx}pY`@^&~BbqD=YMmC`xm}_C}0u&q*OPn&Vk9(i? zjGz$nPcTq$4ckR_wru3f(OE!&nGxs40-#`T{K#DsCo7h&Mo@5T_8YWl97pwG#}B59 zJQuk$QYT#*FbBtY{(9%v(b5a@G9d3C*5rmX+Hcq7gw(%XlM^%gLN&e)LSJ4@UcNHB zil`}n@(*hP!L0qQq)ZidkvY06Av>a3n`{AGh zdI&Ku6pHN1U6b(4P6gtq`;vgWL(CJOoYaCiw$fQoh3njnUPiFtC+LYZca7|<$$^Un zQk*yd1aNSc2j?O>e>xVSnfdv|nFlI2zi%f@nkZy*{1D+Pw-<|Ep6eMK@12vJ!6L2O1yFvpj{ z;ROWwv(SKWDa>K{FqlD}uw2GE&URsjVdFDf${}U4BY+b z6XqMhVfhnlY#z@)B#6ak_%Q<*-n>@Oe#nP)qVj=OapT*%4YZVrA~g%pVvlYdt`>iy z*JQOS3qKQ}@E;h&@myP_qbdbT!}2Ln!Y114RX?=>K>U;fBMh!%TGs)kQ2~JxgSHX$ zY?z_gzHC1@GsBS_VqQ$HJ4~ppv<-Q_29V?U79Om;aKYA^JrI1&{4Kn#m{2n;ur)t3 zz$DwYqLw8V@U}!?F@djq+UOAcRUt6)A3#OKyQMa`ezVX6h~K2ba7`RKf#TelJhq`e z403FiJCDiWaXc9w{y~1sU|5)YvH}=>>|j{41T$Mv5}f-&G4OA@Yyi%JiQLQ<3*;|> z80^3hrZ0o#kDqgJgBigbzt+|SzmXSkf0Ig#V>)dO!+(|mQ2$KigSXW#!TvsMF5vLb z&KdA-vCTncM52n>iByrqEOuk~9>0Irq@v?Lx1gK%M9%-}FjMo5rvE2Xw%0+g0W%S;i* zcH_7cmH?X&9tRAfHMCzcBkC`SFoL(e9>WuI;Kl$tIh=+yEByERXjVNiH9r$}-IgYa z3Q=1T5PnGmL&0-i&@0i<4D73|Xo5JA2OJ_KMpa@_(+Ycb^!3c1o-$5L|e4AvY-w=z)6kbhKz4--aLOU0~VqjZfi?EN-jX6#E9P8 z)+E?GLIQ8|GjQV8sdbh8vJ=O8{Jc8{Bx=w8z4G}VF919Lfx-WBp^f5yJQe_E!2to7 z22MgCyC8>mUptfab zp8SEk`I)j1XeUB5H+-1^s}E`=U}z0!^SD6p<_BN|Ps9qbtv)2EeoG0!-x6WKoD8PW zP7vHy13LySyRYVfACp^A1(liq`iU?HBALw%HRFY`V1F3Gg+&1I?8WvCfT5Up^QNb* zt*v8VWXysCqY&6U_;P~T@EXjQ?GCGma5H~68Ve>Ct8h-F#SGw>!6q#tEQkX~8(Nst zjp@erg`Han^jg@|;ku6H?-zilWBl)Xw3X-1Rpu|x7(pzCq2VwC126U5F@yXJ^?ykXr>6OGxFO;Ej0`xMX~|3__=WI%f2IJ+?-(%o z$Lt`8p01z-KVB%S1&B`}I3T^11|r@8LGuzJ%tiQK2Ajy89SmDtJjP?0as1%)4c`_0 zSovR)vGy&Az#7U4;Qfi`C-U!kn>F~B8`jwyd9@=ur)VF~R2BqlLf{3Ixm_Lrjmj7t@kkN=;<{kg%K zN5Q`o_h($HxPM^;!1|MJA?5EyrC|OfDACo3nYLrSS+M;0(P;VDEu@b3;~x-yuVd=M zr=tb5h}Nu;mZT1=nJUT8czhdZnUe5uLhuf_)iZ5=9z-KPV}ac!ezV>Bwu`bx0!B)V z*qOJ*O`QJ&9}&V<3HK&Y9zP0)Q*a~^%#ZM2AhlvA)NIX&d@g7yID=~e<}&@*JdR%g zz8ef{YZvunMpVuZoX~La6#`pl8M%8Ym5D-r8O!Ab_Fe~AzX*!2CE%2QS+XH&&@YoBgJL!!(3a$t|l@aOtQn2dsNUSLtm-}4%2hHHlNx3|PM{0t&l zu-9d1x7G_=AfZrJOAPvO+vlFYed74^hF*5x^I z%mjGbK2YTkU2xh0eDH7kY)f#0^xOACZ41l)8VNsXf+Jjby^XeE(AGh$pvab2Sisy8 TfwNfR void; - scopes?: string[]; -}): void; -export = _exports; diff --git a/client/auth/github/getAccessToken.js b/client/auth/github/getAccessToken.js deleted file mode 100644 index cee9ab4..0000000 --- a/client/auth/github/getAccessToken.js +++ /dev/null @@ -1,36 +0,0 @@ -// @ts-check - -/** - * Login with Github Function - * =============================================================================== - * @description This function uses github api to login a user with datasquirel - * - * @async - * - * @param {object} params - Single object passed - * @param {string} params.clientId - Github app client ID: {@link https://datasquirel.com/docs} - * @param {string} params.redirectUrl - Github Redirect URL as listed in your oauth app settings: {@link https://datasquirel.com/docs} - * @param {function(boolean): void} [params.setLoading] - React setState Function: sets whether the google login button is ready or not - * @param {string[]} [params.scopes] - Scopes to be requested from the user - * - * @returns {void} - Return - */ -module.exports = function getAccessToken({ clientId, redirectUrl, setLoading, scopes }) { - /** - * == Initialize - * - * @description Initialize - */ - if (setLoading) setLoading(true); - - const scopeString = scopes ? scopes.join("%20") : "read:user"; - const fetchUrl = `https://github.com/login/oauth/authorize?client_id=${clientId}&scope=${scopeString}&redirect_uri=${redirectUrl}`; - window.location.assign(fetchUrl); - - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// -}; diff --git a/client/auth/github/getAccessToken.ts b/client/auth/github/getAccessToken.ts new file mode 100644 index 0000000..b428f28 --- /dev/null +++ b/client/auth/github/getAccessToken.ts @@ -0,0 +1,24 @@ +type Param = { + clientId: string; + redirectUrl: string; + setLoading?: (arg0: boolean) => void; + scopes?: string[]; +}; + +/** + * Login with Github Function + * =============================================================================== + * @description This function uses github api to login a user with datasquirel + */ +export default function getAccessToken({ + clientId, + redirectUrl, + setLoading, + scopes, +}: Param): void { + if (setLoading) setLoading(true); + + const scopeString = scopes ? scopes.join("%20") : "read:user"; + const fetchUrl = `https://github.com/login/oauth/authorize?client_id=${clientId}&scope=${scopeString}&redirect_uri=${redirectUrl}`; + window.location.assign(fetchUrl); +} diff --git a/client/auth/google/getAccessToken.d.ts b/client/auth/google/getAccessToken.d.ts deleted file mode 100644 index 9893644..0000000 --- a/client/auth/google/getAccessToken.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -declare namespace _exports { - export { GoogleGetAccessTokenFunctionParams }; -} -declare function _exports(params: GoogleGetAccessTokenFunctionParams): Promise; -export = _exports; -type GoogleGetAccessTokenFunctionParams = { - /** - * - Google app client ID: {@link https://datasquirel.com/docs} - */ - clientId: string; - /** - * - Whether to trigger Google signing popup or not: {@link https://datasquirel.com/docs} - */ - triggerPrompt?: boolean; - /** - * - React setState Function: sets whether the google login button is ready or not - */ - setLoading?: React.Dispatch>; -}; diff --git a/client/auth/google/getAccessToken.js b/client/auth/google/getAccessToken.ts similarity index 56% rename from client/auth/google/getAccessToken.js rename to client/auth/google/getAccessToken.ts index 6168cf2..b78cccd 100644 --- a/client/auth/google/getAccessToken.js +++ b/client/auth/google/getAccessToken.ts @@ -1,33 +1,22 @@ -// @ts-check +interface GoogleGetAccessTokenFunctionParams { + clientId: string; + triggerPrompt?: boolean; + setLoading?: React.Dispatch>; +} -/** - * @typedef {object} GoogleGetAccessTokenFunctionParams - * @property {string} clientId - Google app client ID: {@link https://datasquirel.com/docs} - * @property {boolean} [triggerPrompt] - Whether to trigger Google signing popup or not: {@link https://datasquirel.com/docs} - * @property {React.Dispatch>} [setLoading] - React setState Function: sets whether the google login button is ready or not - * - */ - -/** @type {any} */ -let interval; +let interval: any; /** * Login with Google Function * =============================================================================== * @description This function uses google identity api to login a user with datasquirel - * - * @async - * - * @requires script "https://accounts.google.com/gsi/client" async script added to head - * - * @param {GoogleGetAccessTokenFunctionParams} params - Single object passed - - * @returns {Promise} - Access Token String */ -module.exports = async function getAccessToken(params) { +export default async function getAccessToken( + params: GoogleGetAccessTokenFunctionParams +): Promise { params.setLoading?.(true); - const response = await new Promise((resolve, reject) => { + const response = (await new Promise((resolve, reject) => { interval = setInterval(() => { // @ts-ignore let google = window.google; @@ -37,20 +26,22 @@ module.exports = async function getAccessToken(params) { resolve(googleLogin({ ...params, google })); } }, 500); - }); + })) as any; params.setLoading?.(false); return response; -}; +} /** * # Google Login Function - * - * @param {GoogleGetAccessTokenFunctionParams & { google: any }} params - * @returns */ -function googleLogin({ google, clientId, setLoading, triggerPrompt }) { +export function googleLogin({ + google, + clientId, + setLoading, + triggerPrompt, +}: GoogleGetAccessTokenFunctionParams & { google: any }) { setTimeout(() => { setLoading?.(false); }, 3000); @@ -60,7 +51,9 @@ function googleLogin({ google, clientId, setLoading, triggerPrompt }) { * # Callback Function * @param {import("../../../package-shared/types").GoogleAccessTokenObject} response */ - function handleCredentialResponse(response) { + function handleCredentialResponse( + response: import("../../../package-shared/types").GoogleAccessTokenObject + ) { resolve(response.access_token); } @@ -81,7 +74,9 @@ function googleLogin({ google, clientId, setLoading, triggerPrompt }) { * ======================================================== * @param {import("../../../package-shared/types").GoogleIdentityPromptNotification} notification */ - function triggerGooglePromptCallback(notification) { + function triggerGooglePromptCallback( + notification: import("../../../package-shared/types").GoogleIdentityPromptNotification + ) { console.log(notification); } }); diff --git a/client/auth/logout.d.ts b/client/auth/logout.d.ts deleted file mode 100644 index 8535fd9..0000000 --- a/client/auth/logout.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare function _exports(params: object | null): Promise; -export = _exports; diff --git a/client/auth/logout.js b/client/auth/logout.js deleted file mode 100644 index f5fa88c..0000000 --- a/client/auth/logout.js +++ /dev/null @@ -1,146 +0,0 @@ -/** - * Type Definitions - * =============================================================================== - */ - -const parseClientCookies = require("../utils/parseClientCookies"); - -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// - -/** - * Login with Google Function - * =============================================================================== - * @description This function uses google identity api to login a user with datasquirel - * - * @async - * - * @param {object|null} params - Single object passed - * @param {string|null} params.googleClientId - Google client Id if applicable - * - * @requires localStorageUser - a "user" JSON string stored in local storage with all - * the necessary user data gotten from the server - * - * @returns {Promise} - Return - */ -module.exports = async function logout(params) { - /** - * == Initialize - * - * @description Initialize - */ - const localUser = localStorage.getItem("user"); - let targetUser; - - try { - targetUser = JSON.parse(localUser); - } catch (error) { - console.log(error); - } - - if (!targetUser) { - return false; - } - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - - const cookies = parseClientCookies(); - const socialId = cookies?.datasquirel_social_id && typeof cookies.datasquirel_social_id == "string" && !cookies.datasquirel_social_id.match(/^null$/i) ? cookies.datasquirel_social_id : null; - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - - localStorage.setItem("user", "{}"); - localStorage.removeItem("csrf"); - - document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`; - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - - const response = await new Promise((resolve, reject) => { - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - - if (socialId && !socialId?.match(/^null$/i)) { - const googleClientId = params?.googleClientId; - - if (googleClientId) { - const googleScript = document.createElement("script"); - googleScript.src = "https://accounts.google.com/gsi/client"; - googleScript.className = "social-script-tag"; - - document.body.appendChild(googleScript); - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - - googleScript.onload = function (e) { - if (google) { - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - - google.accounts.id.initialize({ - client_id: googleClientId, - }); - - google.accounts.id.revoke(socialId, (done) => { - console.log(done.error); - - resolve(true); - }); - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - } - }; - } else { - resolve(true); - } - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - } else { - resolve(true); - } - - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - }); - - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - - return response; - - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////////////// -}; diff --git a/client/auth/logout.ts b/client/auth/logout.ts new file mode 100644 index 0000000..80ada8a --- /dev/null +++ b/client/auth/logout.ts @@ -0,0 +1,103 @@ +import parseClientCookies from "../utils/parseClientCookies"; +/** + * Login with Google Function + * =============================================================================== + * @description This function uses google identity api to login a user with datasquirel + */ +export default async function logout( + params: { [s: string]: any } | null +): Promise { + try { + const localUser = localStorage.getItem("user"); + let targetUser; + + try { + targetUser = JSON.parse(localUser || ""); + } catch (error) { + console.log(error); + } + + if (!targetUser) { + return false; + } + + //////////////////////////////////////// + //////////////////////////////////////// + //////////////////////////////////////// + + const cookies = parseClientCookies(); + const socialId = + cookies?.datasquirel_social_id && + typeof cookies.datasquirel_social_id == "string" && + !cookies.datasquirel_social_id.match(/^null$/i) + ? cookies.datasquirel_social_id + : null; + + //////////////////////////////////////// + //////////////////////////////////////// + //////////////////////////////////////// + + localStorage.setItem("user", "{}"); + localStorage.removeItem("csrf"); + + document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`; + + //////////////////////////////////////// + //////////////////////////////////////// + //////////////////////////////////////// + + const response: boolean = await new Promise((resolve, reject) => { + if (socialId && !socialId?.match(/^null$/i)) { + const googleClientId = params?.googleClientId; + + if (googleClientId) { + const googleScript = document.createElement("script"); + googleScript.src = "https://accounts.google.com/gsi/client"; + googleScript.className = "social-script-tag"; + + document.body.appendChild(googleScript); + + //////////////////////////////////////// + //////////////////////////////////////// + //////////////////////////////////////// + + googleScript.onload = function (e) { + // @ts-ignore + const google = window.google; + + if (google) { + //////////////////////////////////////// + //////////////////////////////////////// + //////////////////////////////////////// + + google.accounts.id.initialize({ + client_id: googleClientId, + }); + + google.accounts.id.revoke(socialId, (done: any) => { + console.log(done.error); + resolve(true); + }); + + //////////////////////////////////////// + //////////////////////////////////////// + //////////////////////////////////////// + } + }; + } else { + resolve(true); + } + + //////////////////////////////////////// + //////////////////////////////////////// + //////////////////////////////////////// + } else { + resolve(true); + } + }); + + return response; + } catch (error) { + return false; + } +} diff --git a/client/fetch/index.d.ts b/client/fetch/index.d.ts deleted file mode 100644 index fddf1ee..0000000 --- a/client/fetch/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export = clientFetch; -declare function clientFetch(url: string, options?: import("../../package-shared/types").FetchApiOptions, csrf?: boolean): Promise; -declare namespace clientFetch { - export { clientFetch as fetchApi }; -} diff --git a/client/fetch/index.js b/client/fetch/index.js deleted file mode 100644 index f6a141d..0000000 --- a/client/fetch/index.js +++ /dev/null @@ -1,95 +0,0 @@ -// @ts-check - -const _ = require("lodash"); - -/** @type {import("../../package-shared/types").FetchApiFn} */ -async function clientFetch(url, options, csrf) { - let data; - let finalUrl = url; - - if (typeof options === "string") { - try { - let fetchData; - - switch (options) { - case "post": - fetchData = await fetch(finalUrl, { - method: options, - headers: { - "Content-Type": "application/json", - }, - }); - data = await fetchData.json(); - break; - - default: - fetchData = await fetch(finalUrl); - data = await fetchData.json(); - break; - } - } catch (/** @type {any} */ error) { - console.log("FetchAPI error #1:", error.message); - data = null; - } - } else if (typeof options === "object") { - try { - let fetchData; - - if (options.query) { - let pathSuffix = ""; - pathSuffix += "?"; - const queryString = Object.keys(options.query) - ?.map((queryKey) => { - if (!options.query?.[queryKey]) return undefined; - if (typeof options.query[queryKey] == "object") { - return `${queryKey}=${JSON.stringify( - options.query[queryKey] - )}`; - } - return `${queryKey}=${options.query[queryKey]}`; - }) - .filter((prt) => prt) - .join("&"); - pathSuffix += queryString; - finalUrl += pathSuffix; - delete options.query; - } - - if (options.body && typeof options.body === "object") { - let oldOptionsBody = _.cloneDeep(options.body); - options.body = JSON.stringify(oldOptionsBody); - } - - if (options.headers) { - /** @type {any} */ - const finalOptions = { ...options }; - - fetchData = await fetch(finalUrl, finalOptions); - } else { - fetchData = await fetch(finalUrl, { - ...options, - headers: { - "Content-Type": "application/json", - }, - }); - } - data = await fetchData.json(); - } catch (/** @type {any} */ error) { - console.log("FetchAPI error #2:", error.message); - data = null; - } - } else { - try { - let fetchData = await fetch(finalUrl); - data = await fetchData.json(); - } catch (/** @type {any} */ error) { - console.log("FetchAPI error #3:", error.message); - data = null; - } - } - - return data; -} - -module.exports = clientFetch; -exports.fetchApi = clientFetch; diff --git a/client/fetch/index.ts b/client/fetch/index.ts new file mode 100644 index 0000000..682c0d3 --- /dev/null +++ b/client/fetch/index.ts @@ -0,0 +1,113 @@ +import _ from "lodash"; + +type FetchApiOptions = { + method: + | "POST" + | "GET" + | "DELETE" + | "PUT" + | "PATCH" + | "post" + | "get" + | "delete" + | "put" + | "patch"; + body?: object | string; + headers?: FetchHeader; +}; + +type FetchHeader = HeadersInit & { + [key: string]: string | null; +}; + +export type FetchApiReturn = { + success: boolean; + payload: any; + msg?: string; + [key: string]: any; +}; + +/** + * # Fetch API + */ +export default async function fetchApi( + url: string, + options?: FetchApiOptions, + csrf?: boolean, + /** Key to use to grab local Storage csrf value. */ + localStorageCSRFKey?: string +): Promise { + let data; + + const csrfValue = localStorage.getItem(localStorageCSRFKey || "csrf"); + + let finalHeaders = { + "Content-Type": "application/json", + } as FetchHeader; + + if (csrf && csrfValue) { + finalHeaders[`'${csrfValue.replace(/\"/g, "")}'`] = "true"; + } + + if (typeof options === "string") { + try { + let fetchData; + + switch (options) { + case "post": + fetchData = await fetch(url, { + method: options, + headers: finalHeaders, + } as RequestInit); + data = fetchData.json(); + break; + + default: + fetchData = await fetch(url); + data = fetchData.json(); + break; + } + } catch (error: any) { + console.log("FetchAPI error #1:", error.message); + data = null; + } + } else if (typeof options === "object") { + try { + let fetchData; + + if (options.body && typeof options.body === "object") { + let oldOptionsBody = _.cloneDeep(options.body); + options.body = JSON.stringify(oldOptionsBody); + } + + if (options.headers) { + options.headers = _.merge(options.headers, finalHeaders); + + const finalOptions: any = { ...options }; + fetchData = await fetch(url, finalOptions); + } else { + const finalOptions = { + ...options, + headers: finalHeaders, + } as RequestInit; + + fetchData = await fetch(url, finalOptions); + } + + data = fetchData.json(); + } catch (error: any) { + console.log("FetchAPI error #2:", error.message); + data = null; + } + } else { + try { + let fetchData = await fetch(url); + data = await fetchData.json(); + } catch (error: any) { + console.log("FetchAPI error #3:", error.message); + data = null; + } + } + + return data; +} diff --git a/client/index.d.ts b/client/index.d.ts deleted file mode 100644 index 555947d..0000000 --- a/client/index.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -export namespace media { - export { imageInputToBase64 }; - export { imageInputFileToBase64 }; - export { inputFileToBase64 }; -} -export namespace auth { - export namespace google { - export { getAccessToken }; - } - export namespace github { - export { getGithubAccessToken as getAccessToken }; - } - export { logout }; -} -export namespace fetch { - export { fetchApi }; - export { clientFetch }; -} -export namespace utils { - export { serializeQuery }; - export { serializeCookies }; - export { EJSON }; - export { numberfy }; - export { slugify }; -} -import imageInputToBase64 = require("./media/imageInputToBase64"); -import imageInputFileToBase64 = require("./media/imageInputFileToBase64"); -import inputFileToBase64 = require("./media/inputFileToBase64"); -import getAccessToken = require("./auth/google/getAccessToken"); -import getGithubAccessToken = require("./auth/github/getAccessToken"); -import logout = require("./auth/logout"); -import { fetchApi } from "./fetch"; -import clientFetch = require("./fetch"); -import serializeQuery = require("../package-shared/utils/serialize-query"); -import serializeCookies = require("../package-shared/utils/serialize-cookies"); -import EJSON = require("../package-shared/utils/ejson"); -import numberfy = require("../package-shared/utils/numberfy"); -import slugify = require("../package-shared/utils/slugify"); diff --git a/client/index.js b/client/index.js deleted file mode 100644 index 368bf61..0000000 --- a/client/index.js +++ /dev/null @@ -1,67 +0,0 @@ -// @ts-check - -/** - * Imports - */ -const imageInputFileToBase64 = require("./media/imageInputFileToBase64"); -const imageInputToBase64 = require("./media/imageInputToBase64"); -const inputFileToBase64 = require("./media/inputFileToBase64"); -const getAccessToken = require("./auth/google/getAccessToken"); -const getGithubAccessToken = require("./auth/github/getAccessToken"); -const logout = require("./auth/logout"); -const { fetchApi } = require("./fetch"); -const clientFetch = require("./fetch"); -const serializeQuery = require("../package-shared/utils/serialize-query"); -const serializeCookies = require("../package-shared/utils/serialize-cookies"); -const EJSON = require("../package-shared/utils/ejson"); -const numberfy = require("../package-shared/utils/numberfy"); -const slugify = require("../package-shared/utils/slugify"); - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// - -/** - * Media Functions Object - */ -const media = { - imageInputToBase64: imageInputToBase64, - imageInputFileToBase64: imageInputFileToBase64, - inputFileToBase64: inputFileToBase64, -}; - -/** - * User Auth Object - */ -const auth = { - google: { - getAccessToken: getAccessToken, - }, - github: { - getAccessToken: getGithubAccessToken, - }, - logout: logout, -}; - -const utils = { - serializeQuery, - serializeCookies, - EJSON, - numberfy, - slugify, -}; - -/** - * Fetch - */ -const fetch = { - fetchApi, - clientFetch, -}; - -/** - * Main Export - */ -const datasquirelClient = { media, auth, fetch, utils }; - -module.exports = datasquirelClient; diff --git a/client/index.ts b/client/index.ts new file mode 100644 index 0000000..7320ef9 --- /dev/null +++ b/client/index.ts @@ -0,0 +1,62 @@ +import imageInputFileToBase64 from "./media/imageInputFileToBase64"; +import imageInputToBase64 from "./media/imageInputToBase64"; +import inputFileToBase64 from "./media/inputFileToBase64"; +import getAccessToken from "./auth/google/getAccessToken"; +import getGithubAccessToken from "./auth/github/getAccessToken"; +import logout from "./auth/logout"; +import fetchApi from "./fetch"; +import clientFetch from "./fetch"; +import serializeQuery from "../package-shared/utils/serialize-query"; +import serializeCookies from "../package-shared/utils/serialize-cookies"; +import EJSON from "../package-shared/utils/ejson"; +import numberfy from "../package-shared/utils/numberfy"; +import slugify from "../package-shared/utils/slugify"; + +//////////////////////////////////////// +//////////////////////////////////////// +//////////////////////////////////////// + +/** + * Media Functions Object + */ +const media = { + imageInputToBase64: imageInputToBase64, + imageInputFileToBase64: imageInputFileToBase64, + inputFileToBase64: inputFileToBase64, +}; + +/** + * User Auth Object + */ +const auth = { + google: { + getAccessToken: getAccessToken, + }, + github: { + getAccessToken: getGithubAccessToken, + }, + logout: logout, +}; + +const utils = { + serializeQuery, + serializeCookies, + EJSON, + numberfy, + slugify, +}; + +/** + * Fetch + */ +const fetch = { + fetchApi, + clientFetch, +}; + +/** + * Main Export + */ +const datasquirelClient = { media, auth, fetch, utils }; + +export default datasquirelClient; diff --git a/client/media/client.js b/client/media/client.ts similarity index 100% rename from client/media/client.js rename to client/media/client.ts diff --git a/client/media/imageInputFileToBase64.d.ts b/client/media/imageInputFileToBase64.d.ts deleted file mode 100644 index 3769031..0000000 --- a/client/media/imageInputFileToBase64.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -declare function _exports({ imageInputFile, maxWidth, imagePreviewNode, }: { - imageInputFile: { - name: string; - }; - maxWidth?: number; - imagePreviewNode?: HTMLImageElement; -}): Promise; -export = _exports; diff --git a/client/media/imageInputFileToBase64.js b/client/media/imageInputFileToBase64.ts similarity index 63% rename from client/media/imageInputFileToBase64.js rename to client/media/imageInputFileToBase64.ts index 6247cf5..7b77ad1 100644 --- a/client/media/imageInputFileToBase64.js +++ b/client/media/imageInputFileToBase64.ts @@ -1,22 +1,19 @@ +import { ImageInputFileToBase64FunctionReturn } from "../../package-shared/types"; + +type Param = { + imageInputFile: File; + maxWidth?: number; + imagePreviewNode?: HTMLImageElement; +}; + /** - * ============================================================================== - * Main Function - * ============================================================================== - * @async - * - * @param {{ - * imageInputFile: { name:string }, - * maxWidth?: number, - * imagePreviewNode?: HTMLImageElement, - * }} params - Single object passed - * - * @returns { Promise } - Return Object + * # Image input File top Base64 */ -module.exports = async function imageInputFileToBase64({ +export default async function imageInputFileToBase64({ imageInputFile, maxWidth, imagePreviewNode, -}) { +}: Param): Promise { /** * Make https request * @@ -24,15 +21,15 @@ module.exports = async function imageInputFileToBase64({ */ try { let imageName = imageInputFile.name.replace(/\..*/, ""); - let imageDataBase64; - let imageSize; + let imageDataBase64: string | undefined; + let imageSize: number | undefined; let canvas = document.createElement("canvas"); const MIME_TYPE = imageInputFile.type; const QUALITY = 0.95; const MAX_WIDTH = maxWidth ? maxWidth : null; - const file = imageInputFile; // get the file + const file = imageInputFile; const blobURL = URL.createObjectURL(file); const img = new Image(); @@ -47,8 +44,9 @@ module.exports = async function imageInputFileToBase64({ }; /** ********************* Handle new image when loaded */ - img.onload = function () { - URL.revokeObjectURL(this.src); + img.onload = function (e) { + const imgEl = e.target as HTMLImageElement; + URL.revokeObjectURL(imgEl.src); if (MAX_WIDTH) { const scaleSize = MAX_WIDTH / img.naturalWidth; @@ -67,7 +65,7 @@ module.exports = async function imageInputFileToBase64({ } const ctx = canvas.getContext("2d"); - ctx.drawImage(img, 0, 0, canvas.width, canvas.height); + ctx?.drawImage(img, 0, 0, canvas.width, canvas.height); const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY); @@ -82,7 +80,7 @@ module.exports = async function imageInputFileToBase64({ imageSize = await new Promise((res, rej) => { canvas.toBlob( (blob) => { - res(blob.size); + res(blob?.size); }, MIME_TYPE, QUALITY @@ -90,23 +88,19 @@ module.exports = async function imageInputFileToBase64({ }); return { - imageBase64: imageDataBase64.replace(/.*?base64,/, ""), + imageBase64: imageDataBase64?.replace(/.*?base64,/, ""), imageBase64Full: imageDataBase64, imageName: imageName, imageSize: imageSize, }; - } catch (/** @type {*} */ error) { + } catch (error: any) { console.log("Image Processing Error! =>", error.message); return { - imageBase64: null, - imageBase64Full: null, - imageName: null, - imageSize: null, + imageBase64: undefined, + imageBase64Full: undefined, + imageName: undefined, + imageSize: undefined, }; } -}; - -/** ********************************************** */ -/** ********************************************** */ -/** ********************************************** */ +} diff --git a/client/media/imageInputToBase64.d.ts b/client/media/imageInputToBase64.d.ts deleted file mode 100644 index d24dd25..0000000 --- a/client/media/imageInputToBase64.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -declare namespace _exports { - export { FunctionReturn }; -} -declare function _exports({ imageInput, maxWidth, mimeType, }: { - imageInput: HTMLInputElement; - maxWidth?: number; - mimeType?: [string]; -}): Promise; -export = _exports; -type FunctionReturn = { - imageBase64: string; - imageBase64Full: string; - imageName: string; -}; diff --git a/client/media/imageInputToBase64.js b/client/media/imageInputToBase64.js deleted file mode 100644 index 30d128b..0000000 --- a/client/media/imageInputToBase64.js +++ /dev/null @@ -1,115 +0,0 @@ -/** - * @typedef {{ - * imageBase64: string, - * imageBase64Full: string, - * imageName: string, - * }} FunctionReturn - */ - -/** - * ============================================================================== - * Main Function - * ============================================================================== - * @async - * - * @param {{ - * imageInput: HTMLInputElement, - * maxWidth?: number, - * mimeType?: [string='image/jpeg'] - * }} params - Single object passed - * - * @returns { Promise } - Return Object - */ -module.exports = async function imageInputToBase64({ - imageInput, - maxWidth, - mimeType, -}) { - /** - * Make https request - * - * @description make a request to datasquirel.com - */ - try { - let imagePreviewNode = document.querySelector( - `[data-imagepreview='image']` - ); - let imageName = imageInput.files[0].name.replace(/\..*/, ""); - let imageDataBase64; - - const MIME_TYPE = mimeType ? mimeType : "image/jpeg"; - const QUALITY = 0.95; - const MAX_WIDTH = maxWidth ? maxWidth : null; - - const file = imageInput.files[0]; // get the file - const blobURL = URL.createObjectURL(file); - const img = new Image(); - - /** ********************* Add source to new image */ - img.src = blobURL; - - imageDataBase64 = await new Promise((res, rej) => { - /** ********************* Handle Errors in loading image */ - img.onerror = function () { - URL.revokeObjectURL(this.src); - window.alert("Cannot load image!"); - }; - - /** ********************* Handle new image when loaded */ - img.onload = function () { - URL.revokeObjectURL(this.src); - - const canvas = document.createElement("canvas"); - - if (MAX_WIDTH) { - const scaleSize = MAX_WIDTH / img.naturalWidth; - - canvas.width = - img.naturalWidth < MAX_WIDTH - ? img.naturalWidth - : MAX_WIDTH; - canvas.height = - img.naturalWidth < MAX_WIDTH - ? img.naturalHeight - : img.naturalHeight * scaleSize; - } else { - canvas.width = img.naturalWidth; - canvas.height = img.naturalHeight; - } - - const ctx = canvas.getContext("2d"); - ctx.drawImage(img, 0, 0, canvas.width, canvas.height); - - const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY); - - if (imagePreviewNode) { - document - .querySelectorAll(`[data-imagepreview='image']`) - .forEach((img) => { - img.src = srcEncoded; - }); - } - - res(srcEncoded); - }; - }); - - return { - imageBase64: imageDataBase64.replace(/.*?base64,/, ""), - imageBase64Full: imageDataBase64, - imageName: imageName, - }; - } catch (/** @type {*} */ error) { - console.log("Image Processing Error! =>", error.message); - - return { - imageBase64: null, - imageBase64Full: null, - imageName: null, - }; - } -}; - -/** ********************************************** */ -/** ********************************************** */ -/** ********************************************** */ diff --git a/client/media/imageInputToBase64.ts b/client/media/imageInputToBase64.ts new file mode 100644 index 0000000..d5e0596 --- /dev/null +++ b/client/media/imageInputToBase64.ts @@ -0,0 +1,104 @@ +type FunctionReturn = { + imageBase64?: string; + imageBase64Full?: string; + imageName?: string; +}; + +type Param = { + imageInput: HTMLInputElement; + maxWidth?: number; + mimeType?: string; +}; + +/** + * # Image Input Element to Base 64 + */ +export default async function imageInputToBase64({ + imageInput, + maxWidth, + mimeType, +}: Param): Promise { + /** + * Make https request + * + * @description make a request to datasquirel.com + */ + try { + let imagePreviewNode = document.querySelector( + `[data-imagepreview='image']` + ); + let imageName = imageInput.files?.[0].name.replace(/\..*/, ""); + let imageDataBase64: string | undefined; + + const MIME_TYPE = mimeType ? mimeType : "image/jpeg"; + const QUALITY = 0.95; + const MAX_WIDTH = maxWidth ? maxWidth : null; + + const file = imageInput.files?.[0]; + const blobURL = file ? URL.createObjectURL(file) : undefined; + const img = new Image(); + + if (blobURL) { + img.src = blobURL; + + imageDataBase64 = await new Promise((res, rej) => { + /** ********************* Handle Errors in loading image */ + img.onerror = function () { + URL.revokeObjectURL(this.src); + window.alert("Cannot load image!"); + }; + + img.onload = function (e) { + const imgEl = e.target as HTMLImageElement; + URL.revokeObjectURL(imgEl.src); + + const canvas = document.createElement("canvas"); + + if (MAX_WIDTH) { + const scaleSize = MAX_WIDTH / img.naturalWidth; + + canvas.width = + img.naturalWidth < MAX_WIDTH + ? img.naturalWidth + : MAX_WIDTH; + canvas.height = + img.naturalWidth < MAX_WIDTH + ? img.naturalHeight + : img.naturalHeight * scaleSize; + } else { + canvas.width = img.naturalWidth; + canvas.height = img.naturalHeight; + } + + const ctx = canvas.getContext("2d"); + ctx?.drawImage(img, 0, 0, canvas.width, canvas.height); + + const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY); + + if (imagePreviewNode) { + document + .querySelectorAll(`[data-imagepreview='image']`) + .forEach((_img) => { + const _imgEl = _img as HTMLImageElement; + _imgEl.src = srcEncoded; + }); + } + + res(srcEncoded); + }; + }); + + return { + imageBase64: imageDataBase64?.replace(/.*?base64,/, ""), + imageBase64Full: imageDataBase64, + imageName: imageName, + }; + } else { + return {}; + } + } catch (/** @type {*} */ error: any) { + console.log("Image Processing Error! =>", error.message); + + return {}; + } +} diff --git a/client/media/inputFileToBase64.d.ts b/client/media/inputFileToBase64.d.ts deleted file mode 100644 index 7497274..0000000 --- a/client/media/inputFileToBase64.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -declare namespace _exports { - export { FunctionReturn }; -} -declare function _exports({ inputFile, allowedRegex }: { - inputFile: { - name: string; - size: number; - type: string; - }; - allowedRegex?: RegExp; -}): Promise; -export = _exports; -type FunctionReturn = { - fileBase64: string; - fileBase64Full: string; - fileName: string; - fileSize: number; - fileType: string; -}; diff --git a/client/media/inputFileToBase64.js b/client/media/inputFileToBase64.js deleted file mode 100644 index 9927707..0000000 --- a/client/media/inputFileToBase64.js +++ /dev/null @@ -1,96 +0,0 @@ -/** - * @typedef {{ - * fileBase64: string, - * fileBase64Full: string, - * fileName: string, - * fileSize: number, - * fileType: string, - * }} FunctionReturn - */ - -/** - * Input File to base64 - * ============================================================================== - * - * @description This function takes in a *SINGLE* input file from a HTML file input element. - * HTML file input elements usually return an array of input objects, so be sure to select the target - * file from the array. - * - * @async - * - * @param {object} params - Single object passed - * @param {object} params.inputFile - HTML input File - * @param {string} params.inputFile.name - Input File Name - * @param {number} params.inputFile.size - Input File Size in bytes - * @param {string} params.inputFile.type - Input File Type: "JPEG", "PNG", "PDF", etc. Whichever allowed regexp is provided - * @param {RegExp} [params.allowedRegex] - Regexp containing the allowed file types - * - * @returns { Promise } - Return Object - */ -module.exports = async function inputFileToBase64({ inputFile, allowedRegex }) { - /** - * == Initialize - * - * @description Initialize - */ - const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/; - - if (!inputFile?.type?.match(allowedTypesRegex)) { - window.alert(`We currently don't support ${inputFile.type} file types. Support is coming soon. For now we support only images and PDFs.`); - - return { - fileBase64: null, - fileBase64Full: null, - fileName: inputFile.name, - fileSize: null, - fileType: null, - }; - } - - try { - /** Process File **/ - let fileName = inputFile.name.replace(/\..*/, ""); - - /** Add source to new file **/ - const fileData = await new Promise((resolve, reject) => { - var reader = new FileReader(); - reader.readAsDataURL(inputFile); - reader.onload = function () { - resolve(reader.result); - }; - reader.onerror = function (/** @type {*} */ error) { - console.log("Error: ", error.message); - }; - }); - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - - return { - fileBase64: fileData.replace(/.*?base64,/, ""), - fileBase64Full: fileData, - fileName: fileName, - fileSize: inputFile.size, - fileType: inputFile.type, - }; - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - } catch (/** @type {*} */ error) { - console.log("File Processing Error! =>", error.message); - - return { - fileBase64: null, - fileBase64Full: null, - fileName: inputFile.name, - fileSize: null, - fileType: null, - }; - } -}; - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// diff --git a/client/media/inputFileToBase64.ts b/client/media/inputFileToBase64.ts new file mode 100644 index 0000000..ee23a72 --- /dev/null +++ b/client/media/inputFileToBase64.ts @@ -0,0 +1,68 @@ +type FunctionReturn = { + fileBase64?: string; + fileBase64Full?: string; + fileName?: string; + fileSize?: number; + fileType?: string; +}; + +type Param = { + inputFile: File; + allowedRegex?: RegExp; +}; + +/** + * Input File to base64 + * ============================================================================== + * + * @description This function takes in a *SINGLE* input file from a HTML file input element. + * HTML file input elements usually return an array of input objects, so be sure to select the target + * file from the array. + */ +export default async function inputFileToBase64({ + inputFile, + allowedRegex, +}: Param): Promise { + const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/; + + if (!inputFile?.type?.match(allowedTypesRegex)) { + window.alert( + `We currently don't support ${inputFile.type} file types. Support is coming soon. For now we support only images and PDFs.` + ); + + return { + fileName: inputFile.name, + }; + } + + try { + let fileName = inputFile.name.replace(/\..*/, ""); + + const fileData: string | undefined = await new Promise( + (resolve, reject) => { + var reader = new FileReader(); + reader.readAsDataURL(inputFile); + reader.onload = function () { + resolve(reader.result?.toString()); + }; + reader.onerror = function (/** @type {*} */ error: any) { + console.log("Error: ", error.message); + }; + } + ); + + return { + fileBase64: fileData?.replace(/.*?base64,/, ""), + fileBase64Full: fileData, + fileName: fileName, + fileSize: inputFile.size, + fileType: inputFile.type, + }; + } catch (error: any) { + console.log("File Processing Error! =>", error.message); + + return { + fileName: inputFile.name, + }; + } +} diff --git a/client/utils/parseClientCookies.d.ts b/client/utils/parseClientCookies.d.ts deleted file mode 100644 index 1f6b937..0000000 --- a/client/utils/parseClientCookies.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare function _exports(): {} | null; -export = _exports; diff --git a/client/utils/parseClientCookies.js b/client/utils/parseClientCookies.js deleted file mode 100644 index 7b7eb70..0000000 --- a/client/utils/parseClientCookies.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * ============================================================================== - * Imports - * ============================================================================== - */ - -/** - * Parse request cookies - * ============================================================================== - * - * @description This function takes in a request object and returns the cookies as a JS object - * - * @async - * - * @param {object} params - main params object - * @param {object} params.request - HTTPS request object - * - * @returns {{}|null} - */ -module.exports = function () { - /** - * Check inputs - * - * @description Check inputs - */ - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - - /** @type {string|null} */ - const cookieString = document.cookie; - - if (!cookieString || typeof cookieString !== "string") { - return null; - } - - /** @type {string[]} */ - const cookieSplitArray = cookieString.split(";"); - - let cookieObject = {}; - - cookieSplitArray.forEach((keyValueString) => { - const [key, value] = keyValueString.split("="); - if (key && typeof key == "string") { - cookieObject[key.replace(/^ +| +$/, "")] = value && typeof value == "string" ? value.replace(/^ +| +$/, "") : null; - } - }); - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - - /** - * Make https request - * - * @description make a request to datasquirel.com - */ - - return cookieObject; -}; - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// diff --git a/client/utils/parseClientCookies.ts b/client/utils/parseClientCookies.ts new file mode 100644 index 0000000..e514e9b --- /dev/null +++ b/client/utils/parseClientCookies.ts @@ -0,0 +1,34 @@ +/** + * Parse request cookies + * ============================================================================== * + * @description This function takes in a request object and returns the cookies as a JS object + */ +export default function (): { [s: string]: any } | null { + /** + * Check inputs + * + * @description Check inputs + */ + + const cookieString: string | null = document.cookie; + + if (!cookieString || typeof cookieString !== "string") { + return null; + } + + const cookieSplitArray: string[] = cookieString.split(";"); + + let cookieObject: { [s: string]: any } = {}; + + cookieSplitArray.forEach((keyValueString) => { + const [key, value] = keyValueString.split("="); + if (key && typeof key == "string") { + cookieObject[key.replace(/^ +| +$/, "")] = + value && typeof value == "string" + ? value.replace(/^ +| +$/, "") + : null; + } + }); + + return cookieObject; +} diff --git a/console-colors.js b/console-colors.ts similarity index 91% rename from console-colors.js rename to console-colors.ts index 708acf6..4d0e6a6 100644 --- a/console-colors.js +++ b/console-colors.ts @@ -28,4 +28,4 @@ const colors = { BgGray: "\x1b[100m", }; -module.exports = colors; +export default colors; diff --git a/engine/dsql.js b/engine/dsql.ts similarity index 84% rename from engine/dsql.js rename to engine/dsql.ts index 2b0ee7b..266088a 100644 --- a/engine/dsql.js +++ b/engine/dsql.ts @@ -1,17 +1,17 @@ #! /usr/bin/env node -// @ts-check -const fs = require("fs"); -const path = require("path"); -const { execSync } = require("child_process"); +import fs from "fs"; +import path from "path"; +import { execSync } from "child_process"; require("dotenv").config({ path: path.resolve(process.cwd(), ".env"), }); -const datasquirel = require("../index"); -const colors = require("../console-colors"); -const createDbFromSchema = require("../package-shared/shell/createDbFromSchema"); +import datasquirel from "../index"; +import colors from "../console-colors"; +import createDbFromSchema from "../package-shared/shell/createDbFromSchema"; +import { DSQL_DatabaseSchemaType } from "../package-shared/types"; if (!fs.existsSync(path.resolve(process.cwd(), ".env"))) { console.log(".env file not found"); @@ -45,9 +45,8 @@ if (!DSQL_PASS?.match(/./)) { const dbSchemaLocalFilePath = path.resolve(process.cwd(), "dsql.schema.json"); -async function run() { - /** @type {any} */ - let schemaData; +export default async function run() { + let schemaData: any; if (DSQL_KEY && DSQL_REF_DB_NAME?.match(/./)) { const dbSchemaDataResponse = await datasquirel.getSchema({ @@ -66,8 +65,8 @@ async function run() { process.exit(); } - /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType} */ // @ts-ignore - let fetchedDbSchemaObject = dbSchemaDataResponse.payload; + let fetchedDbSchemaObject = + dbSchemaDataResponse.payload as DSQL_DatabaseSchemaType; if (DSQL_DB_NAME) fetchedDbSchemaObject.dbFullName = DSQL_DB_NAME; schemaData = [fetchedDbSchemaObject]; @@ -129,8 +128,6 @@ async function run() { ); } -// let timeout; - let interval; if (fs.existsSync(dbSchemaLocalFilePath) && !DSQL_KEY?.match(/....../)) { diff --git a/engine/dump.js b/engine/dump.ts similarity index 87% rename from engine/dump.js rename to engine/dump.ts index a19d519..6139f1b 100644 --- a/engine/dump.js +++ b/engine/dump.ts @@ -1,9 +1,8 @@ #! /usr/bin/env node -// @ts-check -const fs = require("fs"); -const path = require("path"); -const { execSync } = require("child_process"); +import fs from "fs"; +import path from "path"; +import { execSync } from "child_process"; require("dotenv").config({ path: path.resolve(process.cwd(), ".env"), @@ -57,6 +56,6 @@ try { //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// -} catch (/** @type {*} */ error) { +} catch (error: any) { console.log("Dump Error: ", error.message); } diff --git a/index.d.ts b/index.d.ts deleted file mode 100644 index 837c3d5..0000000 --- a/index.d.ts +++ /dev/null @@ -1,75 +0,0 @@ -import get = require("./utils/get"); -import post = require("./utils/post"); -export namespace media { - export { uploadImage }; - export { uploadFile }; - export { deleteFile }; -} -export namespace user { - export { createUser }; - export let deleteUser: typeof import("./users/delete-user"); - export { loginUser }; - export { sendEmailCode }; - export { logoutUser }; - export { userAuth }; - export { reAuthUser }; - export { updateUser }; - export { getUser }; - export { getToken }; - export { validateToken }; - export let validateTempEmailCode: typeof import("./users/validate-temp-email-code"); - export namespace social { - export { loginWithGoogle }; - export { loginWithGithub }; - } -} -import getSchema = require("./utils/get-schema"); -import datasquirelClient = require("./client"); -export namespace sql { - export { sqlGenerator }; - export { sqlInsertGenerator }; - export { sqlDeleteGenerator }; - export { trimSql as trim }; -} -import parseCookies = require("./package-shared/utils/backend/parseCookies"); -import httpRequest = require("./package-shared/functions/backend/httpRequest"); -import uploadImage = require("./utils/upload-image"); -import uploadFile = require("./utils/upload-file"); -import deleteFile = require("./utils/delete-file"); -import createUser = require("./users/add-user"); -import loginUser = require("./users/login-user"); -import sendEmailCode = require("./users/send-email-code"); -import logoutUser = require("./users/logout-user"); -import userAuth = require("./users/user-auth"); -import reAuthUser = require("./users/reauth-user"); -import updateUser = require("./users/update-user"); -import getUser = require("./users/get-user"); -import getToken = require("./users/get-token"); -import validateToken = require("./users/validate-token"); -import loginWithGoogle = require("./users/social/google-auth"); -import loginWithGithub = require("./users/social/github-auth"); -import sqlGenerator = require("./package-shared/functions/dsql/sql/sql-generator"); -import sqlInsertGenerator = require("./package-shared/functions/dsql/sql/sql-insert-generator"); -import sqlDeleteGenerator = require("./package-shared/functions/dsql/sql/sql-delete-generator"); -import trimSql = require("./package-shared/utils/trim-sql"); -export declare namespace utils { - export namespace crypto { - let encrypt: ({ data, encryptionKey, encryptionSalt }: { - data: string; - encryptionKey?: string; - encryptionSalt?: string; - }) => string | null; - let decrypt: ({ encryptedString, encryptionKey, encryptionSalt }: { - encryptedString: string; - encryptionKey?: string; - encryptionSalt?: string; - }) => string; - let hash: ({ password, encryptionKey }: { - password: string; - encryptionKey?: string; - }) => string; - } - export { parseCookies }; - export { httpRequest }; -} -export { get, post, getSchema, datasquirelClient as client }; diff --git a/index.js b/index.js deleted file mode 100644 index 927d3c1..0000000 --- a/index.js +++ /dev/null @@ -1,104 +0,0 @@ -// @ts-check - -/** - * Imports - */ -const get = require("./utils/get"); -const post = require("./utils/post"); -const getSchema = require("./utils/get-schema"); - -const uploadImage = require("./utils/upload-image"); -const uploadFile = require("./utils/upload-file"); -const deleteFile = require("./utils/delete-file"); - -const createUser = require("./users/add-user"); -const updateUser = require("./users/update-user"); -const loginUser = require("./users/login-user"); -const sendEmailCode = require("./users/send-email-code"); -const logoutUser = require("./users/logout-user"); - -const userAuth = require("./users/user-auth"); -const reAuthUser = require("./users/reauth-user"); -const getUser = require("./users/get-user"); - -const loginWithGoogle = require("./users/social/google-auth"); -const loginWithGithub = require("./users/social/github-auth"); -const getToken = require("./users/get-token"); -const validateToken = require("./users/validate-token"); - -const datasquirelClient = require("./client"); -const sqlGenerator = require("./package-shared/functions/dsql/sql/sql-generator"); -const sqlInsertGenerator = require("./package-shared/functions/dsql/sql/sql-insert-generator"); -const sqlDeleteGenerator = require("./package-shared/functions/dsql/sql/sql-delete-generator"); -const trimSql = require("./package-shared/utils/trim-sql"); -const parseCookies = require("./package-shared/utils/backend/parseCookies"); -const httpRequest = require("./package-shared/functions/backend/httpRequest"); - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// - -/** - * User Functions Object - */ -const user = { - createUser: createUser, - deleteUser: require("./users/delete-user"), - loginUser: loginUser, - sendEmailCode: sendEmailCode, - logoutUser: logoutUser, - userAuth: userAuth, - reAuthUser: reAuthUser, - updateUser: updateUser, - getUser: getUser, - getToken: getToken, - validateToken: validateToken, - validateTempEmailCode: require("./users/validate-temp-email-code"), - social: { - loginWithGoogle: loginWithGoogle, - loginWithGithub: loginWithGithub, - }, -}; - -/** - * Media Functions Object - */ -const media = { - uploadImage: uploadImage, - uploadFile: uploadFile, - deleteFile: deleteFile, -}; - -/** - * SQL Utils - */ -const sql = { - sqlGenerator, - sqlInsertGenerator, - sqlDeleteGenerator, - trim: trimSql, -}; - -/** - * Main Export - */ -const datasquirel = { - get, - post, - media, - user, - getSchema, - client: datasquirelClient, - sql, - utils: { - crypto: { - encrypt: require("./package-shared/functions/dsql/encrypt"), - decrypt: require("./package-shared/functions/dsql/decrypt"), - hash: require("./package-shared/functions/dsql/hashPassword"), - }, - parseCookies, - httpRequest, - }, -}; - -module.exports = datasquirel; diff --git a/index.ts b/index.ts new file mode 100644 index 0000000..1a5e1ca --- /dev/null +++ b/index.ts @@ -0,0 +1,104 @@ +// @ts-check + +/** + * Imports + */ +import get from "./utils/get"; +import post from "./utils/post"; +import getSchema from "./utils/get-schema"; + +import uploadImage from "./utils/upload-image"; +import uploadFile from "./utils/upload-file"; +import deleteFile from "./utils/delete-file"; + +import createUser from "./users/add-user"; +import updateUser from "./users/update-user"; +import loginUser from "./users/login-user"; +import sendEmailCode from "./users/send-email-code"; +import logoutUser from "./users/logout-user"; + +import userAuth from "./users/user-auth"; +import reAuthUser from "./users/reauth-user"; +import getUser from "./users/get-user"; + +import loginWithGoogle from "./users/social/google-auth"; +import loginWithGithub from "./users/social/github-auth"; +import getToken from "./users/get-token"; +import validateToken from "./users/validate-token"; + +import datasquirelClient from "./client"; +import sqlGenerator from "./package-shared/functions/dsql/sql/sql-generator"; +import sqlInsertGenerator from "./package-shared/functions/dsql/sql/sql-insert-generator"; +import sqlDeleteGenerator from "./package-shared/functions/dsql/sql/sql-delete-generator"; +import trimSql from "./package-shared/utils/trim-sql"; +import parseCookies from "./package-shared/utils/backend/parseCookies"; +import httpRequest from "./package-shared/functions/backend/httpRequest"; + +//////////////////////////////////////// +//////////////////////////////////////// +//////////////////////////////////////// + +/** + * User Functions Object + */ +const user = { + createUser: createUser, + deleteUser: require("./users/delete-user"), + loginUser: loginUser, + sendEmailCode: sendEmailCode, + logoutUser: logoutUser, + userAuth: userAuth, + reAuthUser: reAuthUser, + updateUser: updateUser, + getUser: getUser, + getToken: getToken, + validateToken: validateToken, + validateTempEmailCode: require("./users/validate-temp-email-code"), + social: { + loginWithGoogle: loginWithGoogle, + loginWithGithub: loginWithGithub, + }, +}; + +/** + * Media Functions Object + */ +const media = { + uploadImage: uploadImage, + uploadFile: uploadFile, + deleteFile: deleteFile, +}; + +/** + * SQL Utils + */ +const sql = { + sqlGenerator, + sqlInsertGenerator, + sqlDeleteGenerator, + trim: trimSql, +}; + +/** + * Main Export + */ +const datasquirel = { + get, + post, + media, + user, + getSchema, + client: datasquirelClient, + sql, + utils: { + crypto: { + encrypt: require("./package-shared/functions/dsql/encrypt"), + decrypt: require("./package-shared/functions/dsql/decrypt"), + hash: require("./package-shared/functions/dsql/hashPassword"), + }, + parseCookies, + httpRequest, + }, +}; + +export default datasquirel; diff --git a/package-shared/functions/api/query/get.d.ts b/package-shared/functions/api/query/get.d.ts deleted file mode 100644 index 2caa093..0000000 --- a/package-shared/functions/api/query/get.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -declare function _exports({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: { - query: string; - queryValues?: (string | number)[]; - dbFullName: string; - tableName?: string; - dbSchema?: import("../../../types").DSQL_DatabaseSchemaType; - useLocal?: boolean; -}): Promise; -export = _exports; diff --git a/package-shared/functions/api/query/get.js b/package-shared/functions/api/query/get.ts similarity index 76% rename from package-shared/functions/api/query/get.js rename to package-shared/functions/api/query/get.ts index ca5ce26..f121159 100644 --- a/package-shared/functions/api/query/get.js +++ b/package-shared/functions/api/query/get.ts @@ -1,30 +1,29 @@ // @ts-check -const _ = require("lodash"); -const serverError = require("../../backend/serverError"); -const runQuery = require("../../backend/db/runQuery"); +import _ from "lodash"; +import serverError from "../../backend/serverError"; +import runQuery from "../../backend/db/runQuery"; + +type Param = { + query: string; + queryValues?: (string | number)[]; + dbFullName: string; + tableName?: string; + dbSchema?: import("../../../types").DSQL_DatabaseSchemaType; + useLocal?: boolean; +}; /** * # Get Function FOr API - * - * @param {object} params - * @param {string} params.query - * @param {(string|number)[]} [params.queryValues] - * @param {string} params.dbFullName - * @param {string} [params.tableName] - * @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema] - * @param {boolean} [params.useLocal] - * - * @returns {Promise} */ -module.exports = async function apiGet({ +export default async function apiGet({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, -}) { +}: Param): Promise { if ( typeof query == "string" && query.match(/^alter|^delete|information_schema|databases|^create/i) @@ -51,7 +50,9 @@ module.exports = async function apiGet({ }); /** @type {import("../../../types").DSQL_TableSchemaType | undefined} */ - let tableSchema; + let tableSchema: + | import("../../../types").DSQL_TableSchemaType + | undefined; if (dbSchema) { const targetTable = dbSchema.tables.find( @@ -77,14 +78,14 @@ module.exports = async function apiGet({ results = result; /** @type {import("../../../types").GetReturn} */ - const resObject = { + const resObject: import("../../../types").GetReturn = { success: true, payload: results, schema: tableName && tableSchema ? tableSchema : undefined, }; return resObject; - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { serverError({ component: "/api/query/get/lines-85-94", message: error.message, @@ -92,4 +93,4 @@ module.exports = async function apiGet({ return { success: false, payload: null, error: error.message }; } -}; +} diff --git a/package-shared/functions/api/query/post.d.ts b/package-shared/functions/api/query/post.d.ts deleted file mode 100644 index b80a593..0000000 --- a/package-shared/functions/api/query/post.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -declare function _exports({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: { - query: any; - queryValues?: (string | number)[]; - dbFullName: string; - tableName?: string; - dbSchema?: import("../../../types").DSQL_DatabaseSchemaType; - useLocal?: boolean; -}): Promise; -export = _exports; diff --git a/package-shared/functions/api/query/post.js b/package-shared/functions/api/query/post.ts similarity index 75% rename from package-shared/functions/api/query/post.js rename to package-shared/functions/api/query/post.ts index c78fbfb..9c2e537 100644 --- a/package-shared/functions/api/query/post.js +++ b/package-shared/functions/api/query/post.ts @@ -1,30 +1,28 @@ -// @ts-check +import _ from "lodash"; +import serverError from "../../backend/serverError"; +import runQuery from "../../backend/db/runQuery"; +import { DSQL_DatabaseSchemaType, PostReturn } from "../../../types"; -const _ = require("lodash"); -const serverError = require("../../backend/serverError"); -const runQuery = require("../../backend/db/runQuery"); +type Param = { + query: any; + queryValues?: (string | number)[]; + dbFullName: string; + tableName?: string; + dbSchema?: DSQL_DatabaseSchemaType; + useLocal?: boolean; +}; /** * # Post Function For API - * - * @param {object} params - * @param {any} params.query - * @param {(string|number)[]} [params.queryValues] - * @param {string} params.dbFullName - * @param {string} [params.tableName] - * @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema] - * @param {boolean} [params.useLocal] - * - * @returns {Promise} */ -module.exports = async function apiPost({ +export default async function apiPost({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, -}) { +}: Param): Promise { if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) { return { success: false, msg: "Wrong Input" }; } @@ -37,7 +35,7 @@ module.exports = async function apiPost({ } /** @type {any} */ - let results; + let results: any; /** * Create new user folder and file @@ -59,7 +57,9 @@ module.exports = async function apiPost({ if (error) throw error; /** @type {import("../../../types").DSQL_TableSchemaType | undefined} */ - let tableSchema; + let tableSchema: + | import("../../../types").DSQL_TableSchemaType + | undefined; if (dbSchema) { const targetTable = dbSchema.tables.find( @@ -76,6 +76,7 @@ module.exports = async function apiPost({ delete clonedTargetTable.updateData; delete clonedTargetTable.tableNameOld; delete clonedTargetTable.indexes; + tableSchema = clonedTargetTable; } } @@ -86,9 +87,7 @@ module.exports = async function apiPost({ error: error, schema: tableName && tableSchema ? tableSchema : undefined, }; - - //////////////////////////////////////// - } catch (/** @type {any} */ error) { + } catch (error: any) { serverError({ component: "/api/query/post/lines-132-142", message: error.message, @@ -100,4 +99,4 @@ module.exports = async function apiPost({ error: error.message, }; } -}; +} diff --git a/package-shared/functions/api/social-login/facebookLogin.js b/package-shared/functions/api/social-login/facebookLogin.js deleted file mode 100755 index f17a161..0000000 --- a/package-shared/functions/api/social-login/facebookLogin.js +++ /dev/null @@ -1,128 +0,0 @@ -// @ts-check - -/** - * ============================================================================== - * Imports - * ============================================================================== - */ - -const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER"); -const handleNodemailer = require("../../backend/handleNodemailer"); -const serverError = require("../../backend/serverError"); -const hashPassword = require("../../dsql/hashPassword"); - -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// - -/** - * ============================================================================== - * Main Function - * ============================================================================== - * @param {object} params - parameters object - * @param {any} params.body - * @param {import("../../../types").UserType} params.usertype - */ -module.exports = async function facebookLogin({ usertype, body }) { - try { - //////////////////////////////////////////////// - //////////////////////////////////////////////// - //////////////////////////////////////////////// - - const foundUser = await DB_HANDLER( - `SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'` - ); - - if (foundUser && foundUser[0]) { - return foundUser[0]; - } - - //////////////////////////////////////////////// - //////////////////////////////////////////////// - //////////////////////////////////////////////// - - let socialHashedPassword = hashPassword({ - password: body.facebookUserId, - }); - - let newUser = await DB_HANDLER(`INSERT INTO ${usertype} ( - first_name, - last_name, - social_platform, - social_name, - email, - image, - image_thumbnail, - password, - verification_status, - social_login, - social_id, - terms_agreement, - date_created, - date_code - ) VALUES ( - '${body.facebookUserFirstName}', - '${body.facebookUserLastName}', - 'facebook', - 'facebook_${ - body.facebookUserEmail - ? body.facebookUserEmail.replace(/@.*/, "") - : body.facebookUserFirstName.toLowerCase() - }', - '${body.facebookUserEmail}', - '${body.facebookUserImage}', - '${body.facebookUserImage}', - '${socialHashedPassword}', - '1', - '1', - '${body.facebookUserId}', - '1', - '${Date()}', - '${Date.now()}' - )`); - - const newFoundUser = await DB_HANDLER( - `SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'` - ); - - //////////////////////////////////////////////// - //////////////////////////////////////////////// - //////////////////////////////////////////////// - - /** - * Send email notifications to admin - * - * @description Send verification email to newly created agent - */ - // handleNodemailer({ - // to: "", - // subject: "New Registered Buyer", - // text: "We have a new registered Buyer from facebook", - // html: ` - //

${newFoundUser[0].first_name} ${newFoundUser[0].last_name} just registered from facebook.

- //

We have a new buyer registration

- //
Name: ${newFoundUser[0].first_name} ${newFoundUser[0].last_name}
- //
Email: ${newFoundUser[0].email}
- //
Site: ${process.env.DSQL_DB_HOST}
- // `, - // }).catch((error) => { - // console.log( - // "error in mail notification for new Facebook user =>", - // error.message - // ); - // }); - } catch (/** @type {any} */ error) { - serverError({ - component: "functions/backend/facebookLogin", - message: error.message, - }); - } - - return { - isFacebookAuthValid: false, - newFoundUser: null, - }; -}; diff --git a/package-shared/functions/api/social-login/facebookLogin.ts b/package-shared/functions/api/social-login/facebookLogin.ts new file mode 100755 index 0000000..82dc6a5 --- /dev/null +++ b/package-shared/functions/api/social-login/facebookLogin.ts @@ -0,0 +1,80 @@ +import { UserType } from "../../../types"; +import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER"; +import handleNodemailer from "../../backend/handleNodemailer"; +import serverError from "../../backend/serverError"; +import hashPassword from "../../dsql/hashPassword"; + +/** + * # Facebook Login + */ +export default async function facebookLogin({ + usertype, + body, +}: { + body: any; + usertype: UserType; +}) { + try { + const foundUser = await DB_HANDLER( + `SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'` + ); + + if (foundUser && foundUser[0]) { + return foundUser[0]; + } + + let socialHashedPassword = hashPassword({ + password: body.facebookUserId, + }); + + let newUser = await DB_HANDLER(`INSERT INTO ${usertype} ( + first_name, + last_name, + social_platform, + social_name, + email, + image, + image_thumbnail, + password, + verification_status, + social_login, + social_id, + terms_agreement, + date_created, + date_code + ) VALUES ( + '${body.facebookUserFirstName}', + '${body.facebookUserLastName}', + 'facebook', + 'facebook_${ + body.facebookUserEmail + ? body.facebookUserEmail.replace(/@.*/, "") + : body.facebookUserFirstName.toLowerCase() + }', + '${body.facebookUserEmail}', + '${body.facebookUserImage}', + '${body.facebookUserImage}', + '${socialHashedPassword}', + '1', + '1', + '${body.facebookUserId}', + '1', + '${Date()}', + '${Date.now()}' + )`); + + const newFoundUser = await DB_HANDLER( + `SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'` + ); + } catch (/** @type {any} */ error: any) { + serverError({ + component: "functions/backend/facebookLogin", + message: error.message, + }); + } + + return { + isFacebookAuthValid: false, + newFoundUser: null, + }; +} diff --git a/package-shared/functions/api/social-login/githubLogin.d.ts b/package-shared/functions/api/social-login/githubLogin.d.ts deleted file mode 100644 index cb8276f..0000000 --- a/package-shared/functions/api/social-login/githubLogin.d.ts +++ /dev/null @@ -1,135 +0,0 @@ -declare namespace _exports { - export { GithubUserPayload }; -} -declare function _exports({ code, clientId, clientSecret }: { - code: string; - clientId: string; - clientSecret: string; -}): Promise; -export = _exports; -type GithubUserPayload = { - /** - * - Full name merged eg. "JohnDoe" - */ - login: string; - /** - * - github user id - */ - id: number; - /** - * - Some other id - */ - node_id: string; - /** - * - profile picture - */ - avatar_url: string; - /** - * - some other id - */ - gravatar_id: string; - /** - * - Github user URL - */ - url: string; - /** - * - User html URL - whatever that means - */ - html_url: string; - /** - * - Followers URL - */ - followers_url: string; - /** - * - Following URL - */ - following_url: string; - /** - * - Gists URL - */ - gists_url: string; - /** - * - Starred URL - */ - starred_url: string; - /** - * - Subscriptions URL - */ - subscriptions_url: string; - /** - * - Organizations URL - */ - organizations_url: string; - /** - * - Repositories URL - */ - repos_url: string; - /** - * - Received Events URL - */ - received_events_url: string; - /** - * - Common value => "User" - */ - type: string; - /** - * - Is site admin or not? Boolean - */ - site_admin: boolean; - /** - * - More like "username" - */ - name: string; - /** - * - User company - */ - company: string; - /** - * - User blog URL - */ - blog: string; - /** - * - User Location - */ - location: string; - /** - * - User Email - */ - email: string; - /** - * - Is user hireable - */ - hireable: string; - /** - * - User bio - */ - bio: string; - /** - * - User twitter username - */ - twitter_username: string; - /** - * - Number of public repositories - */ - public_repos: number; - /** - * - Number of public gists - */ - public_gists: number; - /** - * - Number of followers - */ - followers: number; - /** - * - Number of following - */ - following: number; - /** - * - Date created - */ - created_at: string; - /** - * - Date updated - */ - updated_at: string; -}; diff --git a/package-shared/functions/api/social-login/githubLogin.js b/package-shared/functions/api/social-login/githubLogin.js deleted file mode 100755 index 1bb2329..0000000 --- a/package-shared/functions/api/social-login/githubLogin.js +++ /dev/null @@ -1,160 +0,0 @@ -// @ts-check - -const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER"); -const httpsRequest = require("../../backend/httpsRequest"); - -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// - -/** - * - * @typedef {object} GithubUserPayload - * @property {string} login - Full name merged eg. "JohnDoe" - * @property {number} id - github user id - * @property {string} node_id - Some other id - * @property {string} avatar_url - profile picture - * @property {string} gravatar_id - some other id - * @property {string} url - Github user URL - * @property {string} html_url - User html URL - whatever that means - * @property {string} followers_url - Followers URL - * @property {string} following_url - Following URL - * @property {string} gists_url - Gists URL - * @property {string} starred_url - Starred URL - * @property {string} subscriptions_url - Subscriptions URL - * @property {string} organizations_url - Organizations URL - * @property {string} repos_url - Repositories URL - * @property {string} received_events_url - Received Events URL - * @property {string} type - Common value => "User" - * @property {boolean} site_admin - Is site admin or not? Boolean - * @property {string} name - More like "username" - * @property {string} company - User company - * @property {string} blog - User blog URL - * @property {string} location - User Location - * @property {string} email - User Email - * @property {string} hireable - Is user hireable - * @property {string} bio - User bio - * @property {string} twitter_username - User twitter username - * @property {number} public_repos - Number of public repositories - * @property {number} public_gists - Number of public gists - * @property {number} followers - Number of followers - * @property {number} following - Number of following - * @property {string} created_at - Date created - * @property {string} updated_at - Date updated - */ - -/** - * Login/signup a github user - * ============================================================================== - * @async - * - * @param {Object} params - foundUser if any - * @param {string} params.code - github auth token - * @param {string} params.clientId - github client Id - * @param {string} params.clientSecret - github client Secret - * - * @returns {Promise} - */ -module.exports = async function githubLogin({ code, clientId, clientSecret }) { - /** @type {GithubUserPayload | undefined} */ - let gitHubUser; - - //////////////////////////////////////////////// - //////////////////////////////////////////////// - //////////////////////////////////////////////// - - try { - /** - * Create new user folder and file - * - * @description Create new user folder and file - */ - // const response = await fetch(`https://github.com/login/oauth/access_token?client_id=${process.env.DSQL_GITHUB_ID}`); - const response = await httpsRequest({ - method: "POST", - hostname: "github.com", - path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`, - headers: { - Accept: "application/json", - "User-Agent": "*", - }, - scheme: "https", - }); - - // `https://github.com/login/oauth/access_token?client_id=${process.env.DSQL_GITHUB_ID}&client_secret=${process.env.DSQL_GITHUB_SECRET}&code=${code}`, - // body: JSON.stringify({ - // client_id: process.env.DSQL_GITHUB_ID, - // client_secret: process.env.DSQL_GITHUB_SECRET, - // code: code, - // }), - - const accessTokenObject = JSON.parse(response); - - if (!accessTokenObject?.access_token) { - return gitHubUser; - } - - //////////////////////////////////////////////// - //////////////////////////////////////////////// - //////////////////////////////////////////////// - - const userDataResponse = await httpsRequest({ - method: "GET", - hostname: "api.github.com", - path: "/user", - headers: { - Authorization: `Bearer ${accessTokenObject.access_token}`, - "User-Agent": "*", - }, - scheme: "https", - }); - - gitHubUser = JSON.parse(userDataResponse); - - //////////////////////////////////////////////// - //////////////////////////////////////////////// - //////////////////////////////////////////////// - - if (!gitHubUser?.email && gitHubUser) { - const existingGithubUser = await DB_HANDLER( - `SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'` - ); - - if (existingGithubUser && existingGithubUser[0]) { - gitHubUser.email = existingGithubUser[0].email; - } - } - - //////////////////////////////////////////////// - //////////////////////////////////////////////// - //////////////////////////////////////////////// - } catch (/** @type {any} */ error) { - //////////////////////////////////////////////// - //////////////////////////////////////////////// - //////////////////////////////////////////////// - - console.log( - "ERROR in githubLogin.js backend function =>", - error.message - ); - - // serverError({ - // component: "/api/social-login/github-auth/catch-error", - // message: error.message, - // user: user, - // }); - - //////////////////////////////////////////////// - //////////////////////////////////////////////// - //////////////////////////////////////////////// - } - - //////////////////////////////////////////////// - //////////////////////////////////////////////// - //////////////////////////////////////////////// - - return gitHubUser; -}; diff --git a/package-shared/functions/api/social-login/githubLogin.ts b/package-shared/functions/api/social-login/githubLogin.ts new file mode 100755 index 0000000..6996803 --- /dev/null +++ b/package-shared/functions/api/social-login/githubLogin.ts @@ -0,0 +1,102 @@ +import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER"; +import httpsRequest from "../../backend/httpsRequest"; + +export interface GithubUserPayload { + login: string; + id: number; + node_id: string; + avatar_url: string; + gravatar_id: string; + url: string; + html_url: string; + followers_url: string; + following_url: string; + gists_url: string; + starred_url: string; + subscriptions_url: string; + organizations_url: string; + repos_url: string; + received_events_url: string; + type: string; + site_admin: boolean; + name: string; + company: string; + blog: string; + location: string; + email: string; + hireable: string; + bio: string; + twitter_username: string; + public_repos: number; + public_gists: number; + followers: number; + following: number; + created_at: string; + updated_at: string; +} + +type Param = { + code: string; + clientId: string; + clientSecret: string; +}; + +/** + * # Login/signup a github user + */ +export default async function githubLogin({ + code, + clientId, + clientSecret, +}: Param): Promise { + let gitHubUser: GithubUserPayload | undefined; + + try { + const response = await httpsRequest({ + method: "POST", + hostname: "github.com", + path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`, + headers: { + Accept: "application/json", + "User-Agent": "*", + }, + scheme: "https", + }); + + const accessTokenObject = JSON.parse(response as string); + + if (!accessTokenObject?.access_token) { + return gitHubUser; + } + + const userDataResponse = await httpsRequest({ + method: "GET", + hostname: "api.github.com", + path: "/user", + headers: { + Authorization: `Bearer ${accessTokenObject.access_token}`, + "User-Agent": "*", + }, + scheme: "https", + }); + + gitHubUser = JSON.parse(userDataResponse as string); + + if (!gitHubUser?.email && gitHubUser) { + const existingGithubUser = await DB_HANDLER( + `SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'` + ); + + if (existingGithubUser && existingGithubUser[0]) { + gitHubUser.email = existingGithubUser[0].email; + } + } + } catch (/** @type {any} */ error: any) { + console.log( + "ERROR in githubLogin.js backend function =>", + error.message + ); + } + + return gitHubUser; +} diff --git a/package-shared/functions/api/social-login/googleLogin.js b/package-shared/functions/api/social-login/googleLogin.ts similarity index 64% rename from package-shared/functions/api/social-login/googleLogin.js rename to package-shared/functions/api/social-login/googleLogin.ts index bd4d57a..3b6ea82 100755 --- a/package-shared/functions/api/social-login/googleLogin.js +++ b/package-shared/functions/api/social-login/googleLogin.ts @@ -1,44 +1,23 @@ -// @ts-check +import fs from "fs"; +import { OAuth2Client } from "google-auth-library"; +import serverError from "../../backend/serverError"; +import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER"; +import hashPassword from "../../dsql/hashPassword"; + +type Param = { + usertype: string; + foundUser: any; + isSocialValidated: boolean; + isUserValid: boolean; + reqBody: any; + serverRes: any; + loginFailureReason: any; +}; /** - * ============================================================================== - * Imports - * ============================================================================== + * # Google Login */ -const fs = require("fs"); - -//////////////////////////////////////////////// -//////////////////////////////////////////////// -//////////////////////////////////////////////// - -const { OAuth2Client } = require("google-auth-library"); - -const serverError = require("../../backend/serverError"); -const { ServerResponse } = require("http"); -const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER"); -const hashPassword = require("../../dsql/hashPassword"); - -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// - -/** - * ============================================================================== - * Main Function - * ============================================================================== - * @param {Object} params - * @param {string} params.usertype - * @param {any} params.foundUser - * @param {boolean} params.isSocialValidated - * @param {boolean} params.isUserValid - * @param {any} params.reqBody - * @param {any} params.serverRes - * @param {any} params.loginFailureReason - */ -module.exports = async function googleLogin({ +export default async function googleLogin({ usertype, foundUser, isSocialValidated, @@ -46,7 +25,7 @@ module.exports = async function googleLogin({ reqBody, serverRes, loginFailureReason, -}) { +}: Param) { const client = new OAuth2Client( process.env.NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID ); @@ -156,11 +135,7 @@ module.exports = async function googleLogin({ newFoundUser = await DB_HANDLER( `SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'` ); - - //////////////////////////////////////////////// - //////////////////////////////////////////////// - //////////////////////////////////////////////// - } catch (/** @type {any} */ error) { + } catch (error: any) { serverError({ component: "googleLogin", message: error.message, @@ -172,9 +147,5 @@ module.exports = async function googleLogin({ isSocialValidated = false; } - //////////////////////////////////////////////// - //////////////////////////////////////////////// - //////////////////////////////////////////////// - return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser }; -}; +} diff --git a/package-shared/functions/api/social-login/handleSocialDb.d.ts b/package-shared/functions/api/social-login/handleSocialDb.d.ts deleted file mode 100644 index 31dd893..0000000 --- a/package-shared/functions/api/social-login/handleSocialDb.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare const _exports: import("../../../types").HandleSocialDbFunction; -export = _exports; diff --git a/package-shared/functions/api/social-login/handleSocialDb.js b/package-shared/functions/api/social-login/handleSocialDb.ts similarity index 88% rename from package-shared/functions/api/social-login/handleSocialDb.js rename to package-shared/functions/api/social-login/handleSocialDb.ts index 5db76a7..c264dc4 100755 --- a/package-shared/functions/api/social-login/handleSocialDb.js +++ b/package-shared/functions/api/social-login/handleSocialDb.ts @@ -1,18 +1,20 @@ -// @ts-check - -const fs = require("fs"); -const handleNodemailer = require("../../backend/handleNodemailer"); -const path = require("path"); -const addMariadbUser = require("../../backend/addMariadbUser"); -const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); -const encrypt = require("../../dsql/encrypt"); -const addDbEntry = require("../../backend/db/addDbEntry"); -const loginSocialUser = require("./loginSocialUser"); +import fs from "fs"; +import handleNodemailer from "../../backend/handleNodemailer"; +import path from "path"; +import addMariadbUser from "../../backend/addMariadbUser"; +import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler"; +import encrypt from "../../dsql/encrypt"; +import addDbEntry from "../../backend/db/addDbEntry"; +import loginSocialUser from "./loginSocialUser"; +import { + APILoginFunctionReturn, + HandleSocialDbFunctionParams, +} from "../../../types"; /** - * @type {import("../../../types").HandleSocialDbFunction} + * # Handle Social DB */ -module.exports = async function handleSocialDb({ +export default async function handleSocialDb({ database, social_id, email, @@ -22,7 +24,7 @@ module.exports = async function handleSocialDb({ supEmail, additionalFields, useLocal, -}) { +}: HandleSocialDbFunctionParams): Promise { try { const existingSocialIdUserQuery = `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `; const existingSocialIdUserValues = [ @@ -99,8 +101,7 @@ module.exports = async function handleSocialDb({ data: social_id.toString(), }); - /** @type {any} */ - const data = { + const data: { [k: string]: any } = { social_login: "1", verification_status: supEmail ? "0" : "1", password: socialHashedPassword, @@ -173,7 +174,7 @@ module.exports = async function handleSocialDb({ ) .replace(/{{host}}/, process.env.DSQL_HOST || "") .replace(/{{token}}/, generatedToken || ""), - }).then((mail) => {}); + }).then(() => {}); } const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR; @@ -230,7 +231,7 @@ module.exports = async function handleSocialDb({ msg: "Social User Failed to insert in 'handleSocialDb.js' backend function", }; } - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log( "ERROR in 'handleSocialDb.js' backend function =>", error.message @@ -242,4 +243,4 @@ module.exports = async function handleSocialDb({ msg: error.message, }; } -}; +} diff --git a/package-shared/functions/api/social-login/loginSocialUser.d.ts b/package-shared/functions/api/social-login/loginSocialUser.d.ts deleted file mode 100644 index a4b06c4..0000000 --- a/package-shared/functions/api/social-login/loginSocialUser.d.ts +++ /dev/null @@ -1,37 +0,0 @@ -export = loginSocialUser; -/** - * Function to login social user - * ============================================================================== - * @description This function logs in the user after 'handleSocialDb' function finishes - * the user creation or confirmation process - * - * @async - * - * @param {object} params - function parameters inside an object - * @param {{ - * first_name: string, - * last_name: string, - * email: string, - * social_id: string|number, - * }} params.user - user object - * @param {string} params.social_platform - Whether its "google" or "facebook" or "github" - * @param {any} [params.invitation] - A query object if user was invited - * @param {string} [params.database] - Target Database - * @param {string[]} [params.additionalFields] - Additional fields to be added to the user payload - * @param {boolean} [params.useLocal] - * - * @returns {Promise} - */ -declare function loginSocialUser({ user, social_platform, invitation, database, additionalFields, useLocal, }: { - user: { - first_name: string; - last_name: string; - email: string; - social_id: string | number; - }; - social_platform: string; - invitation?: any; - database?: string; - additionalFields?: string[]; - useLocal?: boolean; -}): Promise; diff --git a/package-shared/functions/api/social-login/loginSocialUser.js b/package-shared/functions/api/social-login/loginSocialUser.ts similarity index 64% rename from package-shared/functions/api/social-login/loginSocialUser.js rename to package-shared/functions/api/social-login/loginSocialUser.ts index 839db5f..b45d380 100755 --- a/package-shared/functions/api/social-login/loginSocialUser.js +++ b/package-shared/functions/api/social-login/loginSocialUser.ts @@ -1,42 +1,35 @@ -// @ts-check +import addAdminUserOnLogin from "../../backend/addAdminUserOnLogin"; +import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler"; +import { APILoginFunctionReturn } from "../../../types"; -const addAdminUserOnLogin = require("../../backend/addAdminUserOnLogin"); -const { ServerResponse } = require("http"); -const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); -const encrypt = require("../../dsql/encrypt"); -const getAuthCookieNames = require("../../backend/cookies/get-auth-cookie-names"); +type Param = { + user: { + first_name: string; + last_name: string; + email: string; + social_id: string | number; + }; + social_platform: string; + invitation?: any; + database?: string; + additionalFields?: string[]; + useLocal?: boolean; +}; /** * Function to login social user * ============================================================================== * @description This function logs in the user after 'handleSocialDb' function finishes * the user creation or confirmation process - * - * @async - * - * @param {object} params - function parameters inside an object - * @param {{ - * first_name: string, - * last_name: string, - * email: string, - * social_id: string|number, - * }} params.user - user object - * @param {string} params.social_platform - Whether its "google" or "facebook" or "github" - * @param {any} [params.invitation] - A query object if user was invited - * @param {string} [params.database] - Target Database - * @param {string[]} [params.additionalFields] - Additional fields to be added to the user payload - * @param {boolean} [params.useLocal] - * - * @returns {Promise} */ -async function loginSocialUser({ +export default async function loginSocialUser({ user, social_platform, invitation, database, additionalFields, useLocal, -}) { +}: Param): Promise { const foundUserQuery = `SELECT * FROM users WHERE email=? AND social_id=? AND social_platform=?`; const foundUserValues = [user.email, user.social_id, social_platform]; @@ -59,7 +52,7 @@ async function loginSocialUser({ Math.random().toString(36).substring(2); /** @type {import("../../../types").DATASQUIREL_LoggedInUser} */ - let userPayload = { + let userPayload: import("../../../types").DATASQUIREL_LoggedInUser = { id: foundUser[0].id, first_name: foundUser[0].first_name, last_name: foundUser[0].last_name, @@ -92,7 +85,7 @@ async function loginSocialUser({ } /** @type {import("../../../types").APILoginFunctionReturn} */ - let result = { + let result: import("../../../types").APILoginFunctionReturn = { success: true, payload: userPayload, csrf: csrfKey, @@ -100,5 +93,3 @@ async function loginSocialUser({ return result; } - -module.exports = loginSocialUser; diff --git a/package-shared/functions/api/users/api-create-user.d.ts b/package-shared/functions/api/users/api-create-user.d.ts deleted file mode 100644 index 18e5985..0000000 --- a/package-shared/functions/api/users/api-create-user.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare const _exports: import("../../../types").APICreateUserFunction; -export = _exports; diff --git a/package-shared/functions/api/users/api-create-user.js b/package-shared/functions/api/users/api-create-user.ts similarity index 87% rename from package-shared/functions/api/users/api-create-user.js rename to package-shared/functions/api/users/api-create-user.ts index 64a9458..224da0c 100644 --- a/package-shared/functions/api/users/api-create-user.js +++ b/package-shared/functions/api/users/api-create-user.ts @@ -1,19 +1,22 @@ // @ts-check -const addUsersTableToDb = require("../../backend/addUsersTableToDb"); -const addDbEntry = require("../../backend/db/addDbEntry"); -const updateUsersTableSchema = require("../../backend/updateUsersTableSchema"); -const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); -const hashPassword = require("../../dsql/hashPassword"); +import { APICreateUserFunctionParams } from "../../../types"; +import addUsersTableToDb from "../../backend/addUsersTableToDb"; +import addDbEntry from "../../backend/db/addDbEntry"; +import updateUsersTableSchema from "../../backend/updateUsersTableSchema"; +import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler"; +import hashPassword from "../../dsql/hashPassword"; -/** @type {import("../../../types").APICreateUserFunction} */ -module.exports = async function apiCreateUser({ +/** + * # API Create User + */ +export default async function apiCreateUser({ encryptionKey, payload, database, userId, useLocal, -}) { +}: APICreateUserFunctionParams) { const dbFullName = database; const API_USER_ID = userId || process.env.DSQL_API_USER_ID; @@ -73,9 +76,7 @@ module.exports = async function apiCreateUser({ }; } - const fieldsTitles = fields.map( - (/** @type {any} */ fieldObject) => fieldObject.Field - ); + const fieldsTitles = fields.map((fieldObject: any) => fieldObject.Field); let invalidField = null; @@ -159,4 +160,4 @@ module.exports = async function apiCreateUser({ payload: null, }; } -}; +} diff --git a/package-shared/functions/api/users/api-delete-user.d.ts b/package-shared/functions/api/users/api-delete-user.d.ts deleted file mode 100644 index 21e432c..0000000 --- a/package-shared/functions/api/users/api-delete-user.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -declare function _exports({ dbFullName, deletedUserId, useLocal, }: { - dbFullName: string; - deletedUserId: string | number; - useLocal?: boolean; -}): Promise<{ - success: boolean; - result?: any; - msg?: string; -}>; -export = _exports; diff --git a/package-shared/functions/api/users/api-delete-user.js b/package-shared/functions/api/users/api-delete-user.ts similarity index 66% rename from package-shared/functions/api/users/api-delete-user.js rename to package-shared/functions/api/users/api-delete-user.ts index b240daa..d1dc8bd 100644 --- a/package-shared/functions/api/users/api-delete-user.js +++ b/package-shared/functions/api/users/api-delete-user.ts @@ -1,23 +1,21 @@ -// @ts-check +import deleteDbEntry from "../../backend/db/deleteDbEntry"; +import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler"; -const deleteDbEntry = require("../../backend/db/deleteDbEntry"); -const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); +type Param = { + dbFullName: string; + deletedUserId: string | number; + useLocal?: boolean; +}; +type Return = { success: boolean; result?: any; msg?: string }; /** * # Update API User Function - * - * @param {object} params - * @param {string} params.dbFullName - * @param {string | number} params.deletedUserId - * @param {boolean} [params.useLocal] - * - * @returns {Promise<{ success: boolean, result?: any, msg?: string }>} */ -module.exports = async function apiDeleteUser({ +export default async function apiDeleteUser({ dbFullName, deletedUserId, useLocal, -}) { +}: Param): Promise { const existingUserQuery = `SELECT * FROM users WHERE id = ?`; const existingUserValues = [deletedUserId]; @@ -49,4 +47,4 @@ module.exports = async function apiDeleteUser({ success: true, result: deleteUser, }; -}; +} diff --git a/package-shared/functions/api/users/api-get-user.d.ts b/package-shared/functions/api/users/api-get-user.d.ts deleted file mode 100644 index fb49dc2..0000000 --- a/package-shared/functions/api/users/api-get-user.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare const _exports: import("../../../types").APIGetUserFunction; -export = _exports; diff --git a/package-shared/functions/api/users/api-get-user.js b/package-shared/functions/api/users/api-get-user.ts similarity index 66% rename from package-shared/functions/api/users/api-get-user.js rename to package-shared/functions/api/users/api-get-user.ts index ab0025b..07d1250 100644 --- a/package-shared/functions/api/users/api-get-user.js +++ b/package-shared/functions/api/users/api-get-user.ts @@ -1,14 +1,18 @@ -// @ts-check +import { + APIGetUserFunctionParams, + GetUserFunctionReturn, +} from "../../../types"; +import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler"; -const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); - -/** @type {import("../../../types").APIGetUserFunction} */ -module.exports = async function apiGetUser({ +/** + * # API Get User + */ +export default async function apiGetUser({ fields, dbFullName, userId, useLocal, -}) { +}: APIGetUserFunctionParams): Promise { const query = `SELECT ${fields.join(",")} FROM users WHERE id=?`; const API_USER_ID = userId || process.env.DSQL_API_USER_ID; @@ -30,4 +34,4 @@ module.exports = async function apiGetUser({ success: true, payload: foundUser[0], }; -}; +} diff --git a/package-shared/functions/api/users/api-login.d.ts b/package-shared/functions/api/users/api-login.d.ts deleted file mode 100644 index 747fc57..0000000 --- a/package-shared/functions/api/users/api-login.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare const _exports: import("../../../types").APILoginFunction; -export = _exports; diff --git a/package-shared/functions/api/users/api-login.js b/package-shared/functions/api/users/api-login.ts similarity index 86% rename from package-shared/functions/api/users/api-login.js rename to package-shared/functions/api/users/api-login.ts index 6a7f28a..3bd729f 100644 --- a/package-shared/functions/api/users/api-login.js +++ b/package-shared/functions/api/users/api-login.ts @@ -1,10 +1,15 @@ -// @ts-check +import { + APILoginFunctionParams, + APILoginFunctionReturn, + DATASQUIREL_LoggedInUser, +} from "../../../types"; +import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler"; +import hashPassword from "../../dsql/hashPassword"; -const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); -const hashPassword = require("../../dsql/hashPassword"); - -/** @type {import("../../../types").APILoginFunction} */ -module.exports = async function apiLoginUser({ +/** + * # API Login + */ +export default async function apiLoginUser({ encryptionKey, email, username, @@ -18,7 +23,7 @@ module.exports = async function apiLoginUser({ skipPassword, social, useLocal, -}) { +}: APILoginFunctionParams): Promise { const dbFullName = database; /** @@ -115,8 +120,7 @@ module.exports = async function apiLoginUser({ "-" + Math.random().toString(36).substring(2); - /** @type {import("../../../types").DATASQUIREL_LoggedInUser} */ - let userPayload = { + let userPayload: DATASQUIREL_LoggedInUser = { id: foundUser[0].id, first_name: foundUser[0].first_name, last_name: foundUser[0].last_name, @@ -135,14 +139,10 @@ module.exports = async function apiLoginUser({ date: Date.now(), }; - /** @type {import("../../../types").APILoginFunctionReturn} */ - const resposeObject = { + const resposeObject: APILoginFunctionReturn = { success: true, msg: "Login Successful", - payload: - /** @type {import("../../../types").DATASQUIREL_LoggedInUser} */ ( - userPayload - ), + payload: userPayload, userId: foundUser[0].id, csrf: csrfKey, }; @@ -158,4 +158,4 @@ module.exports = async function apiLoginUser({ } return resposeObject; -}; +} diff --git a/package-shared/functions/api/users/api-reauth-user.d.ts b/package-shared/functions/api/users/api-reauth-user.d.ts deleted file mode 100644 index c5b9f99..0000000 --- a/package-shared/functions/api/users/api-reauth-user.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -declare function _exports({ existingUser, database, additionalFields, useLocal, }: { - existingUser: { - [x: string]: any; - }; - database?: string; - additionalFields?: string[]; - useLocal?: boolean; -}): Promise; -export = _exports; diff --git a/package-shared/functions/api/users/api-reauth-user.js b/package-shared/functions/api/users/api-reauth-user.ts similarity index 64% rename from package-shared/functions/api/users/api-reauth-user.js rename to package-shared/functions/api/users/api-reauth-user.ts index 3386bbb..3ab3d60 100644 --- a/package-shared/functions/api/users/api-reauth-user.js +++ b/package-shared/functions/api/users/api-reauth-user.ts @@ -1,25 +1,22 @@ -// @ts-check +import { APILoginFunctionReturn } from "../../../types"; +import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler"; -const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"); -const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); -const nodemailer = require("nodemailer"); +type Param = { + existingUser: { [s: string]: any }; + database?: string; + additionalFields?: string[]; + useLocal?: boolean; +}; /** * # Re-authenticate API user - * @param {object} param - * @param {Object} param.existingUser - * @param {string} [param.database] - * @param {string[]} [param.additionalFields] - * @param {boolean} [param.useLocal] - * - * @returns {Promise} */ -module.exports = async function apiReauthUser({ +export default async function apiReauthUser({ existingUser, database, additionalFields, useLocal, -}) { +}: Param): Promise { let foundUser = existingUser?.id && existingUser.id.toString().match(/./) ? await varDatabaseDbHandler({ @@ -30,10 +27,6 @@ module.exports = async function apiReauthUser({ }) : null; - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - if (!foundUser || !foundUser[0]) return { success: false, @@ -41,17 +34,13 @@ module.exports = async function apiReauthUser({ msg: "No user found", }; - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - let csrfKey = Math.random().toString(36).substring(2) + "-" + Math.random().toString(36).substring(2); /** @type {import("../../../types").DATASQUIREL_LoggedInUser} */ - let userPayload = { + let userPayload: import("../../../types").DATASQUIREL_LoggedInUser = { id: foundUser[0].id, first_name: foundUser[0].first_name, last_name: foundUser[0].last_name, @@ -80,15 +69,10 @@ module.exports = async function apiReauthUser({ }); } - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - - /** ********************* Send Response */ return { success: true, msg: "Login Successful", payload: userPayload, csrf: csrfKey, }; -}; +} diff --git a/package-shared/functions/api/users/api-send-email-code.d.ts b/package-shared/functions/api/users/api-send-email-code.d.ts deleted file mode 100644 index 5cbcb68..0000000 --- a/package-shared/functions/api/users/api-send-email-code.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -declare function _exports({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, useLocal, response, extraCookies, }: { - email: string; - database: string; - email_login_field?: string; - mail_domain?: string; - mail_port?: number; - sender?: string; - mail_username?: string; - mail_password?: string; - html: string; - useLocal?: boolean; - response?: http.ServerResponse & { - [x: string]: any; - }; - extraCookies?: import("../../../../package-shared/types").CookieObject[]; -}): Promise; -export = _exports; -import http = require("http"); diff --git a/package-shared/functions/api/users/api-send-email-code.js b/package-shared/functions/api/users/api-send-email-code.ts similarity index 64% rename from package-shared/functions/api/users/api-send-email-code.js rename to package-shared/functions/api/users/api-send-email-code.ts index 1192c58..3426edb 100644 --- a/package-shared/functions/api/users/api-send-email-code.js +++ b/package-shared/functions/api/users/api-send-email-code.ts @@ -1,32 +1,30 @@ -// @ts-check +import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler"; +import nodemailer, { SendMailOptions } from "nodemailer"; +import http from "http"; +import getAuthCookieNames from "../../backend/cookies/get-auth-cookie-names"; +import encrypt from "../../dsql/encrypt"; +import serializeCookies from "../../../utils/serialize-cookies"; +import { SendOneTimeCodeEmailResponse } from "../../../types"; -const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); -const nodemailer = require("nodemailer"); -const http = require("http"); -const getAuthCookieNames = require("../../backend/cookies/get-auth-cookie-names"); -const encrypt = require("../../dsql/encrypt"); -const serializeCookies = require("../../../utils/serialize-cookies"); +type Param = { + email: string; + database: string; + email_login_field?: string; + mail_domain?: string; + mail_port?: number; + sender?: string; + mail_username?: string; + mail_password?: string; + html: string; + useLocal?: boolean; + response?: http.ServerResponse & { [s: string]: any }; + extraCookies?: import("../../../../package-shared/types").CookieObject[]; +}; /** * # Send Email Login Code - * - * @param {object} param - * @param {string} param.email - * @param {string} param.database - * @param {string} [param.email_login_field] - * @param {string} [param.mail_domain] - * @param {number} [param.mail_port] - * @param {string} [param.sender] - * @param {string} [param.mail_username] - * @param {string} [param.mail_password] - * @param {string} param.html - * @param {boolean} [param.useLocal] - * @param {http.ServerResponse & Object} [param.response] - * @param {import("../../../../package-shared/types").CookieObject[]} [param.extraCookies] - * - * @returns {Promise} */ -module.exports = async function apiSendEmailCode({ +export default async function apiSendEmailCode({ email, database, email_login_field, @@ -39,7 +37,7 @@ module.exports = async function apiSendEmailCode({ useLocal, response, extraCookies, -}) { +}: Param): Promise { if (email?.match(/ /)) { return { success: false, @@ -83,7 +81,11 @@ module.exports = async function apiSendEmailCode({ let transporter = nodemailer.createTransport({ host: mail_domain || process.env.DSQL_MAIL_HOST, - port: mail_port || process.env.DSQL_MAIL_PORT || 465, + port: mail_port + ? mail_port + : process.env.DSQL_MAIL_PORT + ? Number(process.env.DSQL_MAIL_PORT) + : 465, secure: true, auth: { user: mail_username || process.env.DSQL_MAIL_EMAIL, @@ -91,7 +93,7 @@ module.exports = async function apiSendEmailCode({ }, }); - let mailObject = {}; + let mailObject: SendMailOptions = {}; mailObject["from"] = `"Datasquirel SSO" <${ sender || "support@datasquirel.com" @@ -116,13 +118,14 @@ module.exports = async function apiSendEmailCode({ }); /** @type {import("../../../types").SendOneTimeCodeEmailResponse} */ - const resObject = { - success: true, - code: tempCode, - email: email, - createdAt, - msg: "Success", - }; + const resObject: import("../../../types").SendOneTimeCodeEmailResponse = + { + success: true, + code: tempCode, + email: email, + createdAt, + msg: "Success", + }; if (response) { const cookieKeyNames = getAuthCookieNames(); @@ -139,19 +142,21 @@ module.exports = async function apiSendEmailCode({ } /** @type {import("../../../../package-shared/types").CookieObject} */ - const oneTimeCookieObject = { - name: oneTimeCodeCookieName, - value: encryptedPayload, - sameSite: "Strict", - path: "/", - httpOnly: true, - secure: true, - }; + const oneTimeCookieObject: import("../../../../package-shared/types").CookieObject = + { + name: oneTimeCodeCookieName, + value: encryptedPayload, + sameSite: "Strict", + path: "/", + httpOnly: true, + secure: true, + }; /** @type {import("../../../../package-shared/types").CookieObject[]} */ - const cookiesObjectArray = extraCookies - ? [...extraCookies, oneTimeCookieObject] - : [oneTimeCookieObject]; + const cookiesObjectArray: import("../../../../package-shared/types").CookieObject[] = + extraCookies + ? [...extraCookies, oneTimeCookieObject] + : [oneTimeCookieObject]; const serializedCookies = serializeCookies({ cookies: cookiesObjectArray, @@ -167,4 +172,4 @@ module.exports = async function apiSendEmailCode({ msg: "Invalid Email/Password format", }; } -}; +} diff --git a/package-shared/functions/api/users/api-update-user.d.ts b/package-shared/functions/api/users/api-update-user.d.ts deleted file mode 100644 index bf0df17..0000000 --- a/package-shared/functions/api/users/api-update-user.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -declare function _exports({ payload, dbFullName, updatedUserId, useLocal, dbSchema, }: { - payload: { - [x: string]: any; - }; - dbFullName: string; - updatedUserId: string | number; - useLocal?: boolean; - dbSchema?: import("../../../types").DSQL_DatabaseSchemaType; -}): Promise<{ - success: boolean; - payload?: any; - msg?: string; -}>; -export = _exports; diff --git a/package-shared/functions/api/users/api-update-user.js b/package-shared/functions/api/users/api-update-user.ts similarity index 74% rename from package-shared/functions/api/users/api-update-user.js rename to package-shared/functions/api/users/api-update-user.ts index 2214210..a6641ce 100644 --- a/package-shared/functions/api/users/api-update-user.js +++ b/package-shared/functions/api/users/api-update-user.ts @@ -1,29 +1,30 @@ // @ts-check -const updateDbEntry = require("../../backend/db/updateDbEntry"); -const encrypt = require("../../dsql/encrypt"); -const hashPassword = require("../../dsql/hashPassword"); -const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); +import updateDbEntry from "../../backend/db/updateDbEntry"; +import encrypt from "../../dsql/encrypt"; +import hashPassword from "../../dsql/hashPassword"; +import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler"; + +type Param = { + payload: { [s: string]: any }; + dbFullName: string; + updatedUserId: string | number; + useLocal?: boolean; + dbSchema?: import("../../../types").DSQL_DatabaseSchemaType; +}; + +type Return = { success: boolean; payload?: any; msg?: string }; /** * # Update API User Function - * - * @param {object} params - * @param {Object} params.payload - * @param {string} params.dbFullName - * @param {string | number} params.updatedUserId - * @param {boolean} [params.useLocal] - * @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema] - * - * @returns {Promise<{ success: boolean, payload?: any, msg?: string }>} */ -module.exports = async function apiUpdateUser({ +export default async function apiUpdateUser({ payload, dbFullName, updatedUserId, useLocal, dbSchema, -}) { +}: Param): Promise { const existingUserQuery = `SELECT * FROM users WHERE id = ?`; const existingUserValues = [updatedUserId]; @@ -56,7 +57,7 @@ module.exports = async function apiUpdateUser({ })(); /** @type {any} */ - const finalData = {}; + const finalData: any = {}; reqBodyKeys.forEach((key) => { const targetFieldSchema = targetTableSchema?.fields?.find( @@ -95,4 +96,4 @@ module.exports = async function apiUpdateUser({ success: true, payload: updateUser, }; -}; +} diff --git a/package-shared/functions/api/users/social/api-github-login.d.ts b/package-shared/functions/api/users/social/api-github-login.d.ts deleted file mode 100644 index 2e78000..0000000 --- a/package-shared/functions/api/users/social/api-github-login.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -declare function _exports({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }: { - code?: string; - clientId?: string; - clientSecret?: string; - database?: string; - additionalFields?: string[]; - additionalData?: { - [x: string]: string | number; - }; - email?: string; -}): Promise; -export = _exports; diff --git a/package-shared/functions/api/users/social/api-github-login.js b/package-shared/functions/api/users/social/api-github-login.ts similarity index 75% rename from package-shared/functions/api/users/social/api-github-login.js rename to package-shared/functions/api/users/social/api-github-login.ts index 93fbccd..98ba564 100644 --- a/package-shared/functions/api/users/social/api-github-login.js +++ b/package-shared/functions/api/users/social/api-github-login.ts @@ -1,23 +1,22 @@ -// @ts-check +import handleSocialDb from "../../social-login/handleSocialDb"; +import githubLogin from "../../social-login/githubLogin"; +import camelJoinedtoCamelSpace from "../../../../utils/camelJoinedtoCamelSpace"; +import { APILoginFunctionReturn } from "../../../../types"; -const handleSocialDb = require("../../social-login/handleSocialDb"); -const githubLogin = require("../../social-login/githubLogin"); -const camelJoinedtoCamelSpace = require("../../../../utils/camelJoinedtoCamelSpace"); +type Param = { + code?: string; + clientId?: string; + clientSecret?: string; + database?: string; + additionalFields?: string[]; + additionalData?: { [s: string]: string | number }; + email?: string; +}; /** - * # Login with Github - * @param {object} param - * @param {string} [param.code] - * @param {string} [param.clientId] - * @param {string} [param.clientSecret] - * @param {string} [param.database] - * @param {string[]} [param.additionalFields] - * @param {Object} [param.additionalData] - * @param {string} [param.email] - * - * @returns {Promise} + * # API Login with Github */ -module.exports = async function apiGithubLogin({ +export default async function apiGithubLogin({ code, clientId, clientSecret, @@ -25,7 +24,7 @@ module.exports = async function apiGithubLogin({ additionalFields, email, additionalData, -}) { +}: Param): Promise { if (!code || !clientId || !clientSecret || !database) { return { success: false, @@ -101,4 +100,4 @@ module.exports = async function apiGithubLogin({ //////////////////////////////////////////////// return { ...loggedInGithubUser }; -}; +} diff --git a/package-shared/functions/api/users/social/api-google-login.d.ts b/package-shared/functions/api/users/social/api-google-login.d.ts deleted file mode 100644 index 95a7eb3..0000000 --- a/package-shared/functions/api/users/social/api-google-login.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare const _exports: import("../../../../types").APIGoogleLoginFunction; -export = _exports; diff --git a/package-shared/functions/api/users/social/api-google-login.js b/package-shared/functions/api/users/social/api-google-login.ts similarity index 56% rename from package-shared/functions/api/users/social/api-google-login.js rename to package-shared/functions/api/users/social/api-google-login.ts index b185a6e..2626620 100644 --- a/package-shared/functions/api/users/social/api-google-login.js +++ b/package-shared/functions/api/users/social/api-google-login.ts @@ -1,41 +1,47 @@ -// @ts-check +import https from "https"; +import handleSocialDb from "../../social-login/handleSocialDb"; +import EJSON from "../../../../utils/ejson"; +import { + APIGoogleLoginFunctionParams, + APILoginFunctionReturn, + GoogleOauth2User, +} from "../../../../types"; -const https = require("https"); -const handleSocialDb = require("../../social-login/handleSocialDb"); -const EJSON = require("../../../../utils/ejson"); - -/** @type {import("../../../../types").APIGoogleLoginFunction} */ -module.exports = async function apiGoogleLogin({ +/** + * # API google login + */ +export default async function apiGoogleLogin({ token, database, additionalFields, additionalData, -}) { +}: APIGoogleLoginFunctionParams): Promise { try { - /** @type {import("../../../../types").GoogleOauth2User | undefined} */ - const gUser = await new Promise((resolve, reject) => { - https - .request( - { - method: "GET", - hostname: "www.googleapis.com", - path: "/oauth2/v3/userinfo", - headers: { - Authorization: `Bearer ${token}`, + const gUser: GoogleOauth2User | undefined = await new Promise( + (resolve, reject) => { + https + .request( + { + method: "GET", + hostname: "www.googleapis.com", + path: "/oauth2/v3/userinfo", + headers: { + Authorization: `Bearer ${token}`, + }, }, - }, - (res) => { - let data = ""; - res.on("data", (chunk) => { - data += chunk; - }); - res.on("end", () => { - resolve(/** @type {any} */ (EJSON.parse(data))); - }); - } - ) - .end(); - }); + (res) => { + let data = ""; + res.on("data", (chunk) => { + data += chunk; + }); + res.on("end", () => { + resolve(EJSON.parse(data) as any); + }); + } + ) + .end(); + } + ); if (!gUser?.email_verified) throw new Error("No Google User."); @@ -60,7 +66,7 @@ module.exports = async function apiGoogleLogin({ const { given_name, family_name, email, sub, picture } = gUser; /** @type {Object} */ - let payloadObject = { + let payloadObject: { [s: string]: any } = { email: email, first_name: given_name, last_name: family_name, @@ -89,7 +95,7 @@ module.exports = async function apiGoogleLogin({ //////////////////////////////////////// return { ...loggedInGoogleUser }; - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log(`apo-google-login.js ERROR: ${error.message}`); return { @@ -98,4 +104,4 @@ module.exports = async function apiGoogleLogin({ msg: error.message, }; } -}; +} diff --git a/package-shared/functions/backend/addAdminUserOnLogin.d.ts b/package-shared/functions/backend/addAdminUserOnLogin.d.ts deleted file mode 100644 index 8c88dcb..0000000 --- a/package-shared/functions/backend/addAdminUserOnLogin.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -declare function _exports({ query, user, useLocal }: { - query: { - invite: number; - database_access: string; - priviledge: string; - email: string; - }; - useLocal?: boolean; - user: import("../../types").DATASQUIREL_LoggedInUser; -}): Promise; -export = _exports; diff --git a/package-shared/functions/backend/addAdminUserOnLogin.js b/package-shared/functions/backend/addAdminUserOnLogin.ts similarity index 75% rename from package-shared/functions/backend/addAdminUserOnLogin.js rename to package-shared/functions/backend/addAdminUserOnLogin.ts index d034302..d1b0908 100755 --- a/package-shared/functions/backend/addAdminUserOnLogin.js +++ b/package-shared/functions/backend/addAdminUserOnLogin.ts @@ -1,9 +1,19 @@ -// @ts-check +import serverError from "./serverError"; +import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER"; +import addDbEntry from "./db/addDbEntry"; +import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER"; +import { DATASQUIREL_LoggedInUser } from "../../types"; -const serverError = require("./serverError"); -const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER"); -const addDbEntry = require("./db/addDbEntry"); -const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER"); +type Param = { + query: { + invite: number; + database_access: string; + priviledge: string; + email: string; + }; + useLocal?: boolean; + user: DATASQUIREL_LoggedInUser; +}; /** * Add Admin User on Login @@ -12,21 +22,12 @@ const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER * @description this function handles admin users that have been invited by another * admin user. This fires when the invited user has been logged in or a new account * has been created for the invited user - * - * @param {object} params - parameters object - * - * @param {object} params.query - query object - * @param {number} params.query.invite - Invitation user id - * @param {string} params.query.database_access - String containing authorized databases - * @param {string} params.query.priviledge - String containing databases priviledges - * @param {string} params.query.email - Inviting user email address - * - * @param {boolean} [params.useLocal] - * @param {import("../../types").DATASQUIREL_LoggedInUser} params.user - invited user object - * - * @returns {Promise} new user auth object payload */ -module.exports = async function addAdminUserOnLogin({ query, user, useLocal }) { +export default async function addAdminUserOnLogin({ + query, + user, + useLocal, +}: Param): Promise { try { const finalDbHandler = useLocal ? LOCAL_DB_HANDLER : DB_HANDLER; const { invite, database_access, priviledge, email } = query; @@ -132,23 +133,11 @@ module.exports = async function addAdminUserOnLogin({ query, user, useLocal }) { [invite, email] ); } - - //////////////////////////////////////////////// - //////////////////////////////////////////////// - //////////////////////////////////////////////// - } catch (/** @type {any} */ error) { - //////////////////////////////////////////////// - //////////////////////////////////////////////// - //////////////////////////////////////////////// - + } catch (error: any) { serverError({ component: "addAdminUserOnLogin", message: error.message, user: user, }); } -}; - -//////////////////////////////////////////////// -//////////////////////////////////////////////// -//////////////////////////////////////////////// +} diff --git a/package-shared/functions/backend/addMariadbUser.d.ts b/package-shared/functions/backend/addMariadbUser.d.ts deleted file mode 100644 index f8e228f..0000000 --- a/package-shared/functions/backend/addMariadbUser.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -declare function _exports({ userId, useLocal }: { - userId: number | string; - useLocal?: boolean; -}): Promise; -export = _exports; diff --git a/package-shared/functions/backend/addMariadbUser.js b/package-shared/functions/backend/addMariadbUser.ts similarity index 69% rename from package-shared/functions/backend/addMariadbUser.js rename to package-shared/functions/backend/addMariadbUser.ts index b07700d..bed8a83 100644 --- a/package-shared/functions/backend/addMariadbUser.js +++ b/package-shared/functions/backend/addMariadbUser.ts @@ -1,24 +1,22 @@ -// @ts-check +import generator from "generate-password"; +import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER"; +import NO_DB_HANDLER from "../../utils/backend/global-db/NO_DB_HANDLER"; +import addDbEntry from "./db/addDbEntry"; +import encrypt from "../dsql/encrypt"; +import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER"; -const generator = require("generate-password"); -const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER"); -const NO_DB_HANDLER = require("../../utils/backend/global-db/NO_DB_HANDLER"); -const addDbEntry = require("./db/addDbEntry"); -const encrypt = require("../dsql/encrypt"); -const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER"); +type Param = { + userId: number | string; + useLocal?: boolean; +}; /** * # Add Mariadb User - * - * @description this function adds a Mariadb user to the database server - * - * @param {object} params - parameters object * - * @param {number | string} params.userId - invited user object - * @param {boolean} [params.useLocal] - * - * @returns {Promise} new user auth object payload */ -module.exports = async function addMariadbUser({ userId, useLocal }) { +export default async function addMariadbUser({ + userId, + useLocal, +}: Param): Promise { try { const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1"; @@ -62,13 +60,13 @@ module.exports = async function addMariadbUser({ userId, useLocal }) { }); console.log(`User ${userId} SQL credentials successfully added.`); - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log( `Error in adding SQL user in 'addMariadbUser' function =>`, error.message ); } -}; +} //////////////////////////////////////////////// //////////////////////////////////////////////// diff --git a/package-shared/functions/backend/addUsersTableToDb.d.ts b/package-shared/functions/backend/addUsersTableToDb.d.ts deleted file mode 100644 index 798532c..0000000 --- a/package-shared/functions/backend/addUsersTableToDb.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -declare function _exports({ userId, database, useLocal, payload, }: { - userId: number; - database: string; - useLocal?: boolean; - payload?: { - [x: string]: any; - }; -}): Promise; -export = _exports; diff --git a/package-shared/functions/backend/addUsersTableToDb.js b/package-shared/functions/backend/addUsersTableToDb.ts similarity index 64% rename from package-shared/functions/backend/addUsersTableToDb.js rename to package-shared/functions/backend/addUsersTableToDb.ts index 9b3e699..3671742 100755 --- a/package-shared/functions/backend/addUsersTableToDb.js +++ b/package-shared/functions/backend/addUsersTableToDb.ts @@ -1,34 +1,28 @@ -// @ts-check +import serverError from "./serverError"; +import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER"; +import { default as grabUserSchemaData } from "./grabUserSchemaData"; +import { default as setUserSchemaData } from "./setUserSchemaData"; +import addDbEntry from "./db/addDbEntry"; +import createDbFromSchema from "../../shell/createDbFromSchema"; +import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER"; +import grabNewUsersTableSchema from "./grabNewUsersTableSchema"; -const fs = require("fs"); -const path = require("path"); -const { execSync } = require("child_process"); -const serverError = require("./serverError"); -const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER"); -const { default: grabUserSchemaData } = require("./grabUserSchemaData"); -const { default: setUserSchemaData } = require("./setUserSchemaData"); -const addDbEntry = require("./db/addDbEntry"); -const createDbFromSchema = require("../../shell/createDbFromSchema"); -const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER"); -const grabNewUsersTableSchema = require("./grabNewUsersTableSchema"); +type Param = { + userId: number; + database: string; + useLocal?: boolean; + payload?: { [s: string]: any }; +}; /** * # Add User Table to Database - * - * @param {object} params - * @param {number} params.userId - user id - * @param {string} params.database - * @param {boolean} [params.useLocal] - * @param {Object} [params.payload] - payload object - * - * @returns {Promise} new user auth object payload */ -module.exports = async function addUsersTableToDb({ +export default async function addUsersTableToDb({ userId, database, useLocal, payload, -}) { +}: Param): Promise { try { const dbFullName = database; @@ -39,7 +33,7 @@ module.exports = async function addUsersTableToDb({ if (!userSchemaData) throw new Error("User schema data not found!"); let targetDatabase = userSchemaData.find( - (db) => db.dbFullName === database + (db: any) => db.dbFullName === database ); if (!targetDatabase) { @@ -47,7 +41,7 @@ module.exports = async function addUsersTableToDb({ } let existingTableIndex = targetDatabase?.tables.findIndex( - (table) => table.tableName === "users" + (table: any) => table.tableName === "users" ); if (typeof existingTableIndex == "number" && existingTableIndex > 0) { @@ -59,7 +53,7 @@ module.exports = async function addUsersTableToDb({ setUserSchemaData({ schemaData: userSchemaData, userId }); /** @type {any[] | null} */ - const targetDb = useLocal + const targetDb: any[] | null = useLocal ? await LOCAL_DB_HANDLER( `SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database] @@ -90,7 +84,7 @@ module.exports = async function addUsersTableToDb({ }); return `Done!`; - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log(`addUsersTableToDb.js ERROR: ${error.message}`); serverError({ @@ -100,4 +94,4 @@ module.exports = async function addUsersTableToDb({ }); return error.message; } -}; +} diff --git a/package-shared/functions/backend/api-cred.js b/package-shared/functions/backend/api-cred.ts similarity index 73% rename from package-shared/functions/backend/api-cred.js rename to package-shared/functions/backend/api-cred.ts index ceecb4f..0aa54c1 100644 --- a/package-shared/functions/backend/api-cred.js +++ b/package-shared/functions/backend/api-cred.ts @@ -1,10 +1,17 @@ -// @ts-check +import fs from "fs"; +import decrypt from "../dsql/decrypt"; +import { CheckApiCredentialsFn } from "../../types"; -const fs = require("fs"); -const decrypt = require("../dsql/decrypt"); - -/** @type {import("../../types").CheckApiCredentialsFn} */ -const grabApiCred = ({ key, database, table, user_id, media }) => { +/** + * # Grap API Credentials + */ +const grabApiCred: CheckApiCredentialsFn = ({ + key, + database, + table, + user_id, + media, +}) => { if (!key) return null; if (!user_id) return null; @@ -18,7 +25,9 @@ const grabApiCred = ({ key, database, table, user_id, media }) => { const ApiJSON = decrypt({ encryptedString: key }); /** @type {import("../../types").ApiKeyObject} */ - const ApiObject = JSON.parse(ApiJSON || ""); + const ApiObject: import("../../types").ApiKeyObject = JSON.parse( + ApiJSON || "" + ); const isApiKeyValid = fs.existsSync( `${allowedKeysPath}/${ApiObject.sign}` ); @@ -41,10 +50,10 @@ const grabApiCred = ({ key, database, table, user_id, media }) => { .includes(String(table)); if (isTableAllowed) return ApiObject; return null; - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log(`api-cred ERROR: ${error.message}`); return { error: `api-cred ERROR: ${error.message}` }; } }; -module.exports = grabApiCred; +export default grabApiCred; diff --git a/package-shared/functions/backend/auth/write-auth-files.d.ts b/package-shared/functions/backend/auth/write-auth-files.d.ts deleted file mode 100644 index a37c4b5..0000000 --- a/package-shared/functions/backend/auth/write-auth-files.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -export function grabAuthDirs(): { - root: string; - auth: string; -}; -export function initAuthFiles(): boolean; -/** - * # Write Auth Files - * @param {string} name - * @param {string} data - */ -export function writeAuthFile(name: string, data: string): boolean; -/** - * # Get Auth Files - * @param {string} name - */ -export function getAuthFile(name: string): string; -/** - * # Delete Auth Files - * @param {string} name - */ -export function deleteAuthFile(name: string): void; -/** - * # Delete Auth Files - * @param {string} name - */ -export function checkAuthFile(name: string): boolean; diff --git a/package-shared/functions/backend/auth/write-auth-files.js b/package-shared/functions/backend/auth/write-auth-files.ts similarity index 67% rename from package-shared/functions/backend/auth/write-auth-files.js rename to package-shared/functions/backend/auth/write-auth-files.ts index 7edca89..00edcb4 100644 --- a/package-shared/functions/backend/auth/write-auth-files.js +++ b/package-shared/functions/backend/auth/write-auth-files.ts @@ -1,9 +1,7 @@ -// @ts-check +import fs from "fs"; +import path from "path"; -const fs = require("fs"); -const path = require("path"); - -const grabAuthDirs = () => { +export const grabAuthDirs = () => { const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR; const ROOT_DIR = DSQL_AUTH_DIR?.match(/./) ? DSQL_AUTH_DIR @@ -13,7 +11,7 @@ const grabAuthDirs = () => { return { root: ROOT_DIR, auth: AUTH_DIR }; }; -const initAuthFiles = () => { +export const initAuthFiles = () => { try { const authDirs = grabAuthDirs(); @@ -22,7 +20,7 @@ const initAuthFiles = () => { if (!fs.existsSync(authDirs.auth)) fs.mkdirSync(authDirs.auth, { recursive: true }); return true; - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log(`Error initializing Auth Files: ${error.message}`); return false; } @@ -30,15 +28,13 @@ const initAuthFiles = () => { /** * # Write Auth Files - * @param {string} name - * @param {string} data */ -const writeAuthFile = (name, data) => { +export const writeAuthFile = (name: string, data: string) => { initAuthFiles(); try { fs.writeFileSync(path.join(grabAuthDirs().auth, name), data); return true; - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log(`Error writing Auth File: ${error.message}`); return false; } @@ -46,13 +42,12 @@ const writeAuthFile = (name, data) => { /** * # Get Auth Files - * @param {string} name */ -const getAuthFile = (name) => { +export const getAuthFile = (name: string) => { try { const authFilePath = path.join(grabAuthDirs().auth, name); return fs.readFileSync(authFilePath, "utf-8"); - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log(`Error getting Auth File: ${error.message}`); return null; } @@ -62,10 +57,10 @@ const getAuthFile = (name) => { * # Delete Auth Files * @param {string} name */ -const deleteAuthFile = (name) => { +export const deleteAuthFile = (name: string) => { try { return fs.rmSync(path.join(grabAuthDirs().auth, name)); - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log(`Error deleting Auth File: ${error.message}`); return null; } @@ -75,19 +70,12 @@ const deleteAuthFile = (name) => { * # Delete Auth Files * @param {string} name */ -const checkAuthFile = (name) => { +export const checkAuthFile = (name: string) => { try { return fs.existsSync(path.join(grabAuthDirs().auth, name)); return true; - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log(`Error checking Auth File: ${error.message}`); return false; } }; - -exports.grabAuthDirs = grabAuthDirs; -exports.initAuthFiles = initAuthFiles; -exports.writeAuthFile = writeAuthFile; -exports.getAuthFile = getAuthFile; -exports.deleteAuthFile = deleteAuthFile; -exports.checkAuthFile = checkAuthFile; diff --git a/package-shared/functions/backend/cookies/get-auth-cookie-names.d.ts b/package-shared/functions/backend/cookies/get-auth-cookie-names.d.ts deleted file mode 100644 index 12aa588..0000000 --- a/package-shared/functions/backend/cookies/get-auth-cookie-names.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -declare function _exports(params?: { - database?: string; - userId?: string | number; -}): { - keyCookieName: string; - csrfCookieName: string; - oneTimeCodeName: string; -}; -export = _exports; diff --git a/package-shared/functions/backend/cookies/get-auth-cookie-names.js b/package-shared/functions/backend/cookies/get-auth-cookie-names.ts similarity index 82% rename from package-shared/functions/backend/cookies/get-auth-cookie-names.js rename to package-shared/functions/backend/cookies/get-auth-cookie-names.ts index 9cecf42..7fd56f3 100644 --- a/package-shared/functions/backend/cookies/get-auth-cookie-names.js +++ b/package-shared/functions/backend/cookies/get-auth-cookie-names.ts @@ -1,15 +1,18 @@ -// @ts-check +type Param = { + database?: string; + userId?: string | number; +}; + +type Return = { + keyCookieName: string; + csrfCookieName: string; + oneTimeCodeName: string; +}; /** * # Grab Auth Cookie Names - * - * @param {object} [params] - * @param {string} [params.database] - * @param {string | number} [params.userId] - * - * @returns {{ keyCookieName: string, csrfCookieName: string, oneTimeCodeName: string }} */ -module.exports = function getAuthCookieNames(params) { +export default function getAuthCookieNames(params?: Param): Return { const cookiesPrefix = process.env.DSQL_COOKIES_PREFIX || "dsql_"; const cookiesKeyName = process.env.DSQL_COOKIES_KEY_NAME || "key"; const cookiesCSRFName = process.env.DSQL_COOKIES_CSRF_NAME || "csrf"; @@ -40,4 +43,4 @@ module.exports = function getAuthCookieNames(params) { csrfCookieName, oneTimeCodeName, }; -}; +} diff --git a/package-shared/functions/backend/db/addDbEntry.d.ts b/package-shared/functions/backend/db/addDbEntry.d.ts deleted file mode 100644 index 602330b..0000000 --- a/package-shared/functions/backend/db/addDbEntry.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -export = addDbEntry; -/** - * Add a db Entry Function - * ============================================================================== - * @description Description - * @async - * - * @param {object} params - An object containing the function parameters. - * @param {("Master" | "Dsql User")} [params.dbContext] - What is the database context? "Master" - * or "Dsql User". Defaults to "Master" - * @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"? - * "Read only" or "Full Access"? Defaults to "Read Only" - * @param {string} [params.dbFullName] - Database full name - * @param {string} params.tableName - Table name - * @param {any} params.data - Data to add - * @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema - * @param {string} [params.duplicateColumnName] - Duplicate column name - * @param {string} [params.duplicateColumnValue] - Duplicate column value - * @param {boolean} [params.update] - Update this row if it exists - * @param {string} [params.encryptionKey] - Update this row if it exists - * @param {string} [params.encryptionSalt] - Update this row if it exists - * @param {boolean} [params.useLocal] - * - * @returns {Promise} - */ -declare function addDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, useLocal, }: { - dbContext?: ("Master" | "Dsql User"); - paradigm?: ("Read Only" | "Full Access"); - dbFullName?: string; - tableName: string; - data: any; - tableSchema?: import("../../../types").DSQL_TableSchemaType; - duplicateColumnName?: string; - duplicateColumnValue?: string; - update?: boolean; - encryptionKey?: string; - encryptionSalt?: string; - useLocal?: boolean; -}): Promise; diff --git a/package-shared/functions/backend/db/addDbEntry.js b/package-shared/functions/backend/db/addDbEntry.ts similarity index 85% rename from package-shared/functions/backend/db/addDbEntry.js rename to package-shared/functions/backend/db/addDbEntry.ts index 0520980..4d9c6bd 100644 --- a/package-shared/functions/backend/db/addDbEntry.js +++ b/package-shared/functions/backend/db/addDbEntry.ts @@ -1,13 +1,28 @@ // @ts-check -const sanitizeHtml = require("sanitize-html"); -const sanitizeHtmlOptions = require("../html/sanitizeHtmlOptions"); -const updateDbEntry = require("./updateDbEntry"); -const _ = require("lodash"); -const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER"); -const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"); -const encrypt = require("../../dsql/encrypt"); -const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"); +import sanitizeHtml from "sanitize-html"; +import sanitizeHtmlOptions from "../html/sanitizeHtmlOptions"; +import updateDbEntry from "./updateDbEntry"; +import _ from "lodash"; +import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER"; +import DSQL_USER_DB_HANDLER from "../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"; +import encrypt from "../../dsql/encrypt"; +import LOCAL_DB_HANDLER from "../../../utils/backend/global-db/LOCAL_DB_HANDLER"; + +type Param = { + dbContext?: "Master" | "Dsql User"; + paradigm?: "Read Only" | "Full Access"; + dbFullName?: string; + tableName: string; + data: any; + tableSchema?: import("../../../types").DSQL_TableSchemaType; + duplicateColumnName?: string; + duplicateColumnValue?: string; + update?: boolean; + encryptionKey?: string; + encryptionSalt?: string; + useLocal?: boolean; +}; /** * Add a db Entry Function @@ -33,7 +48,7 @@ const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HAND * * @returns {Promise} */ -async function addDbEntry({ +export default async function addDbEntry({ dbContext, paradigm, dbFullName, @@ -46,7 +61,7 @@ async function addDbEntry({ encryptionKey, encryptionSalt, useLocal, -}) { +}: Param): Promise { /** * Initialize variables */ @@ -59,7 +74,7 @@ async function addDbEntry({ : true; /** @type { any } */ - const dbHandler = useLocal + const dbHandler: any = useLocal ? LOCAL_DB_HANDLER : isMaster ? DB_HANDLER @@ -187,7 +202,7 @@ async function addDbEntry({ } else { insertValuesArray.push(value); } - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log("DSQL: Error in parsing data keys =>", error.message); continue; } @@ -233,18 +248,8 @@ async function addDbEntry({ queryValues: queryValuesArray, }); - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - /** * Return statement */ return newInsert; } - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// - -module.exports = addDbEntry; diff --git a/package-shared/functions/backend/db/deleteDbEntry.d.ts b/package-shared/functions/backend/db/deleteDbEntry.d.ts deleted file mode 100644 index 5392da5..0000000 --- a/package-shared/functions/backend/db/deleteDbEntry.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -export = deleteDbEntry; -/** - * Imports: Handle imports - */ -/** - * Delete DB Entry Function - * ============================================================================== - * @description Description - * @async - * - * @param {object} params - An object containing the function parameters. - * @param {string} [params.dbContext] - What is the database context? "Master" - * or "Dsql User". Defaults to "Master" - * @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"? - * "Read only" or "Full Access"? Defaults to "Read Only" - * @param {string} params.dbFullName - Database full name - * @param {string} params.tableName - Table name - * @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema - * @param {string} params.identifierColumnName - Update row identifier column name - * @param {string|number} params.identifierValue - Update row identifier column value - * @param {boolean} [params.useLocal] - * - * @returns {Promise} - */ -declare function deleteDbEntry({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue, useLocal, }: { - dbContext?: string; - paradigm?: ("Read Only" | "Full Access"); - dbFullName: string; - tableName: string; - tableSchema?: import("../../../types").DSQL_TableSchemaType; - identifierColumnName: string; - identifierValue: string | number; - useLocal?: boolean; -}): Promise; diff --git a/package-shared/functions/backend/db/deleteDbEntry.js b/package-shared/functions/backend/db/deleteDbEntry.js deleted file mode 100644 index ca450b8..0000000 --- a/package-shared/functions/backend/db/deleteDbEntry.js +++ /dev/null @@ -1,104 +0,0 @@ -// @ts-check - -const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER"); -const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"); -const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"); - -/** - * Imports: Handle imports - */ - -/** - * Delete DB Entry Function - * ============================================================================== - * @description Description - * @async - * - * @param {object} params - An object containing the function parameters. - * @param {string} [params.dbContext] - What is the database context? "Master" - * or "Dsql User". Defaults to "Master" - * @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"? - * "Read only" or "Full Access"? Defaults to "Read Only" - * @param {string} params.dbFullName - Database full name - * @param {string} params.tableName - Table name - * @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema - * @param {string} params.identifierColumnName - Update row identifier column name - * @param {string|number} params.identifierValue - Update row identifier column value - * @param {boolean} [params.useLocal] - * - * @returns {Promise} - */ -async function deleteDbEntry({ - dbContext, - paradigm, - dbFullName, - tableName, - identifierColumnName, - identifierValue, - useLocal, -}) { - try { - /** - * Check if data is valid - */ - const isMaster = useLocal - ? true - : dbContext?.match(/dsql.user/i) - ? false - : dbFullName && !dbFullName.match(/^datasquirel$/) - ? false - : true; - - /** @type { (a1:any, a2?:any) => any } */ - const dbHandler = useLocal - ? LOCAL_DB_HANDLER - : isMaster - ? DB_HANDLER - : DSQL_USER_DB_HANDLER; - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - - /** - * Execution - * - * @description - */ - const query = `DELETE FROM ${tableName} WHERE \`${identifierColumnName}\`=?`; - - const deletedEntry = isMaster - ? await dbHandler(query, [identifierValue]) - : await dbHandler({ - paradigm, - queryString: query, - database: dbFullName, - queryValues: [identifierValue], - }); - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - - /** - * Return statement - */ - return deletedEntry; - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - } catch (error) { - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - - return null; - } -} - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// - -module.exports = deleteDbEntry; diff --git a/package-shared/functions/backend/db/deleteDbEntry.ts b/package-shared/functions/backend/db/deleteDbEntry.ts new file mode 100644 index 0000000..2c9df39 --- /dev/null +++ b/package-shared/functions/backend/db/deleteDbEntry.ts @@ -0,0 +1,68 @@ +import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER"; +import DSQL_USER_DB_HANDLER from "../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"; +import LOCAL_DB_HANDLER from "../../../utils/backend/global-db/LOCAL_DB_HANDLER"; + +type Param = { + dbContext?: string; + paradigm?: "Read Only" | "Full Access"; + dbFullName: string; + tableName: string; + tableSchema?: import("../../../types").DSQL_TableSchemaType; + identifierColumnName: string; + identifierValue: string | number; + useLocal?: boolean; +}; + +/** + * # Delete DB Entry Function + * @description + */ +export default async function deleteDbEntry({ + dbContext, + paradigm, + dbFullName, + tableName, + identifierColumnName, + identifierValue, + useLocal, +}: Param): Promise { + try { + const isMaster = useLocal + ? true + : dbContext?.match(/dsql.user/i) + ? false + : dbFullName && !dbFullName.match(/^datasquirel$/) + ? false + : true; + + /** @type { (a1:any, a2?:any) => any } */ + const dbHandler: (a1: any, a2?: any) => any = useLocal + ? LOCAL_DB_HANDLER + : isMaster + ? DB_HANDLER + : DSQL_USER_DB_HANDLER; + + /** + * Execution + * + * @description + */ + const query = `DELETE FROM ${tableName} WHERE \`${identifierColumnName}\`=?`; + + const deletedEntry = isMaster + ? await dbHandler(query, [identifierValue]) + : await dbHandler({ + paradigm, + queryString: query, + database: dbFullName, + queryValues: [identifierValue], + }); + + /** + * Return statement + */ + return deletedEntry; + } catch (error) { + return null; + } +} diff --git a/package-shared/functions/backend/db/pathTraversalCheck.js b/package-shared/functions/backend/db/pathTraversalCheck.js deleted file mode 100644 index ee66714..0000000 --- a/package-shared/functions/backend/db/pathTraversalCheck.js +++ /dev/null @@ -1,14 +0,0 @@ -// @ts-check - -/** - * # Path Traversal Check - * - * @param {string|number} text - Text or number or object - * - * @returns {string} - */ -function pathTraversalCheck(text) { - return text.toString().replace(/\//g, ""); -} - -module.exports = pathTraversalCheck; diff --git a/package-shared/functions/backend/db/pathTraversalCheck.ts b/package-shared/functions/backend/db/pathTraversalCheck.ts new file mode 100644 index 0000000..10a2eec --- /dev/null +++ b/package-shared/functions/backend/db/pathTraversalCheck.ts @@ -0,0 +1,7 @@ +/** + * # Path Traversal Check + * @returns {string} + */ +export default function pathTraversalCheck(text: string | number): string { + return text.toString().replace(/\//g, ""); +} diff --git a/package-shared/functions/backend/db/runQuery.d.ts b/package-shared/functions/backend/db/runQuery.d.ts deleted file mode 100644 index 3353d87..0000000 --- a/package-shared/functions/backend/db/runQuery.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -export = runQuery; -/** - * Run DSQL users queries - * ============================================================================== - * @param {object} params - An object containing the function parameters. - * @param {string} params.dbFullName - Database full name. Eg. "datasquire_user_2_test" - * @param {string | any} params.query - Query string or object - * @param {boolean} [params.readOnly] - Is this operation read only? - * @param {boolean} [params.local] - Is this operation read only? - * @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema] - Database schema - * @param {(string | number)[]} [params.queryValuesArray] - An optional array of query values if "?" is used in the query string - * @param {string} [params.tableName] - Table Name - * - * @return {Promise} - */ -declare function runQuery({ dbFullName, query, readOnly, dbSchema, queryValuesArray, tableName, local, }: { - dbFullName: string; - query: string | any; - readOnly?: boolean; - local?: boolean; - dbSchema?: import("../../../types").DSQL_DatabaseSchemaType; - queryValuesArray?: (string | number)[]; - tableName?: string; -}): Promise; diff --git a/package-shared/functions/backend/db/runQuery.js b/package-shared/functions/backend/db/runQuery.ts similarity index 67% rename from package-shared/functions/backend/db/runQuery.js rename to package-shared/functions/backend/db/runQuery.ts index 1c4eb3b..8d47274 100644 --- a/package-shared/functions/backend/db/runQuery.js +++ b/package-shared/functions/backend/db/runQuery.ts @@ -1,32 +1,26 @@ -// @ts-check +import fullAccessDbHandler from "../fullAccessDbHandler"; +import varReadOnlyDatabaseDbHandler from "../varReadOnlyDatabaseDbHandler"; +import serverError from "../serverError"; +import addDbEntry from "./addDbEntry"; +import updateDbEntry from "./updateDbEntry"; +import deleteDbEntry from "./deleteDbEntry"; +import trimSql from "../../../utils/trim-sql"; +import { DSQL_TableSchemaType } from "../../../types"; -const fs = require("fs"); - -const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"); -const fullAccessDbHandler = require("../fullAccessDbHandler"); -const varReadOnlyDatabaseDbHandler = require("../varReadOnlyDatabaseDbHandler"); -const serverError = require("../serverError"); -const addDbEntry = require("./addDbEntry"); -const updateDbEntry = require("./updateDbEntry"); -const deleteDbEntry = require("./deleteDbEntry"); -const parseDbResults = require("../parseDbResults"); -const trimSql = require("../../../utils/trim-sql"); +type Param = { + dbFullName: string; + query: string | any; + readOnly?: boolean; + local?: boolean; + dbSchema?: import("../../../types").DSQL_DatabaseSchemaType; + queryValuesArray?: (string | number)[]; + tableName?: string; +}; /** - * Run DSQL users queries - * ============================================================================== - * @param {object} params - An object containing the function parameters. - * @param {string} params.dbFullName - Database full name. Eg. "datasquire_user_2_test" - * @param {string | any} params.query - Query string or object - * @param {boolean} [params.readOnly] - Is this operation read only? - * @param {boolean} [params.local] - Is this operation read only? - * @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema] - Database schema - * @param {(string | number)[]} [params.queryValuesArray] - An optional array of query values if "?" is used in the query string - * @param {string} [params.tableName] - Table Name - * - * @return {Promise} + * # Run DSQL users queries */ -async function runQuery({ +export default async function runQuery({ dbFullName, query, readOnly, @@ -34,19 +28,16 @@ async function runQuery({ queryValuesArray, tableName, local, -}) { +}: Param): Promise { /** * Declare variables * * @description Declare "results" variable */ - /** @type {any} */ - let result; - /** @type {any} */ - let error; - /** @type {import("../../../types").DSQL_TableSchemaType | undefined} */ - let tableSchema; + let result: any; + let error: any; + let tableSchema: DSQL_TableSchemaType | undefined; if (dbSchema) { try { @@ -178,11 +169,7 @@ async function runQuery({ break; } } - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { serverError({ component: "functions/backend/runQuery", message: error.message, @@ -191,15 +178,5 @@ async function runQuery({ error = error.message; } - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - return { result, error }; - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// } - -module.exports = runQuery; diff --git a/package-shared/functions/backend/db/sanitizeSql.js b/package-shared/functions/backend/db/sanitizeSql.ts similarity index 85% rename from package-shared/functions/backend/db/sanitizeSql.js rename to package-shared/functions/backend/db/sanitizeSql.ts index 9cc6fdd..1e50003 100644 --- a/package-shared/functions/backend/db/sanitizeSql.js +++ b/package-shared/functions/backend/db/sanitizeSql.ts @@ -1,20 +1,12 @@ -// @ts-check - -const _ = require("lodash"); +import _ from "lodash"; /** * Sanitize SQL function * ============================================================================== * @description this function takes in a text(or number) and returns a sanitized * text, usually without spaces - * - * @param {any} text - Text or number or object - * @param {boolean} [spaces] - Allow spaces - * @param {RegExp?} [regex] - Regular expression, removes any match - * - * @returns {any} */ -function sanitizeSql(text, spaces, regex) { +function sanitizeSql(text: any, spaces: boolean, regex?: RegExp | null): any { if (!text) return ""; if (typeof text == "number" || typeof text == "boolean") return text; if (typeof text == "string" && !text?.toString()?.match(/./)) return ""; @@ -63,9 +55,9 @@ function sanitizeSql(text, spaces, regex) { * * @returns {object} */ -function sanitizeObjects(object, spaces) { +function sanitizeObjects(object: any, spaces: boolean): object { /** @type {any} */ - let objectUpdated = { ...object }; + let objectUpdated: any = { ...object }; const keys = Object.keys(objectUpdated); keys.forEach((key) => { @@ -98,7 +90,10 @@ function sanitizeObjects(object, spaces) { * * @returns {string[]|number[]|object[]} */ -function sanitizeArrays(array, spaces) { +function sanitizeArrays( + array: any[], + spaces: boolean +): string[] | number[] | object[] { let arrayUpdated = _.cloneDeep(array); arrayUpdated.forEach((item, index) => { @@ -121,4 +116,4 @@ function sanitizeArrays(array, spaces) { return arrayUpdated; } -module.exports = sanitizeSql; +export default sanitizeSql; diff --git a/package-shared/functions/backend/db/updateDbEntry.d.ts b/package-shared/functions/backend/db/updateDbEntry.d.ts deleted file mode 100644 index 8c2345d..0000000 --- a/package-shared/functions/backend/db/updateDbEntry.d.ts +++ /dev/null @@ -1,37 +0,0 @@ -export = updateDbEntry; -/** - * Update DB Function - * ============================================================================== - * @description Description - * @async - * - * @param {object} params - An object containing the function parameters. - * @param {("Master" | "Dsql User")} [params.dbContext] - What is the database context? "Master" - * or "Dsql User". Defaults to "Master" - * @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"? - * "Read only" or "Full Access"? Defaults to "Read Only" - * @param {string} [params.dbFullName] - Database full name - * @param {string} params.tableName - Table name - * @param {string} [params.encryptionKey] - * @param {string} [params.encryptionSalt] - * @param {any} params.data - Data to add - * @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema - * @param {string} params.identifierColumnName - Update row identifier column name - * @param {string | number} params.identifierValue - Update row identifier column value - * @param {boolean} [params.useLocal] - * - * @returns {Promise} - */ -declare function updateDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, useLocal, }: { - dbContext?: ("Master" | "Dsql User"); - paradigm?: ("Read Only" | "Full Access"); - dbFullName?: string; - tableName: string; - encryptionKey?: string; - encryptionSalt?: string; - data: any; - tableSchema?: import("../../../types").DSQL_TableSchemaType; - identifierColumnName: string; - identifierValue: string | number; - useLocal?: boolean; -}): Promise; diff --git a/package-shared/functions/backend/db/updateDbEntry.js b/package-shared/functions/backend/db/updateDbEntry.ts similarity index 67% rename from package-shared/functions/backend/db/updateDbEntry.js rename to package-shared/functions/backend/db/updateDbEntry.ts index 63f1329..25186cd 100644 --- a/package-shared/functions/backend/db/updateDbEntry.js +++ b/package-shared/functions/backend/db/updateDbEntry.ts @@ -1,39 +1,29 @@ -// @ts-check +import sanitizeHtml from "sanitize-html"; +import sanitizeHtmlOptions from "../html/sanitizeHtmlOptions"; +import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER"; +import DSQL_USER_DB_HANDLER from "../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"; +import encrypt from "../../dsql/encrypt"; +import LOCAL_DB_HANDLER from "../../../utils/backend/global-db/LOCAL_DB_HANDLER"; + +type Param = { + dbContext?: "Master" | "Dsql User"; + paradigm?: "Read Only" | "Full Access"; + dbFullName?: string; + tableName: string; + encryptionKey?: string; + encryptionSalt?: string; + data: any; + tableSchema?: import("../../../types").DSQL_TableSchemaType; + identifierColumnName: string; + identifierValue: string | number; + useLocal?: boolean; +}; /** - * Imports: Handle imports + * # Update DB Function + * @description */ -const sanitizeHtml = require("sanitize-html"); -const sanitizeHtmlOptions = require("../html/sanitizeHtmlOptions"); -const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER"); -const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"); -const encrypt = require("../../dsql/encrypt"); -const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"); - -/** - * Update DB Function - * ============================================================================== - * @description Description - * @async - * - * @param {object} params - An object containing the function parameters. - * @param {("Master" | "Dsql User")} [params.dbContext] - What is the database context? "Master" - * or "Dsql User". Defaults to "Master" - * @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"? - * "Read only" or "Full Access"? Defaults to "Read Only" - * @param {string} [params.dbFullName] - Database full name - * @param {string} params.tableName - Table name - * @param {string} [params.encryptionKey] - * @param {string} [params.encryptionSalt] - * @param {any} params.data - Data to add - * @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema - * @param {string} params.identifierColumnName - Update row identifier column name - * @param {string | number} params.identifierValue - Update row identifier column value - * @param {boolean} [params.useLocal] - * - * @returns {Promise} - */ -async function updateDbEntry({ +export default async function updateDbEntry({ dbContext, paradigm, dbFullName, @@ -45,7 +35,7 @@ async function updateDbEntry({ encryptionKey, encryptionSalt, useLocal, -}) { +}: Param): Promise { /** * Check if data is valid */ @@ -60,7 +50,7 @@ async function updateDbEntry({ : true; /** @type {(a1:any, a2?:any)=> any } */ - const dbHandler = useLocal + const dbHandler: (a1: any, a2?: any) => any = useLocal ? LOCAL_DB_HANDLER : isMaster ? DB_HANDLER @@ -153,7 +143,7 @@ async function updateDbEntry({ //////////////////////////////////////// //////////////////////////////////////// - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { //////////////////////////////////////// //////////////////////////////////////// @@ -189,18 +179,8 @@ async function updateDbEntry({ queryValues: updateValues, }); - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - /** * Return statement */ return updatedEntry; } - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// - -module.exports = updateDbEntry; diff --git a/package-shared/functions/backend/dbHandler.js b/package-shared/functions/backend/dbHandler.ts similarity index 62% rename from package-shared/functions/backend/dbHandler.js rename to package-shared/functions/backend/dbHandler.ts index 1bf0f83..8dd3df8 100644 --- a/package-shared/functions/backend/dbHandler.js +++ b/package-shared/functions/backend/dbHandler.ts @@ -1,10 +1,8 @@ -// @ts-check +import fs from "fs"; +import serverError from "./serverError"; -const fs = require("fs"); -const serverError = require("./serverError"); - -const mysql = require("serverless-mysql"); -const grabDbSSL = require("../../utils/backend/grabDbSSL"); +import mysql from "serverless-mysql"; +import grabDbSSL from "../../utils/backend/grabDbSSL"; const connection = mysql({ config: { @@ -18,14 +16,9 @@ const connection = mysql({ }); /** - * Main DB Handler Function - * ============================================================================== - * @async - * - * @param {any} args - * @returns {Promise} + * # Main DB Handler Function */ -module.exports = async function dbHandler(...args) { +export default async function dbHandler(...args: any[]) { process.env.NODE_ENV?.match(/dev/) && fs.appendFileSync( "./.tmp/sqlQuery.sql", @@ -47,18 +40,20 @@ module.exports = async function dbHandler(...args) { */ try { results = await new Promise((resolve, reject) => { - // @ts-ignore - connection.query(...args, (error, result, fields) => { - if (error) { - resolve({ error: error.message }); - } else { - resolve(result); + connection.query( + ...args, + (error: any, result: any, fields: any) => { + if (error) { + resolve({ error: error.message }); + } else { + resolve(result); + } } - }); + ); }); await connection.end(); - } catch (/** @type {any} */ error) { + } catch (error: any) { fs.appendFileSync( "./.tmp/dbErrorLogs.txt", JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n", @@ -83,4 +78,4 @@ module.exports = async function dbHandler(...args) { } else { return null; } -}; +} diff --git a/package-shared/functions/backend/defaultFieldsRegexp.d.ts b/package-shared/functions/backend/defaultFieldsRegexp.d.ts deleted file mode 100644 index fc8ca8c..0000000 --- a/package-shared/functions/backend/defaultFieldsRegexp.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export = defaultFieldsRegexp; -/** - * Regular expression to match default fields - * - * @description Regular expression to match default fields - */ -declare const defaultFieldsRegexp: RegExp; diff --git a/package-shared/functions/backend/defaultFieldsRegexp.js b/package-shared/functions/backend/defaultFieldsRegexp.ts similarity index 81% rename from package-shared/functions/backend/defaultFieldsRegexp.js rename to package-shared/functions/backend/defaultFieldsRegexp.ts index acbcde7..6171a8f 100644 --- a/package-shared/functions/backend/defaultFieldsRegexp.js +++ b/package-shared/functions/backend/defaultFieldsRegexp.ts @@ -1,5 +1,3 @@ -// @ts-check - /** * Regular expression to match default fields * @@ -8,4 +6,4 @@ const defaultFieldsRegexp = /^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/; -module.exports = defaultFieldsRegexp; +export default defaultFieldsRegexp; diff --git a/package-shared/functions/backend/fullAccessDbHandler.d.ts b/package-shared/functions/backend/fullAccessDbHandler.d.ts deleted file mode 100644 index 7511d7c..0000000 --- a/package-shared/functions/backend/fullAccessDbHandler.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -declare function _exports({ queryString, database, tableSchema, queryValuesArray, local, }: { - queryString: string; - database: string; - local?: boolean; - tableSchema?: import("../../types").DSQL_TableSchemaType | null; - queryValuesArray?: string[]; -}): Promise; -export = _exports; diff --git a/package-shared/functions/backend/fullAccessDbHandler.js b/package-shared/functions/backend/fullAccessDbHandler.ts similarity index 66% rename from package-shared/functions/backend/fullAccessDbHandler.js rename to package-shared/functions/backend/fullAccessDbHandler.ts index beb7b5a..7d4a026 100644 --- a/package-shared/functions/backend/fullAccessDbHandler.js +++ b/package-shared/functions/backend/fullAccessDbHandler.ts @@ -1,27 +1,28 @@ // @ts-check -const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER"); -const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER"); -const parseDbResults = require("./parseDbResults"); -const serverError = require("./serverError"); +import DSQL_USER_DB_HANDLER from "../../utils/backend/global-db/DSQL_USER_DB_HANDLER"; +import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER"; +import parseDbResults from "./parseDbResults"; +import serverError from "./serverError"; + +type Param = { + queryString: string; + database: string; + local?: boolean; + tableSchema?: import("../../types").DSQL_TableSchemaType | null; + queryValuesArray?: string[]; +}; /** - * - * @param {object} param0 - * @param {string} param0.queryString - * @param {string} param0.database - * @param {boolean} [param0.local] - * @param {import("../../types").DSQL_TableSchemaType | null} [param0.tableSchema] - * @param {string[]} [param0.queryValuesArray] - * @returns + * # Full Access Db Handler */ -module.exports = async function fullAccessDbHandler({ +export default async function fullAccessDbHandler({ queryString, database, tableSchema, queryValuesArray, local, -}) { +}: Param) { /** * Declare variables * @@ -47,7 +48,7 @@ module.exports = async function fullAccessDbHandler({ }); //////////////////////////////////////// - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { //////////////////////////////////////// serverError({ @@ -78,4 +79,4 @@ module.exports = async function fullAccessDbHandler({ } else { return null; } -}; +} diff --git a/package-shared/functions/backend/grabNewUsersTableSchema.d.ts b/package-shared/functions/backend/grabNewUsersTableSchema.d.ts deleted file mode 100644 index 350ce2d..0000000 --- a/package-shared/functions/backend/grabNewUsersTableSchema.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -declare function _exports(params?: { - payload?: { - [x: string]: any; - }; -}): import("../../types").DSQL_TableSchemaType | null; -export = _exports; diff --git a/package-shared/functions/backend/grabNewUsersTableSchema.js b/package-shared/functions/backend/grabNewUsersTableSchema.ts similarity index 55% rename from package-shared/functions/backend/grabNewUsersTableSchema.js rename to package-shared/functions/backend/grabNewUsersTableSchema.ts index d31fd6d..89d8ddd 100755 --- a/package-shared/functions/backend/grabNewUsersTableSchema.js +++ b/package-shared/functions/backend/grabNewUsersTableSchema.ts @@ -1,22 +1,16 @@ -// @ts-check - -const grabSchemaFieldsFromData = require("./grabSchemaFieldsFromData"); -const serverError = require("./serverError"); +import { DSQL_FieldSchemaType, DSQL_TableSchemaType } from "../../types"; +import grabSchemaFieldsFromData from "./grabSchemaFieldsFromData"; +import serverError from "./serverError"; /** * # Add User Table to Database - * - * @param {object} [params] - * @param {Object} [params.payload] - fields to add to the table - * - * @returns {import("../../types").DSQL_TableSchemaType | null} new user auth object payload */ -module.exports = function grabNewUsersTableSchema(params) { +export default function grabNewUsersTableSchema(params: { + payload?: { [s: string]: any }; +}): DSQL_TableSchemaType | null { try { - /** @type {import("../../types").DSQL_TableSchemaType} */ - const userPreset = require("../../data/presets/users.json"); - /** @type {import("../../types").DSQL_FieldSchemaType[]} */ - const defaultFields = require("../../data/defaultFields.json"); + const userPreset: DSQL_TableSchemaType = require("../../data/presets/users.json"); + const defaultFields: DSQL_FieldSchemaType[] = require("../../data/defaultFields.json"); const supplementalFields = params?.payload ? grabSchemaFieldsFromData({ @@ -41,7 +35,7 @@ module.exports = function grabNewUsersTableSchema(params) { userPreset.fields = [...finalFields]; return userPreset; - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log(`grabNewUsersTableSchema.js ERROR: ${error.message}`); serverError({ @@ -51,4 +45,4 @@ module.exports = function grabNewUsersTableSchema(params) { return null; } -}; +} diff --git a/package-shared/functions/backend/grabSchemaFieldsFromData.d.ts b/package-shared/functions/backend/grabSchemaFieldsFromData.d.ts deleted file mode 100644 index 1ff25bf..0000000 --- a/package-shared/functions/backend/grabSchemaFieldsFromData.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -declare function _exports({ data, fields, excludeData, excludeFields, }: { - data?: { - [x: string]: any; - }; - fields?: string[]; - excludeData?: { - [x: string]: any; - }; - excludeFields?: import("../../types").DSQL_FieldSchemaType[]; -}): import("../../types").DSQL_FieldSchemaType[]; -export = _exports; diff --git a/package-shared/functions/backend/grabSchemaFieldsFromData.js b/package-shared/functions/backend/grabSchemaFieldsFromData.ts similarity index 51% rename from package-shared/functions/backend/grabSchemaFieldsFromData.js rename to package-shared/functions/backend/grabSchemaFieldsFromData.ts index ec813db..d364f34 100755 --- a/package-shared/functions/backend/grabSchemaFieldsFromData.js +++ b/package-shared/functions/backend/grabSchemaFieldsFromData.ts @@ -1,33 +1,31 @@ -// @ts-check +import { DSQL_FieldSchemaType } from "../../types"; +import serverError from "./serverError"; -const serverError = require("./serverError"); +type Param = { + data?: { [s: string]: any }; + fields?: string[]; + excludeData?: { [s: string]: any }; + excludeFields?: DSQL_FieldSchemaType[]; +}; /** * # Add User Table to Database - * - * @param {object} params - * @param {Object} [params.data] - * @param {string[]} [params.fields] - * @param {Object} [params.excludeData] - * @param {import("../../types").DSQL_FieldSchemaType[]} [params.excludeFields] - * - * @returns {import("../../types").DSQL_FieldSchemaType[]} new user auth object payload */ -module.exports = function grabSchemaFieldsFromData({ +export default function grabSchemaFieldsFromData({ data, fields, excludeData, excludeFields, -}) { +}: Param): DSQL_FieldSchemaType[] { try { const possibleFields = require("../../data/possibleFields.json"); const dataTypes = require("../../data/dataTypes.json"); - /** @type {import("../../types").DSQL_FieldSchemaType[]} */ - const finalFields = []; + /** @type {DSQL_FieldSchemaType[]} */ + const finalFields: DSQL_FieldSchemaType[] = []; /** @type {string[]} */ - let filteredFields = []; + let filteredFields: string[] = []; if (data && Object.keys(data)?.[0]) { filteredFields = Object.keys(data); @@ -52,11 +50,10 @@ module.exports = function grabSchemaFieldsFromData({ const value = data ? data[fld] : null; if (typeof value == "string") { - const newField = - /** @type {import("../../types").DSQL_FieldSchemaType} */ ({ - fieldName: fld, - dataType: value.length > 255 ? "TEXT" : "VARCHAR(255)", - }); + const newField: DSQL_FieldSchemaType = { + fieldName: fld, + dataType: value.length > 255 ? "TEXT" : "VARCHAR(255)", + }; if (Boolean(value.match(/<[^>]+>/g))) { newField.richText = true; @@ -64,24 +61,20 @@ module.exports = function grabSchemaFieldsFromData({ finalFields.push(newField); } else if (typeof value == "number") { - finalFields.push( - /** @type {import("../../types").DSQL_FieldSchemaType} */ ({ - fieldName: fld, - dataType: "INT", - }) - ); + finalFields.push({ + fieldName: fld, + dataType: "INT", + }); } else { - finalFields.push( - /** @type {import("../../types").DSQL_FieldSchemaType} */ ({ - fieldName: fld, - dataType: "VARCHAR(255)", - }) - ); + finalFields.push({ + fieldName: fld, + dataType: "VARCHAR(255)", + }); } }); return finalFields; - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log(`grabSchemaFieldsFromData.js ERROR: ${error.message}`); serverError({ @@ -91,4 +84,4 @@ module.exports = function grabSchemaFieldsFromData({ return []; } -}; +} diff --git a/package-shared/functions/backend/grabUserSchemaData.d.ts b/package-shared/functions/backend/grabUserSchemaData.d.ts deleted file mode 100644 index b3d9e3b..0000000 --- a/package-shared/functions/backend/grabUserSchemaData.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -declare function _exports({ userId }: { - userId: string | number; -}): import("../../types").DSQL_DatabaseSchemaType[] | null; -export = _exports; diff --git a/package-shared/functions/backend/grabUserSchemaData.js b/package-shared/functions/backend/grabUserSchemaData.js deleted file mode 100755 index 417f7bb..0000000 --- a/package-shared/functions/backend/grabUserSchemaData.js +++ /dev/null @@ -1,46 +0,0 @@ -// @ts-check - -const serverError = require("./serverError"); -const fs = require("fs"); -const path = require("path"); - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -/** - * ============================================================================== - * @param {Object} params - * @param {string | number} params.userId - * @returns {import("../../types").DSQL_DatabaseSchemaType[] | null} - */ -module.exports = function grabUserSchemaData({ userId }) { - try { - const userSchemaFilePath = path.resolve( - process.cwd(), - `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json` - ); - const userSchemaData = JSON.parse( - fs.readFileSync(userSchemaFilePath, "utf-8") - ); - - return userSchemaData; - } catch (/** @type {any} */ error) { - serverError({ - component: "grabUserSchemaData", - message: error.message, - }); - - return null; - } -}; - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ diff --git a/package-shared/functions/backend/grabUserSchemaData.ts b/package-shared/functions/backend/grabUserSchemaData.ts new file mode 100755 index 0000000..02dc5bb --- /dev/null +++ b/package-shared/functions/backend/grabUserSchemaData.ts @@ -0,0 +1,31 @@ +import serverError from "./serverError"; +import fs from "fs"; +import path from "path"; + +/** + * # Grab User Schema Data + */ +export default function grabUserSchemaData({ + userId, +}: { + userId: string | number; +}): import("../../types").DSQL_DatabaseSchemaType[] | null { + try { + const userSchemaFilePath = path.resolve( + process.cwd(), + `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json` + ); + const userSchemaData = JSON.parse( + fs.readFileSync(userSchemaFilePath, "utf-8") + ); + + return userSchemaData; + } catch (error: any) { + serverError({ + component: "grabUserSchemaData", + message: error.message, + }); + + return null; + } +} diff --git a/package-shared/functions/backend/handleNodemailer.d.ts b/package-shared/functions/backend/handleNodemailer.d.ts deleted file mode 100644 index b812686..0000000 --- a/package-shared/functions/backend/handleNodemailer.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -declare function _exports({ to, subject, text, html, alias, }: { - to?: string; - subject?: string; - text?: string; - html?: string; - alias?: string | null; -}): Promise; -export = _exports; diff --git a/package-shared/functions/backend/handleNodemailer.js b/package-shared/functions/backend/handleNodemailer.ts similarity index 53% rename from package-shared/functions/backend/handleNodemailer.js rename to package-shared/functions/backend/handleNodemailer.ts index aeb91eb..edeb68d 100755 --- a/package-shared/functions/backend/handleNodemailer.js +++ b/package-shared/functions/backend/handleNodemailer.ts @@ -1,21 +1,5 @@ -// @ts-check - -/** - * Imports - * ============================================================================== - */ - -const fs = require("fs"); - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// - -const nodemailer = require("nodemailer"); - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// +import fs from "fs"; +import nodemailer, { SendMailOptions } from "nodemailer"; let transporter = nodemailer.createTransport({ host: process.env.DSQL_MAIL_HOST, @@ -27,31 +11,26 @@ let transporter = nodemailer.createTransport({ }, }); -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ +type Param = { + to?: string; + subject?: string; + text?: string; + html?: string; + senderName?: string; + alias?: string | null; +}; /** - * # Handle mails - * @param {object} mailObject - Mail Object with params - * @param {string} [mailObject.to] - who is recieving this email? Comma separated for multiple recipients - * @param {string} [mailObject.subject] - Mail Subject - * @param {string} [mailObject.text] - Mail text - * @param {string} [mailObject.html] - Mail HTML - * @param {string | null} [mailObject.alias] - Sender alias: "support" or null - * - * @returns {Promise} mail object + * # Handle mails With Nodemailer */ -module.exports = async function handleNodemailer({ +export default async function handleNodemailer({ to, subject, text, html, alias, -}) { + senderName, +}: Param): Promise { //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// @@ -89,12 +68,11 @@ module.exports = async function handleNodemailer({ //////////////////////////////////////// try { - let mailObject = {}; + let mailObject: SendMailOptions = {}; - mailObject["from"] = `"Datasquirel" <${sender}>`; + mailObject["from"] = `"${senderName || "Datasquirel"}" <${sender}>`; mailObject["sender"] = sender; - if (alias) mailObject["replyTo "] = sender; - // mailObject["priority"] = "high"; + if (alias) mailObject["replyTo"] = sender; mailObject["to"] = to; mailObject["subject"] = subject; mailObject["text"] = text; @@ -108,7 +86,7 @@ module.exports = async function handleNodemailer({ //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// @@ -122,8 +100,4 @@ module.exports = async function handleNodemailer({ } return sentMessage; -}; - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// +} diff --git a/package-shared/functions/backend/html/sanitizeHtmlOptions.d.ts b/package-shared/functions/backend/html/sanitizeHtmlOptions.d.ts deleted file mode 100644 index 7e587c9..0000000 --- a/package-shared/functions/backend/html/sanitizeHtmlOptions.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export let allowedTags: string[]; -export let allowedAttributes: { - a: string[]; - img: string[]; - "*": string[]; -}; diff --git a/package-shared/functions/backend/html/sanitizeHtmlOptions.js b/package-shared/functions/backend/html/sanitizeHtmlOptions.js deleted file mode 100644 index fecd803..0000000 --- a/package-shared/functions/backend/html/sanitizeHtmlOptions.js +++ /dev/null @@ -1,12 +0,0 @@ -// @ts-check - -const sanitizeHtmlOptions = { - allowedTags: ["b", "i", "em", "strong", "a", "p", "span", "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6", "img", "div", "button", "pre", "code", "br"], - allowedAttributes: { - a: ["href"], - img: ["src", "alt", "width", "height", "class", "style"], - "*": ["style", "class"], - }, -}; - -module.exports = sanitizeHtmlOptions; diff --git a/package-shared/functions/backend/html/sanitizeHtmlOptions.ts b/package-shared/functions/backend/html/sanitizeHtmlOptions.ts new file mode 100644 index 0000000..347ae66 --- /dev/null +++ b/package-shared/functions/backend/html/sanitizeHtmlOptions.ts @@ -0,0 +1,35 @@ +// @ts-check + +const sanitizeHtmlOptions = { + allowedTags: [ + "b", + "i", + "em", + "strong", + "a", + "p", + "span", + "ul", + "ol", + "li", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "img", + "div", + "button", + "pre", + "code", + "br", + ], + allowedAttributes: { + a: ["href"], + img: ["src", "alt", "width", "height", "class", "style"], + "*": ["style", "class"], + }, +}; + +export default sanitizeHtmlOptions; diff --git a/package-shared/functions/backend/httpRequest.d.ts b/package-shared/functions/backend/httpRequest.d.ts deleted file mode 100644 index fca4e0f..0000000 --- a/package-shared/functions/backend/httpRequest.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export = httpRequest; -/** - * # Generate a http Request - * @type {import("../../types").HttpRequestFunction} - */ -declare const httpRequest: import("../../types").HttpRequestFunction; diff --git a/package-shared/functions/backend/httpRequest.js b/package-shared/functions/backend/httpRequest.ts similarity index 80% rename from package-shared/functions/backend/httpRequest.js rename to package-shared/functions/backend/httpRequest.ts index bf22ad9..800634d 100644 --- a/package-shared/functions/backend/httpRequest.js +++ b/package-shared/functions/backend/httpRequest.ts @@ -1,16 +1,17 @@ -// @ts-check - -const http = require("node:http"); -const https = require("node:https"); -const querystring = require("querystring"); -const serializeQuery = require("../../utils/serialize-query"); -const _ = require("lodash"); +import http from "node:http"; +import https from "node:https"; +import querystring from "querystring"; +import serializeQuery from "../../utils/serialize-query"; +import _ from "lodash"; +import { HttpFunctionResponse, HttpRequestParams } from "../../types"; /** * # Generate a http Request - * @type {import("../../types").HttpRequestFunction} */ -const httpRequest = (params) => { +export default function httpRequest< + ReqObj extends { [k: string]: any } = { [k: string]: any }, + ResObj extends { [k: string]: any } = { [k: string]: any } +>(params: HttpRequestParams): Promise> { return new Promise((resolve, reject) => { const isUrlEncodedFormBody = params.urlEncodedFormBody; @@ -37,7 +38,7 @@ const httpRequest = (params) => { delete params.urlEncodedFormBody; /** @type {import("node:https").RequestOptions} */ - const requestOptions = { + const requestOptions: import("node:https").RequestOptions = { ...params, headers: { "Content-Type": isUrlEncodedFormBody @@ -69,13 +70,13 @@ const httpRequest = (params) => { response.on("end", function () { const data = (() => { try { - /** @type {Object} */ - const jsonObj = JSON.parse(str); + const jsonObj: { [k: string]: any } = + JSON.parse(str); return jsonObj; } catch (error) { return undefined; } - })(); + })() as any; resolve({ status: response.statusCode || 404, @@ -106,6 +107,4 @@ const httpRequest = (params) => { httpsRequest.end(); }); -}; - -module.exports = httpRequest; +} diff --git a/package-shared/functions/backend/httpsRequest.d.ts b/package-shared/functions/backend/httpsRequest.d.ts deleted file mode 100644 index 1c67f8c..0000000 --- a/package-shared/functions/backend/httpsRequest.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -declare function _exports({ url, method, hostname, path, headers, body, port, scheme, }: { - scheme?: string; - url?: string; - method?: string; - hostname?: string; - path?: string; - port?: number | string; - headers?: object; - body?: object; -}): Promise; -export = _exports; diff --git a/package-shared/functions/backend/httpsRequest.js b/package-shared/functions/backend/httpsRequest.ts similarity index 61% rename from package-shared/functions/backend/httpsRequest.js rename to package-shared/functions/backend/httpsRequest.ts index 90d912e..493544d 100644 --- a/package-shared/functions/backend/httpsRequest.js +++ b/package-shared/functions/backend/httpsRequest.ts @@ -1,35 +1,22 @@ -// @ts-check +import https from "https"; +import http from "http"; +import { URL } from "url"; + +type Param = { + scheme?: string; + url?: string; + method?: string; + hostname?: string; + path?: string; + port?: number | string; + headers?: object; + body?: object; +}; /** - * Imports - * ============================================================================== + * # Make Https Request */ -const https = require("https"); -const http = require("http"); -const { URL } = require("url"); - -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// - -/** - * Main Function - * ============================================================================== - * @param {{ - * scheme?: string, - * url?: string, - * method?: string, - * hostname?: string, - * path?: string, - * port?: number | string, - * headers?: object, - * body?: object, - * }} params - params - */ -module.exports = function httpsRequest({ +export default function httpsRequest({ url, method, hostname, @@ -38,7 +25,7 @@ module.exports = function httpsRequest({ body, port, scheme, -}) { +}: Param) { const reqPayloadString = body ? JSON.stringify(body) : null; const PARSED_URL = url ? new URL(url) : null; @@ -48,7 +35,7 @@ module.exports = function httpsRequest({ //////////////////////////////////////////////// /** @type {any} */ - let requestOptions = { + let requestOptions: any = { method: method || "GET", hostname: PARSED_URL ? PARSED_URL.hostname : hostname, port: scheme?.match(/https/i) @@ -126,16 +113,5 @@ module.exports = function httpsRequest({ }); httpsRequest.end(); - - //////////////////////////////////////////////// - //////////////////////////////////////////////// - //////////////////////////////////////////////// }); -}; - -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// +} diff --git a/package-shared/functions/backend/noDatabaseDbHandler.js b/package-shared/functions/backend/noDatabaseDbHandler.ts similarity index 65% rename from package-shared/functions/backend/noDatabaseDbHandler.js rename to package-shared/functions/backend/noDatabaseDbHandler.ts index 081a3c6..a4efb55 100644 --- a/package-shared/functions/backend/noDatabaseDbHandler.js +++ b/package-shared/functions/backend/noDatabaseDbHandler.ts @@ -1,16 +1,13 @@ -// @ts-check - -const fs = require("fs"); -const serverError = require("./serverError"); -const NO_DB_HANDLER = require("../../../package-shared/utils/backend/global-db/NO_DB_HANDLER"); +import fs from "fs"; +import serverError from "./serverError"; +import NO_DB_HANDLER from "../../../package-shared/utils/backend/global-db/NO_DB_HANDLER"; /** - * Create database from Schema Function - * ============================================================================== - * @param {string} queryString - Query String - * @returns {Promise} + * # No Database DB Handler */ -module.exports = async function noDatabaseDbHandler(queryString) { +export default async function noDatabaseDbHandler( + queryString: string +): Promise { process.env.NODE_ENV?.match(/dev/) && fs.appendFileSync( "./.tmp/sqlQuery.sql", @@ -37,7 +34,7 @@ module.exports = async function noDatabaseDbHandler(queryString) { //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { serverError({ component: "noDatabaseDbHandler", message: error.message, @@ -56,4 +53,4 @@ module.exports = async function noDatabaseDbHandler(queryString) { } else { return null; } -}; +} diff --git a/package-shared/functions/backend/parseDbResults.d.ts b/package-shared/functions/backend/parseDbResults.d.ts deleted file mode 100644 index b04bca9..0000000 --- a/package-shared/functions/backend/parseDbResults.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -declare function _exports({ unparsedResults, tableSchema, }: { - unparsedResults: any[]; - tableSchema?: import("../../types").DSQL_TableSchemaType; -}): Promise; -export = _exports; diff --git a/package-shared/functions/backend/parseDbResults.js b/package-shared/functions/backend/parseDbResults.ts similarity index 75% rename from package-shared/functions/backend/parseDbResults.js rename to package-shared/functions/backend/parseDbResults.ts index 9959390..63f759b 100644 --- a/package-shared/functions/backend/parseDbResults.js +++ b/package-shared/functions/backend/parseDbResults.ts @@ -1,7 +1,12 @@ // @ts-check -const decrypt = require("../dsql/decrypt"); -const defaultFieldsRegexp = require("./defaultFieldsRegexp"); +import decrypt from "../dsql/decrypt"; +import defaultFieldsRegexp from "./defaultFieldsRegexp"; + +type Param = { + unparsedResults: any[]; + tableSchema?: import("../../types").DSQL_TableSchemaType; +}; /** * Parse Database results @@ -9,17 +14,11 @@ const defaultFieldsRegexp = require("./defaultFieldsRegexp"); * @description this function takes a database results array gotten from a DB handler * function, decrypts encrypted fields, and returns an updated array with no encrypted * fields - * - * @param {object} params - Single object params - * @param {any[]} params.unparsedResults - Array of data objects containing Fields(keys) - * and corresponding values of the fields(values) - * @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema - * @returns {Promise} */ -module.exports = async function parseDbResults({ +export default async function parseDbResults({ unparsedResults, tableSchema, -}) { +}: Param): Promise { /** * Declare variables * @@ -71,8 +70,8 @@ module.exports = async function parseDbResults({ * @description Declare "results" variable */ return parsedResults; - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log("ERROR in parseDbResults Function =>", error.message); return unparsedResults; } -}; +} diff --git a/package-shared/functions/backend/serverError.d.ts b/package-shared/functions/backend/serverError.d.ts deleted file mode 100644 index c1688ba..0000000 --- a/package-shared/functions/backend/serverError.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -declare function _exports({ user, message, component, noMail, req, }: { - user?: { - id?: number | string; - first_name?: string; - last_name?: string; - email?: string; - } & any; - message: string; - component?: string; - noMail?: boolean; - req?: import("next").NextApiRequest & IncomingMessage; -}): Promise; -export = _exports; -import { IncomingMessage } from "http"; diff --git a/package-shared/functions/backend/serverError.js b/package-shared/functions/backend/serverError.ts similarity index 79% rename from package-shared/functions/backend/serverError.js rename to package-shared/functions/backend/serverError.ts index 7306aae..149757d 100755 --- a/package-shared/functions/backend/serverError.js +++ b/package-shared/functions/backend/serverError.ts @@ -1,28 +1,31 @@ // @ts-check -const fs = require("fs"); -const { IncomingMessage } = require("http"); +import fs from "fs"; +import { IncomingMessage } from "http"; + +type Param = { + user?: { + id?: number | string; + first_name?: string; + last_name?: string; + email?: string; + } & any; + message: string; + component?: string; + noMail?: boolean; + req?: import("next").NextApiRequest & IncomingMessage; +}; /** * # Server Error - * - * @param {{ - * user?: { id?: number | string, first_name?: string, last_name?: string, email?: string } & *, - * message: string, - * component?: string, - * noMail?: boolean, - * req?: import("next").NextApiRequest & IncomingMessage, - * }} params - user id - * - * @returns {Promise} */ -module.exports = async function serverError({ +export default async function serverError({ user, message, component, noMail, req, -}) { +}: Param): Promise { const date = new Date(); const reqIp = (() => { @@ -80,10 +83,10 @@ module.exports = async function serverError({ fs.writeFileSync(`./.tmp/error.log`, log); fs.appendFileSync(`./.tmp/error.log`, `\n\n\n\n\n${initialText}`); - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log("Server Error Reporting Error:", error.message); } -}; +} //////////////////////////////////////// //////////////////////////////////////// diff --git a/package-shared/functions/backend/setUserSchemaData.d.ts b/package-shared/functions/backend/setUserSchemaData.d.ts deleted file mode 100644 index 8ce9742..0000000 --- a/package-shared/functions/backend/setUserSchemaData.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -declare function _exports({ userId, schemaData }: { - userId: string | number; - schemaData: import("../../types").DSQL_DatabaseSchemaType[]; -}): boolean; -export = _exports; diff --git a/package-shared/functions/backend/setUserSchemaData.js b/package-shared/functions/backend/setUserSchemaData.js deleted file mode 100755 index 6472dc9..0000000 --- a/package-shared/functions/backend/setUserSchemaData.js +++ /dev/null @@ -1,49 +0,0 @@ -// @ts-check - -const serverError = require("./serverError"); -const fs = require("fs"); -const path = require("path"); - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -/** - * ============================================================================== - * @param {Object} params - * @param {string | number} params.userId - * @param {import("../../types").DSQL_DatabaseSchemaType[]} params.schemaData - * @returns {boolean} - */ -module.exports = function setUserSchemaData({ userId, schemaData }) { - try { - const userSchemaFilePath = path.resolve( - process.cwd(), - `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json` - ); - fs.writeFileSync( - userSchemaFilePath, - JSON.stringify(schemaData), - "utf8" - ); - - return true; - } catch (/** @type {any} */ error) { - serverError({ - component: "/functions/backend/setUserSchemaData", - message: error.message, - }); - - return false; - } -}; - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ diff --git a/package-shared/functions/backend/setUserSchemaData.ts b/package-shared/functions/backend/setUserSchemaData.ts new file mode 100755 index 0000000..2ad1d83 --- /dev/null +++ b/package-shared/functions/backend/setUserSchemaData.ts @@ -0,0 +1,45 @@ +import serverError from "./serverError"; +import fs from "fs"; +import path from "path"; +import { DSQL_DatabaseSchemaType } from "../../types"; + +type Param = { + userId: string | number; + schemaData: DSQL_DatabaseSchemaType[]; +}; + +/** + * # Set User Schema Data + */ +export default function setUserSchemaData({ + userId, + schemaData, +}: Param): boolean { + try { + const userSchemaFilePath = path.resolve( + process.cwd(), + `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json` + ); + fs.writeFileSync( + userSchemaFilePath, + JSON.stringify(schemaData), + "utf8" + ); + + return true; + } catch (error: any) { + serverError({ + component: "/functions/backend/setUserSchemaData", + message: error.message, + }); + + return false; + } +} + +/** ****************************************************************************** */ +/** ****************************************************************************** */ +/** ****************************************************************************** */ +/** ****************************************************************************** */ +/** ****************************************************************************** */ +/** ****************************************************************************** */ diff --git a/package-shared/functions/backend/suSocketAuth.js b/package-shared/functions/backend/suSocketAuth.ts similarity index 64% rename from package-shared/functions/backend/suSocketAuth.js rename to package-shared/functions/backend/suSocketAuth.ts index f2acdb9..d162b24 100644 --- a/package-shared/functions/backend/suSocketAuth.js +++ b/package-shared/functions/backend/suSocketAuth.ts @@ -1,17 +1,17 @@ // @ts-check -const { IncomingMessage } = require("http"); -const parseCookies = require("../../utils/backend/parseCookies"); -const decrypt = require("../dsql/decrypt"); -const getAuthCookieNames = require("./cookies/get-auth-cookie-names"); +import { IncomingMessage } from "http"; +import parseCookies from "../../utils/backend/parseCookies"; +import decrypt from "../dsql/decrypt"; +import getAuthCookieNames from "./cookies/get-auth-cookie-names"; -/** - * @async - * @param {IncomingMessage} req - https request object - * - * @returns {Promise<({ email: string, password: string, authKey: string, logged_in_status: boolean, date: number } | null)>} - */ -module.exports = async function (req) { +export default async function (req: IncomingMessage): Promise<{ + email: string; + password: string; + authKey: string; + logged_in_status: boolean; + date: number; +} | null> { const { keyCookieName, csrfCookieName } = getAuthCookieNames(); const suKeyName = `${keyCookieName}_su`; @@ -40,4 +40,4 @@ module.exports = async function (req) { /** ********************* return user object */ return userObject; -}; +} diff --git a/package-shared/functions/backend/updateUsersTableSchema.d.ts b/package-shared/functions/backend/updateUsersTableSchema.d.ts deleted file mode 100644 index c4d1b86..0000000 --- a/package-shared/functions/backend/updateUsersTableSchema.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -declare function _exports({ userId, database, newFields, newPayload, }: { - userId: number | string; - database: string; - newFields?: string[]; - newPayload?: { - [x: string]: any; - }; -}): Promise; -export = _exports; diff --git a/package-shared/functions/backend/updateUsersTableSchema.js b/package-shared/functions/backend/updateUsersTableSchema.ts similarity index 68% rename from package-shared/functions/backend/updateUsersTableSchema.js rename to package-shared/functions/backend/updateUsersTableSchema.ts index c83230b..be12b58 100755 --- a/package-shared/functions/backend/updateUsersTableSchema.js +++ b/package-shared/functions/backend/updateUsersTableSchema.ts @@ -1,28 +1,25 @@ -// @ts-check +import serverError from "./serverError"; +import grabUserSchemaData from "./grabUserSchemaData"; +import setUserSchemaData from "./setUserSchemaData"; +import createDbFromSchema from "../../shell/createDbFromSchema"; +import grabSchemaFieldsFromData from "./grabSchemaFieldsFromData"; -const serverError = require("./serverError"); -const grabUserSchemaData = require("./grabUserSchemaData"); -const setUserSchemaData = require("./setUserSchemaData"); -const createDbFromSchema = require("../../shell/createDbFromSchema"); -const grabSchemaFieldsFromData = require("./grabSchemaFieldsFromData"); +type Param = { + userId: number | string; + database: string; + newFields?: string[]; + newPayload?: { [s: string]: any }; +}; /** * # Add User Table to Database - * - * @param {object} params - * @param {number | string} params.userId - user id - * @param {string} params.database - * @param {string[]} [params.newFields] - new fields to add to the users table - * @param {Object} [params.newPayload] - * - * @returns {Promise} new user auth object payload */ -module.exports = async function updateUsersTableSchema({ +export default async function updateUsersTableSchema({ userId, database, newFields, newPayload, -}) { +}: Param): Promise { try { const dbFullName = database; @@ -67,7 +64,7 @@ module.exports = async function updateUsersTableSchema({ }); return `Done!`; - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log(`addUsersTableToDb.js ERROR: ${error.message}`); serverError({ @@ -77,4 +74,4 @@ module.exports = async function updateUsersTableSchema({ }); return error.message; } -}; +} diff --git a/package-shared/functions/backend/varDatabaseDbHandler.d.ts b/package-shared/functions/backend/varDatabaseDbHandler.d.ts deleted file mode 100644 index b653b3f..0000000 --- a/package-shared/functions/backend/varDatabaseDbHandler.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -declare function _exports({ queryString, queryValuesArray, database, tableSchema, useLocal, }: { - queryString: string; - queryValuesArray?: any[]; - database?: string; - tableSchema?: import("../../types").DSQL_TableSchemaType; - useLocal?: boolean; -}): Promise; -export = _exports; diff --git a/package-shared/functions/backend/varDatabaseDbHandler.js b/package-shared/functions/backend/varDatabaseDbHandler.ts similarity index 58% rename from package-shared/functions/backend/varDatabaseDbHandler.js rename to package-shared/functions/backend/varDatabaseDbHandler.ts index 5e225dd..dbda796 100644 --- a/package-shared/functions/backend/varDatabaseDbHandler.js +++ b/package-shared/functions/backend/varDatabaseDbHandler.ts @@ -1,31 +1,27 @@ -// @ts-check +import parseDbResults from "./parseDbResults"; +import serverError from "./serverError"; +import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER"; +import DSQL_USER_DB_HANDLER from "../../utils/backend/global-db/DSQL_USER_DB_HANDLER"; +import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER"; -const fs = require("fs"); -const parseDbResults = require("./parseDbResults"); -const serverError = require("./serverError"); -const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER"); -const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER"); -const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER"); +type Param = { + queryString: string; + queryValuesArray?: any[]; + database?: string; + tableSchema?: import("../../types").DSQL_TableSchemaType; + useLocal?: boolean; +}; /** - * DB handler for specific database - * ============================================================================== - * @async - * @param {object} params - Single object params - * @param {string} params.queryString - SQL string - * @param {*[]} [params.queryValuesArray] - Values Array - * @param {string} [params.database] - Database name - * @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema - * @param {boolean} [params.useLocal] - * @returns {Promise} + * # DB handler for specific database */ -module.exports = async function varDatabaseDbHandler({ +export default async function varDatabaseDbHandler({ queryString, queryValuesArray, database, tableSchema, useLocal, -}) { +}: Param): Promise { /** * Declare variables * @@ -38,7 +34,7 @@ module.exports = async function varDatabaseDbHandler({ : false; /** @type {any} */ - const FINAL_DB_HANDLER = useLocal + const FINAL_DB_HANDLER: any = useLocal ? LOCAL_DB_HANDLER : isMaster ? DB_HANDLER @@ -75,11 +71,7 @@ module.exports = async function varDatabaseDbHandler({ queryString, }); } - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - } catch (/** @type {any} */ error) { + } catch (error: any) { serverError({ component: "varDatabaseDbHandler/lines-29-32", message: error.message, @@ -99,7 +91,7 @@ module.exports = async function varDatabaseDbHandler({ tableSchema: tableSchema, }); return parsedResults; - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log( "\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>", database, @@ -111,17 +103,9 @@ module.exports = async function varDatabaseDbHandler({ }); return null; } - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// } else if (results) { return results; - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// } else { return null; } -}; +} diff --git a/package-shared/functions/backend/varReadOnlyDatabaseDbHandler.d.ts b/package-shared/functions/backend/varReadOnlyDatabaseDbHandler.d.ts deleted file mode 100644 index a698c12..0000000 --- a/package-shared/functions/backend/varReadOnlyDatabaseDbHandler.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -declare function _exports({ queryString, database, queryValuesArray, tableSchema, useLocal, }: { - queryString: string; - database: string; - queryValuesArray?: string[]; - tableSchema?: import("../../types").DSQL_TableSchemaType; - useLocal?: boolean; -}): Promise; -export = _exports; diff --git a/package-shared/functions/backend/varReadOnlyDatabaseDbHandler.js b/package-shared/functions/backend/varReadOnlyDatabaseDbHandler.ts similarity index 64% rename from package-shared/functions/backend/varReadOnlyDatabaseDbHandler.js rename to package-shared/functions/backend/varReadOnlyDatabaseDbHandler.ts index 5910b67..f3d2787 100644 --- a/package-shared/functions/backend/varReadOnlyDatabaseDbHandler.js +++ b/package-shared/functions/backend/varReadOnlyDatabaseDbHandler.ts @@ -1,28 +1,30 @@ // @ts-check -const fs = require("fs"); -const serverError = require("./serverError"); -const parseDbResults = require("./parseDbResults"); -const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER"); -const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER"); +import fs from "fs"; +import serverError from "./serverError"; +import parseDbResults from "./parseDbResults"; +import DSQL_USER_DB_HANDLER from "../../utils/backend/global-db/DSQL_USER_DB_HANDLER"; +import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER"; + +type Param = { + queryString: string; + database: string; + queryValuesArray?: string[]; + tableSchema?: import("../../types").DSQL_TableSchemaType; + useLocal?: boolean; +}; /** - * - * @param {object} param0 - * @param {string} param0.queryString - * @param {string} param0.database - * @param {string[]} [param0.queryValuesArray] - * @param {import("../../types").DSQL_TableSchemaType} [param0.tableSchema] - * @param {boolean} [param0.useLocal] + * # Read Only Db Handler with Varaibles * @returns */ -module.exports = async function varReadOnlyDatabaseDbHandler({ +export default async function varReadOnlyDatabaseDbHandler({ queryString, database, queryValuesArray, tableSchema, useLocal, -}) { +}: Param) { /** * Declare variables * @@ -46,7 +48,7 @@ module.exports = async function varReadOnlyDatabaseDbHandler({ }); //////////////////////////////////////// - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { //////////////////////////////////////// serverError({ @@ -76,4 +78,4 @@ module.exports = async function varReadOnlyDatabaseDbHandler({ } else { return null; } -}; +} diff --git a/package-shared/functions/dsql/decrypt.d.ts b/package-shared/functions/dsql/decrypt.d.ts deleted file mode 100644 index 1ade814..0000000 --- a/package-shared/functions/dsql/decrypt.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -export = decrypt; -/** - * @param {object} param0 - * @param {string} param0.encryptedString - * @param {string} [param0.encryptionKey] - * @param {string} [param0.encryptionSalt] - * @returns - */ -declare function decrypt({ encryptedString, encryptionKey, encryptionSalt }: { - encryptedString: string; - encryptionKey?: string; - encryptionSalt?: string; -}): string; diff --git a/package-shared/functions/dsql/decrypt.js b/package-shared/functions/dsql/decrypt.ts similarity index 71% rename from package-shared/functions/dsql/decrypt.js rename to package-shared/functions/dsql/decrypt.ts index e6c4da7..f25ed5d 100644 --- a/package-shared/functions/dsql/decrypt.js +++ b/package-shared/functions/dsql/decrypt.ts @@ -1,16 +1,22 @@ // @ts-check -const { scryptSync, createDecipheriv } = require("crypto"); -const { Buffer } = require("buffer"); +import { scryptSync, createDecipheriv } from "crypto"; +import { Buffer } from "buffer"; + +type Param = { + encryptedString: string; + encryptionKey?: string; + encryptionSalt?: string; +}; /** - * @param {object} param0 - * @param {string} param0.encryptedString - * @param {string} [param0.encryptionKey] - * @param {string} [param0.encryptionSalt] - * @returns + * # Decrypt Function */ -const decrypt = ({ encryptedString, encryptionKey, encryptionSalt }) => { +export default function decrypt({ + encryptedString, + encryptionKey, + encryptionSalt, +}: Param) { if (!encryptedString?.match(/./)) { console.log("Encrypted string is invalid"); return encryptedString; @@ -38,17 +44,15 @@ const decrypt = ({ encryptedString, encryptionKey, encryptionSalt }) => { let key = scryptSync(finalEncryptionKey, finalEncryptionSalt, finalKeyLen); let iv = Buffer.alloc(16, 0); - // @ts-ignore + const decipher = createDecipheriv(algorithm, key, iv); try { let decrypted = decipher.update(encryptedString, "hex", "utf8"); decrypted += decipher.final("utf8"); return decrypted; - } catch (/** @type {*} */ error) { + } catch (error: any) { console.log("Error in decrypting =>", error.message); return encryptedString; } -}; - -module.exports = decrypt; +} diff --git a/package-shared/functions/dsql/encrypt.d.ts b/package-shared/functions/dsql/encrypt.d.ts deleted file mode 100644 index 85beae8..0000000 --- a/package-shared/functions/dsql/encrypt.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -export = encrypt; -/** - * - * @param {object} param0 - * @param {string} param0.data - * @param {string} [param0.encryptionKey] - * @param {string} [param0.encryptionSalt] - * @returns {string | null} - */ -declare function encrypt({ data, encryptionKey, encryptionSalt }: { - data: string; - encryptionKey?: string; - encryptionSalt?: string; -}): string | null; diff --git a/package-shared/functions/dsql/encrypt.js b/package-shared/functions/dsql/encrypt.ts similarity index 74% rename from package-shared/functions/dsql/encrypt.js rename to package-shared/functions/dsql/encrypt.ts index c839b79..7e0f95f 100644 --- a/package-shared/functions/dsql/encrypt.js +++ b/package-shared/functions/dsql/encrypt.ts @@ -1,17 +1,22 @@ // @ts-check -const { scryptSync, createCipheriv } = require("crypto"); -const { Buffer } = require("buffer"); +import { scryptSync, createCipheriv } from "crypto"; +import { Buffer } from "buffer"; + +type Param = { + data: string; + encryptionKey?: string; + encryptionSalt?: string; +}; /** - * - * @param {object} param0 - * @param {string} param0.data - * @param {string} [param0.encryptionKey] - * @param {string} [param0.encryptionSalt] - * @returns {string | null} + * # Encrypt String */ -const encrypt = ({ data, encryptionKey, encryptionSalt }) => { +export default function encrypt({ + data, + encryptionKey, + encryptionSalt, +}: Param): string | null { if (!data?.match(/./)) { console.log("Encryption string is invalid"); return data; @@ -46,10 +51,10 @@ const encrypt = ({ data, encryptionKey, encryptionSalt }) => { let encrypted = cipher.update(data, "utf8", "hex"); encrypted += cipher.final("hex"); return encrypted; - } catch (/** @type {*} */ error) { + } catch (/** @type {*} */ error: any) { console.log("Error in encrypting =>", error.message); return data; } -}; +} module.exports = encrypt; diff --git a/package-shared/functions/dsql/hashPassword.d.ts b/package-shared/functions/dsql/hashPassword.d.ts deleted file mode 100644 index 8f94a6b..0000000 --- a/package-shared/functions/dsql/hashPassword.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -declare function _exports({ password, encryptionKey }: { - password: string; - encryptionKey?: string; -}): string; -export = _exports; diff --git a/package-shared/functions/dsql/hashPassword.js b/package-shared/functions/dsql/hashPassword.ts similarity index 55% rename from package-shared/functions/dsql/hashPassword.js rename to package-shared/functions/dsql/hashPassword.ts index edbed31..b5c6f6a 100644 --- a/package-shared/functions/dsql/hashPassword.js +++ b/package-shared/functions/dsql/hashPassword.ts @@ -1,15 +1,17 @@ -// @ts-check +import { createHmac } from "crypto"; -const { createHmac } = require("crypto"); +type Param = { + password: string; + encryptionKey?: string; +}; /** * # Hash password Function - * @param {object} param0 - * @param {string} param0.password - Password to hash - * @param {string} [param0.encryptionKey] - Encryption key - * @returns {string} */ -module.exports = function hashPassword({ password, encryptionKey }) { +export default function hashPassword({ + password, + encryptionKey, +}: Param): string { const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD; @@ -21,4 +23,4 @@ module.exports = function hashPassword({ password, encryptionKey }) { hmac.update(password); let hashed = hmac.digest("base64"); return hashed; -}; +} diff --git a/package-shared/functions/dsql/sql/sql-delete-generator.d.ts b/package-shared/functions/dsql/sql/sql-delete-generator.d.ts deleted file mode 100644 index 438f8a0..0000000 --- a/package-shared/functions/dsql/sql/sql-delete-generator.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -export = sqlDeleteGenerator; -/** - * @typedef {object} SQLDeleteGenReturn - * @property {string} query - * @property {string[]} values - */ -/** - * @param {object} param0 - * @param {any} param0.data - * @param {string} param0.tableName - * - * @return {SQLDeleteGenReturn | undefined} - */ -declare function sqlDeleteGenerator({ tableName, data }: { - data: any; - tableName: string; -}): SQLDeleteGenReturn | undefined; -declare namespace sqlDeleteGenerator { - export { SQLDeleteGenReturn }; -} -type SQLDeleteGenReturn = { - query: string; - values: string[]; -}; diff --git a/package-shared/functions/dsql/sql/sql-delete-generator.js b/package-shared/functions/dsql/sql/sql-delete-generator.js deleted file mode 100644 index 781e9e5..0000000 --- a/package-shared/functions/dsql/sql/sql-delete-generator.js +++ /dev/null @@ -1,41 +0,0 @@ -// @ts-check - -/** - * @typedef {object} SQLDeleteGenReturn - * @property {string} query - * @property {string[]} values - */ - -/** - * @param {object} param0 - * @param {any} param0.data - * @param {string} param0.tableName - * - * @return {SQLDeleteGenReturn | undefined} - */ -function sqlDeleteGenerator({ tableName, data }) { - try { - let queryStr = `DELETE FROM ${tableName}`; - - /** @type {string[]} */ - let deleteBatch = []; - /** @type {string[]} */ - let queryArr = []; - - Object.keys(data).forEach((ky) => { - deleteBatch.push(`${ky}=?`); - queryArr.push(data[ky]); - }); - queryStr += ` WHERE ${deleteBatch.join(" AND ")}`; - - return { - query: queryStr, - values: queryArr, - }; - } catch (/** @type {any} */ error) { - console.log(`SQL delete gen ERROR: ${error.message}`); - return undefined; - } -} - -module.exports = sqlDeleteGenerator; diff --git a/package-shared/functions/dsql/sql/sql-delete-generator.ts b/package-shared/functions/dsql/sql/sql-delete-generator.ts new file mode 100644 index 0000000..460bb1c --- /dev/null +++ b/package-shared/functions/dsql/sql/sql-delete-generator.ts @@ -0,0 +1,36 @@ +interface SQLDeleteGenReturn { + query: string; + values: string[]; +} + +/** + * # SQL Delete Generator + */ +export default function sqlDeleteGenerator({ + tableName, + data, +}: { + data: any; + tableName: string; +}): SQLDeleteGenReturn | undefined { + try { + let queryStr = `DELETE FROM ${tableName}`; + + let deleteBatch: string[] = []; + let queryArr: string[] = []; + + Object.keys(data).forEach((ky) => { + deleteBatch.push(`${ky}=?`); + queryArr.push(data[ky]); + }); + queryStr += ` WHERE ${deleteBatch.join(" AND ")}`; + + return { + query: queryStr, + values: queryArr, + }; + } catch (/** @type {any} */ error: any) { + console.log(`SQL delete gen ERROR: ${error.message}`); + return undefined; + } +} diff --git a/package-shared/functions/dsql/sql/sql-generator.d.ts b/package-shared/functions/dsql/sql/sql-generator.d.ts deleted file mode 100644 index dc6ab9b..0000000 --- a/package-shared/functions/dsql/sql/sql-generator.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -export = sqlGenerator; -declare function sqlGenerator(Param0: { - genObject?: import("../../../types").ServerQueryParam; - tableName: string; -}): { - string: string; - values: string[]; -} | undefined; diff --git a/package-shared/functions/dsql/sql/sql-generator.js b/package-shared/functions/dsql/sql/sql-generator.ts similarity index 90% rename from package-shared/functions/dsql/sql/sql-generator.js rename to package-shared/functions/dsql/sql/sql-generator.ts index f258db3..c7fe824 100644 --- a/package-shared/functions/dsql/sql/sql-generator.js +++ b/package-shared/functions/dsql/sql/sql-generator.ts @@ -1,28 +1,46 @@ -// @ts-check +import { + ServerQueryParam, + ServerQueryParamsJoin, + ServerQueryQueryObject, +} from "../../../types"; + +type Param = { + genObject?: ServerQueryParam; + tableName: string; +}; + +type Return = + | { + string: string; + values: string[]; + } + | undefined; /** * # SQL Query Generator * @description Generates an SQL Query for node module `mysql` or `serverless-mysql` - * @type {import("../../../types").SqlGeneratorFn} */ -function sqlGenerator({ tableName, genObject }) { +export default function sqlGenerator({ tableName, genObject }: Param): Return { if (!genObject) return undefined; const finalQuery = genObject.query ? genObject.query : undefined; const queryKeys = finalQuery ? Object.keys(finalQuery) : undefined; - /** @type {string[]} */ - const sqlSearhValues = []; + const sqlSearhValues: string[] = []; /** * # Generate Query - * @param {object} param - * @param {import("../../../types").ServerQueryQueryObject[string]} param.queryObj - * @param {import("../../../types").ServerQueryParamsJoin[]} [param.join] - * @param {string} [param.field] */ - function genSqlSrchStr({ queryObj, join, field }) { + function genSqlSrchStr({ + queryObj, + join, + field, + }: { + queryObj: ServerQueryQueryObject[string]; + join?: ServerQueryParamsJoin[]; + field?: string; + }) { const finalFieldName = (() => { if (queryObj?.tableName) { return `${queryObj.tableName}.${field}`; @@ -51,7 +69,7 @@ function sqlGenerator({ tableName, genObject }) { } } else if (Array.isArray(queryObj.value)) { /** @type {string[]} */ - const strArray = []; + const strArray: string[] = []; queryObj.value.forEach((val) => { const valueParsed = val; if (queryObj.equality == "LIKE") { @@ -75,16 +93,14 @@ function sqlGenerator({ tableName, genObject }) { const sqlSearhString = queryKeys?.map((field) => { const queryObj = - /** @type {import("../../../types").ServerQueryQueryObject} */ ( - finalQuery?.[field] - ); + /** @type {import("../../../types").ServerQueryQueryObject} */ finalQuery?.[ + field + ]; if (!queryObj) return; if (queryObj.__query) { const subQueryGroup = - /** @type {import("../../../types").ServerQueryQueryObject}} */ ( - queryObj.__query - ); + /** @type {import("../../../types").ServerQueryQueryObject}} */ queryObj.__query; const subSearchKeys = Object.keys(subQueryGroup); const subSearchString = subSearchKeys.map((_field) => { @@ -109,8 +125,8 @@ function sqlGenerator({ tableName, genObject }) { }); function generateJoinStr( - /** @type {import("../../../types").ServerQueryParamsJoinMatchObject} */ mtch, - /** @type {import("../../../types").ServerQueryParamsJoin} */ join + /** @type {import("../../../types").ServerQueryParamsJoinMatchObject} */ mtch: import("../../../types").ServerQueryParamsJoinMatchObject, + /** @type {import("../../../types").ServerQueryParamsJoin} */ join: import("../../../types").ServerQueryParamsJoin ) { return `${ typeof mtch.source == "object" ? mtch.source.tableName : tableName @@ -165,7 +181,7 @@ function sqlGenerator({ tableName, genObject }) { if (genObject.join) { /** @type {string[]} */ - const existingJoinTableNames = [tableName]; + const existingJoinTableNames: string[] = [tableName]; str += "," + @@ -263,5 +279,3 @@ function sqlGenerator({ tableName, genObject }) { values: sqlSearhValues, }; } - -module.exports = sqlGenerator; diff --git a/package-shared/functions/dsql/sql/sql-insert-generator.d.ts b/package-shared/functions/dsql/sql/sql-insert-generator.d.ts deleted file mode 100644 index c256cbc..0000000 --- a/package-shared/functions/dsql/sql/sql-insert-generator.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -export = sqlInsertGenerator; -/** - * @typedef {object} SQLInsertGenReturn - * @property {string} query - * @property {string[]} values - */ -/** - * @param {object} param0 - * @param {any[]} param0.data - * @param {string} param0.tableName - * - * @return {SQLInsertGenReturn | undefined} - */ -declare function sqlInsertGenerator({ tableName, data }: { - data: any[]; - tableName: string; -}): SQLInsertGenReturn | undefined; -declare namespace sqlInsertGenerator { - export { SQLInsertGenReturn }; -} -type SQLInsertGenReturn = { - query: string; - values: string[]; -}; diff --git a/package-shared/functions/dsql/sql/sql-insert-generator.js b/package-shared/functions/dsql/sql/sql-insert-generator.ts similarity index 74% rename from package-shared/functions/dsql/sql/sql-insert-generator.js rename to package-shared/functions/dsql/sql/sql-insert-generator.ts index ac9dca9..78dcae4 100644 --- a/package-shared/functions/dsql/sql/sql-insert-generator.js +++ b/package-shared/functions/dsql/sql/sql-insert-generator.ts @@ -1,23 +1,24 @@ // @ts-check -/** - * @typedef {object} SQLInsertGenReturn - * @property {string} query - * @property {string[]} values - */ +interface SQLInsertGenReturn { + query: string; + values: string[]; +} /** - * @param {object} param0 - * @param {any[]} param0.data - * @param {string} param0.tableName - * - * @return {SQLInsertGenReturn | undefined} + * # SQL Insert Generator */ -function sqlInsertGenerator({ tableName, data }) { +export default function sqlInsertGenerator({ + tableName, + data, +}: { + data: any[]; + tableName: string; +}): SQLInsertGenReturn | undefined { try { if (Array.isArray(data) && data?.[0]) { /** @type {string[]} */ - let insertKeys = []; + let insertKeys: string[] = []; data.forEach((dt) => { const kys = Object.keys(dt); @@ -29,9 +30,9 @@ function sqlInsertGenerator({ tableName, data }) { }); /** @type {string[]} */ - let queryBatches = []; + let queryBatches: string[] = []; /** @type {string[]} */ - let queryValues = []; + let queryValues: string[] = []; data.forEach((item) => { queryBatches.push( @@ -58,10 +59,8 @@ function sqlInsertGenerator({ tableName, data }) { } else { return undefined; } - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log(`SQL insert gen ERROR: ${error.message}`); return undefined; } } - -module.exports = sqlInsertGenerator; diff --git a/package-shared/shell/checkDb.js b/package-shared/shell/checkDb.ts similarity index 54% rename from package-shared/shell/checkDb.js rename to package-shared/shell/checkDb.ts index ce59d38..58bf4c6 100755 --- a/package-shared/shell/checkDb.js +++ b/package-shared/shell/checkDb.ts @@ -1,12 +1,6 @@ -// @ts-check - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// - require("dotenv").config({ path: "./../.env" }); -const mysql = require("serverless-mysql"); -const grabDbSSL = require("../utils/backend/grabDbSSL"); +import mysql from "serverless-mysql"; +import grabDbSSL from "../utils/backend/grabDbSSL"; const connection = mysql({ config: { @@ -19,13 +13,6 @@ const connection = mysql({ }, }); -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// - /** * # Main DB Handler Function * @async @@ -48,7 +35,7 @@ const connection = mysql({ "SELECT id,first_name,last_name FROM users LIMIT 3" ); console.log("Connection Query Success =>", result); - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log("Connection query ERROR =>", error.message); } finally { connection.end(); diff --git a/package-shared/shell/createDbFromSchema.d.ts b/package-shared/shell/createDbFromSchema.d.ts deleted file mode 100644 index 5509679..0000000 --- a/package-shared/shell/createDbFromSchema.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -export = createDbFromSchema; -/** - * Create database from Schema Function - * ============================================= - * @param {object} params - Single object params - * @param {number|string|null} [params.userId] - User ID or null - * @param {string} [params.targetDatabase] - User Database full name - * @param {import("../types").DSQL_DatabaseSchemaType[]} [params.dbSchemaData] - */ -declare function createDbFromSchema({ userId, targetDatabase, dbSchemaData }: { - userId?: number | string | null; - targetDatabase?: string; - dbSchemaData?: import("../types").DSQL_DatabaseSchemaType[]; -}): Promise; diff --git a/package-shared/shell/createDbFromSchema.js b/package-shared/shell/createDbFromSchema.ts similarity index 86% rename from package-shared/shell/createDbFromSchema.js rename to package-shared/shell/createDbFromSchema.ts index 1832ef4..22d0070 100755 --- a/package-shared/shell/createDbFromSchema.js +++ b/package-shared/shell/createDbFromSchema.ts @@ -1,28 +1,32 @@ -// @ts-check - -const path = require("path"); -const fs = require("fs"); +import path from "path"; +import fs from "fs"; require("dotenv").config({ path: "./../.env" }); -const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler"); -const varDatabaseDbHandler = require("./utils/varDatabaseDbHandler"); -const createTable = require("./utils/createTable"); -const updateTable = require("./utils/updateTable"); -const dbHandler = require("./utils/dbHandler"); -const EJSON = require("../utils/ejson"); +import noDatabaseDbHandler from "./utils/noDatabaseDbHandler"; +import varDatabaseDbHandler from "./utils/varDatabaseDbHandler"; +import createTable from "./utils/createTable"; +import updateTable from "./utils/updateTable"; +import dbHandler from "./utils/dbHandler"; +import EJSON from "../utils/ejson"; +import { DSQL_DatabaseSchemaType } from "../types"; const execFlag = process.argv.find((arg) => arg === "--exec"); +type Param = { + userId?: number | string | null; + targetDatabase?: string; + dbSchemaData?: import("../types").DSQL_DatabaseSchemaType[]; +}; + /** - * Create database from Schema Function - * ============================================= - * @param {object} params - Single object params - * @param {number|string|null} [params.userId] - User ID or null - * @param {string} [params.targetDatabase] - User Database full name - * @param {import("../types").DSQL_DatabaseSchemaType[]} [params.dbSchemaData] + * # Create database from Schema Function */ -async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) { +export default async function createDbFromSchema({ + userId, + targetDatabase, + dbSchemaData, +}: Param) { const schemaPath = userId ? path.join( String(process.env.DSQL_USER_DB_SCHEMA_PATH), @@ -30,12 +34,11 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) { ) : path.resolve(__dirname, "../../jsonData/dbSchemas/main.json"); - /** @type {import("../types").DSQL_DatabaseSchemaType[] | undefined} */ - const dbSchema = + const dbSchema: DSQL_DatabaseSchemaType[] | undefined = dbSchemaData || - /** @type {import("../types").DSQL_DatabaseSchemaType[] | undefined} */ ( - EJSON.parse(fs.readFileSync(schemaPath, "utf8")) - ); + (EJSON.parse(fs.readFileSync(schemaPath, "utf8")) as + | DSQL_DatabaseSchemaType[] + | undefined); if (!dbSchema) { console.log("Schema Not Found!"); @@ -46,7 +49,8 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) { for (let i = 0; i < dbSchema.length; i++) { /** @type {import("../types").DSQL_DatabaseSchemaType} */ - const database = dbSchema[i]; + const database: import("../types").DSQL_DatabaseSchemaType = + dbSchema[i]; const { dbFullName, tables, dbName, dbSlug, childrenDatabases } = database; @@ -55,7 +59,7 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) { } /** @type {any} */ - const dbCheck = await noDatabaseDbHandler( + const dbCheck: any = await noDatabaseDbHandler( `SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${dbFullName}'` ); @@ -72,7 +76,7 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) { * @type {any} * @description Select All tables in target database */ - const allTables = await noDatabaseDbHandler( + const allTables: any = await noDatabaseDbHandler( `SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${dbFullName}'` ); @@ -143,7 +147,7 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) { * @description Check if table exists * @type {any} */ - const tableCheck = await varDatabaseDbHandler({ + const tableCheck: any = await varDatabaseDbHandler({ queryString: ` SELECT EXISTS ( SELECT @@ -240,7 +244,7 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) { * @type {import("../types").DSQL_MYSQL_SHOW_INDEXES_Type[]} * @description All indexes from MYSQL db */ // @ts-ignore - const allExistingIndexes = + const allExistingIndexes: import("../types").DSQL_MYSQL_SHOW_INDEXES_Type[] = await varDatabaseDbHandler({ queryString: `SHOW INDEXES FROM \`${tableName}\``, database: dbFullName, @@ -295,8 +299,6 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) { } } -module.exports = createDbFromSchema; - if (execFlag) { createDbFromSchema({}); } diff --git a/package-shared/shell/deploy.js b/package-shared/shell/deploy.js deleted file mode 100755 index 1a3b34b..0000000 --- a/package-shared/shell/deploy.js +++ /dev/null @@ -1,7 +0,0 @@ -// @ts-check - -const fs = require("fs"); - -async function deploy() {} - -deploy(); diff --git a/package-shared/shell/deploy.ts b/package-shared/shell/deploy.ts new file mode 100755 index 0000000..5bfc310 --- /dev/null +++ b/package-shared/shell/deploy.ts @@ -0,0 +1,5 @@ +import fs from "fs"; + +async function deploy() {} + +deploy(); diff --git a/package-shared/shell/encodingUpdate.js b/package-shared/shell/encodingUpdate.ts similarity index 85% rename from package-shared/shell/encodingUpdate.js rename to package-shared/shell/encodingUpdate.ts index 4e87021..6ddce06 100755 --- a/package-shared/shell/encodingUpdate.js +++ b/package-shared/shell/encodingUpdate.ts @@ -1,10 +1,6 @@ -// @ts-check - require("dotenv").config({ path: "./../.env" }); -//////////////////////////////////////// - -const varDatabaseDbHandler = require("../functions/backend/varDatabaseDbHandler"); +import varDatabaseDbHandler from "../functions/backend/varDatabaseDbHandler"; /** ****************************************************************************** */ /** ****************************************************************************** */ @@ -52,7 +48,3 @@ varDatabaseDbHandler({ process.exit(); }); - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// diff --git a/package-shared/shell/functions/jsonToBase64.js b/package-shared/shell/functions/jsonToBase64.ts similarity index 73% rename from package-shared/shell/functions/jsonToBase64.js rename to package-shared/shell/functions/jsonToBase64.ts index 7e224c0..de5d8c5 100644 --- a/package-shared/shell/functions/jsonToBase64.js +++ b/package-shared/shell/functions/jsonToBase64.ts @@ -1,7 +1,5 @@ -// @ts-check - -const fs = require("fs"); -const path = require("path"); +import fs from "fs"; +import path from "path"; const jsonFile = path.resolve(__dirname, "../../jsonData/userPriviledges.json"); const base64File = Buffer.from(fs.readFileSync(jsonFile, "utf8")).toString( diff --git a/package-shared/shell/grantFullPriviledges.js b/package-shared/shell/grantFullPriviledges.js deleted file mode 100755 index 431b407..0000000 --- a/package-shared/shell/grantFullPriviledges.js +++ /dev/null @@ -1,79 +0,0 @@ -// @ts-check - -require("dotenv").config({ path: "./../.env" }); - -const serverError = require("../functions/backend/serverError"); -const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler"); -//////////////////////////////////////// - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -/** - * # Create Database From Schema - * @param {object} param0 - * @param {string | null} param0.userId - */ -async function createDbFromSchema({ userId }) { - /** - * Grab Schema - * - * @description Grab Schema - */ - try { - const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1"; - - const allDatabases = await noDatabaseDbHandler(`SHOW DATABASES`); - - const datasquirelUserDatabases = allDatabases.filter( - (/** @type {any} */ database) => - database.Database.match(/datasquirel_user_/) - ); - - for (let i = 0; i < datasquirelUserDatabases.length; i++) { - const datasquirelUserDatabase = datasquirelUserDatabases[i]; - const { Database } = datasquirelUserDatabase; - - const grantDbPriviledges = await noDatabaseDbHandler( - `GRANT ALL PRIVILEGES ON ${Database}.* TO '${process.env.DSQL_DB_FULL_ACCESS_USERNAME}'@'%' WITH GRANT OPTION` - ); - - const grantRead = await noDatabaseDbHandler( - `GRANT SELECT ON ${Database}.* TO '${process.env.DSQL_DB_READ_ONLY_USERNAME}'@'%'` - ); - } - - const flushPriviledged = await noDatabaseDbHandler(`FLUSH PRIVILEGES`); - } catch (/** @type {any} */ error) { - serverError({ - component: "shell/grantDbPriviledges/main-catch-error", - message: error.message, - user: { id: userId }, - }); - } - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - - process.exit(); - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// -} - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -const userArg = process.argv[process.argv.indexOf("--user")]; -const externalUser = process.argv[process.argv.indexOf("--user") + 1]; - -createDbFromSchema({ userId: userArg ? externalUser : null }); diff --git a/package-shared/shell/grantFullPriviledges.ts b/package-shared/shell/grantFullPriviledges.ts new file mode 100755 index 0000000..8fd6246 --- /dev/null +++ b/package-shared/shell/grantFullPriviledges.ts @@ -0,0 +1,52 @@ +require("dotenv").config({ path: "./../.env" }); +import serverError from "../functions/backend/serverError"; +import noDatabaseDbHandler from "./utils/noDatabaseDbHandler"; + +/** + * # Create Database From Schema + */ +async function grantFullPrivileges({ userId }: { userId: string | null }) { + /** + * Grab Schema + * + * @description Grab Schema + */ + try { + const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1"; + + const allDatabases = await noDatabaseDbHandler(`SHOW DATABASES`); + + const datasquirelUserDatabases = allDatabases.filter( + (/** @type {any} */ database: any) => + database.Database.match(/datasquirel_user_/) + ); + + for (let i = 0; i < datasquirelUserDatabases.length; i++) { + const datasquirelUserDatabase = datasquirelUserDatabases[i]; + const { Database } = datasquirelUserDatabase; + + const grantDbPriviledges = await noDatabaseDbHandler( + `GRANT ALL PRIVILEGES ON ${Database}.* TO '${process.env.DSQL_DB_FULL_ACCESS_USERNAME}'@'%' WITH GRANT OPTION` + ); + + const grantRead = await noDatabaseDbHandler( + `GRANT SELECT ON ${Database}.* TO '${process.env.DSQL_DB_READ_ONLY_USERNAME}'@'%'` + ); + } + + const flushPriviledged = await noDatabaseDbHandler(`FLUSH PRIVILEGES`); + } catch (/** @type {any} */ error: any) { + serverError({ + component: "shell/grantDbPriviledges/main-catch-error", + message: error.message, + user: { id: userId }, + }); + } + + process.exit(); +} + +const userArg = process.argv[process.argv.indexOf("--user")]; +const externalUser = process.argv[process.argv.indexOf("--user") + 1]; + +grantFullPrivileges({ userId: userArg ? externalUser : null }); diff --git a/package-shared/shell/lessWatch.js b/package-shared/shell/lessWatch.ts similarity index 68% rename from package-shared/shell/lessWatch.js rename to package-shared/shell/lessWatch.ts index 306114a..62f4ea1 100755 --- a/package-shared/shell/lessWatch.js +++ b/package-shared/shell/lessWatch.ts @@ -1,5 +1,5 @@ -const fs = require("fs"); -const { exec } = require("child_process"); +import fs from "fs"; +import { exec } from "child_process"; require("dotenv").config({ path: "./../.env" }); @@ -12,17 +12,14 @@ const destinationFile = ? process.argv[process.argv.indexOf("--dst") + 1] : null; -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - console.log("Running Less compiler ..."); -const sourceFiles = sourceFile.split(","); -const dstFiles = destinationFile.split(","); +const sourceFiles = sourceFile?.split(","); +const dstFiles = destinationFile?.split(","); + +if (!sourceFiles || !dstFiles) { + throw new Error("No Source or Destination Files!"); +} for (let i = 0; i < sourceFiles.length; i++) { const srcFolder = sourceFiles[i]; @@ -61,11 +58,10 @@ for (let i = 0; i < sourceFiles.length; i++) { : finalDstPath.replace(/\/$/, "") + "/_main.css" }`, (error, stdout, stderr) => { - /** @type {Error} */ if (error) { console.log("ERROR =>", error.message); - if (!evtType?.match(/change/i) && prev.match(/\[/)) { + if (!evtType?.match(/change/i) && prev?.match(/\[/)) { fs.unlinkSync(finalDstPath); } diff --git a/package-shared/shell/mariadb-users/handleGrants.js b/package-shared/shell/mariadb-users/handleGrants.ts similarity index 73% rename from package-shared/shell/mariadb-users/handleGrants.js rename to package-shared/shell/mariadb-users/handleGrants.ts index 271c290..8ae5e6a 100755 --- a/package-shared/shell/mariadb-users/handleGrants.js +++ b/package-shared/shell/mariadb-users/handleGrants.ts @@ -1,26 +1,27 @@ -// @ts-check +import noDatabaseDbHandler from "../utils/noDatabaseDbHandler"; -const noDatabaseDbHandler = require("../utils/noDatabaseDbHandler"); +export interface GrantType { + database: string; + table: string; + privileges: string[]; +} + +type Param = { + username: string; + host: string; + grants: GrantType[]; + userId: string; +}; /** - * @typedef {object} GrantType - * @property {string} database - Database Name - * @property {string} table - Table Name - * @property {string[]} privileges - Privileges + * # Handle Grants for Users */ - -/** - * Handle Grants for Users - * ================================================ - * @param {object} params - Single object params - * @param {string} params.username - Username - * @param {string} params.host - Host - * @param {GrantType[]} params.grants - Grants - * @param {string} params.userId - * - * @returns {Promise} success - */ -async function handleGrants({ username, host, grants, userId }) { +export default async function handleGrants({ + username, + host, + grants, + userId, +}: Param): Promise { let success = false; console.log(`Handling Grants for User =>`, username, host); @@ -72,7 +73,7 @@ async function handleGrants({ username, host, grants, userId }) { /** * @type {GrantType[]} */ - const grantsArray = grants; + const grantsArray: GrantType[] = grants; for (let i = 0; i < grantsArray.length; i++) { const grantObject = grantsArray[i]; @@ -95,11 +96,9 @@ async function handleGrants({ username, host, grants, userId }) { } success = true; - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log(`Error in adding SQL user =>`, error.message); } return success; } - -module.exports = handleGrants; diff --git a/package-shared/shell/mariadb-users/refreshUsersAndGrants.js b/package-shared/shell/mariadb-users/refreshUsersAndGrants.ts similarity index 79% rename from package-shared/shell/mariadb-users/refreshUsersAndGrants.js rename to package-shared/shell/mariadb-users/refreshUsersAndGrants.ts index b38395d..455e1b9 100755 --- a/package-shared/shell/mariadb-users/refreshUsersAndGrants.js +++ b/package-shared/shell/mariadb-users/refreshUsersAndGrants.ts @@ -1,37 +1,36 @@ -// @ts-check - -const path = require("path"); +import path from "path"; require("dotenv").config({ path: path.resolve(__dirname, "../../../.env") }); -const generator = require("generate-password"); -const noDatabaseDbHandler = require("../utils/noDatabaseDbHandler"); -const dbHandler = require("../utils/dbHandler"); -const handleGrants = require("./handleGrants"); -const encrypt = require("../../functions/dsql/encrypt"); -const decrypt = require("../../functions/dsql/decrypt"); +import generator from "generate-password"; +import noDatabaseDbHandler from "../utils/noDatabaseDbHandler"; +import dbHandler from "../utils/dbHandler"; +import handleGrants, { GrantType } from "./handleGrants"; +import encrypt from "../../functions/dsql/encrypt"; +import decrypt from "../../functions/dsql/decrypt"; const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1"; +type Param = { + userId?: number | string; + mariadbUserHost?: string; + mariadbUser?: string; + sqlUserID?: string | number; +}; + /** - * Refresh Mariadb User Grants - * =================================================== - * @param {object} params - * @param {number | string} [params.userId] - * @param {string} [params.mariadbUserHost] - * @param {string} [params.mariadbUser] - * @param {string | number} [params.sqlUserID] + * # Refresh Mariadb User Grants */ -async function refreshUsersAndGrants({ +export default async function refreshUsersAndGrants({ userId, mariadbUserHost, mariadbUser, sqlUserID, -}) { +}: Param) { /** * @description Users * @type {*[] | null} */ // @ts-ignore - const users = await dbHandler({ + const users: any[] | null = await dbHandler({ query: `SELECT * FROM users`, }); @@ -62,9 +61,9 @@ async function refreshUsersAndGrants({ /** * @type {import("../../types").MYSQL_mariadb_users_table_def | undefined} */ - const activeMariadbUserObject = Array.isArray( - existingMariaDBUserArray - ) + const activeMariadbUserObject: + | import("../../types").MYSQL_mariadb_users_table_def + | undefined = Array.isArray(existingMariaDBUserArray) ? existingMariaDBUserArray?.[0] : undefined; @@ -163,8 +162,7 @@ async function refreshUsersAndGrants({ existingMariadbPrimaryUser?.[0]?.user_id ); - /** @type {import("./handleGrants").GrantType[]} */ - const primaryUserGrants = [ + const primaryUserGrants: GrantType[] = [ { database: "*", table: "*", @@ -244,26 +242,8 @@ async function refreshUsersAndGrants({ } } } - - ////////////////////////////////////////////// - ////////////////////////////////////////////// - ////////////////////////////////////////////// - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log(`Error in adding SQL user =>`, error.message); } } - - process.exit(); - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// } - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -module.exports = refreshUsersAndGrants; diff --git a/package-shared/shell/mariadb-users/resetSQLPasswords.js b/package-shared/shell/mariadb-users/resetSQLPasswords.js deleted file mode 100755 index c0823c8..0000000 --- a/package-shared/shell/mariadb-users/resetSQLPasswords.js +++ /dev/null @@ -1,105 +0,0 @@ -// @ts-check - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// - -require("dotenv").config({ path: "../../.env" }); -const generator = require("generate-password"); -const noDatabaseDbHandler = require("../utils/noDatabaseDbHandler"); -const dbHandler = require("../utils/dbHandler"); -const encrypt = require("../../functions/dsql/encrypt"); - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -/** - * Create database from Schema Function - * ============================================================================== - * @param {object} params - Single object params - * @param {number|string|null} params.userId - User ID or null - */ -async function resetSQLCredentialsPasswords() { - /** - * @description Users - * @type {*[] | null} - */ // @ts-ignore - const users = await dbHandler({ - query: `SELECT * FROM users`, - }); - - if (!users) { - process.exit(); - } - - for (let i = 0; i < users.length; i++) { - const user = users[i]; - - if (!user) continue; - - try { - /** - * @type {any[]} - */ // @ts-ignore - const maridbUsers = await dbHandler({ - query: `SELECT * FROM mysql.user WHERE User = 'dsql_user_${user.id}'`, - }); - - for (let j = 0; j < maridbUsers.length; j++) { - const { User, Host } = maridbUsers[j]; - - const password = generator.generate({ - length: 16, - numbers: true, - symbols: true, - uppercase: true, - exclude: "*#.'`\"", - }); - - const encryptedPassword = encrypt({ - data: password, - encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD, - encryptionSalt: process.env.DSQL_ENCRYPTION_SALT, - }); - - await noDatabaseDbHandler( - `SET PASSWORD FOR '${User}'@'${Host}' = PASSWORD('${password}')` - ); - - if (user.mariadb_user == User && user.mariadb_host == Host) { - const updateUser = await dbHandler({ - query: `UPDATE users SET mariadb_pass = ? WHERE id = ?`, - values: [encryptedPassword, user.id], - }); - } - - console.log( - `User ${user.id}: ${user.first_name} ${user.last_name} Password Updated successfully added.` - ); - } - } catch (/** @type {any} */ error) { - console.log( - `Error Updating User ${user.id} Password =>`, - error.message - ); - } - } - - process.exit(); - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// -} - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -resetSQLCredentialsPasswords(); diff --git a/package-shared/shell/mariadb-users/resetSQLPasswords.ts b/package-shared/shell/mariadb-users/resetSQLPasswords.ts new file mode 100755 index 0000000..65bbbe1 --- /dev/null +++ b/package-shared/shell/mariadb-users/resetSQLPasswords.ts @@ -0,0 +1,72 @@ +require("dotenv").config({ path: "../../.env" }); +import generator from "generate-password"; +import noDatabaseDbHandler from "../utils/noDatabaseDbHandler"; +import dbHandler from "../utils/dbHandler"; +import encrypt from "../../functions/dsql/encrypt"; + +/** + * # Reset SQL Passwords + */ +async function resetSQLCredentialsPasswords() { + const users = (await dbHandler({ + query: `SELECT * FROM users`, + })) as any[]; + + if (!users) { + process.exit(); + } + + for (let i = 0; i < users.length; i++) { + const user = users[i]; + + if (!user) continue; + + try { + const maridbUsers = (await dbHandler({ + query: `SELECT * FROM mysql.user WHERE User = 'dsql_user_${user.id}'`, + })) as any[]; + + for (let j = 0; j < maridbUsers.length; j++) { + const { User, Host } = maridbUsers[j]; + + const password = generator.generate({ + length: 16, + numbers: true, + symbols: true, + uppercase: true, + exclude: "*#.'`\"", + }); + + const encryptedPassword = encrypt({ + data: password, + encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD, + encryptionSalt: process.env.DSQL_ENCRYPTION_SALT, + }); + + await noDatabaseDbHandler( + `SET PASSWORD FOR '${User}'@'${Host}' = PASSWORD('${password}')` + ); + + if (user.mariadb_user == User && user.mariadb_host == Host) { + const updateUser = await dbHandler({ + query: `UPDATE users SET mariadb_pass = ? WHERE id = ?`, + values: [encryptedPassword, user.id], + }); + } + + console.log( + `User ${user.id}: ${user.first_name} ${user.last_name} Password Updated successfully added.` + ); + } + } catch (error: any) { + console.log( + `Error Updating User ${user.id} Password =>`, + error.message + ); + } + } + + process.exit(); +} + +resetSQLCredentialsPasswords(); diff --git a/package-shared/shell/mariadb-users/users/create-user.js b/package-shared/shell/mariadb-users/users/create-user.ts similarity index 86% rename from package-shared/shell/mariadb-users/users/create-user.js rename to package-shared/shell/mariadb-users/users/create-user.ts index 6b2d145..89f3293 100755 --- a/package-shared/shell/mariadb-users/users/create-user.js +++ b/package-shared/shell/mariadb-users/users/create-user.ts @@ -1,15 +1,13 @@ -// @ts-check - -const path = require("path"); +import path from "path"; require("dotenv").config({ path: "../../../.env" }); -const fs = require("fs"); -const { execSync } = require("child_process"); -const EJSON = require("../../../utils/ejson"); -const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER"); -const addDbEntry = require("../../../functions/backend/db/addDbEntry"); -const addMariadbUser = require("../../../functions/backend/addMariadbUser"); -const updateDbEntry = require("../../../functions/backend/db/updateDbEntry"); -const hashPassword = require("../../../functions/dsql/hashPassword"); +import fs from "fs"; +import { execSync } from "child_process"; +import EJSON from "../../../utils/ejson"; +import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER"; +import addDbEntry from "../../../functions/backend/db/addDbEntry"; +import addMariadbUser from "../../../functions/backend/addMariadbUser"; +import updateDbEntry from "../../../functions/backend/db/updateDbEntry"; +import hashPassword from "../../../functions/dsql/hashPassword"; const tmpDir = process.argv[process.argv.length - 1]; @@ -169,7 +167,7 @@ async function createUser() { } return true; - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log(`Error in creating user => ${error.message}`); return false; } diff --git a/package-shared/shell/mariadb-users/users/update-user.js b/package-shared/shell/mariadb-users/users/update-user.ts similarity index 80% rename from package-shared/shell/mariadb-users/users/update-user.js rename to package-shared/shell/mariadb-users/users/update-user.ts index 575502e..c75c927 100755 --- a/package-shared/shell/mariadb-users/users/update-user.js +++ b/package-shared/shell/mariadb-users/users/update-user.ts @@ -1,11 +1,9 @@ -// @ts-check - -const path = require("path"); +import path from "path"; require("dotenv").config({ path: "../../../.env" }); -const fs = require("fs"); -const EJSON = require("../../../utils/ejson"); -const hashPassword = require("../../../functions/dsql/hashPassword"); -const updateDbEntry = require("../../../functions/backend/db/updateDbEntry"); +import fs from "fs"; +import EJSON from "../../../utils/ejson"; +import hashPassword from "../../../functions/dsql/hashPassword"; +import updateDbEntry from "../../../functions/backend/db/updateDbEntry"; const tmpDir = process.argv[process.argv.length - 1]; @@ -40,8 +38,7 @@ async function createUser() { updatePayload["password"] = hashedPassword; } - /** @type {any} */ - const newUser = await updateDbEntry({ + const newUser: any = await updateDbEntry({ dbFullName: "datasquirel", tableName: "users", data: { ...updatePayload, id: undefined }, @@ -58,7 +55,7 @@ async function createUser() { } return true; - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log(`Error in creating user => ${error.message}`); return false; } diff --git a/package-shared/shell/readImage.js b/package-shared/shell/readImage.js deleted file mode 100755 index 654e0b4..0000000 --- a/package-shared/shell/readImage.js +++ /dev/null @@ -1,24 +0,0 @@ -// @ts-check - -const fs = require("fs"); - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -/** - * Grab Schema - * - * @description Grab Schema - */ -const imageBase64 = fs.readFileSync( - "./../public/images/unique-tokens-icon.png", - "base64" -); - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// diff --git a/package-shared/shell/readImage.ts b/package-shared/shell/readImage.ts new file mode 100755 index 0000000..1023481 --- /dev/null +++ b/package-shared/shell/readImage.ts @@ -0,0 +1,6 @@ +import fs from "fs"; + +const imageBase64 = fs.readFileSync( + "./../public/images/unique-tokens-icon.png", + "base64" +); diff --git a/package-shared/shell/recoverMainJsonFromDb.js b/package-shared/shell/recoverMainJsonFromDb.ts similarity index 67% rename from package-shared/shell/recoverMainJsonFromDb.js rename to package-shared/shell/recoverMainJsonFromDb.ts index e812686..3fe8f88 100755 --- a/package-shared/shell/recoverMainJsonFromDb.js +++ b/package-shared/shell/recoverMainJsonFromDb.ts @@ -1,27 +1,13 @@ -// @ts-check - -const fs = require("fs"); +import fs from "fs"; require("dotenv").config({ path: "./../.env" }); - -//////////////////////////////////////// - -const varDatabaseDbHandler = require("../functions/backend/varDatabaseDbHandler"); -const DB_HANDLER = require("../utils/backend/global-db/DB_HANDLER"); - -/** ****************************************************************************** */ +import varDatabaseDbHandler from "../functions/backend/varDatabaseDbHandler"; +import DB_HANDLER from "../utils/backend/global-db/DB_HANDLER"; const userId = process.argv.indexOf("--userId") >= 0 ? process.argv[process.argv.indexOf("--userId") + 1] : null; -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - /** * Grab Schema * @@ -43,8 +29,7 @@ async function recoverMainJsonFromDb() { const { id, db_name, db_slug, db_full_name, db_image, db_description } = databases[i]; - /** @type {any} */ - const dbObject = { + const dbObject: any = { dbName: db_name, dbSlug: db_slug, dbFullName: db_full_name, @@ -60,8 +45,7 @@ async function recoverMainJsonFromDb() { for (let j = 0; j < tables.length; j++) { const { table_name, table_slug, table_description } = tables[j]; - /** @type {any} */ - const tableObject = { + const tableObject: any = { tableName: table_slug, tableFullName: table_name, fields: [], @@ -76,8 +60,7 @@ async function recoverMainJsonFromDb() { for (let k = 0; k < tableFields.length; k++) { const { Field, Type, Null, Default, Key } = tableFields[k]; - /** @type {any} */ - const fieldObject = { + const fieldObject: any = { fieldName: Field, dataType: Type.toUpperCase(), }; @@ -113,8 +96,4 @@ async function recoverMainJsonFromDb() { process.exit(); } -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// - recoverMainJsonFromDb(); diff --git a/package-shared/shell/resetSQLCredentials.js b/package-shared/shell/resetSQLCredentials.ts similarity index 56% rename from package-shared/shell/resetSQLCredentials.js rename to package-shared/shell/resetSQLCredentials.ts index 8ad39ac..e449077 100755 --- a/package-shared/shell/resetSQLCredentials.js +++ b/package-shared/shell/resetSQLCredentials.ts @@ -1,21 +1,8 @@ -// @ts-check - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// - require("dotenv").config({ path: "./../.env" }); -const generator = require("generate-password"); -const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler"); -const dbHandler = require("./utils/dbHandler"); -const encrypt = require("../functions/dsql/encrypt"); - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ +import generator from "generate-password"; +import noDatabaseDbHandler from "./utils/noDatabaseDbHandler"; +import dbHandler from "./utils/dbHandler"; +import encrypt from "../functions/dsql/encrypt"; /** * Create database from Schema Function @@ -24,13 +11,9 @@ const encrypt = require("../functions/dsql/encrypt"); * @param {number|string|null} params.userId - User ID or null */ async function resetSQLCredentials() { - /** - * @description Users - * @type {*[] | null} - */ // @ts-ignore - const users = await dbHandler({ + const users = (await dbHandler({ query: `SELECT * FROM users`, - }); + })) as any[]; if (!users) { process.exit(); @@ -82,22 +65,12 @@ async function resetSQLCredentials() { console.log( `User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.` ); - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log(`Error in adding SQL user =>`, error.message); } } process.exit(); - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// } -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - resetSQLCredentials(); diff --git a/package-shared/shell/resetSQLCredentialsPasswords.js b/package-shared/shell/resetSQLCredentialsPasswords.js deleted file mode 100755 index d34300f..0000000 --- a/package-shared/shell/resetSQLCredentialsPasswords.js +++ /dev/null @@ -1,90 +0,0 @@ -// @ts-check - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// - -require("dotenv").config({ path: "./../.env" }); -const generator = require("generate-password"); -const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler"); -const dbHandler = require("./utils/dbHandler"); -const encrypt = require("../functions/dsql/encrypt"); - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -/** - * Create database from Schema Function - * ============================================================================== - * @param {object} params - Single object params - * @param {number|string|null} params.userId - User ID or null - */ -async function resetSQLCredentialsPasswords() { - /** - * @description Users - * @type {*[] | null} - */ // @ts-ignore - const users = await dbHandler({ - query: `SELECT * FROM users`, - }); - - if (!users) { - process.exit(); - } - - for (let i = 0; i < users.length; i++) { - const user = users[i]; - - if (!user) continue; - - const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1"; - - try { - const username = `dsql_user_${user.id}`; - const password = generator.generate({ - length: 16, - numbers: true, - symbols: true, - uppercase: true, - exclude: "*#.'`\"", - }); - const encryptedPassword = encrypt({ data: password }); - - await noDatabaseDbHandler( - `SET PASSWORD FOR '${username}'@'${defaultMariadbUserHost}' = PASSWORD('${password}')` - ); - - const updateUser = await dbHandler({ - query: `UPDATE users SET mariadb_pass = ? WHERE id = ?`, - values: [encryptedPassword, user.id], - }); - - console.log( - `User ${user.id}: ${user.first_name} ${user.last_name} Password Updated successfully added.` - ); - } catch (/** @type {any} */ error) { - console.log( - `Error Updating User ${user.id} Password =>`, - error.message - ); - } - } - - process.exit(); - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// -} - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -resetSQLCredentialsPasswords(); diff --git a/package-shared/shell/resetSQLCredentialsPasswords.ts b/package-shared/shell/resetSQLCredentialsPasswords.ts new file mode 100755 index 0000000..700b6f6 --- /dev/null +++ b/package-shared/shell/resetSQLCredentialsPasswords.ts @@ -0,0 +1,60 @@ +require("dotenv").config({ path: "./../.env" }); +import generator from "generate-password"; +import noDatabaseDbHandler from "./utils/noDatabaseDbHandler"; +import dbHandler from "./utils/dbHandler"; +import encrypt from "../functions/dsql/encrypt"; + +/** + * # Create database from Schema Function + */ +async function resetSQLCredentialsPasswords() { + const users = (await dbHandler({ + query: `SELECT * FROM users`, + })) as any[]; + + if (!users) { + process.exit(); + } + + for (let i = 0; i < users.length; i++) { + const user = users[i]; + + if (!user) continue; + + const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1"; + + try { + const username = `dsql_user_${user.id}`; + const password = generator.generate({ + length: 16, + numbers: true, + symbols: true, + uppercase: true, + exclude: "*#.'`\"", + }); + const encryptedPassword = encrypt({ data: password }); + + await noDatabaseDbHandler( + `SET PASSWORD FOR '${username}'@'${defaultMariadbUserHost}' = PASSWORD('${password}')` + ); + + const updateUser = await dbHandler({ + query: `UPDATE users SET mariadb_pass = ? WHERE id = ?`, + values: [encryptedPassword, user.id], + }); + + console.log( + `User ${user.id}: ${user.first_name} ${user.last_name} Password Updated successfully added.` + ); + } catch (error: any) { + console.log( + `Error Updating User ${user.id} Password =>`, + error.message + ); + } + } + + process.exit(); +} + +resetSQLCredentialsPasswords(); diff --git a/package-shared/shell/scripts/convert-js-to-ts.ts b/package-shared/shell/scripts/convert-js-to-ts.ts new file mode 100644 index 0000000..48afab5 --- /dev/null +++ b/package-shared/shell/scripts/convert-js-to-ts.ts @@ -0,0 +1,46 @@ +import path from "path"; +import fs from "fs"; + +const rootDir = path.resolve(__dirname, "../../../"); +const ignorePattern = + /\/\.git\/|\/\.next\/|\/\.dist\/|node_modules|\/\.local_dist\/|\/\.tmp\/|\/types\/|\.config\.js|\/public\//; + +function transformJsToTs(dir: string) { + const dirContent = fs.readdirSync(dir); + + for (let i = 0; i < dirContent.length; i++) { + const fileFolder = dirContent[i]; + const fullFileFolderPath = path.join(dir, fileFolder); + const stat = fs.statSync(fullFileFolderPath); + + if (stat.isDirectory()) { + transformJsToTs(fullFileFolderPath); + continue; + } + + if (ignorePattern.test(fullFileFolderPath)) continue; + + if (fullFileFolderPath.match(/\.jsx?$/)) { + const extension = fullFileFolderPath.match(/\.jsx?$/)?.[0]; + if (!extension) continue; + const newExtension = extension.replace("js", "ts"); + const newFilePath = fullFileFolderPath.replace( + /\.jsx?$/, + newExtension + ); + + console.log(fullFileFolderPath); + console.log(extension, "=>", newExtension); + console.log(newFilePath); + console.log("\n/////////////////////////////////////////"); + console.log("/////////////////////////////////////////\n"); + + fs.copyFileSync(fullFileFolderPath, newFilePath); + fs.unlinkSync(fullFileFolderPath); + } + } +} + +console.log("rootDir", rootDir); + +transformJsToTs(rootDir); diff --git a/package-shared/shell/setSQLCredentials.js b/package-shared/shell/setSQLCredentials.ts similarity index 59% rename from package-shared/shell/setSQLCredentials.js rename to package-shared/shell/setSQLCredentials.ts index ca12fc6..e5d61a9 100755 --- a/package-shared/shell/setSQLCredentials.js +++ b/package-shared/shell/setSQLCredentials.ts @@ -1,14 +1,8 @@ -// @ts-check - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// - require("dotenv").config({ path: "./../.env" }); -const generator = require("generate-password"); -const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler"); -const dbHandler = require("./utils/dbHandler"); -const encrypt = require("../functions/dsql/encrypt"); +import generator from "generate-password"; +import noDatabaseDbHandler from "./utils/noDatabaseDbHandler"; +import dbHandler from "./utils/dbHandler"; +import encrypt from "../functions/dsql/encrypt"; /** ****************************************************************************** */ /** ****************************************************************************** */ @@ -18,19 +12,12 @@ const encrypt = require("../functions/dsql/encrypt"); /** ****************************************************************************** */ /** - * Create database from Schema Function - * ============================================================================== - * @param {object} params - Single object params - * @param {number|string|null} params.userId - User ID or null + * # Set SQL Credentials */ async function setSQLCredentials() { - /** - * @description Users - * @type {*[] | null} - */ // @ts-ignore - const users = await dbHandler({ + const users = (await dbHandler({ query: `SELECT * FROM users`, - }); + })) as any[] | null; if (!users) { process.exit(); @@ -72,22 +59,10 @@ async function setSQLCredentials() { console.log( `User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.` ); - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log(`Error in adding SQL user =>`, error.message); } } - - process.exit(); - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// } -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - setSQLCredentials(); diff --git a/package-shared/shell/tailwindWatch.js b/package-shared/shell/tailwindWatch.js deleted file mode 100755 index e947252..0000000 --- a/package-shared/shell/tailwindWatch.js +++ /dev/null @@ -1,29 +0,0 @@ -// @ts-check - -const fs = require("fs"); -const { exec } = require("child_process"); - -require("dotenv").config({ path: "./../.env" }); - -const sourceFile = process.argv.indexOf("--src") >= 0 ? process.argv[process.argv.indexOf("--src") + 1] : null; -const destinationFile = process.argv.indexOf("--dst") >= 0 ? process.argv[process.argv.indexOf("--dst") + 1] : null; - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -console.log("Running Tailwind CSS compiler ..."); - -fs.watch("./../", (curr, prev) => { - exec(`npx tailwindcss -i ./tailwind/main.css -o ./styles/tailwind.css`, (error, stdout, stderr) => { - if (error) { - console.log("ERROR =>", error.message); - return; - } - - console.log("Tailwind CSS Compilation \x1b[32msuccessful\x1b[0m!"); - }); -}); diff --git a/package-shared/shell/tailwindWatch.ts b/package-shared/shell/tailwindWatch.ts new file mode 100755 index 0000000..d16d92e --- /dev/null +++ b/package-shared/shell/tailwindWatch.ts @@ -0,0 +1,36 @@ +import fs from "fs"; +import { exec } from "child_process"; + +require("dotenv").config({ path: "./../.env" }); + +const sourceFile = + process.argv.indexOf("--src") >= 0 + ? process.argv[process.argv.indexOf("--src") + 1] + : null; +const destinationFile = + process.argv.indexOf("--dst") >= 0 + ? process.argv[process.argv.indexOf("--dst") + 1] + : null; + +/** ****************************************************************************** */ +/** ****************************************************************************** */ +/** ****************************************************************************** */ +/** ****************************************************************************** */ +/** ****************************************************************************** */ +/** ****************************************************************************** */ + +console.log("Running Tailwind CSS compiler ..."); + +fs.watch("./../", (curr, prev) => { + exec( + `npx tailwindcss -i ./tailwind/main.css -o ./styles/tailwind.css`, + (error, stdout, stderr) => { + if (error) { + console.log("ERROR =>", error.message); + return; + } + + console.log("Tailwind CSS Compilation \x1b[32msuccessful\x1b[0m!"); + } + ); +}); diff --git a/package-shared/shell/test-external-server.js b/package-shared/shell/test-external-server.ts similarity index 54% rename from package-shared/shell/test-external-server.js rename to package-shared/shell/test-external-server.ts index c5c93eb..1602624 100755 --- a/package-shared/shell/test-external-server.js +++ b/package-shared/shell/test-external-server.ts @@ -1,12 +1,6 @@ -// @ts-check - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// - require("dotenv").config({ path: "./.env" }); -const grabDbSSL = require("../utils/backend/grabDbSSL"); -const mysql = require("serverless-mysql"); +import grabDbSSL from "../utils/backend/grabDbSSL"; +import mysql from "serverless-mysql"; const connection = mysql({ config: { @@ -19,13 +13,6 @@ const connection = mysql({ }, }); -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// - /** * # Main DB Handler Function * @async @@ -49,7 +36,7 @@ const connection = mysql({ const parsedResults = JSON.parse(JSON.stringify(result)); console.log("parsedResults =>", parsedResults); - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log("Connection query ERROR =>", error.message); } finally { connection.end(); diff --git a/package-shared/shell/test.js b/package-shared/shell/test.js deleted file mode 100755 index 51cb797..0000000 --- a/package-shared/shell/test.js +++ /dev/null @@ -1,221 +0,0 @@ -require("dotenv").config({ path: "./../.env" }); - -const dbEngine = require("@moduletrace/datasquirel/engine"); -const http = require("http"); - -const datasquirel = require("@moduletrace/datasquirel"); - -`curl http://www.dataden.tech`; - -datasquirel - .get({ - db: "test", - key: process.env.DATASQUIREL_READ_ONLY_KEY, - query: "SELECT title, slug, body FROM blog_posts", - }) - .then((response) => { - console.log(response); - }); - -// dbEngine.db -// .query({ -// dbFullName: "datasquirel", -// dbHost: process.env.DSQL_DB_HOST, -// dbPassword: process.env.DSQL_DB_PASSWORD, -// dbUsername: process.env.DSQL_DB_USERNAME, -// query: "SHOW TABLES", -// }) -// .then((res) => { -// console.log("res =>", res); -// }); - -// run({ -// key: "bc057a2cd57922e085739c89b4985e5e676b655d7cc0ba7604659cad0a08c252040120c06597a5d22959a502a44bd816", -// db: "showmerebates", -// query: "SELECT * FROM test_table", -// }).then((res) => { -// console.log("res =>", res); -// }); - -post({ - key: "3115fce7ea7772eda75f8f0e55a1414c5c018b4920f4bc99a2d4d7000bac203c15a7036fd3d7ef55ae67a002d4c757895b5c58ff82079a04ba6d42d23d4353256985090959a58a9af8e03cb277fc7895413e6f28ae11b1cc15329c7f94cdcf9a795f54d6e1d319adc287dc147143e62d", - database: "showmerebates", - query: { - action: "delete", - table: "test_table", - identifierColumnName: "id", - identifierValue: 6, - }, -}).then((res) => { - console.log("res =>", res); -}); - -async function run({ key, db, query }) { - const httpResponse = await new Promise((resolve, reject) => { - http.request( - { - method: "GET", - headers: { - "Content-Type": "application/json", - Authorization: key, - }, - hostname: "localhost", - port: 7070, - path: `/api/query/get?db=${db}&query=${query - .replace(/\n|\r|\n\r/g, "") - .replace(/ {2,}/g, " ") - .replace(/ /g, "+")}`, - }, - - /** - * Callback Function - * - * @description https request callback - */ - (response) => { - var str = ""; - - response.on("data", function (chunk) { - str += chunk; - }); - - response.on("end", function () { - resolve(JSON.parse(str)); - }); - - response.on("error", (err) => { - reject(err); - }); - } - ).end(); - }); - - return httpResponse; -} - -/** - * @typedef {Object} PostReturn - * @property {boolean} success - Did the function run successfully? - * @property {(Object[]|string)} [payload=[]] - The Y Coordinate - */ - -/** - * @typedef {object} PostDataPayload - * @property {string} action - "insert" | "update" | "delete" - * @property {string} table - Table name(slug) eg "blog_posts" - * @property {string} identifierColumnName - Table identifier field name => eg. "id" OR "email" - * @property {string} identifierValue - Corresponding value of the selected field name => This - * checks identifies a the target row for "update" or "delete". Not needed for "insert" - * @property {object} data - Table insert payload object => This must have keys that match - * table fields - * @property {string?} duplicateColumnName - Duplicate column name to check for - * @property {string?} duplicateColumnValue - Duplicate column value to match. If no "update" param - * provided, function will return null - * @property {boolean?} update - Should the "insert" action update the existing entry if indeed - * the entry with "duplicateColumnValue" exists? - */ - -/** - * Post request - * ============================================================================== - * @async - * - * @param {Object} params - Single object passed - * @param {string} params.key - FULL ACCESS API Key - * @param {string} params.database - Database Name - * @param {PostDataPayload} params.query - SQL query String or Request Object - * - * @returns { Promise } - Return Object - */ -async function post({ key, query, database }) { - /** - * Make https request - * - * @description make a request to datasquirel.com - */ - const httpResponse = await new Promise((resolve, reject) => { - const reqPayloadString = JSON.stringify({ - query, - database, - }).replace(/\n|\r|\n\r/gm, ""); - - try { - JSON.parse(reqPayloadString); - } catch (error) { - console.log(error); - console.log(reqPayloadString); - - return { - success: false, - payload: null, - error: "Query object is invalid. Please Check query data values", - }; - } - - const reqPayload = reqPayloadString; - - const httpsRequest = http.request( - { - method: "POST", - headers: { - "Content-Type": "application/json", - "Content-Length": Buffer.from(reqPayload).length, - Authorization: key, - }, - hostname: "localhost", - port: 7070, - path: `/api/query/post`, - }, - - /** - * Callback Function - * - * @description https request callback - */ - (response) => { - var str = ""; - - response.on("data", function (chunk) { - str += chunk; - }); - - response.on("end", function () { - try { - resolve(JSON.parse(str)); - } catch (error) { - console.log(error.message); - console.log("Fetched Payload =>", str); - - resolve({ - success: false, - payload: null, - error: error.message, - }); - } - }); - - response.on("error", (err) => { - resolve({ - success: false, - payload: null, - error: err.message, - }); - }); - } - ); - - httpsRequest.write(reqPayload); - - httpsRequest.on("error", (error) => { - console.log("HTTPS request ERROR =>", error.message); - }); - - httpsRequest.end(); - }); - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - - return httpResponse; -} diff --git a/package-shared/shell/testSQLEscape.js b/package-shared/shell/testSQLEscape.ts similarity index 65% rename from package-shared/shell/testSQLEscape.js rename to package-shared/shell/testSQLEscape.ts index eea4405..174806f 100755 --- a/package-shared/shell/testSQLEscape.js +++ b/package-shared/shell/testSQLEscape.ts @@ -5,10 +5,10 @@ //////////////////////////////////////// require("dotenv").config({ path: "./../.env" }); -const generator = require("generate-password"); -const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler"); -const dbHandler = require("./utils/dbHandler"); -const encrypt = require("../functions/dsql/encrypt"); +import generator from "generate-password"; +import noDatabaseDbHandler from "./utils/noDatabaseDbHandler"; +import dbHandler from "./utils/dbHandler"; +import encrypt from "../functions/dsql/encrypt"; /** ****************************************************************************** */ /** ****************************************************************************** */ @@ -18,19 +18,12 @@ const encrypt = require("../functions/dsql/encrypt"); /** ****************************************************************************** */ /** - * Create database from Schema Function - * ============================================================================== - * @param {object} params - Single object params - * @param {number|string|null} params.userId - User ID or null + * # Test SQL Escape */ -async function testSQLEscape() { - /** - * @description Users - * @type {*[] | null} - */ // @ts-ignore - const users = await dbHandler({ +export default async function testSQLEscape() { + const users = (await dbHandler({ query: `SELECT * FROM users`, - }); + })) as any[]; if (!users) { process.exit(); @@ -81,22 +74,12 @@ async function testSQLEscape() { console.log( `User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.` ); - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log(`Error in adding SQL user =>`, error.message); } } process.exit(); - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// } -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - testSQLEscape(); diff --git a/package-shared/shell/updateChildrenTablesOnDb.js b/package-shared/shell/updateChildrenTablesOnDb.ts similarity index 55% rename from package-shared/shell/updateChildrenTablesOnDb.js rename to package-shared/shell/updateChildrenTablesOnDb.ts index eb3366b..b859230 100755 --- a/package-shared/shell/updateChildrenTablesOnDb.js +++ b/package-shared/shell/updateChildrenTablesOnDb.ts @@ -1,16 +1,7 @@ -// @ts-check - -const DB_HANDLER = require("../utils/backend/global-db/DB_HANDLER"); -const fs = require("fs"); +import DB_HANDLER from "../utils/backend/global-db/DB_HANDLER"; +import fs from "fs"; require("dotenv").config({ path: "./../.env" }); -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - async function updateChildrenTablesOnDb() { /** * Grab Schema @@ -57,24 +48,7 @@ async function updateChildrenTablesOnDb() { console.log(error); } - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - process.exit(); - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// } -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -// const userArg = process.argv[process.argv.indexOf("--user")]; -// const externalUser = process.argv[process.argv.indexOf("--user") + 1]; - updateChildrenTablesOnDb(); diff --git a/package-shared/shell/updateDateTimestamps.js b/package-shared/shell/updateDateTimestamps.ts similarity index 63% rename from package-shared/shell/updateDateTimestamps.js rename to package-shared/shell/updateDateTimestamps.ts index 6729cf7..1a4c7af 100755 --- a/package-shared/shell/updateDateTimestamps.js +++ b/package-shared/shell/updateDateTimestamps.ts @@ -1,17 +1,5 @@ -// @ts-check - require("dotenv").config({ path: "./../.env" }); - -//////////////////////////////////////// - -const varDatabaseDbHandler = require("../functions/backend/varDatabaseDbHandler"); - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ +import varDatabaseDbHandler from "../functions/backend/varDatabaseDbHandler"; /** * Grab Schema @@ -54,7 +42,3 @@ varDatabaseDbHandler({ process.exit(); }); - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// diff --git a/package-shared/shell/updateDbSlugsForTableRecords.js b/package-shared/shell/updateDbSlugsForTableRecords.ts similarity index 77% rename from package-shared/shell/updateDbSlugsForTableRecords.js rename to package-shared/shell/updateDbSlugsForTableRecords.ts index e1d0074..022f3b6 100755 --- a/package-shared/shell/updateDbSlugsForTableRecords.js +++ b/package-shared/shell/updateDbSlugsForTableRecords.ts @@ -1,10 +1,8 @@ -// @ts-check - require("dotenv").config({ path: "./../.env" }); -const serverError = require("../functions/backend/serverError"); -const varDatabaseDbHandler = require("./utils/varDatabaseDbHandler"); -const DB_HANDLER = require("../utils/backend/global-db/DB_HANDLER"); +import serverError from "../functions/backend/serverError"; +import varDatabaseDbHandler from "./utils/varDatabaseDbHandler"; +import DB_HANDLER from "../utils/backend/global-db/DB_HANDLER"; /** ****************************************************************************** */ /** ****************************************************************************** */ @@ -38,7 +36,7 @@ varDatabaseDbHandler({ const updateTableSlug = await DB_HANDLER( `UPDATE user_database_tables SET db_slug='${dbSlug[0].db_slug}' WHERE db_id='${db_id}'` ); - } catch (/** @type {any} */ error) { + } catch (error: any) { serverError({ component: "shell/updateDbSlugsForTableRecords/main-catch-error", @@ -50,7 +48,3 @@ varDatabaseDbHandler({ process.exit(); }); - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// diff --git a/package-shared/shell/updateSSLUsers.js b/package-shared/shell/updateSSLUsers.ts similarity index 88% rename from package-shared/shell/updateSSLUsers.js rename to package-shared/shell/updateSSLUsers.ts index a0a406d..ff1aa01 100755 --- a/package-shared/shell/updateSSLUsers.js +++ b/package-shared/shell/updateSSLUsers.ts @@ -1,8 +1,6 @@ -// @ts-check - require("dotenv").config({ path: "./../.env" }); -const grabDbSSL = require("../utils/backend/grabDbSSL"); -const mysql = require("serverless-mysql"); +import grabDbSSL from "../utils/backend/grabDbSSL"; +import mysql from "serverless-mysql"; const connection = mysql({ config: { @@ -61,7 +59,7 @@ const connection = mysql({ console.log(`addUserSSL => ${User}@${Host}`, addUserSSL); } - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log("Connection query ERROR =>", error.message); } finally { connection.end(); diff --git a/package-shared/shell/utils/camelJoinedtoCamelSpace.js b/package-shared/shell/utils/camelJoinedtoCamelSpace.ts similarity index 85% rename from package-shared/shell/utils/camelJoinedtoCamelSpace.js rename to package-shared/shell/utils/camelJoinedtoCamelSpace.ts index db7413a..126cde1 100755 --- a/package-shared/shell/utils/camelJoinedtoCamelSpace.js +++ b/package-shared/shell/utils/camelJoinedtoCamelSpace.ts @@ -1,16 +1,10 @@ -// @ts-check - /** * Convert Camel Joined Text to Camel Spaced Text * ============================================================================== * @description this function takes a camel cased text without spaces, and returns * a camel-case-spaced text - * - * @param {string} text - text string without spaces - * - * @returns {string | null} */ -module.exports = function camelJoinedtoCamelSpace(text) { +export default function camelJoinedtoCamelSpace(text: string): string | null { if (!text?.match(/./)) { return ""; } @@ -56,4 +50,4 @@ module.exports = function camelJoinedtoCamelSpace(text) { } else { return null; } -}; +} diff --git a/package-shared/shell/utils/createTable.d.ts b/package-shared/shell/utils/createTable.d.ts deleted file mode 100644 index f7c2deb..0000000 --- a/package-shared/shell/utils/createTable.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -declare function _exports({ dbFullName, tableName, tableInfoArray, dbSchema, clone, tableSchema, recordedDbEntry, }: { - dbFullName: string; - tableName: string; - tableInfoArray: any[]; - dbSchema?: import("../../types").DSQL_DatabaseSchemaType[]; - tableSchema?: import("../../types").DSQL_TableSchemaType; - recordedDbEntry?: any; - clone?: boolean; -}): Promise; -export = _exports; diff --git a/package-shared/shell/utils/createTable.js b/package-shared/shell/utils/createTable.ts similarity index 79% rename from package-shared/shell/utils/createTable.js rename to package-shared/shell/utils/createTable.ts index 554f9ab..55be093 100755 --- a/package-shared/shell/utils/createTable.js +++ b/package-shared/shell/utils/createTable.ts @@ -1,30 +1,23 @@ -// @ts-check +import varDatabaseDbHandler from "./varDatabaseDbHandler"; +import generateColumnDescription from "./generateColumnDescription"; +import supplementTable from "./supplementTable"; +import dbHandler from "./dbHandler"; +import { DSQL_DatabaseSchemaType, DSQL_TableSchemaType } from "../../types"; -const varDatabaseDbHandler = require("./varDatabaseDbHandler"); -const generateColumnDescription = require("./generateColumnDescription"); -const supplementTable = require("./supplementTable"); -const dbHandler = require("./dbHandler"); - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ +type Param = { + dbFullName: string; + tableName: string; + tableInfoArray: any[]; + dbSchema?: DSQL_DatabaseSchemaType[]; + tableSchema?: DSQL_TableSchemaType; + recordedDbEntry?: any; + clone?: boolean; +}; /** - * - * @param {object} params - * @param {string} params.dbFullName - * @param {string} params.tableName - * @param {any[]} params.tableInfoArray - * @param {import("../../types").DSQL_DatabaseSchemaType[]} [params.dbSchema] - * @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema] - * @param {any} [params.recordedDbEntry] - * @param {boolean} [params.clone] - Is this a newly cloned table? - * @returns + * # Create Table Functions */ -module.exports = async function createTable({ +export default async function createTable({ dbFullName, tableName, tableInfoArray, @@ -32,7 +25,7 @@ module.exports = async function createTable({ clone, tableSchema, recordedDbEntry, -}) { +}: Param) { /** * Format tableInfoArray * @@ -65,7 +58,8 @@ module.exports = async function createTable({ }); /** @type {import("../../types").MYSQL_user_database_tables_table_def} */ - const table = existingTable?.[0]; + const table: import("../../types").MYSQL_user_database_tables_table_def = + existingTable?.[0]; if (!table?.id) { const newTableEntry = await dbHandler({ @@ -98,7 +92,7 @@ module.exports = async function createTable({ let primaryKeySet = false; /** @type {import("../../types").DSQL_FieldSchemaType[]} */ - let foreignKeys = []; + let foreignKeys: import("../../types").DSQL_FieldSchemaType[] = []; //////////////////////////////////////// @@ -204,7 +198,7 @@ module.exports = async function createTable({ //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// -}; +} /** ****************************************************************************** */ /** ****************************************************************************** */ diff --git a/package-shared/shell/utils/dbHandler.d.ts b/package-shared/shell/utils/dbHandler.d.ts deleted file mode 100644 index b6e4b6b..0000000 --- a/package-shared/shell/utils/dbHandler.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -declare function _exports({ query, values, database }: { - query: string; - values?: string[] | object; - database?: string; -}): Promise; -export = _exports; diff --git a/package-shared/shell/utils/dbHandler.js b/package-shared/shell/utils/dbHandler.ts similarity index 63% rename from package-shared/shell/utils/dbHandler.js rename to package-shared/shell/utils/dbHandler.ts index 7c014c6..8a15e15 100755 --- a/package-shared/shell/utils/dbHandler.js +++ b/package-shared/shell/utils/dbHandler.ts @@ -1,14 +1,8 @@ -// @ts-check +import fs from "fs"; +import path from "path"; -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// - -const fs = require("fs"); -const path = require("path"); - -const mysql = require("serverless-mysql"); -const grabDbSSL = require("../../utils/backend/grabDbSSL"); +import mysql from "serverless-mysql"; +import grabDbSSL from "../../utils/backend/grabDbSSL"; let connection = mysql({ config: { @@ -21,25 +15,20 @@ let connection = mysql({ }, }); -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////// +type Param = { + query: string; + values?: string[] | object; + database?: string; +}; /** * # Main DB Handler Function - * @async - * - * @param {object} params - * @param {string} params.query - * @param {string[] | object} [params.values] - * @param {string} [params.database] - * - * @returns {Promise} */ -module.exports = async function dbHandler({ query, values, database }) { +export default async function dbHandler({ + query, + values, + database, +}: Param): Promise { /** * Switch Database * @@ -88,7 +77,7 @@ module.exports = async function dbHandler({ query, values, database }) { /** ********************* Clean up */ await connection.end(); - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { if (process.env.FIRST_RUN) { return null; } @@ -115,4 +104,4 @@ module.exports = async function dbHandler({ query, values, database }) { } else { return null; } -}; +} diff --git a/package-shared/shell/utils/generateColumnDescription.d.ts b/package-shared/shell/utils/generateColumnDescription.d.ts deleted file mode 100644 index 97fec49..0000000 --- a/package-shared/shell/utils/generateColumnDescription.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -declare function _exports({ columnData, primaryKeySet, }: { - columnData: import("../../types").DSQL_FieldSchemaType; - primaryKeySet?: boolean; -}): { - fieldEntryText: string; - newPrimaryKeySet: boolean; -}; -export = _exports; diff --git a/package-shared/shell/utils/generateColumnDescription.js b/package-shared/shell/utils/generateColumnDescription.js deleted file mode 100755 index dc5a7a8..0000000 --- a/package-shared/shell/utils/generateColumnDescription.js +++ /dev/null @@ -1,108 +0,0 @@ -// @ts-check - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -/** - * Generate SQL text for Field - * ============================================================================== - * @param {object} params - Single object params - * @param {import("../../types").DSQL_FieldSchemaType} params.columnData - Field object - * @param {boolean} [params.primaryKeySet] - Table Name(slug) - * - * @returns {{ fieldEntryText: string, newPrimaryKeySet: boolean }} - */ -module.exports = function generateColumnDescription({ - columnData, - primaryKeySet, -}) { - /** - * Format tableInfoArray - * - * @description Format tableInfoArray - */ - const { - fieldName, - dataType, - nullValue, - primaryKey, - autoIncrement, - defaultValue, - defaultValueLiteral, - foreignKey, - updatedField, - onUpdate, - onUpdateLiteral, - onDelete, - onDeleteLiteral, - defaultField, - encrypted, - json, - newTempField, - notNullValue, - originName, - plainText, - pattern, - patternFlags, - richText, - } = columnData; - - let fieldEntryText = ""; - - fieldEntryText += `\`${fieldName}\` ${dataType}`; - - //////////////////////////////////////// - - // if (String(fieldEntryText).match(/ UUID$/)) { - // fieldEntryText += ` DEFAULT UUID()`; - // } else - if (nullValue) { - fieldEntryText += " DEFAULT NULL"; - } else if (defaultValueLiteral) { - fieldEntryText += ` DEFAULT ${defaultValueLiteral}`; - } else if (defaultValue) { - if (String(defaultValue).match(/uuid\(\)/i)) { - fieldEntryText += ` DEFAULT UUID()`; - } else { - fieldEntryText += ` DEFAULT '${defaultValue}'`; - } - } else if (notNullValue) { - fieldEntryText += ` NOT NULL`; - } - - //////////////////////////////////////// - - if (onUpdateLiteral) { - fieldEntryText += ` ON UPDATE ${onUpdateLiteral}`; - } - - //////////////////////////////////////// - - if (primaryKey && !primaryKeySet) { - fieldEntryText += " PRIMARY KEY"; - primaryKeySet = true; - } - - //////////////////////////////////////// - - if (autoIncrement) { - fieldEntryText += " AUTO_INCREMENT"; - primaryKeySet = true; - } - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - - return { fieldEntryText, newPrimaryKeySet: primaryKeySet || false }; -}; - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ diff --git a/package-shared/shell/utils/generateColumnDescription.ts b/package-shared/shell/utils/generateColumnDescription.ts new file mode 100755 index 0000000..4bbfb42 --- /dev/null +++ b/package-shared/shell/utils/generateColumnDescription.ts @@ -0,0 +1,83 @@ +type Param = { + columnData: import("../../types").DSQL_FieldSchemaType; + primaryKeySet?: boolean; +}; + +type Return = { + fieldEntryText: string; + newPrimaryKeySet: boolean; +}; + +/** + * # Generate Table Column Description + */ +export default function generateColumnDescription({ + columnData, + primaryKeySet, +}: Param): Return { + /** + * Format tableInfoArray + * + * @description Format tableInfoArray + */ + const { + fieldName, + dataType, + nullValue, + primaryKey, + autoIncrement, + defaultValue, + defaultValueLiteral, + onUpdateLiteral, + notNullValue, + } = columnData; + + let fieldEntryText = ""; + + fieldEntryText += `\`${fieldName}\` ${dataType}`; + + //////////////////////////////////////// + + if (nullValue) { + fieldEntryText += " DEFAULT NULL"; + } else if (defaultValueLiteral) { + fieldEntryText += ` DEFAULT ${defaultValueLiteral}`; + } else if (defaultValue) { + if (String(defaultValue).match(/uuid\(\)/i)) { + fieldEntryText += ` DEFAULT UUID()`; + } else { + fieldEntryText += ` DEFAULT '${defaultValue}'`; + } + } else if (notNullValue) { + fieldEntryText += ` NOT NULL`; + } + + //////////////////////////////////////// + + if (onUpdateLiteral) { + fieldEntryText += ` ON UPDATE ${onUpdateLiteral}`; + } + + //////////////////////////////////////// + + if (primaryKey && !primaryKeySet) { + fieldEntryText += " PRIMARY KEY"; + primaryKeySet = true; + } + + //////////////////////////////////////// + + if (autoIncrement) { + fieldEntryText += " AUTO_INCREMENT"; + primaryKeySet = true; + } + + //////////////////////////////////////// + //////////////////////////////////////// + //////////////////////////////////////// + + return { + fieldEntryText, + newPrimaryKeySet: primaryKeySet || false, + }; +} diff --git a/package-shared/shell/utils/noDatabaseDbHandler.d.ts b/package-shared/shell/utils/noDatabaseDbHandler.d.ts deleted file mode 100644 index 4cea1af..0000000 --- a/package-shared/shell/utils/noDatabaseDbHandler.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare function _exports(queryString: string): Promise; -export = _exports; diff --git a/package-shared/shell/utils/noDatabaseDbHandler.js b/package-shared/shell/utils/noDatabaseDbHandler.ts similarity index 65% rename from package-shared/shell/utils/noDatabaseDbHandler.js rename to package-shared/shell/utils/noDatabaseDbHandler.ts index 073d0f1..872ddeb 100755 --- a/package-shared/shell/utils/noDatabaseDbHandler.js +++ b/package-shared/shell/utils/noDatabaseDbHandler.ts @@ -1,14 +1,11 @@ -// @ts-check - -const dbHandler = require("./dbHandler"); +import dbHandler from "./dbHandler"; /** - * Create database from Schema Function - * ============================================================================== - * @param {string} queryString - Query String - * @returns {Promise} + * # Create database from Schema Function */ -module.exports = async function noDatabaseDbHandler(queryString) { +export default async function noDatabaseDbHandler( + queryString: string +): Promise { /** * Declare variables * @@ -28,7 +25,7 @@ module.exports = async function noDatabaseDbHandler(queryString) { //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log("ERROR in noDatabaseDbHandler =>", error.message); } @@ -42,4 +39,4 @@ module.exports = async function noDatabaseDbHandler(queryString) { } else { return null; } -}; +} diff --git a/package-shared/shell/utils/slugToCamelTitle.js b/package-shared/shell/utils/slugToCamelTitle.ts similarity index 77% rename from package-shared/shell/utils/slugToCamelTitle.js rename to package-shared/shell/utils/slugToCamelTitle.ts index 576731c..86c6007 100755 --- a/package-shared/shell/utils/slugToCamelTitle.js +++ b/package-shared/shell/utils/slugToCamelTitle.ts @@ -1,6 +1,7 @@ -// @ts-check - -module.exports = function slugToCamelTitle(/** @type {String} */ text) { +/** + * # Sulg To Camel Case + */ +export default function slugToCamelTitle(text: string) { if (text) { let addArray = text.split("-").filter((item) => item !== ""); let camelArray = addArray.map((item) => { @@ -15,4 +16,4 @@ module.exports = function slugToCamelTitle(/** @type {String} */ text) { } else { return null; } -}; +} diff --git a/package-shared/shell/utils/supplementTable.d.ts b/package-shared/shell/utils/supplementTable.d.ts deleted file mode 100644 index aadf5c6..0000000 --- a/package-shared/shell/utils/supplementTable.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -declare function _exports({ tableInfoArray }: { - tableInfoArray: import("../../types").DSQL_FieldSchemaType[]; -}): import("../../types").DSQL_FieldSchemaType[]; -export = _exports; diff --git a/package-shared/shell/utils/supplementTable.js b/package-shared/shell/utils/supplementTable.ts similarity index 63% rename from package-shared/shell/utils/supplementTable.js rename to package-shared/shell/utils/supplementTable.ts index 1c0a3a6..257787d 100755 --- a/package-shared/shell/utils/supplementTable.js +++ b/package-shared/shell/utils/supplementTable.ts @@ -1,19 +1,13 @@ -// @ts-check +import { DSQL_FieldSchemaType } from "../../types"; -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ +type Param = { + tableInfoArray: DSQL_FieldSchemaType[]; +}; /** - * - * @param {object} param0 - * @param {import("../../types").DSQL_FieldSchemaType[]} param0.tableInfoArray - * @returns + * # Supplement Table */ -module.exports = function supplementTable({ tableInfoArray }) { +export default function supplementTable({ tableInfoArray }: Param) { /** * Format tableInfoArray * @@ -30,7 +24,7 @@ module.exports = function supplementTable({ tableInfoArray }) { //////////////////////////////////////// - defaultFields.forEach((field) => { + defaultFields.forEach((field: any) => { let fieldExists = finalTableArray.filter( (_field) => _field.fieldName === field.fieldName ); @@ -49,7 +43,7 @@ module.exports = function supplementTable({ tableInfoArray }) { //////////////////////////////////////// return finalTableArray; -}; +} /** ****************************************************************************** */ /** ****************************************************************************** */ diff --git a/package-shared/shell/utils/updateTable.d.ts b/package-shared/shell/utils/updateTable.d.ts deleted file mode 100644 index 68e6cf7..0000000 --- a/package-shared/shell/utils/updateTable.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -declare function _exports({ dbFullName, tableName, tableInfoArray, userId, dbSchema, tableIndexes, tableSchema, clone, childDb, tableIndex, tableNameFull, recordedDbEntry, }: { - dbFullName: string; - tableName: string; - tableSchema: import("../../types").DSQL_TableSchemaType; - tableNameFull?: string; - tableInfoArray: import("../../types").DSQL_FieldSchemaType[]; - userId?: number | string | null; - dbSchema: import("../../types").DSQL_DatabaseSchemaType[]; - tableIndexes?: import("../../types").DSQL_IndexSchemaType[]; - clone?: boolean; - tableIndex?: number; - childDb?: boolean; - recordedDbEntry?: any; -}): Promise; -export = _exports; diff --git a/package-shared/shell/utils/updateTable.js b/package-shared/shell/utils/updateTable.ts similarity index 78% rename from package-shared/shell/utils/updateTable.js rename to package-shared/shell/utils/updateTable.ts index 804602a..9e7c0b1 100755 --- a/package-shared/shell/utils/updateTable.js +++ b/package-shared/shell/utils/updateTable.ts @@ -1,46 +1,31 @@ -// @ts-check - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -///////////////////////// - Update Table Function - //////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -const fs = require("fs"); -const varDatabaseDbHandler = require("./varDatabaseDbHandler"); +import fs from "fs"; +import varDatabaseDbHandler from "./varDatabaseDbHandler"; const defaultFieldsRegexp = /^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/; -const generateColumnDescription = require("./generateColumnDescription"); -const dbHandler = require("./dbHandler"); +import generateColumnDescription from "./generateColumnDescription"; +import dbHandler from "./dbHandler"; -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// +type Param = { + dbFullName: string; + tableName: string; + tableSchema: import("../../types").DSQL_TableSchemaType; + tableNameFull?: string; + tableInfoArray: import("../../types").DSQL_FieldSchemaType[]; + userId?: number | string | null; + dbSchema: import("../../types").DSQL_DatabaseSchemaType[]; + tableIndexes?: import("../../types").DSQL_IndexSchemaType[]; + clone?: boolean; + tableIndex?: number; + childDb?: boolean; + recordedDbEntry?: any; +}; /** - * Update table function - * ============================================================================== - * @param {object} params - Single object params - * @param {string} params.dbFullName - Database full name => "datasquirel_user_4394_db_name" - * @param {string} params.tableName - Table Name(slug) - * @param {import("../../types").DSQL_TableSchemaType} params.tableSchema - Table Name(slug) - * @param {string} [params.tableNameFull] - Table Name(slug) - * @param {import("../../types").DSQL_FieldSchemaType[]} params.tableInfoArray - Table Info Array - * @param {number | string | null} [params.userId] - User ID - * @param {import("../../types").DSQL_DatabaseSchemaType[]} params.dbSchema - Single post - * @param {import("../../types").DSQL_IndexSchemaType[]} [params.tableIndexes] - Table Indexes - * @param {boolean} [params.clone] - Is this a newly cloned table? - * @param {number} [params.tableIndex] - The number index of the table in the dbSchema array - * @param {boolean} [params.childDb] - The number index of the table in the dbSchema array - * @param {any} [params.recordedDbEntry] - The database object as recorded in `user_databases` table + * # Update table function */ -module.exports = async function updateTable({ +export default async function updateTable({ dbFullName, tableName, tableInfoArray, @@ -53,7 +38,7 @@ module.exports = async function updateTable({ tableIndex, tableNameFull, recordedDbEntry, -}) { +}: Param) { /** * Initialize * ========================================== @@ -61,7 +46,7 @@ module.exports = async function updateTable({ */ /** @type {any[]} */ - let errorLogs = []; + let errorLogs: any[] = []; /** * @description Initialize table info array. This value will be @@ -79,23 +64,19 @@ module.exports = async function updateTable({ * @type {string[]} * @description Table update query string array */ - const updateTableQueryArray = []; + const updateTableQueryArray: string[] = []; /** * @type {string[]} * @description Constriants query string array */ - const constraintsQueryArray = []; + const constraintsQueryArray: string[] = []; /** * @description Push the query initial value */ updateTableQueryArray.push(`ALTER TABLE \`${tableName}\``); - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - if (childDb) { try { if (!recordedDbEntry) { @@ -109,7 +90,8 @@ module.exports = async function updateTable({ }); /** @type {import("../../types").MYSQL_user_database_tables_table_def} */ - const table = existingTable?.[0]; + const table: import("../../types").MYSQL_user_database_tables_table_def = + existingTable?.[0]; if (!table?.id) { const newTableEntry = await dbHandler({ @@ -136,27 +118,25 @@ module.exports = async function updateTable({ } catch (error) {} } - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - /** * @type {import("../../types").DSQL_MYSQL_SHOW_INDEXES_Type[]} * @description All indexes from MYSQL db */ // @ts-ignore - const allExistingIndexes = await varDatabaseDbHandler({ - queryString: `SHOW INDEXES FROM \`${tableName}\``, - database: dbFullName, - }); + const allExistingIndexes: import("../../types").DSQL_MYSQL_SHOW_INDEXES_Type[] = + await varDatabaseDbHandler({ + queryString: `SHOW INDEXES FROM \`${tableName}\``, + database: dbFullName, + }); /** * @type {import("../../types").DSQL_MYSQL_SHOW_COLUMNS_Type[]} * @description All columns from MYSQL db */ // @ts-ignore - const allExistingColumns = await varDatabaseDbHandler({ - queryString: `SHOW COLUMNS FROM \`${tableName}\``, - database: dbFullName, - }); + const allExistingColumns: import("../../types").DSQL_MYSQL_SHOW_COLUMNS_Type[] = + await varDatabaseDbHandler({ + queryString: `SHOW COLUMNS FROM \`${tableName}\``, + database: dbFullName, + }); //////////////////////////////////////// @@ -164,11 +144,7 @@ module.exports = async function updateTable({ * @type {string[]} * @description Updated column names Array */ - const updatedColumnsArray = []; - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// + const updatedColumnsArray: string[] = []; /** * @description Iterate through every existing column @@ -251,7 +227,7 @@ module.exports = async function updateTable({ JSON.stringify(userSchemaData), "utf8" ); - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log("Update table error =>", error.message); } @@ -271,10 +247,6 @@ module.exports = async function updateTable({ } } - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - /** * Handle MYSQL Table Indexes * =================================================== @@ -350,10 +322,6 @@ module.exports = async function updateTable({ } } - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - /** * Handle MYSQL Foreign Keys * =================================================== @@ -365,7 +333,9 @@ module.exports = async function updateTable({ * @description All MSQL Foreign Keys * @type {import("../../types").DSQL_MYSQL_FOREIGN_KEYS_Type[] | null} */ // @ts-ignore - const allForeignKeys = await varDatabaseDbHandler({ + const allForeignKeys: + | import("../../types").DSQL_MYSQL_FOREIGN_KEYS_Type[] + | null = await varDatabaseDbHandler({ queryString: `SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = '${dbFullName}' AND TABLE_NAME='${tableName}' AND CONSTRAINT_TYPE='FOREIGN KEY'`, database: dbFullName, }); @@ -390,10 +360,6 @@ module.exports = async function updateTable({ } } - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - /** * Handle DATASQUIREL schema fields for current table * =================================================== @@ -435,7 +401,7 @@ module.exports = async function updateTable({ //////////////////////////////////////// /** @type {any} */ - let existingColumnIndex; + let existingColumnIndex: any; /** * @description Existing MYSQL field object @@ -516,10 +482,6 @@ module.exports = async function updateTable({ */ updateTableQueryArray.push(updateText + ","); - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - /** * @description Handle foreing keys if available, and if there is no * "clone" boolean = true @@ -582,19 +544,9 @@ module.exports = async function updateTable({ */ return "No Changes Made to Table"; } - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log('Error in "updateTable" shell function =>', error.message); return "Error in Updating Table"; } -}; - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// +} diff --git a/package-shared/shell/utils/varDatabaseDbHandler.d.ts b/package-shared/shell/utils/varDatabaseDbHandler.d.ts deleted file mode 100644 index d21b4c2..0000000 --- a/package-shared/shell/utils/varDatabaseDbHandler.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -declare function _exports({ queryString, queryValuesArray, database, tableSchema, }: { - queryString: string; - queryValuesArray?: string[]; - database?: string; - tableSchema?: import("../../types").DSQL_TableSchemaType; -}): Promise; -export = _exports; diff --git a/package-shared/shell/utils/varDatabaseDbHandler.js b/package-shared/shell/utils/varDatabaseDbHandler.ts similarity index 56% rename from package-shared/shell/utils/varDatabaseDbHandler.js rename to package-shared/shell/utils/varDatabaseDbHandler.ts index 807fbdb..3652727 100755 --- a/package-shared/shell/utils/varDatabaseDbHandler.js +++ b/package-shared/shell/utils/varDatabaseDbHandler.ts @@ -1,25 +1,22 @@ -// @ts-check +import dbHandler from "./dbHandler"; +import { DSQL_TableSchemaType } from "../../types"; -const fs = require("fs"); -const dbHandler = require("./dbHandler"); +type Param = { + queryString: string; + queryValuesArray?: string[]; + database?: string; + tableSchema?: DSQL_TableSchemaType; +}; /** - * DB handler for specific database - * ============================================================================== - * @async - * @param {object} params - Single object params - * @param {string} params.queryString - SQL string - * @param {string[]} [params.queryValuesArray] - Values Array - * @param {string} [params.database] - Database name - * @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema - * @returns {Promise} + * # DB handler for specific database */ -module.exports = async function varDatabaseDbHandler({ +export default async function varDatabaseDbHandler({ queryString, queryValuesArray, database, tableSchema, -}) { +}: Param): Promise { /** * Declare variables * @@ -54,7 +51,7 @@ module.exports = async function varDatabaseDbHandler({ //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log("Shell Vardb Error =>", error.message); } @@ -64,8 +61,4 @@ module.exports = async function varDatabaseDbHandler({ * @description Return results add to cache if "req" param is passed */ return results; - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// -}; +} diff --git a/package-shared/types/index.d.ts b/package-shared/types/index.d.ts deleted file mode 100644 index 2821b5d..0000000 --- a/package-shared/types/index.d.ts +++ /dev/null @@ -1,1258 +0,0 @@ -import { RequestOptions } from "https"; -import { Editor } from "tinymce"; -export type DSQL_DatabaseFullName = string; -export interface DSQL_DatabaseSchemaType { - dbName: string; - dbSlug: string; - dbFullName: string; - dbDescription?: string; - dbImage?: string; - tables: DSQL_TableSchemaType[]; - childrenDatabases?: DSQL_ChildrenDatabaseObject[]; - childDatabase?: boolean; - childDatabaseDbFullName?: string; - updateData?: boolean; -} -export interface DSQL_ChildrenDatabaseObject { - dbFullName: string; -} -export interface DSQL_TableSchemaType { - tableName: string; - tableFullName: string; - tableDescription?: string; - fields: DSQL_FieldSchemaType[]; - indexes?: DSQL_IndexSchemaType[]; - childrenTables?: DSQL_ChildrenTablesType[]; - childTable?: boolean; - updateData?: boolean; - childTableName?: string; - childTableDbFullName?: string; - tableNameOld?: string; -} -export interface DSQL_ChildrenTablesType { - dbNameFull: string; - tableName: string; - tableNameFull?: string; -} -export interface DSQL_FieldSchemaType { - fieldName?: string; - originName?: string; - updatedField?: boolean; - dataType?: string; - nullValue?: boolean; - notNullValue?: boolean; - primaryKey?: boolean; - encrypted?: boolean; - autoIncrement?: boolean; - defaultValue?: string | number; - defaultValueLiteral?: string; - foreignKey?: DSQL_ForeignKeyType; - richText?: boolean; - json?: boolean; - yaml?: boolean; - html?: boolean; - css?: boolean; - javascript?: boolean; - shell?: boolean; - newTempField?: boolean; - defaultField?: boolean; - plainText?: boolean; - unique?: boolean; - pattern?: string; - patternFlags?: string; - onUpdate?: string; - onUpdateLiteral?: string; - onDelete?: string; - onDeleteLiteral?: string; - cssFiles?: string[]; -} -export interface DSQL_ForeignKeyType { - foreignKeyName?: string; - destinationTableName?: string; - destinationTableColumnName?: string; - destinationTableColumnType?: string; - cascadeDelete?: boolean; - cascadeUpdate?: boolean; -} -export interface DSQL_IndexSchemaType { - indexName?: string; - indexType?: string; - indexTableFields?: DSQL_IndexTableFieldType[]; - alias?: string; - newTempIndex?: boolean; -} -export interface DSQL_IndexTableFieldType { - value: string; - dataType: string; -} -export interface DSQL_MYSQL_SHOW_INDEXES_Type { - Key_name: string; - Table: string; - Column_name: string; - Collation: string; - Index_type: string; - Cardinality: string; - Index_comment: string; - Comment: string; -} -export interface DSQL_MYSQL_SHOW_COLUMNS_Type { - Field: string; - Type: string; - Null: string; - Key: string; - Default: string; - Extra: string; -} -export interface DSQL_MYSQL_FOREIGN_KEYS_Type { - CONSTRAINT_NAME: string; - CONSTRAINT_SCHEMA: string; - TABLE_NAME: string; -} -export interface DSQL_MYSQL_user_databases_Type { - id: number; - user_id: number; - db_full_name: string; - db_name: string; - db_slug: string; - db_image: string; - db_description: string; - active_clone: number; - active_clone_parent_db: string; - remote_connected?: number; - remote_db_full_name?: string; - remote_connection_host?: string; - remote_connection_key?: string; - remote_connection_type?: string; - user_priviledge?: string; - date_created?: string; - image_thumbnail?: string; - first_name?: string; - last_name?: string; - email?: string; -} -export interface PackageUserLoginRequestBody { - encryptionKey: string; - payload: any; - database: string; - additionalFields?: string[]; - email_login?: boolean; - email_login_code?: string; - email_login_field?: string; - token?: boolean; - social?: boolean; - dbSchema?: DSQL_DatabaseSchemaType; - skipPassword?: boolean; -} -export interface PackageUserLoginLocalBody { - payload: any; - additionalFields?: string[]; - email_login?: boolean; - email_login_code?: string; - email_login_field?: string; - token?: boolean; - social?: boolean; - dbSchema?: DSQL_DatabaseSchemaType; - skipPassword?: boolean; -} -export interface GetReqQueryObject { - db: string; - query: string; - queryValues?: string; - tableName?: string; -} -export type SerializeQueryFnType = (query: any) => string; -export type DATASQUIREL_LoggedInUser = { - id: number; - uuid?: string; - first_name: string; - last_name: string; - email: string; - phone?: string; - user_type?: string; - username?: string; - image?: string; - image_thumbnail?: string; - social_login?: number; - social_platform?: string; - social_id?: string; - verification_status?: number; - csrf_k: string; - logged_in_status: boolean; - date: number; -} & { - [key: string]: any; -}; -export interface AuthenticatedUser { - success: boolean; - payload: DATASQUIREL_LoggedInUser | null; - msg?: string; - userId?: number; - cookieNames?: any; -} -export interface SuccessUserObject { - id: number; - first_name: string; - last_name: string; - email: string; -} -export interface AddUserFunctionReturn { - success: boolean; - payload?: SuccessUserObject | null; - msg?: string; - sqlResult?: any; -} -export interface GoogleIdentityPromptNotification { - getMomentType: () => string; - getDismissedReason: () => string; - getNotDisplayedReason: () => string; - getSkippedReason: () => string; - isDismissedMoment: () => boolean; - isDisplayMoment: () => boolean; - isDisplayed: () => boolean; - isNotDisplayed: () => boolean; - isSkippedMoment: () => boolean; -} -export type UserDataPayload = { - first_name: string; - last_name: string; - email: string; - password?: string; - username?: string; -} & { - [key: string]: any; -}; -export interface GetUserFunctionReturn { - success: boolean; - payload: { - id: number; - first_name: string; - last_name: string; - username: string; - email: string; - phone: string; - social_id: [string]; - image: string; - image_thumbnail: string; - verification_status: [number]; - } | null; -} -export interface ReauthUserFunctionReturn { - success: boolean; - payload: DATASQUIREL_LoggedInUser | null; - msg?: string; - userId?: number; - token?: string; -} -export interface UpdateUserFunctionReturn { - success: boolean; - payload?: Object[] | string; -} -export interface GetReturn { - success: boolean; - payload?: any; - msg?: string; - error?: string; - schema?: DSQL_TableSchemaType; -} -export interface GetSchemaRequestQuery { - database?: string; - table?: string; - field?: string; - user_id?: string | number; -} -export interface GetSchemaAPICredentialsParam { - key: string; -} -export type GetSchemaAPIParam = GetSchemaRequestQuery & GetSchemaAPICredentialsParam; -export interface PostReturn { - success: boolean; - payload?: Object[] | string | PostInsertReturn; - msg?: string; - error?: any; - schema?: DSQL_TableSchemaType; -} -export interface PostDataPayload { - action: "insert" | "update" | "delete"; - table: string; - data?: object; - identifierColumnName?: string; - identifierValue?: string; - duplicateColumnName?: string; - duplicateColumnValue?: string; - update?: boolean; -} -export interface LocalPostReturn { - success: boolean; - payload?: any; - msg?: string; - error?: string; -} -export interface LocalPostQueryObject { - query: string | PostDataPayload; - tableName?: string; - queryValues?: string[]; -} -export interface PostInsertReturn { - fieldCount: number; - affectedRows: number; - insertId: number; - serverStatus: number; - warningCount: number; - message: string; - protocol41: boolean; - changedRows: number; -} -export type UserType = DATASQUIREL_LoggedInUser; -export interface ApiKeyDef { - name: string; - scope: string; - date_created: string; - apiKeyPayload: string; -} -export interface MetricsType { - dbCount: number; - tablesCount: number; - mediaCount: number; - apiKeysCount: number; -} -export interface DashboardContextType { - user?: UserType; - databases?: DSQL_MYSQL_user_databases_Type[]; - setTargetDatabase?: React.Dispatch>; - targetDatabase?: DSQL_MYSQL_user_databases_Type; - metrics?: MetricsType; -} -export interface AddDbContextType { - user?: UserType; - databases?: DSQL_MYSQL_user_databases_Type[]; - dbImage?: string | null | ImageObjectType; - setDbImage?: React.Dispatch>; - query?: any; - duplicateDb?: DSQL_MYSQL_user_databases_Type; -} -export interface EditDbContextType { - user?: UserType; - database?: DSQL_MYSQL_user_databases_Type; - dbImage?: string | null | ImageObjectType; - setDbImage?: React.Dispatch>; -} -export interface RichTextEditorsRefArray { - fieldName: string; - ref: React.MutableRefObject; -} -export interface JSONTextEditorsRefArray { - fieldName: string; - ref: React.MutableRefObject; -} -export interface TableEntriesContextType { - user: UserType; - database: DSQL_MYSQL_user_databases_Type; - table: DSQL_TableSchemaType; - dbSchemaData: DSQL_DatabaseSchemaType[]; - entries: any[]; - targetEntry?: any; - setTargetEntry: React.Dispatch>; - richTextEditors: React.MutableRefObject; - jsonTextEditors: React.MutableRefObject; - query?: any; - confirmedDelegetedUser?: any; - activeEntries: any[] | null; - setActiveEntries: React.Dispatch>; - targetField: React.MutableRefObject; - searchTerm: React.MutableRefObject; - entriesCount: number; -} -export interface AddEntryContextType { - user: UserType; - database: DSQL_MYSQL_user_databases_Type; - table: DSQL_TableSchemaType; - dbSchemaData: DSQL_DatabaseSchemaType[]; - richTextEditors: React.MutableRefObject; - jsonTextEditors: React.MutableRefObject; - query: any; - duplicateEntry?: any; - confirmedDelegetedUser: any; -} -export interface UserDatabasesContextType { - user: UserType; - users: any[]; - targetUser: any; - setTargetUser: React.Dispatch>; - databases: DSQL_MYSQL_user_databases_Type[]; -} -export interface SettingsPageContextType { - user: UserType; - image: any; - setImage: React.Dispatch>; - activeUser: any; -} -export interface MediaFolderPageContextType { - user: UserType; - media: any[]; - targetMedia: any; - setTargetMedia: React.Dispatch>; - folders: any[]; - query: any; - staticHost: string; - folder: string; -} -export interface TablesContextType { - user: UserType; - database: DSQL_MYSQL_user_databases_Type; - tables: MYSQL_user_database_tables_table_def[]; - targetTable: MYSQL_user_database_tables_table_def | null; - setTargetTable: React.Dispatch>; - query: any; - confirmedDelegetedUser: any; -} -export interface EditTableContextType { - user: UserType; - database: DSQL_MYSQL_user_databases_Type; - table: DSQL_TableSchemaType; - tableFields: DSQL_FieldSchemaType[]; - setTableFields: React.Dispatch>; - targetField: DSQL_FieldSchemaType | null; - setTargetField: React.Dispatch>; - pageRefresh: number; - setPageRefresh: React.Dispatch>; - refreshFieldsListRef: React.MutableRefObject> | undefined>; - dbSchemaData: DSQL_DatabaseSchemaType[]; - query: any; - confirmedDelegetedUser: any; -} -export interface SingleDatabaseContextType { - user: UserType; - database: DSQL_MYSQL_user_databases_Type; - tables: MYSQL_user_database_tables_table_def[]; - targetTable: MYSQL_user_database_tables_table_def | null; - setTargetTable: React.Dispatch>; - query: any; - confirmedDelegetedUser: any; -} -export interface ApiKeysContextType { - user: UserType; - apiKeys: any[]; - setApiKeys: React.Dispatch>; - targetApiKey: any | null; - setTargetApiKey: React.Dispatch>; - newApiKey: any | null; - setNewApiKey: React.Dispatch>; -} -export interface LoginFormContextType { - user?: UserType | null; - loading: boolean; - setLoading: React.Dispatch>; - alert: string | boolean; - setAlert: React.Dispatch>; -} -export interface CreateAccountContextType { - user?: UserType | null; - query: CreateAccountQueryType; - invitingUser: any; -} -export interface CreateAccountQueryType { - invite?: number; - database_access?: string; - priviledge?: string; - email?: string; -} -export interface DocsAsidePageObject { - id: number; - title: string; - slug: string; - parent_id?: number; - level?: number; -} -export interface AllUserUsersContextType { - user: UserType; - users: MYSQL_delegated_users_table_def[]; - targetUser: MYSQL_user_users_table_def | null; - setTargetUser: React.Dispatch>; - databases: DSQL_MYSQL_user_databases_Type[]; - pendingInvitations: MYSQL_invitations_table_def[]; - pendingInvitationsReceived: any[]; - adminUsers: any[]; - invitedAccounts: any[]; -} -export interface AddSocialLoginContextType { - user: UserType; - database: DSQL_MYSQL_user_databases_Type; - query: any; - socialLogins: SocialLoginObjectType[]; -} -export interface DelegatedDbContextType { - user: UserType; - users: MYSQL_user_users_table_def[]; - targetUser: MYSQL_user_users_table_def | null; - setTargetUser: React.Dispatch>; - database: DSQL_MYSQL_user_databases_Type; -} -export interface AddUserUserContextType { - user: UserType; - database: DSQL_MYSQL_user_databases_Type; - table: DSQL_TableSchemaType; - query: any; - confirmedDelegetedUser: any; -} -export interface UserUsersContextType { - user: UserType; - users: MYSQL_user_users_table_def[]; - targetUser: MYSQL_user_users_table_def; - setTargetUser: React.Dispatch>; - database: DSQL_MYSQL_user_databases_Type; - table: DSQL_TableSchemaType; - dbSchemaData: DSQL_DatabaseSchemaType[]; - query: any; - confirmedDelegetedUser: any; -} -export interface DatabaseSingleUserContextType { - user: UserType; - database: DSQL_MYSQL_user_databases_Type; - singleUser: MYSQL_user_users_table_def; - table: DSQL_TableSchemaType; - dbSchemaData: DSQL_DatabaseSchemaType[]; - query: any; - confirmedDelegetedUser: any; -} -export interface SingleUserUserContextType { - user: UserType; - singleUser: MYSQL_user_users_table_def; -} -export interface AddUserContextType { - user: UserType; - users: MYSQL_delegated_users_table_def[]; - databases: DSQL_MYSQL_user_databases_Type[]; - query: any; -} -export interface MediaContextType { - user: UserType; - media: MYSQL_user_media_table_def[]; - targetMedia: MYSQL_user_media_table_def | null; - setTargetMedia: React.Dispatch>; - folders: string[]; - staticHost: string; -} -export interface MediaSubFolderContextType { - user: UserType; - media: MYSQL_user_media_table_def[]; - targetMedia: MYSQL_user_media_table_def | null; - setTargetMedia: React.Dispatch>; - folders: string[]; - query: any; - folder: string; - staticHost: string; -} -export interface FieldsContextType { - user: UserType; - database: DSQL_MYSQL_user_databases_Type; - table: DSQL_TableSchemaType; - dbSchemaData: DSQL_DatabaseSchemaType[]; - targetField: DSQL_FieldSchemaType | null; - setTargetField: React.Dispatch>; - refreshFieldsListRef: React.MutableRefObject> | undefined>; - tableFields: DSQL_FieldSchemaType[]; - setTableFields: React.Dispatch>; - updateTableAfterFieldsUpdateFunction: () => void; - query: any; - confirmedDelegetedUser: any; -} -export interface SingleTableContextType { - user: UserType; - database: DSQL_MYSQL_user_databases_Type; - table: DSQL_TableSchemaType; - tableRecord: MYSQL_user_database_tables_table_def; - tableFields: DSQL_FieldSchemaType[]; - setTableFields: React.Dispatch>; - tableIndexes: DSQL_IndexSchemaType[]; - setTableIndexes: React.Dispatch>; - dbSchemaData: DSQL_DatabaseSchemaType[]; - entries: any[]; - targetEntry: any; - setTargetEntry: React.Dispatch>; - richTextEditors: React.MutableRefObject; - jsonTextEditors: React.MutableRefObject; - query: any; - confirmedDelegetedUser: any; - targetField: DSQL_FieldSchemaType | null; - setTargetField: React.Dispatch>; - refreshFieldsListRef: React.MutableRefObject>>; - updateTableAfterFieldsUpdateFunction: () => void; - entriesCount: number; -} -export interface SingleEntryContextType { - user: UserType; - database: DSQL_MYSQL_user_databases_Type; - table: DSQL_TableSchemaType; - dbSchemaData: DSQL_DatabaseSchemaType[]; - entry: any; - targetEntry: any; - setTargetEntry: React.Dispatch>; - richTextEditors: React.MutableRefObject; - jsonTextEditors: React.MutableRefObject; - query: any; - confirmedDelegetedUser: any; - prevEntry: any; - nextEntry: any; -} -export interface UserSchemaContextType { - user: UserType; - dbSchemaData: DSQL_DatabaseSchemaType[]; -} -export interface ConnectContextType { - user: UserType; - query: any; - mariadbUserCred: MariaDBUserCredType; - mariadbUsers: MYSQL_mariadb_users_table_def[]; - targetMariadbUser: MYSQL_mariadb_users_table_def | null; - setTargetMariadbUser: React.Dispatch>; - refresh: number; - setRefresh: React.Dispatch>; -} -export interface MYSQL_mariadb_users_table_def { - id?: number; - user_id?: number; - username?: string; - host?: string; - password?: string; - primary?: number; - grants?: string; - date_created?: string; - date_created_code?: number; - date_created_timestamp?: string; - date_updated?: string; - date_updated_code?: number; - date_updated_timestamp?: string; -} -export interface DbContextType { - user?: UserType; - databases?: DSQL_MYSQL_user_databases_Type[]; - targetDatabase?: DSQL_MYSQL_user_databases_Type; - setTargetDatabase?: React.Dispatch>; -} -export interface MariaDBUserCredType { - mariadb_user?: string; - mariadb_host?: string; - mariadb_pass?: string; -} -export interface AddTableContextType { - user: UserType; - dbSchemaData: DSQL_DatabaseSchemaType[]; - database: DSQL_MYSQL_user_databases_Type; - tables: DSQL_TableSchemaType[]; - tableFields: DSQL_FieldSchemaType[]; - setTableFields: React.Dispatch>; - targetField: DSQL_FieldSchemaType | null; - setTargetField: React.Dispatch>; - pageRefresh: number | null; - setPageRefresh: React.Dispatch>; - refreshFieldsListRef: React.MutableRefObject>>; - query: any; -} -export interface DbSchemaContextType { - user: UserType; - database: DSQL_MYSQL_user_databases_Type; - dbImage: string; - setDbImage: React.Dispatch>; - dbSchemaData: DSQL_DatabaseSchemaType[]; - tables: any[]; -} -export interface DbShellContextType { - user?: UserType; - database?: DSQL_MYSQL_user_databases_Type; - dbImage?: string; - setDbImage?: React.Dispatch>; - dbSchemaData?: DSQL_DatabaseSchemaType[]; - tables?: any[]; -} -export interface DbConnectContextType { - user: UserType; - database: DSQL_MYSQL_user_databases_Type; - targetDbSchema: DSQL_DatabaseSchemaType; - query: any; -} -export interface ImageObjectType { - imageName?: string; - mimeType?: string; - imageSize?: number; - private?: boolean; - imageBase64?: string; - imageBase64Full?: string; -} -export interface FileObjectType { - fileName?: string; - private?: boolean; - fileType?: string; - fileSize?: number; - fileBase64?: string; - fileBase64Full?: string; -} -export interface SocialLoginObjectType { - platform?: string; - paradigm?: string; - clientId?: string; - clientSecret?: string; - callbackUrl?: string; - domain1?: string; - domain2?: string; - domain3?: string; -} -export interface DbConnectType { - url: string; - key: string; - database: DSQL_MYSQL_user_databases_Type; - dbSchema: DSQL_DatabaseSchemaType; - type: "pull" | "push"; - remoteDbs?: DSQL_DatabaseSchemaType[]; - targetDb?: DSQL_DatabaseSchemaType; -} -export interface MYSQL_MediaType { - id?: number; - user_id?: number; - media_name?: string; - folder?: string; - media_url?: string; - media_thumbnail_url?: string; - media_type?: string; - width?: string; - height?: string; - size?: string; - private?: string; -} -export interface UserFileObject { - title?: string; - path?: string; - data?: string; -} -export interface UserFileObject2 { - type?: string; - name?: string; - root?: string; - content?: UserFileObject2[]; -} -export interface MYSQL_user_users_table_def { - id?: number; - user_id?: number; - invited_user_id?: number; - database?: string; - database_access?: string; - first_name?: string; - last_name?: string; - email?: string; - username?: string; - password?: string; - phone?: string; - user_type?: string; - user_priviledge?: string; - image?: string; - image_thumbnail?: string; - city?: string; - state?: string; - country?: string; - zip_code?: string; - address?: string; - social_login?: number; - social_platform?: string; - social_id?: string; - verification_status?: number; - more_user_data?: string; - date_created?: string; - date_created_code?: number; - date_created_timestamp?: string; - date_updated?: string; - date_updated_code?: number; - date_updated_timestamp?: string; - inviteeFirstName?: string; - inviteeLastName?: string; - inviteeEmail?: string; - inviteeImage?: string; -} -export interface MYSQL_user_database_tables_table_def { - id?: number; - user_id?: number; - db_id?: number; - db_slug?: string; - table_name?: string; - table_slug?: string; - table_description?: string; - child_table?: number; - child_table_parent_database?: string; - child_table_parent_table?: string; - date_created?: string; - date_created_code?: number; - date_created_timestamp?: string; - date_updated?: string; - date_updated_code?: number; - date_updated_timestamp?: string; -} -export interface MYSQL_user_media_table_def { - id?: number; - user_id?: number; - media_name?: string; - folder?: string; - media_url?: string; - media_thumbnail_url?: string; - media_path?: string; - media_thumbnail_path?: string; - media_type?: string; - width?: number; - height?: number; - size?: number; - private?: number; - date_created?: string; - date_created_code?: number; - date_created_timestamp?: string; - date_updated?: string; - date_updated_code?: number; - date_updated_timestamp?: string; -} -export interface MYSQL_delegated_users_table_def { - id?: number; - user_id?: number; - delegated_user_id?: number; - permissions?: string; - permission_level_code?: number; - date_created?: string; - date_created_code?: number; - date_created_timestamp?: string; - date_updated?: string; - date_updated_code?: number; - date_updated_timestamp?: string; -} -export interface MYSQL_invitations_table_def { - id?: number; - inviting_user_id?: number; - invited_user_email?: string; - invitation_status?: string; - database_access?: string; - priviledge?: string; - db_tables_data?: string; - date_created?: string; - date_created_code?: number; - date_created_timestamp?: string; - date_updated?: string; - date_updated_code?: number; - date_updated_timestamp?: string; -} -export interface MYSQL_docs_pages_table_def { - id?: number; - title?: string; - slug?: string; - description?: string; - content?: string; - text_content?: string; - level?: number; - page_order?: number; - parent_id?: number; - date_created?: string; - date_created_code?: number; - date_created_timestamp?: string; - date_updated?: string; - date_updated_code?: number; - date_updated_timestamp?: string; -} -export interface MYSQL_delegated_user_tables_table_def { - id?: number; - delegated_user_id?: number; - root_user_id?: number; - database?: string; - table?: string; - priviledge?: string; - date_created?: string; - date_created_code?: number; - date_created_timestamp?: string; - date_updated?: string; - date_updated_code?: number; - date_updated_timestamp?: string; -} -export type ApiKeyObject = { - user_id?: string | number; - full_access?: boolean; - sign?: string; - date_code?: number; - target_database?: string; - target_table?: string; - error?: string; -}; -export type AddApiKeyRequestBody = { - api_key_name: string; - api_key_slug: string; - api_key_scope?: "fullAccess" | "readOnly"; - target_database?: string; - target_table?: string; -}; -export type CheckApiCredentialsFn = (param: CheckApiCredentialsFnParam) => ApiKeyObject | null | undefined; -export type CheckApiCredentialsFnParam = { - key?: string; - database?: string; - table?: string; - user_id?: string | number; - media?: boolean; -}; -export type FetchApiFn = (url: string, options?: FetchApiOptions, csrf?: boolean) => Promise; -export type FetchApiOptions = RequestInit & { - method: "POST" | "GET" | "DELETE" | "PUT" | "PATCH" | "post" | "get" | "delete" | "put" | "patch"; - body?: object | string; - headers?: FetchHeader; - query?: { - [key: string]: any; - }; -}; -export type AuthCsrfHeaderName = "x-csrf-auth"; -type FetchHeader = HeadersInit & { - [key in AuthCsrfHeaderName]?: string | null; -} & { - [key: string]: any; -}; -export type FetchApiReturn = { - success: boolean; - payload: any; - msg?: string; - [key: string]: any; -}; -export declare const ServerQueryOperators: readonly ["AND", "OR"]; -export declare const ServerQueryEqualities: readonly ["EQUAL", "LIKE", "NOT EQUAL"]; -export type ServerQueryParam = { - selectFields?: string[]; - query?: ServerQueryQueryObject; - limit?: number; - offset?: number; - order?: { - field: string; - strategy: "ASC" | "DESC"; - }; - searchOperator?: (typeof ServerQueryOperators)[number]; - searchEquality?: (typeof ServerQueryEqualities)[number]; - addUserId?: { - fieldName: string; - }; - join?: ServerQueryParamsJoin[]; - [key: string]: any; -}; -export type ServerQueryObject = { - value?: string | string[]; - operator?: (typeof ServerQueryOperators)[number]; - equality?: (typeof ServerQueryEqualities)[number]; - tableName?: string; - __query?: { - [key in keyof T]: Omit, "__query">; - }; -}; -export type ServerQueryQueryObject = { - [key in keyof T]: ServerQueryObject; -}; -export type FetchDataParams = { - path: string; - method?: "GET" | "POST" | "PATCH" | "PUT" | "DELETE"; - body?: object | string; - query?: AuthFetchQuery; - tableName?: string; -}; -export type AuthFetchQuery = ServerQueryParam & { - [key: string]: any; -}; -export type ServerQueryParamsJoin = { - joinType: "INNER JOIN" | "JOIN" | "LEFT JOIN" | "RIGHT JOIN"; - alias?: string; - tableName: Table; - match?: ServerQueryParamsJoinMatchObject | ServerQueryParamsJoinMatchObject[]; - selectFields?: (keyof Field | { - field: keyof Field; - alias?: string; - count?: boolean; - })[]; - operator?: (typeof ServerQueryOperators)[number]; -}; -export type ServerQueryParamsJoinMatchObject = { - /** Field name from the **Root Table** */ - source: string | ServerQueryParamsJoinMatchSourceTargetObject; - /** Field name from the **Join Table** */ - target?: keyof Field | ServerQueryParamsJoinMatchSourceTargetObject; - /** A literal value: No source and target Needed! */ - targetLiteral?: string; -}; -export type ServerQueryParamsJoinMatchSourceTargetObject = { - tableName: string; - fieldName: string; -}; -export type SqlGeneratorFn = (Param0: { - genObject?: ServerQueryParam; - tableName: string; -}) => { - string: string; - values: string[]; -} | undefined; -export type ApiConnectBody = { - url: string; - key: string; - database: DSQL_MYSQL_user_databases_Type; - dbSchema: DSQL_DatabaseSchemaType; - type: "pull" | "push"; - user_id?: string | number; -}; -export type SuUserType = { - email: string; - password: string; - authKey: string; - logged_in_status: boolean; - date: number; -}; -export type MariadbRemoteServerObject = { - host: string; - port: number; - primary?: boolean; - loadBalanced?: boolean; - users?: MariadbRemoteServerUserObject[]; -}; -export type MariadbRemoteServerUserObject = { - name: string; - password: string; - host: string; -}; -export type APILoginFunctionParams = { - encryptionKey: string; - email: string; - username?: string; - password?: string; - database: string; - additionalFields?: string[]; - email_login?: boolean; - email_login_code?: string; - email_login_field?: string; - token?: boolean; - skipPassword?: boolean; - social?: boolean; - useLocal?: boolean; -}; -export type APILoginFunctionReturn = { - success: boolean; - msg?: string; - payload?: DATASQUIREL_LoggedInUser | null; - userId?: number | string; - key?: string; - token?: string; - csrf?: string; - cookieNames?: any; -}; -export type APILoginFunction = (params: APILoginFunctionParams) => Promise; -export type APICreateUserFunctionParams = { - encryptionKey?: string; - payload: any; - database: string; - userId?: string | number; - useLocal?: boolean; -}; -export type APICreateUserFunction = (params: APICreateUserFunctionParams) => Promise; -/** - * API Get User Function - */ -export type APIGetUserFunctionParams = { - fields: string[]; - dbFullName: string; - userId: string | number; - useLocal?: boolean; -}; -export type APIGetUserFunction = (params: APIGetUserFunctionParams) => Promise; -/** - * API Google Login Function - */ -export type APIGoogleLoginFunctionParams = { - token: string; - database: string; - additionalFields?: string[]; - additionalData?: { - [key: string]: string | number; - }; -}; -export type APIGoogleLoginFunction = (params: APIGoogleLoginFunctionParams) => Promise; -/** - * Handle Social DB Function - */ -export type HandleSocialDbFunctionParams = { - database?: string; - social_id: string | number; - email: string; - social_platform: string; - payload: any; - invitation?: any; - supEmail?: string; - additionalFields?: string[]; - useLocal?: boolean; -}; -export type HandleSocialDbFunctionReturn = { - success: boolean; - user?: DATASQUIREL_LoggedInUser | null; - msg?: string; - social_id?: string | number; - social_platform?: string; - payload?: any; - alert?: boolean; - newUser?: any; - error?: any; -} | null; -/** - * Handle Social User Auth on Datasquirel Database - * ============================================================================== - * - * @description This function handles all social login logic after the social user - * has been authenticated and userpayload is present. The payload MUST contain the - * specified fields because this funciton will create a new user if the authenticated - * user does not exist. - * - * @param {HandleSocialDbFunctionParams} params - function parameters inside an object - * - * @returns {Promise} - Response object - */ -export type HandleSocialDbFunction = (params: HandleSocialDbFunctionParams) => Promise; -export type ApiReauthUserReturn = { - success: boolean; - payload?: { - [key: string]: any; - } | null; - msg?: string; - userId?: string | number; -}; -export type GoogleAccessTokenObject = { - access_token: string; - token_type: "Bearer"; - expires_in: number; - scope: string; - authuser: string; - prompt: string; -}; -export type GoogleOauth2User = { - sub: string; - name: string; - given_name: string; - family_name: string; - picture: string; - email: string; - email_verified: boolean; -}; -export interface AceEditorOptions { - animatedScroll?: boolean; - autoScrollEditorIntoView?: boolean; - behavioursEnabled?: boolean; - copyWithEmptySelection?: boolean; - cursorStyle?: "ace" | "slim" | "smooth" | "wide"; - customScrollbar?: boolean; - displayIndentGuides?: boolean; - dragDelay?: number; - dragEnabled?: boolean; - enableAutoIndent?: boolean; - enableBasicAutocompletion?: boolean | any[]; - enableKeyboardAccessibility?: boolean; - enableLiveAutocompletion?: boolean | any[]; - enableMobileMenu?: boolean; - enableMultiselect?: boolean; - enableSnippets?: boolean; - fadeFoldWidgets?: boolean; - firstLineNumber?: number; - fixedWidthGutter?: boolean; - focusTimeout?: number; - foldStyle?: "markbegin" | "markbeginend" | "manual"; - fontFamily?: string; - fontSize?: number; - hScrollBarAlwaysVisible?: boolean; - hasCssTransforms?: boolean; - highlightActiveLine?: boolean; - highlightGutterLine?: boolean; - highlightIndentGuides?: boolean; - highlightSelectedWord?: boolean; - indentedSoftWrap?: boolean; - keyboardHandler?: string; - liveAutocompletionDelay?: number; - liveAutocompletionThreshold?: number; - maxLines?: number; - maxPixelHeight?: number; - mergeUndoDeltas?: boolean | "always"; - minLines?: number; - mode?: string; - navigateWithinSoftTabs?: boolean; - newLineMode?: AceAjax.NewLineMode; - overwrite?: boolean; - placeholder?: string; - printMargin?: number | boolean; - printMarginColumn?: number; - readOnly?: boolean; - relativeLineNumbers?: boolean; - scrollPastEnd?: number; - scrollSpeed?: number; - selectionStyle?: string; - session?: any; - showFoldWidgets?: boolean; - showFoldedAnnotations?: boolean; - showGutter?: boolean; - showInvisibles?: boolean; - showLineNumbers?: boolean; - showPrintMargin?: boolean; - tabSize?: number; - textInputAriaLabel?: string; - theme?: string; - tooltipFollowsMouse?: boolean; - useSoftTabs?: boolean; - useSvgGutterIcons?: boolean; - useWorker?: boolean; - vScrollBarAlwaysVisible?: boolean; - value?: string; - wrap?: number | boolean | "off" | "free" | "printmargin"; - wrapBehavioursEnabled?: boolean; - wrapMethod?: "code" | "text" | "auto"; -} -export type SendOneTimeCodeEmailResponse = { - success: boolean; - code?: string; - createdAt?: number; - email?: string; - msg?: string; -}; -export type CookieObject = { - name: string; - value: string; - domain?: string; - path?: string; - expires?: Date; - maxAge?: number; - secure?: boolean; - httpOnly?: boolean; - sameSite?: "Strict" | "Lax" | "None"; - priority?: "Low" | "Medium" | "High"; -}; -export type HttpRequestParams = RequestOptions & { - scheme?: "http" | "https"; - body?: ReqObj; - query?: ReqObj; - urlEncodedFormBody?: boolean; -}; -export type HttpRequestFunction = (param: HttpRequestParams) => Promise>; -export type HttpFunctionResponse = { - status: number; - data?: ResObj; - error?: string; - str?: string; - requestedPath?: string; -}; -export {}; diff --git a/package-shared/types/index.js b/package-shared/types/index.js deleted file mode 100644 index 5eb7a33..0000000 --- a/package-shared/types/index.js +++ /dev/null @@ -1,1166 +0,0 @@ -// @ts-check - -/** - * @typedef {string} DSQL_DatabaseFullName - Database full name(slug) including datasquirel data => "datasquirel_user_7_new_database" - */ - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -/** - * @typedef {object} DSQL_DatabaseSchemaType - * @property {string} dbName - Database Full name with spaces => "New Database" - * @property {string} dbSlug - Database Slug => "new_database" - * @property {string} dbFullName - Database full name(slug) including datasquirel data => "datasquirel_user_7_new_database" - * @property {string} [dbDescription] - Database brief description - * @property {string} [dbImage] - Database image - Defaults to "/images/default.png" - * @property {DSQL_TableSchemaType[]} tables - List of database tables - * @property {DSQL_ChildrenDatabaseObject[]} [childrenDatabases] - List of children databases for current database which is parent - * @property {boolean} [childDatabase] - If current database is a child of a different parent database - * @property {string} [childDatabaseDbFullName] - Parent database full name => "datasquirel_user_7_new_database" - * @property {boolean} [updateData] - Should the child database data update when the parent database data is updated? - */ - -/** - * @typedef {object} DSQL_ChildrenDatabaseObject - * @property {string} dbFullName - Database Full name => "datasquirel_user_4_db_name" - */ - -//////////////////////////////////////// - -/** - * @typedef {object} DSQL_TableSchemaType - * @property {string} tableName - Table slug (blog_posts) - * @property {string} tableFullName - Table full name with spaces => "Blog Posts" - * @property {string} [tableDescription] - Brief description of table - * @property {DSQL_FieldSchemaType[]} fields - List of table Fields - * @property {DSQL_IndexSchemaType[]} [indexes] - List of table indexes, if available - * @property {DSQL_ChildrenTablesType[]} [childrenTables] - List of children tables - * @property {boolean} [childTable] -If current table is a child clone - * @property {boolean} [updateData] -If the current table data updates with the parent table - * @property {string} [childTableName] - Table slug of parent table => "blog_posts" - * @property {string} [childTableDbFullName] - Database full name(slug) including datasquirel data => "datasquirel_user_7_new_database" - * @property {string} [tableNameOld] - Old table name, incase of renaming table - */ - -/** - * @typedef {object} DSQL_ChildrenTablesType - * @property {string} dbNameFull - Database full name(slug) including datasquirel data => "datasquirel_user_7_new_database" - * @property {string} tableName - Table slug => "blog_posts" - * @property {string} [tableNameFull] - */ - -//////////////////////////////////////// - -/** - * @typedef {object} DSQL_FieldSchemaType - * @property {string} [fieldName] - Field Name(slug) => "long_description" - * @property {string} [originName] - Field origin name(optional) - * @property {boolean} [updatedField] - Has this field been renamed? - * @property {string} [dataType] - Field Data type => "BIGIN" | "LONGTEXT" | "VARCHAR(***)" | ... - * @property {boolean} [nullValue] - Is this a null value or not? - * @property {boolean} [notNullValue] - Is this NOT a null value? - * @property {boolean} [primaryKey] - Is this the primary key for table? - * @property {boolean} [encrypted] - Is this field value encrypted? - * @property {boolean} [autoIncrement] - Does this table primary key increment automatically? - * @property {string|number} [defaultValue] - Value of field by default - * @property {string} [defaultValueLiteral] - SQL key word which generates value automatically => "CURRENT_TIMESTAMP" - * @property {DSQL_ForeignKeyType} [foreignKey] - Field foreign key reference object - * @property {boolean} [richText] - Rich text field - * @property {boolean} [json] - * @property {boolean} [yaml] - * @property {boolean} [html] - * @property {boolean} [css] - * @property {boolean} [javascript] - * @property {boolean} [shell] - * @property {boolean} [newTempField] - * @property {boolean} [defaultField] - * @property {boolean} [plainText] - * @property {boolean} [unique] - * @property {string} [pattern] - * @property {string} [patternFlags] - * @property {string} [onUpdate] - * @property {string} [onUpdateLiteral] - * @property {string} [onDelete] - * @property {string} [onDeleteLiteral] - * @property {string[]} [cssFiles] - */ - -/** - * @typedef {object} DSQL_ForeignKeyType - * @property {string} [foreignKeyName] - Unique Name of foreign key - * @property {string} [destinationTableName] - Reference table name(slug) => "blog_posts" - * @property {string} [destinationTableColumnName] - Reference column name(slug) => "id" - * @property {string} [destinationTableColumnType] - Reference table field type => "BIGINT" | "VARCHAR(***)" | ... - * @property {boolean} [cascadeDelete] - Does the reference table entry delete when this key is deleted? - * @property {boolean} [cascadeUpdate] - Does the reference table entry update when this key is updated? - */ - -//////////////////////////////////////// - -/** - * @typedef {object} DSQL_IndexSchemaType - * @property {string} [indexName] - Unique Name of index => "blog_text_index" - * @property {string} [indexType] - "regular" or "fullText" - * @property {DSQL_IndexTableFieldType[]} [indexTableFields] - List of Index table fields - * @property {string} [alias] - List of Index table fields - * @property {boolean} [newTempIndex] - */ - -/** - * @typedef {object} DSQL_IndexTableFieldType - * @property {string} value - Table Field Name - * @property {string} dataType - Table Field data type "VARCHAR(***)" | "BIGINT" | ... - */ - -/** - * @typedef {object} DSQL_MYSQL_SHOW_INDEXES_Type - * @property {string} Key_name - MYSQL Index Name - * @property {string} Table - Table Name(slug) - * @property {string} Column_name - * @property {string} Collation - * @property {string} Index_type - "FULL_TEXT" | ... - * @property {string} Cardinality - * @property {string} Index_comment - * @property {string} Comment - */ - -//////////////////////////////////////// - -/** - * @typedef {object} DSQL_MYSQL_SHOW_COLUMNS_Type - * @property {string} Field - Field Name as represented in MSQL database - * @property {string} Type - varchar(***) | tinyint | bigint | ... - * @property {string} Null - * @property {string} Key - * @property {string} Default - * @property {string} Extra - */ - -//////////////////////////////////////// - -/** - * @typedef {object} DSQL_MYSQL_FOREIGN_KEYS_Type - * @property {string} CONSTRAINT_NAME - Constraint Name => "PRIMARY" | "MUL" | null | ... - * @property {string} CONSTRAINT_SCHEMA - Database name - * @property {string} TABLE_NAME - Table name - */ - -//////////////////////////////////////// - -/** - * @typedef {object} DSQL_MYSQL_user_databases_Type - * @property {number} id - * @property {number} user_id - User Id - * @property {string} db_full_name - Database full name => eg. (dataasquirel_user_2_new_database) - * @property {string} db_name - Database name with spaces => eg. (New Database) - * @property {string} db_slug - Database slug => eg. (new_database) - * @property {string} db_image - Database image path - * @property {string} db_description - Database description - * @property {number} active_clone - is Database active clone => 0 or 1 - * @property {string} active_clone_parent_db - Database parent db full name => eg. "datasquirel_user_7_wexculture" - * @property {number} [remote_connected] - * @property {string} [remote_db_full_name] - * @property {string} [remote_connection_host] - * @property {string} [user_priviledge] - * @property {string} [date_created] - * @property {string} [image_thumbnail] - * @property {string} [first_name] - * @property {string} [last_name] - * @property {string} [email] - */ - -/** - * @typedef {object} PackageUserLoginRequestBody - * @property {string} encryptionKey - * @property {any} payload - * @property {string} database - * @property {string[]} [additionalFields] - * @property {boolean} [email_login] - * @property {string} [email_login_code] - * @property {string} [email_login_field] - * @property {boolean} [token] - * @property {boolean} [social] - * @property {DSQL_DatabaseSchemaType} [dbSchema] - */ - -/** - * @typedef {object} PackageUserLoginLocalBody - * @property {any} payload - * @property {string[]} [additionalFields] - * @property {boolean} [email_login] - * @property {string} [email_login_code] - * @property {string} [email_login_field] - * @property {boolean} [token] - * @property {boolean} [social] - * @property {DSQL_DatabaseSchemaType} [dbSchema] - */ - -const http = require("http"); - -/** - * @typedef {http.IncomingMessage} Request - */ - -/** - * @typedef {http.ServerResponse} Response - */ - -/** - * @typedef {{ - * imageBase64: string, - * imageBase64Full: string, - * imageName: string, - * imageSize: number, - * }} ImageInputFileToBase64FunctionReturn - */ - -/** - * @typedef {object} GetReqQueryObject - * @property {string} db - * @property {string} query - * @property {string} [queryValues] - * @property {string} [tableName] - */ - -/** - * @typedef {(param0: SerializeQueryParams) => string} SerializeQueryFnType - */ - -/** - * @typedef {object} SerializeQueryParams - * @property {any} query - */ - -// @ts-check - -/** - * @typedef {object} DATASQUIREL_LoggedInUser - * @property {number} [id] - * @property {string} first_name - * @property {string} last_name - * @property {string} email - * @property {string} [phone] - * @property {string} [user_type] - * @property {string} [username] - * @property {string} password - * @property {string} [image] - * @property {string} [image_thumbnail] - * @property {string} [address] - * @property {string} [city] - * @property {string} [state] - * @property {string} [country] - * @property {string} [zip_code] - * @property {number} [social_login] - * @property {string} [social_platform] - * @property {string} [social_id] - * @property {string} [more_user_data] - * @property {number} [verification_status] - * @property {number} [loan_officer_id] - * @property {number} [is_admin] - * @property {number} [admin_level] - * @property {string} [admin_permissions] - * @property {string} uuid - * @property {string} [temp_login_code] - * @property {string} [date_created] - * @property {number} [date_created_code] - * @property {string} [date_created_timestamp] - * @property {string} [date_updated] - * @property {number} [date_updated_code] - * @property {string} [date_updated_timestamp] - * @property {string} [csrf_k] - CSRF key - * @property {boolean} [logged_in_status] - * @property {number} [date] - * @property {any} [more_data] - */ - -/** - * @typedef {object} AuthenticatedUser - * @property {boolean} success - Did the function run successfully? - * @property {DATASQUIREL_LoggedInUser | null} payload - Payload of the response - * @property {string} [msg] - An optional message - * @property {number} [userId] - An optional message - */ - -/** - * @typedef {object} SuccessUserObject - * @property {number} id - * @property {string} first_name - * @property {string} last_name - * @property {string} email - */ - -/** - * @typedef {object} AddUserFunctionReturn - * @property {boolean} success - Did the function run successfully? - * @property {SuccessUserObject | null} [payload] - Payload - * @property {string} [msg] - * @property {any} [sqlResult] - */ - -/** - * @typedef {object} GoogleIdentityPromptNotification - * @property {function(): string} getMomentType - Notification moment type - * @property {function(): string} getDismissedReason - Notification get Dismissed Reason - * @property {function(): string} getNotDisplayedReason - Notification get Not Displayed Reason - * @property {function(): string} getSkippedReason - Notification get Skipped Reason - * @property {function(): boolean} isDismissedMoment - Notification is Dismissed Moment - * @property {function(): boolean} isDisplayMoment - Notification is Display Moment - * @property {function(): boolean} isDisplayed - Notification is Displayed - * @property {function(): boolean} isNotDisplayed - Notification is Not Displayed - * @property {function(): boolean} isSkippedMoment - Notification is Skipped Moment - */ - -/** - * @typedef {UserDataPayloadBase & UserDataPayloadSupplement} UserDataPayload - */ - -/** - * @typedef {object} UserDataPayloadBase - * @property {string} first_name - First Name *Required - * @property {string} last_name - Last Name *Required - * @property {string} email - Email *Required - * @property {string} password - Password *Required - * @property {string} username - Username (Optional) - */ - -/** - * @typedef {Object.} UserDataPayloadSupplement - */ - -/** - * @typedef {object} GetUserFunctionReturn - * @property {boolean} success - Did the function run successfully? - * @property {{ - * id: number, - * first_name: string, - * last_name: string, - * username: string, - * email: string, - * phone: string, - * social_id: [string], - * image: string, - * image_thumbnail: string, - * verification_status: [number], - * }} payload - Payload - */ - -/** - * @typedef {object} ReauthUserFunctionReturn - * @property {boolean} success - Did the function run successfully? - * @property {DATASQUIREL_LoggedInUser | null} payload - Payload - * @property {string} [msg] - Response Message - * @property {number} [userId] - user ID - * @property {string} [token] - new Token - */ - -/** - * @typedef {object} UpdateUserFunctionReturn - * @property {boolean} success - Did the function run successfully? - * @property {(Object[]|string)} [payload=[]] - Payload - */ - -/** - * @typedef {Object} GetReturn - * @property {boolean} success - Did the function run successfully? - * @property {*} [payload] - GET request results - * @property {string} [msg] - Message - * @property {string} [error] - Error Message - * @property {DSQL_TableSchemaType} [schema] - Error Message - */ - -/** - * @typedef {object} GetSchemaRequestQuery - * @property {string} [database] - Db Name. eg `test_database` - * @property {string} [table] - Table Name (slug) e.g `test_table` - * @property {string} [field] - */ - -/** - * @typedef {object} GetSchemaAPICredentialsParam - * @property {string} key - API FULL ACCESS Key - */ - -/** - * @typedef {GetSchemaRequestQuery & GetSchemaAPICredentialsParam} GetSchemaAPIParam - */ - -/** - * @typedef {Object} PostReturn - * @property {boolean} success - Did the function run successfully? - * @property {PostInsertReturn | Object[] | string} [payload] - The Y Coordinate - */ - -/** - * @typedef {object} PostDataPayload - * @property {"insert" | "update" | "delete"} action - The target action to take - * @property {string} table - Table name(slug) eg "blog_posts" - * @property {object} [data] - Table insert payload object => This must have keys that match - * table fields - * @property {string} [identifierColumnName] - Table identifier field name => eg. "id" OR "email" - * @property {string} [identifierValue] - Corresponding value of the selected field name => This - * checks identifies a the target row for "update" or "delete". Not needed for "insert" - * @property {string} [duplicateColumnName] - Duplicate column name to check for - * @property {string} [duplicateColumnValue] - Duplicate column value to match. If no "update" param - * provided, function will return null - * @property {boolean} [update] - Should the "insert" action update the existing entry if indeed - * the entry with "duplicateColumnValue" exists? - */ - -/** - * @typedef {Object} LocalPostReturn - * @property {boolean} success - Did the function run successfully? - * @property {*} [payload] - GET request results - * @property {string} [msg] - Message - * @property {string} [error] - Error Message - */ - -/** - * @typedef {Object} LocalPostQueryObject - * @property {PostDataPayload | string} query - Table Name - * @property {string} [tableName] - Table Name - * @property {string[]} [queryValues] - GET request results - */ - -/** - * @typedef {object} PostInsertReturn - * @property {number} fieldCount - * @property {number} affectedRows - * @property {number} insertId - * @property {number} serverStatus - * @property {number} warningCount - * @property {string} message - * @property {boolean} protocol41 - * @property {number} changedRows - */ - -// @ts-check - -const { Editor } = require("tinymce"); - -/** - * @typedef {object} UserType - * @property {number} id - user id (number) - * @property {string} [stripe_id] - Stripe ID for payments - * @property {string} first_name - User First Name - * @property {string} last_name - User Last Name - * @property {string} email - User Email Address - * @property {string} [bio] - User Description HTML - * @property {string} [username] - User Username - * @property {string} image - User Full Image - * @property {string} image_thumbnail - User Image Thumbnail - * @property {string} [social_id] - User Social id if available - * @property {number} [verification_status] - 0 or 1 or 2 - * @property {string} [social_platform] - Google or Facebook or Github - * @property {number} [social_login] - 0 or 1 => is this user a social user(1) or not(0) - * @property {number} [date] - Creation Date - * @property {number | string} [phone] - * @property {string} csrf_k - CSRF key - * @property {boolean} logged_in_status - Is user logged in or not - */ - -/** - * @typedef {object} ApiKeyDef - * @property {string} name - * @property {string} scope - * @property {string} date_created - * @property {string} apiKeyPayload - */ - -/** - * @typedef {object} MetricsType - * @property {number} dbCount - * @property {number} tablesCount - * @property {number} mediaCount - * @property {number} apiKeysCount - */ - -/** - * @typedef {object} DashboardContextType - * @property {UserType} [user] - * @property {DSQL_MYSQL_user_databases_Type[]} [databases] - * @property {React.Dispatch>} [setTargetDatabase] - * @property {DSQL_MYSQL_user_databases_Type} [targetDatabase] - * @property {MetricsType} [metrics] - */ - -/** - * @typedef {object} AddDbContextType - * @property {UserType} [user] - * @property {DSQL_MYSQL_user_databases_Type[]} [databases] - * @property {string | null | ImageObjectType} [dbImage] - * @property {React.Dispatch>} [setDbImage] - * @property {*} [query] - * @property {DSQL_MYSQL_user_databases_Type} [duplicateDb] - */ - -/** - * @typedef {object} EditDbContextType - * @property {UserType} [user] - * @property {DSQL_MYSQL_user_databases_Type} [database] - * @property {string | null | ImageObjectType} [dbImage] - * @property {React.Dispatch>} [setDbImage] - */ - -/** - * @typedef {object} RichTextEditorsRefArray - * @property {string} fieldName - * @property {React.MutableRefObject} ref - */ - -/** - * @typedef {object} JSONTextEditorsRefArray - * @property {string} fieldName - * @property {React.MutableRefObject} ref - */ - -/** - * @typedef {object} TableEntriesContextType - * @property {UserType} user - * @property {DSQL_MYSQL_user_databases_Type} database - * @property {DSQL_TableSchemaType} table - * @property {DSQL_DatabaseSchemaType[]} dbSchemaData - * @property {any[]} entries - * @property {any} [targetEntry] - * @property {React.Dispatch>} setTargetEntry - * @property {React.MutableRefObject} richTextEditors - * @property {React.MutableRefObject} jsonTextEditors - * @property {any} [query] - * @property {any} [confirmedDelegetedUser] - * @property {any[] | null} activeEntries - * @property {React.Dispatch>} setActiveEntries - * @property {React.MutableRefObject} targetField - * @property {React.MutableRefObject} searchTerm - * @property {number} entriesCount - */ - -/** - * @typedef {object} AddEntryContextType - * @property {UserType} user - * @property {DSQL_MYSQL_user_databases_Type} database - * @property {DSQL_TableSchemaType} table - * @property {DSQL_DatabaseSchemaType[]} dbSchemaData - * @property {React.MutableRefObject} richTextEditors - * @property {React.MutableRefObject} jsonTextEditors - * @property {any} query - * @property {any} [duplicateEntry] - * @property {any} confirmedDelegetedUser - */ - -/** - * @typedef {object} UserDatabasesContextType - * @property {UserType} user - * @property {any[]} users - * @property {any} targetUser - * @property {React.Dispatch>} setTargetUser - * @property {DSQL_MYSQL_user_databases_Type[]} databases - */ - -/** - * @typedef {object} SettingsPageContextType - * @property {UserType} user - * @property {any} image - * @property {React.Dispatch>} setImage - * @property {any} activeUser - */ - -/** - * @typedef {object} MediaFolderPageContextType - * @property {UserType} user - * @property {any[]} media - * @property {any} targetMedia - * @property {React.Dispatch>} setTargetMedia - * @property {any[]} folders - * @property {any} query - * @property {string} staticHost - * @property {string} folder - */ - -/** - * @typedef {object} TablesContextType - * @property {UserType} user - * @property {DSQL_MYSQL_user_databases_Type} database - * @property {MYSQL_user_database_tables_table_def[]} tables - * @property {MYSQL_user_database_tables_table_def | null} targetTable - * @property {React.Dispatch>} setTargetTable - * @property {any} query - * @property {any} confirmedDelegetedUser - */ - -/** - * @typedef {object} EditTableContextType - * @property {UserType} user - * @property {DSQL_MYSQL_user_databases_Type} database - * @property {DSQL_TableSchemaType} table - * @property {DSQL_FieldSchemaType[]} tableFields - * @property {React.Dispatch>} setTableFields - * @property {DSQL_FieldSchemaType | null} targetField - * @property {React.Dispatch>} setTargetField - * @property {number} pageRefresh - * @property {React.Dispatch>} setPageRefresh - * @property {React.MutableRefObject> | undefined>} refreshFieldsListRef - * @property {DSQL_DatabaseSchemaType[]} dbSchemaData - * @property {any} query - * @property {any} confirmedDelegetedUser - */ - -/** - * @typedef {object} SingleDatabaseContextType - * @property {UserType} user - * @property {DSQL_MYSQL_user_databases_Type} database - * @property {MYSQL_user_database_tables_table_def[]} tables - * @property {MYSQL_user_database_tables_table_def | null} targetTable - * @property {React.Dispatch>} setTargetTable - * @property {any} query - * @property {any} confirmedDelegetedUser - */ - -/** - * @typedef {object} ApiKeysContextType - * @property {UserType} user - * @property {any[]} apiKeys - * @property {React.Dispatch>} setApiKeys - * @property {any | null} targetApiKey - * @property {React.Dispatch>} setTargetApiKey - * @property {any | null} newApiKey - * @property {React.Dispatch>} setNewApiKey - */ - -/** - * @typedef {object} LoginFormContextType - * @property {UserType | null} [user] - * @property {boolean} loading - * @property {React.Dispatch>} setLoading - * @property {string | boolean} alert - * @property {React.Dispatch>} setAlert - */ - -/** - * @typedef {object} CreateAccountContextType - * @property {UserType | null} [user] - * @property {CreateAccountQueryType} query - * @property {any} invitingUser - */ - -/** - * @typedef {object} CreateAccountQueryType - * @property {number} [invite] - * @property {string} [database_access] - * @property {string} [priviledge] - * @property {string} [email] - */ - -/** - * @typedef {object} DocsAsidePageObject - * @property {number} id - * @property {string} title - * @property {string} slug - * @property {number} [parent_id] - * @property {number} [level] - */ - -/** - * @typedef {object} AllUserUsersContextType - * @property {UserType} user - * @property {MYSQL_delegated_users_table_def[]} users - * @property {MYSQL_user_users_table_def | null} targetUser - * @property {React.Dispatch>} setTargetUser - * @property {DSQL_MYSQL_user_databases_Type[]} databases - * @property {MYSQL_invitations_table_def[]} pendingInvitations - * @property {any[]} pendingInvitationsReceived - * @property {any[]} adminUsers - * @property {any[]} invitedAccounts - */ - -/** - * @typedef {object} AddSocialLoginContextType - * @property {UserType} user - * @property {DSQL_MYSQL_user_databases_Type} database - * @property {any} query - * @property {SocialLoginObjectType[]} socialLogins - */ - -/** - * @typedef {object} DelegatedDbContextType - * @property {UserType} user - * @property {MYSQL_user_users_table_def[]} users - * @property {MYSQL_user_users_table_def | null} targetUser - * @property {React.Dispatch>} setTargetUser - * @property {DSQL_MYSQL_user_databases_Type} database - */ - -/** - * @typedef {object} AddUserUserContextType - * @property {UserType} user - * @property {DSQL_MYSQL_user_databases_Type} database - * @property {DSQL_TableSchemaType} table - * @property {any} query - * @property {any} confirmedDelegetedUser - */ - -/** - * @typedef {object} UserUsersContextType - * @property {UserType} user - * @property {MYSQL_user_users_table_def[]} users - * @property {MYSQL_user_users_table_def} targetUser - * @property {React.Dispatch>} setTargetUser - * @property {DSQL_MYSQL_user_databases_Type} database - * @property {DSQL_TableSchemaType} table - * @property {DSQL_DatabaseSchemaType[]} dbSchemaData - * @property {any} query - * @property {any} confirmedDelegetedUser - */ - -/** - * @typedef {object} DatabaseSingleUserContextType - * @property {UserType} user - * @property {DSQL_MYSQL_user_databases_Type} database - * @property {MYSQL_user_users_table_def} singleUser - * @property {DSQL_TableSchemaType} table - * @property {DSQL_DatabaseSchemaType[]} dbSchemaData - * @property {any} query - * @property {any} confirmedDelegetedUser - */ - -/** - * @typedef {object} SingleUserUserContextType - * @property {UserType} user - * @property {MYSQL_user_users_table_def} singleUser - */ - -/** - * @typedef {object} AddUserContextType - * @property {UserType} user - * @property {MYSQL_delegated_users_table_def[]} users - * @property {DSQL_MYSQL_user_databases_Type[]} databases - * @property {any} query - */ - -/** - * @typedef {object} MediaContextType - * @property {UserType} user - * @property {MYSQL_user_media_table_def[]} media - * @property {MYSQL_user_media_table_def | null} targetMedia - * @property {React.Dispatch>} setTargetMedia - * @property {string[]} folders - * @property {string} staticHost - */ - -/** - * @typedef {object} MediaSubFolderContextType - * @property {UserType} user - * @property {MYSQL_user_media_table_def[]} media - * @property {MYSQL_user_media_table_def | null} targetMedia - * @property {React.Dispatch>} setTargetMedia - * @property {string[]} folders - * @property {any} query - * @property {string} folder - * @property {string} staticHost - */ - -/** - * @typedef {object} FieldsContextType - * @property {UserType} user - * @property {DSQL_MYSQL_user_databases_Type} database - * @property {DSQL_TableSchemaType} table - * @property {DSQL_DatabaseSchemaType[]} dbSchemaData - * @property {DSQL_FieldSchemaType | null} targetField - * @property {React.Dispatch>} setTargetField - * @property {React.MutableRefObject> | undefined>} refreshFieldsListRef - * @property {DSQL_FieldSchemaType[]} tableFields - * @property {React.Dispatch>} setTableFields - * @property {()=>void} updateTableAfterFieldsUpdateFunction - * @property {any} query - * @property {any} confirmedDelegetedUser - */ - -/** - * @typedef {object} SingleTableContextType - * @property {UserType} user - * @property {DSQL_MYSQL_user_databases_Type} database - * @property {DSQL_TableSchemaType} table - * @property {MYSQL_user_database_tables_table_def} tableRecord - * @property {DSQL_FieldSchemaType[]} tableFields - * @property {React.Dispatch>} setTableFields - * @property {DSQL_IndexSchemaType[]} tableIndexes - * @property {React.Dispatch>} setTableIndexes - * @property {DSQL_DatabaseSchemaType[]} dbSchemaData - * @property {any[]} entries - * @property {any} targetEntry - * @property {React.Dispatch>} setTargetEntry - * @property {React.MutableRefObject} richTextEditors - * @property {React.MutableRefObject} jsonTextEditors - * @property {any} query - * @property {any} confirmedDelegetedUser - * @property {DSQL_FieldSchemaType | null} targetField - * @property {React.Dispatch>} setTargetField - * @property {React.MutableRefObject>>} refreshFieldsListRef - * @property {()=>void} updateTableAfterFieldsUpdateFunction - * @property {number} entriesCount - */ - -/** - * @typedef {object} SingleEntryContextType - * @property {UserType} user - * @property {DSQL_MYSQL_user_databases_Type} database - * @property {DSQL_TableSchemaType} table - * @property {DSQL_DatabaseSchemaType[]} dbSchemaData - * @property {any} entry - * @property {any} targetEntry - * @property {React.Dispatch>} setTargetEntry - * @property {React.MutableRefObject} richTextEditors - * @property {React.MutableRefObject} jsonTextEditors - * @property {any} query - * @property {any} confirmedDelegetedUser - * @property {any} prevEntry - * @property {any} nextEntry - */ - -/** - * @typedef {object} UserSchemaContextType - * @property {UserType} user - * @property {DSQL_DatabaseSchemaType[]} dbSchemaData - */ - -/** - * @typedef {object} ConnectContextType - * @property {UserType} user - * @property {any} query - * @property {MariaDBUserCredType} mariadbUserCred - * @property {MYSQL_mariadb_users_table_def[]} mariadbUsers - All MariaDB Users including the primary User - * @property {MYSQL_mariadb_users_table_def | null} targetMariadbUser - * @property {React.Dispatch>} setTargetMariadbUser - * @property {number} refresh - * @property {React.Dispatch>} setRefresh - */ - -/** - * @typedef {object} MYSQL_mariadb_users_table_def - * @property {number} [id] - NULL=`NO` Key=`PRI` Default=`null` Extra=`auto_increment` - * @property {number} [user_id] - NULL=`NO` Key=`MUL` Default=`null` Extra=`` - * @property {string} [username] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [host] - NULL=`YES` Key=`` Default=`%` Extra=`` - * @property {string} [password] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {number} [primary] - NULL=`YES` Key=`` Default=`0` Extra=`` - * @property {string} [grants] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [date_created] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {number} [date_created_code] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [date_created_timestamp] - NULL=`YES` Key=`` Default=`current_timestamp()` Extra=`` - * @property {string} [date_updated] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {number} [date_updated_code] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [date_updated_timestamp] - NULL=`YES` Key=`` Default=`current_timestamp()` Extra=`on update current_timestamp()` - */ - -/** - * @typedef {object} DbContextType - * @property {UserType} [user] - * @property {DSQL_MYSQL_user_databases_Type[]} [databases] - * @property {DSQL_MYSQL_user_databases_Type} [targetDatabase] - * @property {React.Dispatch>} [setTargetDatabase] - */ - -/** - * @typedef {object} MariaDBUserCredType - * @property {string} [mariadb_user] - * @property {string} [mariadb_host] - * @property {string} [mariadb_pass] - */ - -/** - * @typedef {object} AddTableContextType - * @property {UserType} user - * @property {DSQL_DatabaseSchemaType[]} dbSchemaData - * @property {DSQL_MYSQL_user_databases_Type} database - * @property {DSQL_TableSchemaType[]} tables - * @property {DSQL_FieldSchemaType[]} tableFields - * @property {React.Dispatch>} setTableFields - * @property {DSQL_FieldSchemaType | null} targetField - * @property {React.Dispatch>} setTargetField - * @property {number | null} pageRefresh - * @property {React.Dispatch>} setPageRefresh - * @property {React.MutableRefObject>>} refreshFieldsListRef - * @property {any} query - */ - -/** - * @typedef {object} DbSchemaContextType - * @property {UserType} user - * @property {DSQL_MYSQL_user_databases_Type} database - * @property {string} dbImage - * @property {React.Dispatch>} setDbImage - * @property {DSQL_DatabaseSchemaType[]} dbSchemaData - * @property {any[]} tables - */ - -/** - * @typedef {object} DbShellContextType - * @property {UserType} [user] - * @property {DSQL_MYSQL_user_databases_Type} [database] - * @property {string} [dbImage] - * @property {React.Dispatch>} [setDbImage] - * @property {DSQL_DatabaseSchemaType[]} [dbSchemaData] - * @property {any[]} [tables] - */ - -/** - * @typedef {object} DbConnectContextType - * @property {UserType} user - * @property {DSQL_MYSQL_user_databases_Type} database - * @property {DSQL_DatabaseSchemaType} targetDbSchema - * @property {any} query - */ - -/** - * @typedef {object} ImageObjectType - * @property {string} [imageName] - * @property {string} [mimeType] - * @property {number} [imageSize] - * @property {boolean} [private] - * @property {string} [imageBase64] - * @property {string} [imageBase64Full] - */ - -/** - * @typedef {object} FileObjectType - * @property {string} [fileName] - * @property {boolean} [private] - * @property {string} [fileType] - * @property {number} [fileSize] - * @property {string} [fileBase64] - * @property {string} [fileBase64Full] - */ - -/** - * @typedef {object} SocialLoginObjectType - * @property {string} [platform] - * @property {string} [paradigm] - * @property {string} [clientId] - * @property {string} [clientSecret] - * @property {string} [callbackUrl] - * @property {string} [domain1] - * @property {string} [domain2] - * @property {string} [domain3] - */ - -/** - * @typedef {object} DbConnectType - * @property {string} url - Remote URL - * @property {string} key - Full Access API key - * @property {DSQL_MYSQL_user_databases_Type} database - DSQL database entry - * @property {DSQL_DatabaseSchemaType} dbSchema - Database JSON schema - * @property {"pull" | "push"} type - Type of connection: "pull" or "push" - * @property {DSQL_DatabaseSchemaType[]} [remoteDbs] - All Databases Pulled from the remote - * @property {DSQL_DatabaseSchemaType} [targetDb] - The Target Database to be cloned - */ - -/** - * @typedef {object} MYSQL_MediaType - * @property {number} [id] - * @property {number} [user_id] - * @property {string} [media_name] - * @property {string} [folder] - * @property {string} [media_url] - * @property {string} [media_thumbnail_url] - * @property {string} [media_type] - * @property {string} [width] - * @property {string} [height] - * @property {string} [size] - * @property {string} [private] - */ - -/** - * @typedef {object} UserFileObject - * @property {string} [title] - * @property {string} [path] - * @property {string} [data] - */ - -/** - * @typedef {object} UserFileObject2 - * @property {string} [type] - * @property {string} [name] - * @property {string} [root] - * @property {UserFileObject2[]} [content] - */ - -/** - * @typedef {object} MYSQL_user_users_table_def - * @property {number} [id] - NULL=`NO` Key=`PRI` Default=`null` Extra=`auto_increment` - * @property {number} [user_id] - NULL=`NO` Key=`MUL` Default=`null` Extra=`` - * @property {number} [invited_user_id] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [database] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [database_access] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [first_name] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [last_name] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [email] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [username] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [password] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [phone] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [user_type] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [user_priviledge] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [image] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [image_thumbnail] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [city] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [state] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [country] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [zip_code] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [address] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {number} [social_login] - NULL=`YES` Key=`` Default=`0` Extra=`` - * @property {string} [social_platform] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [social_id] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {number} [verification_status] - NULL=`YES` Key=`` Default=`0` Extra=`` - * @property {string} [more_user_data] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [date_created] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {number} [date_created_code] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [date_created_timestamp] - NULL=`YES` Key=`` Default=`CURRENT_TIMESTAMP` Extra=`DEFAULT_GENERATED` - * @property {string} [date_updated] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {number} [date_updated_code] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [date_updated_timestamp] - NULL=`YES` Key=`` Default=`CURRENT_TIMESTAMP` Extra=`DEFAULT_GENERATED on update CURRENT_TIMESTAMP` - * @property {string} [inviteeFirstName] - QUERY JOIN - * @property {string} [inviteeLastName] - QUERY JOIN - * @property {string} [inviteeEmail] - QUERY JOIN - * @property {string} [inviteeImage] - QUERY JOIN - */ - -/** - * @typedef {object} MYSQL_user_database_tables_table_def - * @property {number} [id] - NULL=`NO` Key=`PRI` Default=`null` Extra=`auto_increment` - * @property {number} [user_id] - NULL=`NO` Key=`MUL` Default=`null` Extra=`` - * @property {number} [db_id] - NULL=`NO` Key=`MUL` Default=`null` Extra=`` - * @property {string} [db_slug] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [table_name] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [table_slug] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [table_description] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {number} [child_table] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [child_table_parent_database] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [child_table_parent_table] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [date_created] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {number} [date_created_code] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [date_created_timestamp] - NULL=`YES` Key=`` Default=`CURRENT_TIMESTAMP` Extra=`DEFAULT_GENERATED` - * @property {string} [date_updated] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {number} [date_updated_code] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [date_updated_timestamp] - NULL=`YES` Key=`` Default=`CURRENT_TIMESTAMP` Extra=`DEFAULT_GENERATED on update CURRENT_TIMESTAMP` - */ - -/** - * @typedef {object} MYSQL_user_media_table_def - * @property {number} [id] - NULL=`NO` Key=`PRI` Default=`null` Extra=`auto_increment` - * @property {number} [user_id] - NULL=`NO` Key=`MUL` Default=`null` Extra=`` - * @property {string} [media_name] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [folder] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [media_url] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [media_thumbnail_url] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [media_path] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [media_thumbnail_path] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [media_type] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {number} [width] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {number} [height] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {number} [size] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {number} [private] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [date_created] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {number} [date_created_code] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [date_created_timestamp] - NULL=`YES` Key=`` Default=`CURRENT_TIMESTAMP` Extra=`DEFAULT_GENERATED` - * @property {string} [date_updated] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {number} [date_updated_code] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [date_updated_timestamp] - NULL=`YES` Key=`` Default=`CURRENT_TIMESTAMP` Extra=`DEFAULT_GENERATED on update CURRENT_TIMESTAMP` - */ - -/** - * @typedef {object} MYSQL_delegated_users_table_def - * @property {number} [id] - NULL=`NO` Key=`PRI` Default=`null` Extra=`auto_increment` - * @property {number} [user_id] - NULL=`NO` Key=`MUL` Default=`null` Extra=`` - * @property {number} [delegated_user_id] - NULL=`NO` Key=`MUL` Default=`null` Extra=`` - * @property {string} [permissions] - NULL=`YES` Key=`` Default=`edit` Extra=`` - * @property {number} [permission_level_code] - NULL=`YES` Key=`` Default=`1` Extra=`` - * @property {string} [date_created] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {number} [date_created_code] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [date_created_timestamp] - NULL=`YES` Key=`` Default=`CURRENT_TIMESTAMP` Extra=`DEFAULT_GENERATED` - * @property {string} [date_updated] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {number} [date_updated_code] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [date_updated_timestamp] - NULL=`YES` Key=`` Default=`CURRENT_TIMESTAMP` Extra=`DEFAULT_GENERATED on update CURRENT_TIMESTAMP` - */ - -/** - * @typedef {object} MYSQL_invitations_table_def - * @property {number} [id] - NULL=`NO` Key=`PRI` Default=`null` Extra=`auto_increment` - * @property {number} [inviting_user_id] - NULL=`NO` Key=`MUL` Default=`null` Extra=`` - * @property {string} [invited_user_email] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [invitation_status] - NULL=`YES` Key=`` Default=`Pending` Extra=`` - * @property {string} [database_access] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [priviledge] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [db_tables_data] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [date_created] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {number} [date_created_code] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [date_created_timestamp] - NULL=`YES` Key=`` Default=`CURRENT_TIMESTAMP` Extra=`DEFAULT_GENERATED` - * @property {string} [date_updated] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {number} [date_updated_code] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [date_updated_timestamp] - NULL=`YES` Key=`` Default=`CURRENT_TIMESTAMP` Extra=`DEFAULT_GENERATED on update CURRENT_TIMESTAMP` - */ - -/** - * @typedef {object} MYSQL_docs_pages_table_def - * @property {number} [id] - NULL=`NO` Key=`PRI` Default=`null` Extra=`auto_increment` - * @property {string} [title] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [slug] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [description] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [content] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [text_content] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {number} [level] - NULL=`YES` Key=`` Default=`1` Extra=`` - * @property {number} [page_order] - NULL=`YES` Key=`` Default=`1` Extra=`` - * @property {number} [parent_id] - NULL=`YES` Key=`` Default=`null` Extra=`` - * @property {string} [date_created] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {number} [date_created_code] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [date_created_timestamp] - NULL=`YES` Key=`` Default=`CURRENT_TIMESTAMP` Extra=`DEFAULT_GENERATED` - * @property {string} [date_updated] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {number} [date_updated_code] - NULL=`NO` Key=`` Default=`null` Extra=`` - * @property {string} [date_updated_timestamp] - NULL=`YES` Key=`` Default=`CURRENT_TIMESTAMP` Extra=`DEFAULT_GENERATED on update CURRENT_TIMESTAMP` - */ - -/** - * @typedef {object} MYSQL_delegated_user_tables_table_def - * @property {number} [id] - * @property {number} [delegated_user_id] - * @property {number} [root_user_id] - * @property {string} [database] - * @property {string} [table] - * @property {string} [priviledge] - * @property {string} [date_created] - * @property {number} [date_created_code] - * @property {string} [date_created_timestamp] - * @property {string} [date_updated] - * @property {number} [date_updated_code] - * @property {string} [date_updated_timestamp] - */ - -// React.Dispatch> -// React.MutableRefObject -// React.MutableRefObject>> -// React.LegacyRef - -// /** @type {HTMLFormElement} */ // @ts-ignore -// const formEl = e.target; - -// /** @type {HTMLInputElement} */ // @ts-ignore -// const inputEl = e.target; - -// /** @type {HTMLSelectElement} */ // @ts-ignore -// const selectEl = e.target; - -/** @type {any} */ -/** @type {any} */ // @ts-ignore - -// @ts-ignore - -// @param {object} params - -// /** @type {any} */ -// const dbTablesState = React.useState(0); -// /** @type {[ state: any, dispatch: React.Dispatch> ]} */ // @ts-ignore -// const [dbTables, setDbTables] = dbTablesState; - -// /** @type {import("@/package-shared/types").AddEntryContextType} */ // @ts-ignore -// const init = {}; -// export const AddTableEntryContext = React.createContext(init); diff --git a/package-shared/types/index.ts b/package-shared/types/index.ts index eabddb3..b6b1eab 100644 --- a/package-shared/types/index.ts +++ b/package-shared/types/index.ts @@ -171,15 +171,11 @@ export interface PackageUserLoginLocalBody { skipPassword?: boolean; } -type Request = IncomingMessage; - -type Response = ServerResponse; - -type ImageInputFileToBase64FunctionReturn = { - imageBase64: string; - imageBase64Full: string; - imageName: string; - imageSize: number; +export type ImageInputFileToBase64FunctionReturn = { + imageBase64?: string; + imageBase64Full?: string; + imageName?: string; + imageSize?: number; }; export interface GetReqQueryObject { @@ -189,8 +185,6 @@ export interface GetReqQueryObject { tableName?: string; } -export type SerializeQueryFnType = (query: any) => string; - export type DATASQUIREL_LoggedInUser = { id: number; uuid?: string; @@ -1172,16 +1166,6 @@ export type ServerQueryParamsJoinMatchSourceTargetObject = { fieldName: string; }; -export type SqlGeneratorFn = (Param0: { - genObject?: ServerQueryParam; - tableName: string; -}) => - | { - string: string; - values: string[]; - } - | undefined; - export type ApiConnectBody = { url: string; key: string; @@ -1238,9 +1222,6 @@ export type APILoginFunctionReturn = { csrf?: string; cookieNames?: any; }; -export type APILoginFunction = ( - params: APILoginFunctionParams -) => Promise; export type APICreateUserFunctionParams = { encryptionKey?: string; @@ -1264,10 +1245,6 @@ export type APIGetUserFunctionParams = { useLocal?: boolean; }; -export type APIGetUserFunction = ( - params: APIGetUserFunctionParams -) => Promise; - /** * API Google Login Function */ @@ -1445,7 +1422,7 @@ export type CookieObject = { }; export type HttpRequestParams< - ReqObj extends { [key: string]: any } = { [key: string]: any } + ReqObj extends { [k: string]: any } = { [k: string]: any } > = RequestOptions & { scheme?: "http" | "https"; body?: ReqObj; @@ -1454,12 +1431,12 @@ export type HttpRequestParams< }; export type HttpRequestFunction< - ReqObj extends { [key: string]: any } = { [key: string]: any }, - ResObj extends { [key: string]: any } = { [key: string]: any } + ReqObj extends { [k: string]: any } = { [k: string]: any }, + ResObj extends { [k: string]: any } = { [k: string]: any } > = (param: HttpRequestParams) => Promise>; export type HttpFunctionResponse< - ResObj extends { [key: string]: any } = { [key: string]: any } + ResObj extends { [k: string]: any } = { [k: string]: any } > = { status: number; data?: ResObj; diff --git a/package-shared/utils/backend/global-db/DB_HANDLER.d.ts b/package-shared/utils/backend/global-db/DB_HANDLER.d.ts deleted file mode 100644 index 433d7ec..0000000 --- a/package-shared/utils/backend/global-db/DB_HANDLER.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -export = DB_HANDLER; -/** - * DSQL user read-only DB handler - * @param {object} params - * @param {string} params.paradigm - * @param {string} params.database - * @param {string} params.queryString - * @param {string[]} [params.queryValues] - */ declare function DB_HANDLER(...args: any[]): Promise; diff --git a/package-shared/utils/backend/global-db/DB_HANDLER.js b/package-shared/utils/backend/global-db/DB_HANDLER.ts similarity index 62% rename from package-shared/utils/backend/global-db/DB_HANDLER.js rename to package-shared/utils/backend/global-db/DB_HANDLER.ts index bef595a..e13e922 100644 --- a/package-shared/utils/backend/global-db/DB_HANDLER.js +++ b/package-shared/utils/backend/global-db/DB_HANDLER.ts @@ -1,7 +1,5 @@ -// @ts-check - -const mysql = require("serverless-mysql"); -const grabDbSSL = require("../grabDbSSL"); +import mysql from "serverless-mysql"; +import grabDbSSL from "../grabDbSSL"; const MASTER = mysql({ config: { @@ -18,14 +16,9 @@ const MASTER = mysql({ }); /** - * DSQL user read-only DB handler - * @param {object} params - * @param {string} params.paradigm - * @param {string} params.database - * @param {string} params.queryString - * @param {string[]} [params.queryValues] - */ // @ts-ignore -async function DB_HANDLER(...args) { + * # DSQL user read-only DB handler + */ +export default async function DB_HANDLER(...args: any[]) { try { const results = await MASTER.query(...args); @@ -33,7 +26,7 @@ async function DB_HANDLER(...args) { await MASTER.end(); return JSON.parse(JSON.stringify(results)); - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log("DB Error =>", error); return { success: false, @@ -41,5 +34,3 @@ async function DB_HANDLER(...args) { }; } } - -module.exports = DB_HANDLER; diff --git a/package-shared/utils/backend/global-db/DSQL_USER_DB_HANDLER.d.ts b/package-shared/utils/backend/global-db/DSQL_USER_DB_HANDLER.d.ts deleted file mode 100644 index a616bb1..0000000 --- a/package-shared/utils/backend/global-db/DSQL_USER_DB_HANDLER.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -export = DSQL_USER_DB_HANDLER; -/** - * DSQL user read-only DB handler - * @param {object} params - * @param {"Full Access" | "FA" | "Read Only"} params.paradigm - * @param {string} params.database - * @param {string} params.queryString - * @param {string[]} [params.queryValues] - */ -declare function DSQL_USER_DB_HANDLER({ paradigm, database, queryString, queryValues, }: { - paradigm: "Full Access" | "FA" | "Read Only"; - database: string; - queryString: string; - queryValues?: string[]; -}): Promise | { - success: boolean; - error: any; -}; diff --git a/package-shared/utils/backend/global-db/DSQL_USER_DB_HANDLER.js b/package-shared/utils/backend/global-db/DSQL_USER_DB_HANDLER.ts similarity index 84% rename from package-shared/utils/backend/global-db/DSQL_USER_DB_HANDLER.js rename to package-shared/utils/backend/global-db/DSQL_USER_DB_HANDLER.ts index ead7f56..0957fe4 100644 --- a/package-shared/utils/backend/global-db/DSQL_USER_DB_HANDLER.js +++ b/package-shared/utils/backend/global-db/DSQL_USER_DB_HANDLER.ts @@ -1,10 +1,10 @@ // @ts-check -const fs = require("fs"); -const path = require("path"); +import fs from "fs"; +import path from "path"; -const mysql = require("serverless-mysql"); -const grabDbSSL = require("../grabDbSSL"); +import mysql from "serverless-mysql"; +import grabDbSSL from "../grabDbSSL"; let DSQL_USER = mysql({ config: { @@ -16,20 +16,22 @@ let DSQL_USER = mysql({ }, }); +type Param = { + paradigm: "Full Access" | "FA" | "Read Only"; + database: string; + queryString: string; + queryValues?: string[]; +}; + /** - * DSQL user read-only DB handler - * @param {object} params - * @param {"Full Access" | "FA" | "Read Only"} params.paradigm - * @param {string} params.database - * @param {string} params.queryString - * @param {string[]} [params.queryValues] + * # DSQL user read-only DB handler */ -function DSQL_USER_DB_HANDLER({ +export default function DSQL_USER_DB_HANDLER({ paradigm, database, queryString, queryValues, -}) { +}: Param) { try { return new Promise((resolve, reject) => { const fullAccess = paradigm?.match(/full.access|^fa$/i) @@ -63,7 +65,7 @@ function DSQL_USER_DB_HANDLER({ * ### Run query Function * @param {any} results */ - function runQuery(results) { + function runQuery(results: any) { DSQL_USER.end(); resolve(JSON.parse(JSON.stringify(results))); } @@ -72,7 +74,7 @@ function DSQL_USER_DB_HANDLER({ * ### Query Error * @param {any} err */ - function queryError(err) { + function queryError(err: any) { DSQL_USER.end(); resolve({ error: err.message, @@ -97,7 +99,7 @@ function DSQL_USER_DB_HANDLER({ } //////////////////////////////////////// - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { //////////////////////////////////////// fs.appendFileSync( @@ -111,7 +113,7 @@ function DSQL_USER_DB_HANDLER({ }); } }); - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { return { success: false, error: error.message, diff --git a/package-shared/utils/backend/global-db/LOCAL_DB_HANDLER.d.ts b/package-shared/utils/backend/global-db/LOCAL_DB_HANDLER.d.ts deleted file mode 100644 index 631b49a..0000000 --- a/package-shared/utils/backend/global-db/LOCAL_DB_HANDLER.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -export = LOCAL_DB_HANDLER; -/** - * DSQL user read-only DB handler - * @param {object} params - * @param {string} params.paradigm - * @param {string} params.database - * @param {string} params.queryString - * @param {string[]} [params.queryValues] - */ -declare function LOCAL_DB_HANDLER(...args: any[]): Promise; diff --git a/package-shared/utils/backend/global-db/LOCAL_DB_HANDLER.js b/package-shared/utils/backend/global-db/LOCAL_DB_HANDLER.ts similarity index 64% rename from package-shared/utils/backend/global-db/LOCAL_DB_HANDLER.js rename to package-shared/utils/backend/global-db/LOCAL_DB_HANDLER.ts index 8904937..e008b66 100644 --- a/package-shared/utils/backend/global-db/LOCAL_DB_HANDLER.js +++ b/package-shared/utils/backend/global-db/LOCAL_DB_HANDLER.ts @@ -1,17 +1,10 @@ -// @ts-check - -const mysql = require("serverless-mysql"); -const grabDbSSL = require("../grabDbSSL"); +import mysql from "serverless-mysql"; +import grabDbSSL from "../grabDbSSL"; /** - * DSQL user read-only DB handler - * @param {object} params - * @param {string} params.paradigm - * @param {string} params.database - * @param {string} params.queryString - * @param {string[]} [params.queryValues] + * # DSQL user read-only DB handler */ -async function LOCAL_DB_HANDLER(/** @type {any[]} */ ...args) { +export default async function LOCAL_DB_HANDLER(...args: any[]) { const MASTER = mysql({ config: { host: process.env.DSQL_DB_HOST, @@ -27,10 +20,10 @@ async function LOCAL_DB_HANDLER(/** @type {any[]} */ ...args) { onConnect: () => { console.log("Connection Successful!"); }, - onConnectError: (/** @type {any} */ err) => { + onConnectError: (/** @type {any} */ err: any) => { console.log("Connection Error", err.message); }, - onError: (/** @type {any} */ err) => { + onError: (/** @type {any} */ err: any) => { console.log("Client Error", err.message); }, }); @@ -42,7 +35,7 @@ async function LOCAL_DB_HANDLER(/** @type {any[]} */ ...args) { await MASTER.end(); return JSON.parse(JSON.stringify(results)); - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log("DB Error =>", error.message); return { success: false, @@ -50,5 +43,3 @@ async function LOCAL_DB_HANDLER(/** @type {any[]} */ ...args) { }; } } - -module.exports = LOCAL_DB_HANDLER; diff --git a/package-shared/utils/backend/global-db/NO_DB_HANDLER.d.ts b/package-shared/utils/backend/global-db/NO_DB_HANDLER.d.ts deleted file mode 100644 index 32ba1da..0000000 --- a/package-shared/utils/backend/global-db/NO_DB_HANDLER.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -export = NO_DB_HANDLER; -/** - * DSQL user read-only DB handler - * @param {object} params - * @param {string} params.paradigm - * @param {string} params.database - * @param {string} params.queryString - * @param {string[]} [params.queryValues] - */ declare function NO_DB_HANDLER(...args: any[]): Promise | { - success: boolean; - error: any; -}; diff --git a/package-shared/utils/backend/global-db/ROOT_DB_HANDLER.js b/package-shared/utils/backend/global-db/NO_DB_HANDLER.ts similarity index 65% rename from package-shared/utils/backend/global-db/ROOT_DB_HANDLER.js rename to package-shared/utils/backend/global-db/NO_DB_HANDLER.ts index 3733cef..27b397e 100644 --- a/package-shared/utils/backend/global-db/ROOT_DB_HANDLER.js +++ b/package-shared/utils/backend/global-db/NO_DB_HANDLER.ts @@ -1,7 +1,5 @@ -// @ts-check - -const mysql = require("serverless-mysql"); -const grabDbSSL = require("../grabDbSSL"); +import mysql from "serverless-mysql"; +import grabDbSSL from "../grabDbSSL"; let NO_DB = mysql({ config: { @@ -14,14 +12,9 @@ let NO_DB = mysql({ }); /** - * DSQL user read-only DB handler - * @param {object} params - * @param {string} params.paradigm - * @param {string} params.database - * @param {string} params.queryString - * @param {string[]} [params.queryValues] - */ // @ts-ignore -function ROOT_DB_HANDLER(...args) { + * # DSQL user read-only DB handler + */ +export default function NO_DB_HANDLER(...args: any[]) { try { return new Promise((resolve, reject) => { NO_DB.query(...args) @@ -37,12 +30,10 @@ function ROOT_DB_HANDLER(...args) { }); }); }); - } catch (/** @type {any} */ error) { + } catch (error: any) { return { success: false, error: error.message, }; } } - -module.exports = ROOT_DB_HANDLER; diff --git a/package-shared/utils/backend/global-db/NO_DB_HANDLER.js b/package-shared/utils/backend/global-db/ROOT_DB_HANDLER.ts similarity index 66% rename from package-shared/utils/backend/global-db/NO_DB_HANDLER.js rename to package-shared/utils/backend/global-db/ROOT_DB_HANDLER.ts index 80bf796..cd56728 100644 --- a/package-shared/utils/backend/global-db/NO_DB_HANDLER.js +++ b/package-shared/utils/backend/global-db/ROOT_DB_HANDLER.ts @@ -1,7 +1,7 @@ // @ts-check -const mysql = require("serverless-mysql"); -const grabDbSSL = require("../grabDbSSL"); +import mysql from "serverless-mysql"; +import grabDbSSL from "../grabDbSSL"; let NO_DB = mysql({ config: { @@ -14,14 +14,9 @@ let NO_DB = mysql({ }); /** - * DSQL user read-only DB handler - * @param {object} params - * @param {string} params.paradigm - * @param {string} params.database - * @param {string} params.queryString - * @param {string[]} [params.queryValues] - */ // @ts-ignore -function NO_DB_HANDLER(...args) { + * # Root DB handler + */ +export default function ROOT_DB_HANDLER(...args: any[]) { try { return new Promise((resolve, reject) => { NO_DB.query(...args) @@ -37,12 +32,10 @@ function NO_DB_HANDLER(...args) { }); }); }); - } catch (/** @type {any} */ error) { + } catch (error: any) { return { success: false, error: error.message, }; } } - -module.exports = NO_DB_HANDLER; diff --git a/package-shared/utils/backend/grabDbSSL.d.ts b/package-shared/utils/backend/grabDbSSL.d.ts deleted file mode 100644 index abedcdb..0000000 --- a/package-shared/utils/backend/grabDbSSL.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -declare function _exports(): string | (import("tls").SecureContextOptions & { - rejectUnauthorized?: boolean | undefined; -}) | undefined; -export = _exports; diff --git a/package-shared/utils/backend/grabDbSSL.js b/package-shared/utils/backend/grabDbSSL.ts similarity index 58% rename from package-shared/utils/backend/grabDbSSL.js rename to package-shared/utils/backend/grabDbSSL.ts index 8356e65..e94c28f 100644 --- a/package-shared/utils/backend/grabDbSSL.js +++ b/package-shared/utils/backend/grabDbSSL.ts @@ -1,11 +1,16 @@ -// @ts-check +import fs from "fs"; -const fs = require("fs"); +type Return = + | string + | (import("tls").SecureContextOptions & { + rejectUnauthorized?: boolean | undefined; + }) + | undefined; /** - * @returns {string | (import("tls").SecureContextOptions & { rejectUnauthorized?: boolean | undefined;}) | undefined} + * # Grall SSL */ -module.exports = function grabDbSSL() { +export default function grabDbSSL(): Return { const SSL_DIR = process.env.DSQL_SSL_DIR; if (!SSL_DIR?.match(/./)) { return undefined; @@ -21,4 +26,4 @@ module.exports = function grabDbSSL() { return { ca: fs.readFileSync(`${SSL_DIR}/ca-cert.pem`), }; -}; +} diff --git a/package-shared/utils/backend/parseCookies.d.ts b/package-shared/utils/backend/parseCookies.d.ts deleted file mode 100644 index ab0e658..0000000 --- a/package-shared/utils/backend/parseCookies.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -declare function _exports({ request, cookieString }: { - request?: http.IncomingMessage & { - [x: string]: any; - }; - cookieString?: string; -}): { - [x: string]: string; -}; -export = _exports; -import http = require("http"); diff --git a/package-shared/utils/backend/parseCookies.js b/package-shared/utils/backend/parseCookies.ts similarity index 63% rename from package-shared/utils/backend/parseCookies.js rename to package-shared/utils/backend/parseCookies.ts index 5436e30..71f3602 100644 --- a/package-shared/utils/backend/parseCookies.js +++ b/package-shared/utils/backend/parseCookies.ts @@ -1,6 +1,4 @@ -// @ts-check - -const http = require("http"); +import { IncomingMessage } from "http"; /** * Parse request cookies @@ -8,16 +6,14 @@ const http = require("http"); * * @description This function takes in a request object and * returns the cookies as a JS object - * - * @async - * - * @param {object} params - main params object - * @param {http.IncomingMessage & Object} [params.request] - HTTPS request object - * @param {string} [params.cookieString] - * - * @returns {Object} */ -module.exports = function parseCookies({ request, cookieString }) { +export default function parseCookies({ + request, + cookieString, +}: { + request?: IncomingMessage & { [s: string]: any }; + cookieString?: string; +}): { [s: string]: string } { try { /** @type {string | undefined} */ const cookieStr = request @@ -32,11 +28,9 @@ module.exports = function parseCookies({ request, cookieString }) { return {}; } - /** @type {string[]} */ - const cookieSplitArray = cookieStr.split(";"); + const cookieSplitArray: string[] = cookieStr.split(";"); - /** @type {Object} */ - let cookieObject = {}; + let cookieObject: { [k: string]: string } = {}; cookieSplitArray.forEach((keyValueString) => { const [key, value] = keyValueString.split("="); @@ -50,9 +44,9 @@ module.exports = function parseCookies({ request, cookieString }) { }); return cookieObject; - } catch (/** @type {any} */ error) { + } catch (error: any) { console.log(`ERROR parsing cookies: ${error.message}`); return {}; } -}; +} diff --git a/package-shared/utils/camelJoinedtoCamelSpace.d.ts b/package-shared/utils/camelJoinedtoCamelSpace.d.ts deleted file mode 100644 index 809740c..0000000 --- a/package-shared/utils/camelJoinedtoCamelSpace.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -export = camelJoinedtoCamelSpace; -/** - * Convert Camel Joined Text to Camel Spaced Text - * ============================================================================== - * @description this function takes a camel cased text without spaces, and returns - * a camel-case-spaced text - * - * @param {string} text - text string without spaces - * - * @returns {string | null} - */ -declare function camelJoinedtoCamelSpace(text: string): string | null; diff --git a/package-shared/utils/camelJoinedtoCamelSpace.js b/package-shared/utils/camelJoinedtoCamelSpace.ts similarity index 69% rename from package-shared/utils/camelJoinedtoCamelSpace.js rename to package-shared/utils/camelJoinedtoCamelSpace.ts index ff136bf..126cde1 100644 --- a/package-shared/utils/camelJoinedtoCamelSpace.js +++ b/package-shared/utils/camelJoinedtoCamelSpace.ts @@ -1,16 +1,10 @@ -// @ts-check - /** * Convert Camel Joined Text to Camel Spaced Text * ============================================================================== * @description this function takes a camel cased text without spaces, and returns * a camel-case-spaced text - * - * @param {string} text - text string without spaces - * - * @returns {string | null} */ -function camelJoinedtoCamelSpace(text) { +export default function camelJoinedtoCamelSpace(text: string): string | null { if (!text?.match(/./)) { return ""; } @@ -33,7 +27,9 @@ function camelJoinedtoCamelSpace(text) { } } - let textChunks = [`${textArray[0].toUpperCase()}${text.substring(1, capIndexes[0])}`]; + let textChunks = [ + `${textArray[0].toUpperCase()}${text.substring(1, capIndexes[0])}`, + ]; for (let j = 0; j < capIndexes.length; j++) { const capIndex = capIndexes[j]; @@ -42,7 +38,12 @@ function camelJoinedtoCamelSpace(text) { const startIndex = capIndex + 1; const endIndex = capIndexes[j + 1]; - textChunks.push(`${textArray[capIndex].toUpperCase()}${text.substring(startIndex, endIndex)}`); + textChunks.push( + `${textArray[capIndex].toUpperCase()}${text.substring( + startIndex, + endIndex + )}` + ); } return textChunks.join(" "); @@ -50,5 +51,3 @@ function camelJoinedtoCamelSpace(text) { return null; } } - -module.exports = camelJoinedtoCamelSpace; diff --git a/package-shared/utils/deserialize-query.js b/package-shared/utils/deserialize-query.ts similarity index 66% rename from package-shared/utils/deserialize-query.js rename to package-shared/utils/deserialize-query.ts index c6d16d2..4607108 100644 --- a/package-shared/utils/deserialize-query.js +++ b/package-shared/utils/deserialize-query.ts @@ -1,14 +1,15 @@ -// @ts-check +import EJSON from "./ejson"; -const EJSON = require("./ejson"); /** - * - * @param {string | Object} query - * @returns {Object} + * # Convert Serialized Query back to object */ -function deserializeQuery(query) { +export default function deserializeQuery( + query: string | { [s: string]: any } +): { + [s: string]: any; +} { /** @type {Object} */ - let queryObject = + let queryObject: { [s: string]: any } = typeof query == "object" ? query : Object(EJSON.parse(query)); const keys = Object.keys(queryObject); @@ -26,5 +27,3 @@ function deserializeQuery(query) { return queryObject; } - -module.exports = deserializeQuery; diff --git a/package-shared/utils/ejson.d.ts b/package-shared/utils/ejson.d.ts deleted file mode 100644 index be44f6a..0000000 --- a/package-shared/utils/ejson.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * - * @param {string | null | number} string - * @param {(this: any, key: string, value: any) => any} [reviver] - * @returns {Object | Object[] | undefined} - */ -export function parse(string: string | null | number, reviver?: (this: any, key: string, value: any) => any): { - [x: string]: any; -} | { - [x: string]: any; -}[] | undefined; -/** - * - * @param {any} value - * @param {((this: any, key: string, value: any) => any) | null} [replacer] - * @param { string | number } [space] - * @returns {string | undefined} - */ -export function stringify(value: any, replacer?: ((this: any, key: string, value: any) => any) | null, space?: string | number): string | undefined; diff --git a/package-shared/utils/ejson.js b/package-shared/utils/ejson.js deleted file mode 100644 index 567f452..0000000 --- a/package-shared/utils/ejson.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * - * @param {string | null | number} string - * @param {(this: any, key: string, value: any) => any} [reviver] - * @returns {Object | Object[] | undefined} - */ -function parse(string, reviver) { - if (!string) return undefined; - if (typeof string == "object") return string; - if (typeof string !== "string") return undefined; - try { - return JSON.parse(string, reviver); - } catch (error) { - return undefined; - } -} - -/** - * - * @param {any} value - * @param {((this: any, key: string, value: any) => any) | null} [replacer] - * @param { string | number } [space] - * @returns {string | undefined} - */ -function stringify(value, replacer, space) { - try { - return JSON.stringify(value, replacer, space); - } catch (error) { - return undefined; - } -} - -const EJSON = { - parse, - stringify, -}; - -module.exports = EJSON; diff --git a/package-shared/utils/ejson.ts b/package-shared/utils/ejson.ts new file mode 100644 index 0000000..0a0b92e --- /dev/null +++ b/package-shared/utils/ejson.ts @@ -0,0 +1,38 @@ +/** + * # EJSON parse string + */ +function parse( + string: string | null | number, + reviver?: (this: any, key: string, value: any) => any +): { [s: string]: any } | { [s: string]: any }[] | undefined { + if (!string) return undefined; + if (typeof string == "object") return string; + if (typeof string !== "string") return undefined; + try { + return JSON.parse(string, reviver); + } catch (error) { + return undefined; + } +} + +/** + * # EJSON stringify object + */ +function stringify( + value: any, + replacer?: (this: any, key: string, value: any) => any, + space?: string | number +): string | undefined { + try { + return JSON.stringify(value, replacer, space); + } catch (error) { + return undefined; + } +} + +const EJSON = { + parse, + stringify, +}; + +export default EJSON; diff --git a/package-shared/utils/empty-dir.ts b/package-shared/utils/empty-dir.ts new file mode 100644 index 0000000..1f6393f --- /dev/null +++ b/package-shared/utils/empty-dir.ts @@ -0,0 +1,23 @@ +import fs from "fs"; +import path from "path"; + +export default function emptyDirectory(dir: string) { + try { + const dirContent = fs.readdirSync(dir); + + for (let i = 0; i < dirContent.length; i++) { + const fileFolder = dirContent[i]; + const fullFileFolderPath = path.join(dir, fileFolder); + const stat = fs.statSync(fullFileFolderPath); + + if (stat.isDirectory()) { + emptyDirectory(fullFileFolderPath); + continue; + } + + fs.unlinkSync(fullFileFolderPath); + } + } catch (error: any) { + console.log(`Error Emptying ${dir}: ${error.message}`); + } +} diff --git a/package-shared/utils/endConnection.js b/package-shared/utils/endConnection.ts similarity index 51% rename from package-shared/utils/endConnection.js rename to package-shared/utils/endConnection.ts index c0fc177..e188c7c 100644 --- a/package-shared/utils/endConnection.js +++ b/package-shared/utils/endConnection.ts @@ -1,11 +1,9 @@ -// @ts-check - -const mysql = require("mysql"); +import mysql from "mysql"; /** - * @param {mysql.Connection} connection - the active MYSQL connection + * # End MYSQL Connection */ -function endConnection(connection) { +function endConnection(connection: mysql.Connection) { if (connection.state !== "disconnected") { connection.end((err) => { console.log(err?.message); diff --git a/package-shared/utils/generateColumnDescription.js b/package-shared/utils/generateColumnDescription.ts similarity index 81% rename from package-shared/utils/generateColumnDescription.js rename to package-shared/utils/generateColumnDescription.ts index 97b7455..b7d1d06 100644 --- a/package-shared/utils/generateColumnDescription.js +++ b/package-shared/utils/generateColumnDescription.ts @@ -8,18 +8,15 @@ /** ****************************************************************************** */ /** - * Generate SQL text for Field - * ============================================================================== - * @param {object} params - Single object params - * @param {import("../types").DSQL_FieldSchemaType} params.columnData - Field object - * @param {boolean} [params.primaryKeySet] - Table Name(slug) - * - * @returns {{fieldEntryText: string, newPrimaryKeySet: boolean}} + * # Generate SQL text for Field */ -module.exports = function generateColumnDescription({ +export default function generateColumnDescription({ columnData, primaryKeySet, -}) { +}: { + columnData: import("../types").DSQL_FieldSchemaType; + primaryKeySet?: boolean; +}): { fieldEntryText: string; newPrimaryKeySet: boolean } { /** * Format tableInfoArray * @@ -71,7 +68,7 @@ module.exports = function generateColumnDescription({ //////////////////////////////////////// return { fieldEntryText, newPrimaryKeySet: primaryKeySet || false }; -}; +} /** ****************************************************************************** */ /** ****************************************************************************** */ diff --git a/package-shared/utils/grab-host-names.d.ts b/package-shared/utils/grab-host-names.d.ts deleted file mode 100644 index 66354cb..0000000 --- a/package-shared/utils/grab-host-names.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -export = grabHostNames; -/** - * @typedef {object} GrabHostNamesReturn - * @property {string} host - * @property {number | string} port - * @property {typeof http | typeof https} scheme - * @property {string | number} user_id - */ -/** - * # Grab Names For Query - * @returns {GrabHostNamesReturn} - */ -declare function grabHostNames(): GrabHostNamesReturn; -declare namespace grabHostNames { - export { GrabHostNamesReturn }; -} -type GrabHostNamesReturn = { - host: string; - port: number | string; - scheme: typeof http | typeof https; - user_id: string | number; -}; -import http = require("http"); -import https = require("https"); diff --git a/package-shared/utils/grab-host-names.js b/package-shared/utils/grab-host-names.ts similarity index 67% rename from package-shared/utils/grab-host-names.js rename to package-shared/utils/grab-host-names.ts index ce98682..5ded3bc 100644 --- a/package-shared/utils/grab-host-names.js +++ b/package-shared/utils/grab-host-names.ts @@ -1,21 +1,19 @@ // @ts-check -const https = require("https"); -const http = require("http"); +import https from "https"; +import http from "http"; -/** - * @typedef {object} GrabHostNamesReturn - * @property {string} host - * @property {number | string} port - * @property {typeof http | typeof https} scheme - * @property {string | number} user_id - */ +type GrabHostNamesReturn = { + host: string; + port: number | string; + scheme: typeof http | typeof https; + user_id: string | number; +}; /** * # Grab Names For Query - * @returns {GrabHostNamesReturn} */ -function grabHostNames() { +export default function grabHostNames(): GrabHostNamesReturn { const scheme = process.env.DSQL_HTTP_SCHEME; const localHost = process.env.DSQL_LOCAL_HOST; const localHostPort = process.env.DSQL_LOCAL_HOST_PORT; @@ -33,5 +31,3 @@ function grabHostNames() { user_id: String(process.env.DSQL_API_USER_ID || 0), }; } - -module.exports = grabHostNames; diff --git a/package-shared/utils/numberfy.d.ts b/package-shared/utils/numberfy.d.ts deleted file mode 100644 index 2b18cb9..0000000 --- a/package-shared/utils/numberfy.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare function _exports(num: any, decimals?: number): number; -export = _exports; diff --git a/package-shared/utils/numberfy.js b/package-shared/utils/numberfy.ts similarity index 69% rename from package-shared/utils/numberfy.js rename to package-shared/utils/numberfy.ts index 79a66eb..4f5de1c 100644 --- a/package-shared/utils/numberfy.js +++ b/package-shared/utils/numberfy.ts @@ -1,10 +1,5 @@ -// @ts-check - /** * # Get Number from any input - * @param {any} num input - * @param {number} [decimals] number of decimals to round to - * @returns {number} number or 0 in case of error * @example * numberfy("123") // 123 * numberfy("123.456") // 123 @@ -12,15 +7,15 @@ * numberfy("123.456", 0) // 123 * numberfy("123.456", 3) // 123.456 */ -module.exports = function numberfy(num, decimals) { +export default function numberfy(num: any, decimals: number): number { try { const numberfiedNum = Number(num); if (typeof numberfiedNum !== "number") return 0; if (isNaN(numberfiedNum)) return 0; if (decimals) return Number(numberfiedNum.toFixed(decimals)); return Math.round(numberfiedNum); - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log(`Numberfy ERROR: ${error.message}`); return 0; } -}; +} diff --git a/package-shared/utils/serialize-cookies.d.ts b/package-shared/utils/serialize-cookies.d.ts deleted file mode 100644 index 2576f13..0000000 --- a/package-shared/utils/serialize-cookies.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -export = serializeCookies; -/** - * - * @param {object} params - * @param {import("../types").CookieObject[]} params.cookies - * @returns {string[]} - */ -declare function serializeCookies({ cookies }: { - cookies: import("../types").CookieObject[]; -}): string[]; diff --git a/package-shared/utils/serialize-cookies.js b/package-shared/utils/serialize-cookies.ts similarity index 80% rename from package-shared/utils/serialize-cookies.js rename to package-shared/utils/serialize-cookies.ts index fdcfdeb..1f426c6 100644 --- a/package-shared/utils/serialize-cookies.js +++ b/package-shared/utils/serialize-cookies.ts @@ -1,14 +1,17 @@ // @ts-check +import { CookieObject } from "../types"; + /** - * - * @param {object} params - * @param {import("../types").CookieObject[]} params.cookies - * @returns {string[]} + * # Serialize Cookies + * @description Convert cookie object to string array */ -function serializeCookies({ cookies }) { - /** @type {string[]} */ - let cookiesStringsArray = []; +export default function serializeCookies({ + cookies, +}: { + cookies: CookieObject[]; +}): string[] { + let cookiesStringsArray: string[] = []; for (let i = 0; i < cookies.length; i++) { const cookieObject = cookies[i]; @@ -44,5 +47,3 @@ function serializeCookies({ cookies }) { return cookiesStringsArray; } - -module.exports = serializeCookies; diff --git a/package-shared/utils/serialize-query.d.ts b/package-shared/utils/serialize-query.d.ts deleted file mode 100644 index 3cfd046..0000000 --- a/package-shared/utils/serialize-query.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export = serializeQuery; -declare function serializeQuery(query: any): string; diff --git a/package-shared/utils/serialize-query.js b/package-shared/utils/serialize-query.ts similarity index 80% rename from package-shared/utils/serialize-query.js rename to package-shared/utils/serialize-query.ts index 129006a..e13fa92 100644 --- a/package-shared/utils/serialize-query.js +++ b/package-shared/utils/serialize-query.ts @@ -1,9 +1,9 @@ -// @ts-check +import EJSON from "./ejson"; -const EJSON = require("./ejson"); - -/** @type {import("../types").SerializeQueryFnType} */ -function serializeQuery(query) { +/** + * # Serialize Query + */ +export default function serializeQuery(query: any): string { let str = "?"; if (typeof query !== "object") { @@ -21,8 +21,7 @@ function serializeQuery(query) { const keys = Object.keys(query); - /** @type {string[]} */ - const queryArr = []; + const queryArr: string[] = []; keys.forEach((key) => { if (!key || !query[key]) return; @@ -41,5 +40,3 @@ function serializeQuery(query) { str += queryArr.join("&"); return str; } - -module.exports = serializeQuery; diff --git a/package-shared/utils/slugToCamelTitle.js b/package-shared/utils/slugToCamelTitle.ts similarity index 59% rename from package-shared/utils/slugToCamelTitle.js rename to package-shared/utils/slugToCamelTitle.ts index 21275ed..e576e7a 100644 --- a/package-shared/utils/slugToCamelTitle.js +++ b/package-shared/utils/slugToCamelTitle.ts @@ -1,16 +1,13 @@ -// @ts-check - /** - * - * @param {string} text - * @returns + * # Slug to Camel case Title */ -module.exports = function slugToCamelTitle(text) { +export default function slugToCamelTitle(text: String) { if (text) { let addArray = text.split("-").filter((item) => item !== ""); let camelArray = addArray.map((item) => { return ( - item.substr(0, 1).toUpperCase() + item.substr(1).toLowerCase() + item.substring(0, 1).toUpperCase() + + item.substring(1).toLowerCase() ); }); @@ -20,4 +17,4 @@ module.exports = function slugToCamelTitle(text) { } else { return null; } -}; +} diff --git a/package-shared/utils/slugify.d.ts b/package-shared/utils/slugify.d.ts deleted file mode 100644 index b323843..0000000 --- a/package-shared/utils/slugify.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare function _exports(str: string): string; -export = _exports; diff --git a/package-shared/utils/slugify.js b/package-shared/utils/slugify.ts similarity index 76% rename from package-shared/utils/slugify.js rename to package-shared/utils/slugify.ts index df5c734..87501b3 100644 --- a/package-shared/utils/slugify.js +++ b/package-shared/utils/slugify.ts @@ -2,14 +2,13 @@ /** * # Return the slug of a string - * @param {string} str input - * @returns {string} slug or empty string in case of error + * * @example * slugify("Hello World") // "hello-world" * slugify("Yes!") // "yes" * slugify("Hello!!! World!") // "hello-world" */ -module.exports = function slugify(str) { +export default function slugify(str: string): string { try { return String(str) .trim() @@ -20,8 +19,8 @@ module.exports = function slugify(str) { .replace(/-{2,}/g, "-") .replace(/^-/, "") .replace(/-$/, ""); - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log(`Slugify ERROR: ${error.message}`); return ""; } -}; +} diff --git a/package-shared/utils/trim-sql.d.ts b/package-shared/utils/trim-sql.d.ts deleted file mode 100644 index 5157fa0..0000000 --- a/package-shared/utils/trim-sql.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -export = trimSql; -/** - * @typedef {object} GrabHostNamesReturn - * @property {string} host - * @property {number | string} port - * @property {typeof http | typeof https} scheme - */ -/** - * # Trim SQL - * @description Remove Returns and miltiple spaces from SQL Query - * @param {string} sql - * @returns {string} - */ -declare function trimSql(sql: string): string; -declare namespace trimSql { - export { GrabHostNamesReturn }; -} -type GrabHostNamesReturn = { - host: string; - port: number | string; - scheme: typeof http | typeof https; -}; -import http = require("http"); -import https = require("https"); diff --git a/package-shared/utils/trim-sql.js b/package-shared/utils/trim-sql.js deleted file mode 100644 index 73d2d67..0000000 --- a/package-shared/utils/trim-sql.js +++ /dev/null @@ -1,26 +0,0 @@ -// @ts-check - -const https = require("https"); -const http = require("http"); - -/** - * @typedef {object} GrabHostNamesReturn - * @property {string} host - * @property {number | string} port - * @property {typeof http | typeof https} scheme - */ - -/** - * # Trim SQL - * @description Remove Returns and miltiple spaces from SQL Query - * @param {string} sql - * @returns {string} - */ -function trimSql(sql) { - return sql - .replace(/\n|\r|\n\r|\r\n/gm, " ") - .replace(/ {2,}/g, " ") - .trim(); -} - -module.exports = trimSql; diff --git a/package-shared/utils/trim-sql.ts b/package-shared/utils/trim-sql.ts new file mode 100644 index 0000000..99edae3 --- /dev/null +++ b/package-shared/utils/trim-sql.ts @@ -0,0 +1,10 @@ +/** + * # Trim SQL + * @description Remove Returns and miltiple spaces from SQL Query + */ +export default function trimSql(sql: string) { + return sql + .replace(/\n|\r|\n\r|\r\n/gm, " ") + .replace(/ {2,}/g, " ") + .trim(); +} diff --git a/package.json b/package.json index ec23f12..9d47e65 100644 --- a/package.json +++ b/package.json @@ -1,16 +1,15 @@ { "name": "@moduletrace/datasquirel", - "version": "3.3.8", + "version": "3.4.0", "description": "Cloud-based SQL data management tool", - "main": "index.js", + "main": "dist/index.js", "bin": { - "dsql-watch": "./engine/dsql.js", - "dsql-dump": "./engine/dump.js" + "dsql-watch": "dist/engine/dsql.js", + "dsql-dump": "dist/engine/dump.js" }, "scripts": { - "delete-ts": "find . -name \"*.d.ts\" -type f -not -path \"./node_modules/*\" -delete", - "compile": "find . -name \"*.d.ts\" -type f -not -path \"./node_modules/*\" -delete && tsc --declaration --allowJs --emitDeclarationOnly --resolveJsonModule index.js", - "compile:full": "rm -rf dist && tsc --declaration --allowJs --outDir dist --emitDeclarationOnly --resolveJsonModule index.js && cat ./dist/index.d.ts > ./index.d.ts" + "build": "bun build ./index.ts --outdir ./dist --target node --format esm", + "dev": "bun build ./index.ts --outdir ./dist --target node --format esm --watch" }, "repository": { "type": "git", @@ -49,5 +48,8 @@ "react-dom": "^19.0.0", "sanitize-html": "^2.13.1", "serverless-mysql": "^1.5.5" + }, + "devDependencies": { + "@types/nodemailer": "^6.4.17" } } diff --git a/users/add-user.d.ts b/users/add-user.d.ts deleted file mode 100644 index 6cf271d..0000000 --- a/users/add-user.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -export = addUser; -/** - * Add User to Database - * ============================================ - * @async - * - * @param {object} param - Single object passed - * @param {string} [param.key] - FULL ACCESS API Key - * @param {string} [param.database] - Database Name - * @param {import("../package-shared/types").UserDataPayload} param.payload - User Data Payload - * @param {string} [param.encryptionKey] - * @param {string} [param.encryptionSalt] - * @param {string | number} [param.user_id] - * @param {string | number} [param.apiUserId] - * @param {boolean} [param.useLocal] - * - * @returns { Promise } - */ -declare function addUser({ key, payload, database, encryptionKey, user_id, useLocal, apiUserId, }: { - key?: string; - database?: string; - payload: import("../package-shared/types").UserDataPayload; - encryptionKey?: string; - encryptionSalt?: string; - user_id?: string | number; - apiUserId?: string | number; - useLocal?: boolean; -}): Promise; diff --git a/users/add-user.js b/users/add-user.ts similarity index 71% rename from users/add-user.js rename to users/add-user.ts index 768a724..46ce835 100644 --- a/users/add-user.js +++ b/users/add-user.ts @@ -1,28 +1,27 @@ -// @ts-check +import path from "path"; +import fs from "fs"; +import grabHostNames from "../package-shared/utils/grab-host-names"; +import apiCreateUser from "../package-shared/functions/api/users/api-create-user"; +import { + AddUserFunctionReturn, + UserDataPayload, +} from "../package-shared/types"; -const path = require("path"); -const fs = require("fs"); -const grabHostNames = require("../package-shared/utils/grab-host-names"); -const apiCreateUser = require("../package-shared/functions/api/users/api-create-user"); +type Param = { + key?: string; + database?: string; + payload: UserDataPayload; + encryptionKey?: string; + encryptionSalt?: string; + user_id?: string | number; + apiUserId?: string | number; + useLocal?: boolean; +}; /** - * Add User to Database - * ============================================ - * @async - * - * @param {object} param - Single object passed - * @param {string} [param.key] - FULL ACCESS API Key - * @param {string} [param.database] - Database Name - * @param {import("../package-shared/types").UserDataPayload} param.payload - User Data Payload - * @param {string} [param.encryptionKey] - * @param {string} [param.encryptionSalt] - * @param {string | number} [param.user_id] - * @param {string | number} [param.apiUserId] - * @param {boolean} [param.useLocal] - * - * @returns { Promise } + * # Add User to Database */ -async function addUser({ +export default async function addUser({ key, payload, database, @@ -30,7 +29,7 @@ async function addUser({ user_id, useLocal, apiUserId, -}) { +}: Param): Promise { /** * Check for local DB settings * @@ -55,7 +54,9 @@ async function addUser({ useLocal ) { /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ - let dbSchema; + let dbSchema: + | import("../package-shared/types").DSQL_DatabaseSchemaType + | undefined; try { const localDbSchemaPath = path.resolve( @@ -129,7 +130,5 @@ async function addUser({ httpsRequest.end(); }); - return httpResponse; + return httpResponse as AddUserFunctionReturn; } - -module.exports = addUser; diff --git a/users/delete-user.d.ts b/users/delete-user.d.ts deleted file mode 100644 index 33678f8..0000000 --- a/users/delete-user.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -export = deleteUser; -/** - * # Update User - * @async - * - * @param {object} params - API Key - * @param {String} [params.key] - API Key - * @param {String} [params.database] - Target Database - * @param {String | number} params.deletedUserId - Target Database - * @param {boolean} [params.user_id] - User ID - * @param {boolean} [params.useLocal] - * - * @returns { Promise} - */ -declare function deleteUser({ key, database, user_id, useLocal, deletedUserId }: { - key?: string; - database?: string; - deletedUserId: string | number; - user_id?: boolean; - useLocal?: boolean; -}): Promise; diff --git a/users/delete-user.js b/users/delete-user.ts similarity index 63% rename from users/delete-user.js rename to users/delete-user.ts index 160ec93..f7918a7 100644 --- a/users/delete-user.js +++ b/users/delete-user.ts @@ -1,27 +1,27 @@ -// @ts-check +import path from "path"; +import fs from "fs"; +import grabHostNames from "../package-shared/utils/grab-host-names"; +import apiDeleteUser from "../package-shared/functions/api/users/api-delete-user"; +import { UpdateUserFunctionReturn } from "../package-shared/types"; -const http = require("http"); -const https = require("https"); -const path = require("path"); -const fs = require("fs"); -const grabHostNames = require("../package-shared/utils/grab-host-names"); -const apiUpdateUser = require("../package-shared/functions/api/users/api-update-user"); -const apiDeleteUser = require("../package-shared/functions/api/users/api-delete-user"); +type Param = { + key?: string; + database?: string; + deletedUserId: string | number; + user_id?: boolean; + useLocal?: boolean; +}; /** * # Update User - * @async - * - * @param {object} params - API Key - * @param {String} [params.key] - API Key - * @param {String} [params.database] - Target Database - * @param {String | number} params.deletedUserId - Target Database - * @param {boolean} [params.user_id] - User ID - * @param {boolean} [params.useLocal] - * - * @returns { Promise} */ -async function deleteUser({ key, database, user_id, useLocal, deletedUserId }) { +export default async function deleteUser({ + key, + database, + user_id, + useLocal, + deletedUserId, +}: Param): Promise { /** * Check for local DB settings * @@ -41,7 +41,9 @@ async function deleteUser({ key, database, user_id, useLocal, deletedUserId }) { useLocal ) { /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ - let dbSchema; + let dbSchema: + | import("../package-shared/types").DSQL_DatabaseSchemaType + | undefined; try { const localDbSchemaPath = path.resolve( @@ -63,7 +65,7 @@ async function deleteUser({ key, database, user_id, useLocal, deletedUserId }) { * * @description make a request to datasquirel.com */ - const httpResponse = await new Promise((resolve, reject) => { + const httpResponse = (await new Promise((resolve, reject) => { const reqPayload = JSON.stringify({ database, deletedUserId, @@ -110,17 +112,7 @@ async function deleteUser({ key, database, user_id, useLocal, deletedUserId }) { ); httpsRequest.write(reqPayload); httpsRequest.end(); - }); - - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ + })) as UpdateUserFunctionReturn; return httpResponse; } - -/** ********************************************** */ -/** ********************************************** */ -/** ********************************************** */ - -module.exports = deleteUser; diff --git a/users/get-token.d.ts b/users/get-token.d.ts deleted file mode 100644 index 815ecc0..0000000 --- a/users/get-token.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -export = getToken; -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** - * Get just the access token for user - * ============================================================================== - * @description This Function takes in a request object and returns a user token - * string and csrf token string - * - * @param {Object} params - Arg - * @param {http.IncomingMessage} [params.request] - Http request object - * @param {string} [params.cookieString] - * @param {string} params.encryptionKey - Encryption Key - * @param {string} params.encryptionSalt - Encryption Salt - * @param {string} params.database - Database Name - * @param {boolean} [params.useLocal] - * - * @returns {{ key: string | undefined, csrf: string | undefined }} - */ -declare function getToken({ request, encryptionKey, encryptionSalt, database, useLocal, cookieString, }: { - request?: http.IncomingMessage; - cookieString?: string; - encryptionKey: string; - encryptionSalt: string; - database: string; - useLocal?: boolean; -}): { - key: string | undefined; - csrf: string | undefined; -}; -import http = require("http"); diff --git a/users/get-token.js b/users/get-token.js deleted file mode 100644 index c706568..0000000 --- a/users/get-token.js +++ /dev/null @@ -1,116 +0,0 @@ -// @ts-check - -/** - * ============================================================================== - * Imports - * ============================================================================== - */ -const http = require("http"); -const decrypt = require("../package-shared/functions/dsql/decrypt"); -const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names"); -const parseCookies = require("../package-shared/utils/backend/parseCookies"); - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -/** - * Get just the access token for user - * ============================================================================== - * @description This Function takes in a request object and returns a user token - * string and csrf token string - * - * @param {Object} params - Arg - * @param {http.IncomingMessage} [params.request] - Http request object - * @param {string} [params.cookieString] - * @param {string} params.encryptionKey - Encryption Key - * @param {string} params.encryptionSalt - Encryption Salt - * @param {string} params.database - Database Name - * @param {boolean} [params.useLocal] - * - * @returns {{ key: string | undefined, csrf: string | undefined }} - */ -function getToken({ - request, - encryptionKey, - encryptionSalt, - database, - useLocal, - cookieString, -}) { - try { - /** - * Grab the payload - * - * @description Grab the payload - */ - const cookies = parseCookies({ request, cookieString }); - const keynames = getAuthCookieNames(); - const authKeyName = keynames.keyCookieName; - const csrfName = keynames.csrfCookieName; - - const key = cookies[authKeyName]; - const csrf = cookies[csrfName]; - - /** - * Grab the payload - * - * @description Grab the payload - */ - let userPayload = decrypt({ - encryptedString: key, - encryptionKey, - encryptionSalt, - }); - - /** - * Grab the payload - * - * @description Grab the payload - */ - if (!userPayload) { - return { key: undefined, csrf: undefined }; - } - - /** - * Grab the payload - * - * @description Grab the payload - */ - let userObject = JSON.parse(userPayload); - - if (!userObject.csrf_k) { - return { key: undefined, csrf: undefined }; - } - - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ - - /** - * Return User Object - * - * @description Return User Object - */ - return { key, csrf }; - } catch (error) { - /** - * Return User Object - * - * @description Return User Object - */ - return { - key: undefined, - csrf: undefined, - }; - } -} - -/** ********************************************** */ -/** ********************************************** */ -/** ********************************************** */ - -module.exports = getToken; diff --git a/users/get-token.ts b/users/get-token.ts new file mode 100644 index 0000000..dfeb68c --- /dev/null +++ b/users/get-token.ts @@ -0,0 +1,96 @@ +import http from "http"; +import decrypt from "../package-shared/functions/dsql/decrypt"; +import getAuthCookieNames from "../package-shared/functions/backend/cookies/get-auth-cookie-names"; +import parseCookies from "../package-shared/utils/backend/parseCookies"; + +type Param = { + request?: http.IncomingMessage; + cookieString?: string; + encryptionKey: string; + encryptionSalt: string; + database: string; + useLocal?: boolean; +}; + +type Return = { + key: string | undefined; + csrf: string | undefined; +}; + +/** + * Get just the access token for user + * ============================================================================== + * @description This Function takes in a request object and returns a user token + * string and csrf token string + */ +export default function getToken({ + request, + encryptionKey, + encryptionSalt, + database, + useLocal, + cookieString, +}: Param): Return { + try { + /** + * Grab the payload + * + * @description Grab the payload + */ + const cookies = parseCookies({ request, cookieString }); + const keynames = getAuthCookieNames(); + const authKeyName = keynames.keyCookieName; + const csrfName = keynames.csrfCookieName; + + const key = cookies[authKeyName]; + const csrf = cookies[csrfName]; + + /** + * Grab the payload + * + * @description Grab the payload + */ + let userPayload = decrypt({ + encryptedString: key, + encryptionKey, + encryptionSalt, + }); + + /** + * Grab the payload + * + * @description Grab the payload + */ + if (!userPayload) { + return { key: undefined, csrf: undefined }; + } + + /** + * Grab the payload + * + * @description Grab the payload + */ + let userObject = JSON.parse(userPayload); + + if (!userObject.csrf_k) { + return { key: undefined, csrf: undefined }; + } + + /** + * Return User Object + * + * @description Return User Object + */ + return { key, csrf }; + } catch (error) { + /** + * Return User Object + * + * @description Return User Object + */ + return { + key: undefined, + csrf: undefined, + }; + } +} diff --git a/users/get-user.d.ts b/users/get-user.d.ts deleted file mode 100644 index 29a7b57..0000000 --- a/users/get-user.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -export = getUser; -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** - * ============================================================================== - * Main Function - * ============================================================================== - * @async - * - * @param {object} params - Single Param object containing params - * @param {String} params.key - API Key - * @param {String} params.database - Target Database - * @param {number} params.userId - user to get - * @param {string[]} [params.fields] - fields to select - * @param {boolean} [params.apiUserId] - API User ID - * @param {boolean} [params.useLocal] - Whether to use a remote database instead of API - * - * @returns { Promise} - */ -declare function getUser({ key, userId, database, fields, apiUserId, useLocal }: { - key: string; - database: string; - userId: number; - fields?: string[]; - apiUserId?: boolean; - useLocal?: boolean; -}): Promise; diff --git a/users/get-user.js b/users/get-user.ts similarity index 60% rename from users/get-user.js rename to users/get-user.ts index a430f51..a82f3e8 100644 --- a/users/get-user.js +++ b/users/get-user.ts @@ -1,41 +1,29 @@ -// @ts-check +import path from "path"; +import fs from "fs"; +import grabHostNames from "../package-shared/utils/grab-host-names"; +import apiGetUser from "../package-shared/functions/api/users/api-get-user"; +import { GetUserFunctionReturn } from "../package-shared/types"; + +type Param = { + key: string; + database: string; + userId: number; + fields?: string[]; + apiUserId?: boolean; + useLocal?: boolean; +}; /** - * ============================================================================== - * Imports - * ============================================================================== + * # Get User */ -const path = require("path"); -const fs = require("fs"); -const https = require("https"); -const http = require("http"); -const grabHostNames = require("../package-shared/utils/grab-host-names"); -const apiGetUser = require("../package-shared/functions/api/users/api-get-user"); - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -/** - * ============================================================================== - * Main Function - * ============================================================================== - * @async - * - * @param {object} params - Single Param object containing params - * @param {String} params.key - API Key - * @param {String} params.database - Target Database - * @param {number} params.userId - user to get - * @param {string[]} [params.fields] - fields to select - * @param {boolean} [params.apiUserId] - API User ID - * @param {boolean} [params.useLocal] - Whether to use a remote database instead of API - * - * @returns { Promise} - */ -async function getUser({ key, userId, database, fields, apiUserId, useLocal }) { +export default async function getUser({ + key, + userId, + database, + fields, + apiUserId, + useLocal, +}: Param): Promise { /** * Initialize */ @@ -84,7 +72,9 @@ async function getUser({ key, userId, database, fields, apiUserId, useLocal }) { useLocal ) { /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ - let dbSchema; + let dbSchema: + | import("../package-shared/types").DSQL_DatabaseSchemaType + | undefined; try { const localDbSchemaPath = path.resolve( @@ -156,11 +146,5 @@ async function getUser({ key, userId, database, fields, apiUserId, useLocal }) { /** ********************************************** */ /** ********************************************** */ - return httpResponse; + return httpResponse as GetUserFunctionReturn; } - -/** ********************************************** */ -/** ********************************************** */ -/** ********************************************** */ - -module.exports = getUser; diff --git a/users/login-user.d.ts b/users/login-user.d.ts deleted file mode 100644 index 319ed15..0000000 --- a/users/login-user.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -export = loginUser; -/** - * Login A user - * ============================================================================== - * @async - * - * @param {object} params - Single Param object containing params - * @param {String} [params.key] - FULL ACCESS API Key - * @param {String} params.database - Target Database - * @param {{ - * email?: string, - * username?: string, - * password?: string, - * }} params.payload Login Email/Username and Password - * @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object - * @param {http.ServerResponse & Object} [params.response] - Http response object - * @param {String} [params.encryptionKey] - Encryption Key - * @param {String} [params.encryptionSalt] - Encryption Salt - * @param {boolean} [params.email_login] - Email only Login - * @param {string} [params.email_login_code] - Email login code - * @param {string} [params.temp_code_field] - Database table field name for temporary code - * @param {boolean} [params.token] - Send access key as part of response body? - * @param {string | number} [params.user_id] - User ID - * @param {boolean} [params.skipPassword] - * @param {boolean} [params.useLocal] - * @param {boolean} [params.skipWriteAuthFile] - Skip writing auth file to `.tmp/login` folder - * @param {string | number} [params.apiUserID] - Required for setting of cookies - * - * @returns { Promise} - */ -declare function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, useLocal, apiUserID, skipWriteAuthFile, }: { - key?: string; - database: string; - payload: { - email?: string; - username?: string; - password?: string; - }; - additionalFields?: string[]; - response?: http.ServerResponse & { - [x: string]: any; - }; - encryptionKey?: string; - encryptionSalt?: string; - email_login?: boolean; - email_login_code?: string; - temp_code_field?: string; - token?: boolean; - user_id?: string | number; - skipPassword?: boolean; - useLocal?: boolean; - skipWriteAuthFile?: boolean; - apiUserID?: string | number; -}): Promise; -import http = require("http"); diff --git a/users/login-user.js b/users/login-user.ts similarity index 67% rename from users/login-user.js rename to users/login-user.ts index 226476f..8eadcde 100644 --- a/users/login-user.js +++ b/users/login-user.ts @@ -1,52 +1,40 @@ -// @ts-check +import http from "http"; +import fs from "fs"; +import path from "path"; +import encrypt from "../package-shared/functions/dsql/encrypt"; +import grabHostNames from "../package-shared/utils/grab-host-names"; +import apiLoginUser from "../package-shared/functions/api/users/api-login"; +import getAuthCookieNames from "../package-shared/functions/backend/cookies/get-auth-cookie-names"; +import { writeAuthFile } from "../package-shared/functions/backend/auth/write-auth-files"; +import { APILoginFunctionReturn } from "../package-shared/types"; + +type Param = { + key?: string; + database: string; + payload: { + email?: string; + username?: string; + password?: string; + }; + additionalFields?: string[]; + response?: http.ServerResponse & { [s: string]: any }; + encryptionKey?: string; + encryptionSalt?: string; + email_login?: boolean; + email_login_code?: string; + temp_code_field?: string; + token?: boolean; + user_id?: string | number; + skipPassword?: boolean; + useLocal?: boolean; + skipWriteAuthFile?: boolean; + apiUserID?: string | number; +}; /** - * ============================================================================== - * Imports - * ============================================================================== + * # Login A user */ -const http = require("http"); -const https = require("https"); -const fs = require("fs"); -const path = require("path"); -const encrypt = require("../package-shared/functions/dsql/encrypt"); -const grabHostNames = require("../package-shared/utils/grab-host-names"); -const apiLoginUser = require("../package-shared/functions/api/users/api-login"); -const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names"); -const { - writeAuthFile, -} = require("../package-shared/functions/backend/auth/write-auth-files"); - -/** - * Login A user - * ============================================================================== - * @async - * - * @param {object} params - Single Param object containing params - * @param {String} [params.key] - FULL ACCESS API Key - * @param {String} params.database - Target Database - * @param {{ - * email?: string, - * username?: string, - * password?: string, - * }} params.payload Login Email/Username and Password - * @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object - * @param {http.ServerResponse & Object} [params.response] - Http response object - * @param {String} [params.encryptionKey] - Encryption Key - * @param {String} [params.encryptionSalt] - Encryption Salt - * @param {boolean} [params.email_login] - Email only Login - * @param {string} [params.email_login_code] - Email login code - * @param {string} [params.temp_code_field] - Database table field name for temporary code - * @param {boolean} [params.token] - Send access key as part of response body? - * @param {string | number} [params.user_id] - User ID - * @param {boolean} [params.skipPassword] - * @param {boolean} [params.useLocal] - * @param {boolean} [params.skipWriteAuthFile] - Skip writing auth file to `.tmp/login` folder - * @param {string | number} [params.apiUserID] - Required for setting of cookies - * - * @returns { Promise} - */ -async function loginUser({ +export default async function loginUser({ key, payload, database, @@ -63,7 +51,7 @@ async function loginUser({ useLocal, apiUserID, skipWriteAuthFile, -}) { +}: Param): Promise { const grabedHostNames = grabHostNames(); const { host, port, scheme } = grabedHostNames; @@ -114,9 +102,10 @@ async function loginUser({ */ /** @type {import("../package-shared/types").APILoginFunctionReturn} */ - let httpResponse = { - success: false, - }; + let httpResponse: import("../package-shared/types").APILoginFunctionReturn = + { + success: false, + }; /** * Check for local DB settings @@ -134,7 +123,9 @@ async function loginUser({ useLocal ) { /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ - let dbSchema; + let dbSchema: + | import("../package-shared/types").DSQL_DatabaseSchemaType + | undefined; try { const localDbSchemaPath = path.resolve( @@ -168,17 +159,18 @@ async function loginUser({ */ httpResponse = await new Promise((resolve, reject) => { /** @type {import("../package-shared/types").PackageUserLoginRequestBody} */ - const reqPayload = { - encryptionKey: finalEncryptionKey, - payload, - database, - additionalFields, - email_login, - email_login_code, - email_login_field: emailLoginTempCodeFieldName, - token, - skipPassword: skipPassword, - }; + const reqPayload: import("../package-shared/types").PackageUserLoginRequestBody = + { + encryptionKey: finalEncryptionKey, + payload, + database, + additionalFields, + email_login, + email_login_code, + email_login_field: emailLoginTempCodeFieldName, + token, + skipPassword: skipPassword, + }; const reqPayloadJSON = JSON.stringify(reqPayload); @@ -270,5 +262,3 @@ async function loginUser({ return httpResponse; } - -module.exports = loginUser; diff --git a/users/logout-user.d.ts b/users/logout-user.d.ts deleted file mode 100644 index 278e60c..0000000 --- a/users/logout-user.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -export = logoutUser; -/** - * Logout user - * ============================================================================== - * @param {object} params - Single Param object containing params - * @param {string} [params.encryptedUserString] - Encrypted User String - * @param {http.IncomingMessage & Object} [params.request] - Request Object - * @param {http.ServerResponse & Object} [params.response] - Http response object - * @param {string} [params.cookieString] - * @param {string} [params.database] - Target database name(slug): optional - * @param {string | number} [params.dsqlUserId] - * - * @returns {{success: boolean, msg: string, cookieNames?: any}} - */ -declare function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, }: { - encryptedUserString?: string; - request?: http.IncomingMessage & { - [x: string]: any; - }; - response?: http.ServerResponse & { - [x: string]: any; - }; - cookieString?: string; - database?: string; - dsqlUserId?: string | number; -}): { - success: boolean; - msg: string; - cookieNames?: any; -}; -import http = require("http"); diff --git a/users/logout-user.js b/users/logout-user.ts similarity index 56% rename from users/logout-user.js rename to users/logout-user.ts index 9da39fb..507db24 100644 --- a/users/logout-user.js +++ b/users/logout-user.ts @@ -1,35 +1,37 @@ -// @ts-check +import http from "http"; +import getAuthCookieNames from "../package-shared/functions/backend/cookies/get-auth-cookie-names"; +import decrypt from "../package-shared/functions/dsql/decrypt"; +import EJSON from "../package-shared/utils/ejson"; +import { deleteAuthFile } from "../package-shared/functions/backend/auth/write-auth-files"; +import parseCookies from "../package-shared/utils/backend/parseCookies"; +import { DATASQUIREL_LoggedInUser } from "../package-shared/types"; -const http = require("http"); -const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names"); -const decrypt = require("../package-shared/functions/dsql/decrypt"); -const EJSON = require("../package-shared/utils/ejson"); -const { - deleteAuthFile, -} = require("../package-shared/functions/backend/auth/write-auth-files"); -const parseCookies = require("../package-shared/utils/backend/parseCookies"); +type Param = { + encryptedUserString?: string; + request?: http.IncomingMessage & { [s: string]: any }; + response?: http.ServerResponse & { [s: string]: any }; + cookieString?: string; + database?: string; + dsqlUserId?: string | number; +}; + +type Return = { + success: boolean; + msg: string; + cookieNames?: any; +}; /** - * Logout user - * ============================================================================== - * @param {object} params - Single Param object containing params - * @param {string} [params.encryptedUserString] - Encrypted User String - * @param {http.IncomingMessage & Object} [params.request] - Request Object - * @param {http.ServerResponse & Object} [params.response] - Http response object - * @param {string} [params.cookieString] - * @param {string} [params.database] - Target database name(slug): optional - * @param {string | number} [params.dsqlUserId] - * - * @returns {{success: boolean, msg: string, cookieNames?: any}} + * # Logout user */ -function logoutUser({ +export default function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, -}) { +}: Param): Return { /** * Check Encryption Keys * @@ -44,8 +46,7 @@ function logoutUser({ const csrfName = cookieNames.csrfCookieName; const oneTimeCodeName = getAuthCookieNames().oneTimeCodeName; - /** @type {string | undefined} */ - const decryptedUserJSON = (() => { + const decryptedUserJSON: string | undefined = (() => { try { if (request) { const cookiesObject = parseCookies({ @@ -62,7 +63,7 @@ function logoutUser({ } else { return undefined; } - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log( "Error getting decrypted User JSON to logout:", error.message @@ -74,10 +75,9 @@ function logoutUser({ if (!decryptedUserJSON) throw new Error("Invalid User"); - const userObject = - /** @type {import("../package-shared/types").DATASQUIREL_LoggedInUser | undefined} */ ( - EJSON.parse(decryptedUserJSON) - ); + const userObject = EJSON.parse( + decryptedUserJSON + ) as DATASQUIREL_LoggedInUser; if (!userObject?.csrf_k) throw new Error("Invalid User. Please check key"); @@ -96,7 +96,7 @@ function logoutUser({ msg: "User Logged Out", cookieNames, }; - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log("Logout Error:", error.message); return { success: false, diff --git a/users/reauth-user.d.ts b/users/reauth-user.d.ts deleted file mode 100644 index d6a4d12..0000000 --- a/users/reauth-user.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -export = reauthUser; -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** - * ============================================================================== - * Main Function - * ============================================================================== - * @async - * - * @param {object} params - Single Param object containing params - * @param {String} [params.key] - API Key - * @param {String} [params.database]- Target Database slug - * @param {http.ServerResponse} [params.response] - Http response object - * @param {http.IncomingMessage} [params.request] - Http request object - * @param {("deep" | "normal")} [params.level] - Authentication level - * @param {String} [params.encryptionKey] - Encryption Key - * @param {String} [params.encryptionSalt] - Encryption Salt - * @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object - * @param {string} [params.encryptedUserString] - encrypted user string to use instead of getting from cookie header - * @param {string | number} [params.user_id] - User ID - * @param {boolean} [params.useLocal] - * - * @returns { Promise } - */ -declare function reauthUser({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, useLocal, }: { - key?: string; - database?: string; - response?: http.ServerResponse; - request?: http.IncomingMessage; - level?: ("deep" | "normal"); - encryptionKey?: string; - encryptionSalt?: string; - additionalFields?: string[]; - encryptedUserString?: string; - user_id?: string | number; - useLocal?: boolean; -}): Promise; -import http = require("http"); diff --git a/users/reauth-user.js b/users/reauth-user.ts similarity index 60% rename from users/reauth-user.js rename to users/reauth-user.ts index 0145fbe..02d2830 100644 --- a/users/reauth-user.js +++ b/users/reauth-user.ts @@ -1,54 +1,37 @@ -// @ts-check +import http from "http"; +import https from "https"; +import fs from "fs"; +import path from "path"; +import encrypt from "../package-shared/functions/dsql/encrypt"; -/** - * ============================================================================== - * Imports - * ============================================================================== - */ -const http = require("http"); -const https = require("https"); -const fs = require("fs"); -const path = require("path"); -const encrypt = require("../package-shared/functions/dsql/encrypt"); - -const userAuth = require("./user-auth"); -const grabHostNames = require("../package-shared/utils/grab-host-names"); -const apiReauthUser = require("../package-shared/functions/api/users/api-reauth-user"); -const { +import userAuth from "./user-auth"; +import grabHostNames from "../package-shared/utils/grab-host-names"; +import apiReauthUser from "../package-shared/functions/api/users/api-reauth-user"; +import { writeAuthFile, deleteAuthFile, -} = require("../package-shared/functions/backend/auth/write-auth-files"); -const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names"); +} from "../package-shared/functions/backend/auth/write-auth-files"; +import getAuthCookieNames from "../package-shared/functions/backend/cookies/get-auth-cookie-names"; +import { APILoginFunctionReturn } from "../package-shared/types"; -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ +type Param = { + key?: string; + database?: string; + response?: http.ServerResponse; + request?: http.IncomingMessage; + level?: "deep" | "normal"; + encryptionKey?: string; + encryptionSalt?: string; + additionalFields?: string[]; + encryptedUserString?: string; + user_id?: string | number; + useLocal?: boolean; +}; /** - * ============================================================================== - * Main Function - * ============================================================================== - * @async - * - * @param {object} params - Single Param object containing params - * @param {String} [params.key] - API Key - * @param {String} [params.database]- Target Database slug - * @param {http.ServerResponse} [params.response] - Http response object - * @param {http.IncomingMessage} [params.request] - Http request object - * @param {("deep" | "normal")} [params.level] - Authentication level - * @param {String} [params.encryptionKey] - Encryption Key - * @param {String} [params.encryptionSalt] - Encryption Salt - * @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object - * @param {string} [params.encryptedUserString] - encrypted user string to use instead of getting from cookie header - * @param {string | number} [params.user_id] - User ID - * @param {boolean} [params.useLocal] - * - * @returns { Promise } + * # Reauthorize User */ -async function reauthUser({ +export default async function reauthUser({ key, database, response, @@ -60,7 +43,7 @@ async function reauthUser({ encryptedUserString, user_id, useLocal, -}) { +}: Param): Promise { /** * Check Encryption Keys * @@ -112,7 +95,9 @@ async function reauthUser({ useLocal ) { /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ - let dbSchema; + let dbSchema: + | import("../package-shared/types").DSQL_DatabaseSchemaType + | undefined; try { const localDbSchemaPath = path.resolve( @@ -133,7 +118,7 @@ async function reauthUser({ * * @description make a request to datasquirel.com */ - httpResponse = await new Promise((resolve, reject) => { + httpResponse = (await new Promise((resolve, reject) => { const reqPayload = JSON.stringify({ existingUser: existingUser.payload, database, @@ -182,13 +167,9 @@ async function reauthUser({ httpsRequest.write(reqPayload); httpsRequest.end(); - }); + })) as APILoginFunctionReturn; } - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ - /** * Make https request * @@ -226,15 +207,5 @@ async function reauthUser({ } } - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ - return httpResponse; } - -/** ********************************************** */ -/** ********************************************** */ -/** ********************************************** */ - -module.exports = reauthUser; diff --git a/users/send-email-code.d.ts b/users/send-email-code.d.ts deleted file mode 100644 index aed507e..0000000 --- a/users/send-email-code.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -export = sendEmailCode; -/** - * Send Email Code to a User - * ============================================================================== - * @async - * - * @param {object} params - Single Param object containing params - * @param {String} [params.key] - FULL ACCESS API Key - * @param {String} [params.database] - Target Database - * @param {string} params.email Login Email/Username and Password - * @param {string} [params.temp_code_field_name] - Database table field name for temporary code - * @param {http.ServerResponse & Object} [params.response] - * @param {string} [params.mail_domain] - * @param {string} [params.mail_username] - * @param {string} [params.mail_password] - * @param {number} [params.mail_port] - * @param {string} [params.sender] - * @param {boolean} [params.user_id] - User ID - * @param {boolean} [params.useLocal] - * @param {import("../package-shared/types").CookieObject[]} [params.extraCookies] - * - * @returns { Promise} - */ -declare function sendEmailCode({ key, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, user_id, useLocal, response, extraCookies, }: { - key?: string; - database?: string; - email: string; - temp_code_field_name?: string; - response?: http.ServerResponse & { - [x: string]: any; - }; - mail_domain?: string; - mail_username?: string; - mail_password?: string; - mail_port?: number; - sender?: string; - user_id?: boolean; - useLocal?: boolean; - extraCookies?: import("../package-shared/types").CookieObject[]; -}): Promise; -import http = require("http"); diff --git a/users/send-email-code.js b/users/send-email-code.js deleted file mode 100644 index 8c5fe78..0000000 --- a/users/send-email-code.js +++ /dev/null @@ -1,172 +0,0 @@ -// @ts-check - -const http = require("http"); -const fs = require("fs"); -const path = require("path"); -const grabHostNames = require("../package-shared/utils/grab-host-names"); -const apiSendEmailCode = require("../package-shared/functions/api/users/api-send-email-code"); - -/** - * Send Email Code to a User - * ============================================================================== - * @async - * - * @param {object} params - Single Param object containing params - * @param {String} [params.key] - FULL ACCESS API Key - * @param {String} [params.database] - Target Database - * @param {string} params.email Login Email/Username and Password - * @param {string} [params.temp_code_field_name] - Database table field name for temporary code - * @param {http.ServerResponse & Object} [params.response] - * @param {string} [params.mail_domain] - * @param {string} [params.mail_username] - * @param {string} [params.mail_password] - * @param {number} [params.mail_port] - * @param {string} [params.sender] - * @param {boolean} [params.user_id] - User ID - * @param {boolean} [params.useLocal] - * @param {import("../package-shared/types").CookieObject[]} [params.extraCookies] - * - * @returns { Promise} - */ -async function sendEmailCode({ - key, - email, - database, - temp_code_field_name, - mail_domain, - mail_password, - mail_username, - mail_port, - sender, - user_id, - useLocal, - response, - extraCookies, -}) { - const grabedHostNames = grabHostNames(); - const { host, port, scheme } = grabedHostNames; - - const defaultTempLoginFieldName = "temp_login_code"; - const emailLoginTempCodeFieldName = temp_code_field_name - ? temp_code_field_name - : defaultTempLoginFieldName; - - const emailHtml = fs.readFileSync( - path.resolve(__dirname, "../package-shared/html/one-time-code.html"), - "utf-8" - ); - - /** - * Check for local DB settings - * - * @description Look for local db settings in `.env` file and by pass the http request if available - */ - const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = - process.env; - - if ( - DSQL_DB_HOST?.match(/./) && - DSQL_DB_USERNAME?.match(/./) && - DSQL_DB_PASSWORD?.match(/./) && - DSQL_DB_NAME?.match(/./) && - useLocal - ) { - /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ - let dbSchema; - - try { - const localDbSchemaPath = path.resolve( - process.cwd(), - "dsql.schema.json" - ); - dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8")); - } catch (error) {} - - return await apiSendEmailCode({ - database: DSQL_DB_NAME, - email, - email_login_field: emailLoginTempCodeFieldName, - html: emailHtml, - mail_domain, - mail_password, - mail_port, - mail_username, - sender, - useLocal, - response, - extraCookies, - }); - } else { - /** - * Make https request - * - * @description make a request to datasquirel.com - * - * @type {import("../package-shared/types").SendOneTimeCodeEmailResponse} - */ - const httpResponse = await new Promise((resolve, reject) => { - const reqPayload = JSON.stringify({ - email, - database, - email_login_field: emailLoginTempCodeFieldName, - mail_domain, - mail_password, - mail_username, - mail_port, - sender, - html: emailHtml, - }); - - const httpsRequest = scheme.request( - { - method: "POST", - headers: { - "Content-Type": "application/json", - "Content-Length": Buffer.from(reqPayload).length, - Authorization: - key || - process.env.DSQL_FULL_ACCESS_API_KEY || - process.env.DSQL_API_KEY, - }, - port, - hostname: host, - path: `/api/user/${ - user_id || grabedHostNames.user_id - }/send-email-code`, - }, - - /** - * Callback Function - * - * @description https request callback - */ - (res) => { - var str = ""; - - res.on("data", function (chunk) { - str += chunk; - }); - - res.on("end", function () { - resolve(JSON.parse(str)); - }); - - res.on("error", (err) => { - reject(err); - }); - } - ); - - httpsRequest.write(reqPayload); - httpsRequest.end(); - }); - - return httpResponse; - } -} - -/** ********************************************** */ -/** ********************************************** */ -/** ********************************************** */ - -module.exports = sendEmailCode; diff --git a/users/send-email-code.ts b/users/send-email-code.ts new file mode 100644 index 0000000..f675a75 --- /dev/null +++ b/users/send-email-code.ts @@ -0,0 +1,165 @@ +import http from "http"; +import fs from "fs"; +import path from "path"; +import grabHostNames from "../package-shared/utils/grab-host-names"; +import apiSendEmailCode from "../package-shared/functions/api/users/api-send-email-code"; +import { SendOneTimeCodeEmailResponse } from "../package-shared/types"; + +type Param = { + key?: string; + database?: string; + email: string; + temp_code_field_name?: string; + response?: http.ServerResponse & { [s: string]: any }; + mail_domain?: string; + mail_username?: string; + mail_password?: string; + mail_port?: number; + sender?: string; + user_id?: boolean; + useLocal?: boolean; + extraCookies?: import("../package-shared/types").CookieObject[]; +}; + +/** + * # Send Email Code to a User + */ +export default async function sendEmailCode({ + key, + email, + database, + temp_code_field_name, + mail_domain, + mail_password, + mail_username, + mail_port, + sender, + user_id, + useLocal, + response, + extraCookies, +}: Param): Promise { + const grabedHostNames = grabHostNames(); + const { host, port, scheme } = grabedHostNames; + + const defaultTempLoginFieldName = "temp_login_code"; + const emailLoginTempCodeFieldName = temp_code_field_name + ? temp_code_field_name + : defaultTempLoginFieldName; + + const emailHtml = fs.readFileSync( + path.resolve(__dirname, "../package-shared/html/one-time-code.html"), + "utf-8" + ); + + /** + * Check for local DB settings + * + * @description Look for local db settings in `.env` file and by pass the http request if available + */ + const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = + process.env; + + if ( + DSQL_DB_HOST?.match(/./) && + DSQL_DB_USERNAME?.match(/./) && + DSQL_DB_PASSWORD?.match(/./) && + DSQL_DB_NAME?.match(/./) && + useLocal + ) { + /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ + let dbSchema: + | import("../package-shared/types").DSQL_DatabaseSchemaType + | undefined; + + try { + const localDbSchemaPath = path.resolve( + process.cwd(), + "dsql.schema.json" + ); + dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8")); + } catch (error) {} + + return await apiSendEmailCode({ + database: DSQL_DB_NAME, + email, + email_login_field: emailLoginTempCodeFieldName, + html: emailHtml, + mail_domain, + mail_password, + mail_port, + mail_username, + sender, + useLocal, + response, + extraCookies, + }); + } else { + /** + * Make https request + * + * @description make a request to datasquirel.com + * + * @type {import("../package-shared/types").SendOneTimeCodeEmailResponse} + */ + const httpResponse: import("../package-shared/types").SendOneTimeCodeEmailResponse = + await new Promise((resolve, reject) => { + const reqPayload = JSON.stringify({ + email, + database, + email_login_field: emailLoginTempCodeFieldName, + mail_domain, + mail_password, + mail_username, + mail_port, + sender, + html: emailHtml, + }); + + const httpsRequest = scheme.request( + { + method: "POST", + headers: { + "Content-Type": "application/json", + "Content-Length": Buffer.from(reqPayload).length, + Authorization: + key || + process.env.DSQL_FULL_ACCESS_API_KEY || + process.env.DSQL_API_KEY, + }, + port, + hostname: host, + path: `/api/user/${ + user_id || grabedHostNames.user_id + }/send-email-code`, + }, + + /** + * Callback Function + * + * @description https request callback + */ + (res) => { + var str = ""; + + res.on("data", function (chunk) { + str += chunk; + }); + + res.on("end", function () { + resolve(JSON.parse(str)); + }); + + res.on("error", (err) => { + reject(err); + }); + } + ); + + httpsRequest.write(reqPayload); + httpsRequest.end(); + }); + + return httpResponse; + } +} diff --git a/users/social/github-auth.d.ts b/users/social/github-auth.d.ts deleted file mode 100644 index a730c63..0000000 --- a/users/social/github-auth.d.ts +++ /dev/null @@ -1,80 +0,0 @@ -export = githubAuth; -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** - * @typedef {object} FunctionReturn - * @property {boolean} success - Did the function run successfully? - * @property {{id: number, first_name: string, last_name: string, csrf_k: string, social_id: string} | null} user - Returned User - * @property {number} [dsqlUserId] - Dsql User Id - * @property {string} [msg] - Response message - */ -/** - * SERVER FUNCTION: Login with google Function - * ============================================================================== - * - * @async - * - * @param {object} params - main params object - * @param {string} params.key - API full access key - * @param {string} params.code - Github access code gotten from the client side - * @param {string?} params.email - Email gotten from the client side if available - * @param {string} params.database - Target database name(slug) - * @param {string} params.clientId - Github client id - * @param {string} params.clientSecret - Github client Secret - * @param {http.ServerResponse} params.response - HTTPS response object - * @param {string} params.encryptionKey - Encryption key - * @param {string} params.encryptionSalt - Encryption salt - * @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object - * @param {Object} [params.additionalData] - Additional Data to by added on creation of User - * @param {boolean} [params.user_id] - User ID - * - * @returns { Promise } - */ -declare function githubAuth({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, }: { - key: string; - code: string; - email: string | null; - database: string; - clientId: string; - clientSecret: string; - response: http.ServerResponse; - encryptionKey: string; - encryptionSalt: string; - additionalFields?: string[]; - additionalData?: { - [x: string]: string | number; - }; - user_id?: boolean; -}): Promise; -declare namespace githubAuth { - export { FunctionReturn }; -} -import http = require("http"); -type FunctionReturn = { - /** - * - Did the function run successfully? - */ - success: boolean; - /** - * - Returned User - */ - user: { - id: number; - first_name: string; - last_name: string; - csrf_k: string; - social_id: string; - } | null; - /** - * - Dsql User Id - */ - dsqlUserId?: number; - /** - * - Response message - */ - msg?: string; -}; diff --git a/users/social/github-auth.js b/users/social/github-auth.ts similarity index 62% rename from users/social/github-auth.js rename to users/social/github-auth.ts index 8d5be85..1f9f523 100644 --- a/users/social/github-auth.js +++ b/users/social/github-auth.ts @@ -1,56 +1,42 @@ -// @ts-check +import http from "http"; +import fs from "fs"; +import path from "path"; +import encrypt from "../../package-shared/functions/dsql/encrypt"; +import grabHostNames from "../../package-shared/utils/grab-host-names"; +import apiGithubLogin from "../../package-shared/functions/api/users/social/api-github-login"; + +interface FunctionReturn { + success: boolean; + user: { + id: number; + first_name: string; + last_name: string; + csrf_k: string; + social_id: string; + } | null; + dsqlUserId?: number; + msg?: string; +} + +type Param = { + key: string; + code: string; + email: string | null; + database: string; + clientId: string; + clientSecret: string; + response: http.ServerResponse; + encryptionKey: string; + encryptionSalt: string; + additionalFields?: string[]; + additionalData?: { [s: string]: string | number }; + user_id?: boolean; +}; /** - * ============================================================================== - * Imports - * ============================================================================== + * # SERVER FUNCTION: Login with google Function */ -const http = require("http"); -const https = require("https"); -const fs = require("fs"); -const path = require("path"); -const encrypt = require("../../package-shared/functions/dsql/encrypt"); -const grabHostNames = require("../../package-shared/utils/grab-host-names"); -const apiGithubLogin = require("../../package-shared/functions/api/users/social/api-github-login"); - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - -/** - * @typedef {object} FunctionReturn - * @property {boolean} success - Did the function run successfully? - * @property {{id: number, first_name: string, last_name: string, csrf_k: string, social_id: string} | null} user - Returned User - * @property {number} [dsqlUserId] - Dsql User Id - * @property {string} [msg] - Response message - */ - -/** - * SERVER FUNCTION: Login with google Function - * ============================================================================== - * - * @async - * - * @param {object} params - main params object - * @param {string} params.key - API full access key - * @param {string} params.code - Github access code gotten from the client side - * @param {string?} params.email - Email gotten from the client side if available - * @param {string} params.database - Target database name(slug) - * @param {string} params.clientId - Github client id - * @param {string} params.clientSecret - Github client Secret - * @param {http.ServerResponse} params.response - HTTPS response object - * @param {string} params.encryptionKey - Encryption key - * @param {string} params.encryptionSalt - Encryption salt - * @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object - * @param {Object} [params.additionalData] - Additional Data to by added on creation of User - * @param {boolean} [params.user_id] - User ID - * - * @returns { Promise } - */ -async function githubAuth({ +export default async function githubAuth({ key, code, email, @@ -63,7 +49,7 @@ async function githubAuth({ additionalFields, user_id, additionalData, -}) { +}: Param): Promise { /** * Check inputs * @@ -96,10 +82,6 @@ async function githubAuth({ }; } - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - /** * Initialize HTTP response variable */ @@ -127,7 +109,10 @@ async function githubAuth({ DSQL_DB_NAME?.match(/./) ) { /** @type {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined | undefined} */ - let dbSchema; + let dbSchema: + | import("../../package-shared/types").DSQL_DatabaseSchemaType + | undefined + | undefined; try { const localDbSchemaPath = path.resolve( @@ -153,7 +138,7 @@ async function githubAuth({ * @description make a request to datasquirel.com * @type {FunctionReturn} - Https response object */ - httpResponse = await new Promise((resolve, reject) => { + httpResponse = (await new Promise((resolve, reject) => { const reqPayload = JSON.stringify({ code, email, @@ -215,7 +200,7 @@ async function githubAuth({ ); httpsRequest.write(reqPayload); httpsRequest.end(); - }); + })) as any; } //////////////////////////////////////// @@ -247,15 +232,5 @@ async function githubAuth({ ]); } - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - return httpResponse; } - -//////////////////////////////////////// -//////////////////////////////////////// -//////////////////////////////////////// - -module.exports = githubAuth; diff --git a/users/social/google-auth.d.ts b/users/social/google-auth.d.ts deleted file mode 100644 index 6e96284..0000000 --- a/users/social/google-auth.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -export = googleAuth; -/** - * SERVER FUNCTION: Login with google Function - * ============================================================================== - * - * @async - * - * @param {object} params - main params object - * @param {string} [params.key] - API full access key - * @param {string} params.token - Google access token gotten from the client side - * @param {string} [params.database] - Target database name - * @param {http.ServerResponse} [params.response] - HTTPS response object - * @param {string} [params.encryptionKey] - Encryption key - * @param {string} [params.encryptionSalt] - Encryption salt - * @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object - * @param {Object} [params.additionalData] - Additional Data to by added on creation of User - * @param {string | number} [params.apiUserID] - API user ID - * @param {boolean} [params.useLocal] - Whether to use a remote database instead of API - * - * @returns { Promise } - */ -declare function googleAuth({ key, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, apiUserID, useLocal, }: { - key?: string; - token: string; - database?: string; - response?: http.ServerResponse; - encryptionKey?: string; - encryptionSalt?: string; - additionalFields?: string[]; - additionalData?: { - [x: string]: string | number; - }; - apiUserID?: string | number; - useLocal?: boolean; -}): Promise; -import http = require("http"); diff --git a/users/social/google-auth.js b/users/social/google-auth.ts similarity index 73% rename from users/social/google-auth.js rename to users/social/google-auth.ts index 7150fe7..f9ac610 100644 --- a/users/social/google-auth.js +++ b/users/social/google-auth.ts @@ -1,35 +1,28 @@ -// @ts-check +import http from "http"; +import encrypt from "../../package-shared/functions/dsql/encrypt"; +import grabHostNames from "../../package-shared/utils/grab-host-names"; +import apiGoogleLogin from "../../package-shared/functions/api/users/social/api-google-login"; +import getAuthCookieNames from "../../package-shared/functions/backend/cookies/get-auth-cookie-names"; +import { writeAuthFile } from "../../package-shared/functions/backend/auth/write-auth-files"; +import { APILoginFunctionReturn } from "../../package-shared/types"; -const http = require("http"); -const encrypt = require("../../package-shared/functions/dsql/encrypt"); -const grabHostNames = require("../../package-shared/utils/grab-host-names"); -const apiGoogleLogin = require("../../package-shared/functions/api/users/social/api-google-login"); -const getAuthCookieNames = require("../../package-shared/functions/backend/cookies/get-auth-cookie-names"); -const { - writeAuthFile, -} = require("../../package-shared/functions/backend/auth/write-auth-files"); +type Param = { + key?: string; + token: string; + database?: string; + response?: http.ServerResponse; + encryptionKey?: string; + encryptionSalt?: string; + additionalFields?: string[]; + additionalData?: { [s: string]: string | number }; + apiUserID?: string | number; + useLocal?: boolean; +}; /** - * SERVER FUNCTION: Login with google Function - * ============================================================================== - * - * @async - * - * @param {object} params - main params object - * @param {string} [params.key] - API full access key - * @param {string} params.token - Google access token gotten from the client side - * @param {string} [params.database] - Target database name - * @param {http.ServerResponse} [params.response] - HTTPS response object - * @param {string} [params.encryptionKey] - Encryption key - * @param {string} [params.encryptionSalt] - Encryption salt - * @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object - * @param {Object} [params.additionalData] - Additional Data to by added on creation of User - * @param {string | number} [params.apiUserID] - API user ID - * @param {boolean} [params.useLocal] - Whether to use a remote database instead of API - * - * @returns { Promise } + * # SERVER FUNCTION: Login with google Function */ -async function googleAuth({ +export default async function googleAuth({ key, token, database, @@ -40,7 +33,7 @@ async function googleAuth({ additionalData, apiUserID, useLocal, -}) { +}: Param): Promise { const grabedHostNames = grabHostNames(); const { host, port, scheme } = grabedHostNames; @@ -85,9 +78,10 @@ async function googleAuth({ */ /** @type {import("../../package-shared/types").APILoginFunctionReturn} */ - let httpResponse = { - success: false, - }; + let httpResponse: import("../../package-shared/types").APILoginFunctionReturn = + { + success: false, + }; /** * Check for local DB settings @@ -207,5 +201,3 @@ async function googleAuth({ return httpResponse; } - -module.exports = googleAuth; diff --git a/users/update-user.d.ts b/users/update-user.d.ts deleted file mode 100644 index 1fe448a..0000000 --- a/users/update-user.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -export = updateUser; -/** - * # Update User - * @async - * - * @param {object} params - API Key - * @param {String} [params.key] - API Key - * @param {String} [params.database] - Target Database - * @param {String | number} params.updatedUserId - Target Database - * @param {Object.} params.payload - User Object: ID is required - * @param {boolean} [params.user_id] - User ID - * @param {boolean} [params.useLocal] - * - * @returns { Promise} - */ -declare function updateUser({ key, payload, database, user_id, useLocal, updatedUserId, }: { - key?: string; - database?: string; - updatedUserId: string | number; - payload: { - [x: string]: any; - }; - user_id?: boolean; - useLocal?: boolean; -}): Promise; diff --git a/users/update-user.js b/users/update-user.ts similarity index 67% rename from users/update-user.js rename to users/update-user.ts index e12aae0..771d8db 100644 --- a/users/update-user.js +++ b/users/update-user.ts @@ -1,34 +1,29 @@ -// @ts-check +import path from "path"; +import fs from "fs"; +import grabHostNames from "../package-shared/utils/grab-host-names"; +import apiUpdateUser from "../package-shared/functions/api/users/api-update-user"; +import { UpdateUserFunctionReturn } from "../package-shared/types"; -const http = require("http"); -const https = require("https"); -const path = require("path"); -const fs = require("fs"); -const grabHostNames = require("../package-shared/utils/grab-host-names"); -const apiUpdateUser = require("../package-shared/functions/api/users/api-update-user"); +type Param = { + key?: string; + database?: string; + updatedUserId: string | number; + payload: { [s: string]: any }; + user_id?: boolean; + useLocal?: boolean; +}; /** * # Update User - * @async - * - * @param {object} params - API Key - * @param {String} [params.key] - API Key - * @param {String} [params.database] - Target Database - * @param {String | number} params.updatedUserId - Target Database - * @param {Object.} params.payload - User Object: ID is required - * @param {boolean} [params.user_id] - User ID - * @param {boolean} [params.useLocal] - * - * @returns { Promise} */ -async function updateUser({ +export default async function updateUser({ key, payload, database, user_id, useLocal, updatedUserId, -}) { +}: Param): Promise { /** * Check for local DB settings * @@ -48,7 +43,9 @@ async function updateUser({ useLocal ) { /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ - let dbSchema; + let dbSchema: + | import("../package-shared/types").DSQL_DatabaseSchemaType + | undefined; try { const localDbSchemaPath = path.resolve( @@ -122,15 +119,5 @@ async function updateUser({ httpsRequest.end(); }); - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ - - return httpResponse; + return httpResponse as UpdateUserFunctionReturn; } - -/** ********************************************** */ -/** ********************************************** */ -/** ********************************************** */ - -module.exports = updateUser; diff --git a/users/user-auth.d.ts b/users/user-auth.d.ts deleted file mode 100644 index 1e44a8d..0000000 --- a/users/user-auth.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -export = userAuth; -/** - * Authenticate User from request - * ============================================================================== - * @description This Function takes in a request object and returns a user object - * with the user's data - * - * @param {Object} params - Arg - * @param {http.IncomingMessage & Object} [params.request] - Http request object - * @param {http.IncomingMessage & Object} [params.req] - Http request object - * @param {string} [params.cookieString] - * @param {string} [params.encryptedUserString] - Encrypted user string to use instead of getting from cookie header - * @param {string} [params.encryptionKey] - Encryption Key: alt env: DSQL_ENCRYPTION_PASSWORD - * @param {string} [params.encryptionSalt] - Encryption Salt: alt env: DSQL_ENCRYPTION_SALT - * @param {("deep" | "normal")} [params.level] - Optional. "Deep" value indicates an extra layer of security - * @param {string} [params.database] - Database Name (slug) - * @param {string | number} [params.dsqlUserId] - alt env: DSQL_API_USER_ID - * @param {number} [params.expiry] - Expiry time in milliseconds - * @param {string} [params.csrfHeaderName] - Optional. CSRF Header Name - * @param {boolean} [params.csrfHeaderIsValue] - If the csrf value is the name of the request http header - * - * @returns { import("../package-shared/types").AuthenticatedUser } - */ -declare function userAuth({ request, req, encryptionKey, encryptionSalt, level, database, dsqlUserId, encryptedUserString, expiry, cookieString, csrfHeaderIsValue, csrfHeaderName, }: { - request?: http.IncomingMessage & { - [x: string]: any; - }; - req?: http.IncomingMessage & { - [x: string]: any; - }; - cookieString?: string; - encryptedUserString?: string; - encryptionKey?: string; - encryptionSalt?: string; - level?: ("deep" | "normal"); - database?: string; - dsqlUserId?: string | number; - expiry?: number; - csrfHeaderName?: string; - csrfHeaderIsValue?: boolean; -}): import("../package-shared/types").AuthenticatedUser; -import http = require("http"); diff --git a/users/user-auth.js b/users/user-auth.ts similarity index 72% rename from users/user-auth.js rename to users/user-auth.ts index 671c084..512de9f 100644 --- a/users/user-auth.js +++ b/users/user-auth.ts @@ -1,12 +1,11 @@ // @ts-check -const http = require("http"); -const decrypt = require("../package-shared/functions/dsql/decrypt"); -const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names"); -const { - checkAuthFile, -} = require("../package-shared/functions/backend/auth/write-auth-files"); -const parseCookies = require("../package-shared/utils/backend/parseCookies"); +import http from "http"; +import decrypt from "../package-shared/functions/dsql/decrypt"; +import getAuthCookieNames from "../package-shared/functions/backend/cookies/get-auth-cookie-names"; +import { checkAuthFile } from "../package-shared/functions/backend/auth/write-auth-files"; +import parseCookies from "../package-shared/utils/backend/parseCookies"; +import { AuthenticatedUser } from "../package-shared/types"; const minuteInMilliseconds = 60000; const hourInMilliseconds = minuteInMilliseconds * 60; @@ -15,29 +14,28 @@ const weekInMilliseconds = dayInMilliseconds * 7; const monthInMilliseconds = dayInMilliseconds * 30; const yearInMilliseconds = dayInMilliseconds * 365; +type Param = { + request?: http.IncomingMessage & { [s: string]: any }; + req?: http.IncomingMessage & { [s: string]: any }; + cookieString?: string; + encryptedUserString?: string; + encryptionKey?: string; + encryptionSalt?: string; + level?: "deep" | "normal"; + database?: string; + dsqlUserId?: string | number; + expiry?: number; + csrfHeaderName?: string; + csrfHeaderIsValue?: boolean; +}; + /** * Authenticate User from request * ============================================================================== * @description This Function takes in a request object and returns a user object * with the user's data - * - * @param {Object} params - Arg - * @param {http.IncomingMessage & Object} [params.request] - Http request object - * @param {http.IncomingMessage & Object} [params.req] - Http request object - * @param {string} [params.cookieString] - * @param {string} [params.encryptedUserString] - Encrypted user string to use instead of getting from cookie header - * @param {string} [params.encryptionKey] - Encryption Key: alt env: DSQL_ENCRYPTION_PASSWORD - * @param {string} [params.encryptionSalt] - Encryption Salt: alt env: DSQL_ENCRYPTION_SALT - * @param {("deep" | "normal")} [params.level] - Optional. "Deep" value indicates an extra layer of security - * @param {string} [params.database] - Database Name (slug) - * @param {string | number} [params.dsqlUserId] - alt env: DSQL_API_USER_ID - * @param {number} [params.expiry] - Expiry time in milliseconds - * @param {string} [params.csrfHeaderName] - Optional. CSRF Header Name - * @param {boolean} [params.csrfHeaderIsValue] - If the csrf value is the name of the request http header - * - * @returns { import("../package-shared/types").AuthenticatedUser } */ -function userAuth({ +export default function userAuth({ request, req, encryptionKey, @@ -50,7 +48,7 @@ function userAuth({ cookieString, csrfHeaderIsValue, csrfHeaderName, -}) { +}: Param): AuthenticatedUser { try { const finalRequest = req || request; @@ -108,7 +106,8 @@ function userAuth({ */ /** @type {import("../package-shared/types").DATASQUIREL_LoggedInUser} */ - let userObject = JSON.parse(userPayloadJSON); + let userObject: import("../package-shared/types").DATASQUIREL_LoggedInUser = + JSON.parse(userPayloadJSON); if (!userObject.csrf_k) { return { @@ -192,7 +191,7 @@ function userAuth({ success: true, payload: userObject, }; - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { /** * Return User Object * @@ -205,5 +204,3 @@ function userAuth({ }; } } - -module.exports = userAuth; diff --git a/users/validate-temp-email-code.d.ts b/users/validate-temp-email-code.d.ts deleted file mode 100644 index 83794d7..0000000 --- a/users/validate-temp-email-code.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -export = validateTempEmailCode; -/** - * Verify the temp email code sent to the user's email address - * ============================================================================== - * @async - * - * @param {object} params - Single Param object containing params - * @param {http.IncomingMessage & Object} [params.request] - * @param {string} [params.cookieString] - * @param {string} [params.email] - * - * @returns { Promise} - */ -declare function validateTempEmailCode({ request, email, cookieString }: { - request?: http.IncomingMessage & { - [x: string]: any; - }; - cookieString?: string; - email?: string; -}): Promise; -import http = require("http"); diff --git a/users/validate-temp-email-code.js b/users/validate-temp-email-code.js deleted file mode 100644 index 7b0c3e5..0000000 --- a/users/validate-temp-email-code.js +++ /dev/null @@ -1,53 +0,0 @@ -// @ts-check - -const http = require("http"); -const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names"); -const parseCookies = require("../package-shared/utils/backend/parseCookies"); -const decrypt = require("../package-shared/functions/dsql/decrypt"); -const EJSON = require("../package-shared/utils/ejson"); - -/** - * Verify the temp email code sent to the user's email address - * ============================================================================== - * @async - * - * @param {object} params - Single Param object containing params - * @param {http.IncomingMessage & Object} [params.request] - * @param {string} [params.cookieString] - * @param {string} [params.email] - * - * @returns { Promise} - */ -async function validateTempEmailCode({ request, email, cookieString }) { - try { - const keyNames = getAuthCookieNames(); - const oneTimeCodeCookieName = keyNames.oneTimeCodeName; - - const cookies = parseCookies({ request, cookieString }); - const encryptedOneTimeCode = cookies[oneTimeCodeCookieName]; - - const encryptedPayload = decrypt({ - encryptedString: encryptedOneTimeCode, - }); - - const payload = - /** @type {import("../package-shared/types").SendOneTimeCodeEmailResponse | undefined} */ ( - EJSON.parse(encryptedPayload) - ); - - if (payload?.email && !email) { - return payload; - } - - if (payload?.email && payload.email === email) { - return payload; - } - - return null; - } catch (/** @type {any} */ error) { - console.log("validateTempEmailCode error:", error.message); - return null; - } -} - -module.exports = validateTempEmailCode; diff --git a/users/validate-temp-email-code.ts b/users/validate-temp-email-code.ts new file mode 100644 index 0000000..5335b71 --- /dev/null +++ b/users/validate-temp-email-code.ts @@ -0,0 +1,50 @@ +import http from "http"; +import getAuthCookieNames from "../package-shared/functions/backend/cookies/get-auth-cookie-names"; +import parseCookies from "../package-shared/utils/backend/parseCookies"; +import decrypt from "../package-shared/functions/dsql/decrypt"; +import EJSON from "../package-shared/utils/ejson"; +import { SendOneTimeCodeEmailResponse } from "../package-shared/types"; + +type Param = { + request?: http.IncomingMessage & { [s: string]: any }; + cookieString?: string; + email?: string; +}; + +/** + * # Verify the temp email code sent to the user's email address + */ +export default async function validateTempEmailCode({ + request, + email, + cookieString, +}: Param): Promise { + try { + const keyNames = getAuthCookieNames(); + const oneTimeCodeCookieName = keyNames.oneTimeCodeName; + + const cookies = parseCookies({ request, cookieString }); + const encryptedOneTimeCode = cookies[oneTimeCodeCookieName]; + + const encryptedPayload = decrypt({ + encryptedString: encryptedOneTimeCode, + }); + + const payload = EJSON.parse(encryptedPayload) as + | SendOneTimeCodeEmailResponse + | undefined; + + if (payload?.email && !email) { + return payload; + } + + if (payload?.email && payload.email === email) { + return payload; + } + + return null; + } catch (error: any) { + console.log("validateTempEmailCode error:", error.message); + return null; + } +} diff --git a/users/validate-token.d.ts b/users/validate-token.d.ts deleted file mode 100644 index f52925c..0000000 --- a/users/validate-token.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -export = validateToken; -/** - * Validate Token - * ====================================== - * @description This Function takes in a encrypted token and returns a user object - * - * @param {Object} params - Arg - * @param {string} params.token - Encrypted Token - * @param {string} params.encryptionKey - Encryption Key - * @param {string} params.encryptionSalt - Encryption Salt - * @param {("deep" | "normal")?} [params.level] - Optional. "Deep" value indicates an extra layer of security - * @param {string} params.database - Database Name - * - * @returns { import("../package-shared/types").DATASQUIREL_LoggedInUser | null} - */ -declare function validateToken({ token, encryptionKey, encryptionSalt }: { - token: string; - encryptionKey: string; - encryptionSalt: string; - level?: ("deep" | "normal") | null; - database: string; -}): import("../package-shared/types").DATASQUIREL_LoggedInUser | null; diff --git a/users/validate-token.js b/users/validate-token.ts similarity index 62% rename from users/validate-token.js rename to users/validate-token.ts index 090a719..49bb4b4 100644 --- a/users/validate-token.js +++ b/users/validate-token.ts @@ -1,23 +1,25 @@ -// @ts-check +import http from "http"; +import decrypt from "../package-shared/functions/dsql/decrypt"; +import { DATASQUIREL_LoggedInUser } from "../package-shared/types"; -const http = require("http"); -const decrypt = require("../package-shared/functions/dsql/decrypt"); +type Param = { + token: string; + encryptionKey: string; + encryptionSalt: string; + level?: ("deep" | "normal") | null; + database: string; +}; /** * Validate Token * ====================================== * @description This Function takes in a encrypted token and returns a user object - * - * @param {Object} params - Arg - * @param {string} params.token - Encrypted Token - * @param {string} params.encryptionKey - Encryption Key - * @param {string} params.encryptionSalt - Encryption Salt - * @param {("deep" | "normal")?} [params.level] - Optional. "Deep" value indicates an extra layer of security - * @param {string} params.database - Database Name - * - * @returns { import("../package-shared/types").DATASQUIREL_LoggedInUser | null} */ -function validateToken({ token, encryptionKey, encryptionSalt }) { +export default function validateToken({ + token, + encryptionKey, + encryptionSalt, +}: Param): DATASQUIREL_LoggedInUser | null { try { /** * Grab the payload @@ -72,5 +74,3 @@ function validateToken({ token, encryptionKey, encryptionSalt }) { return null; } } - -module.exports = validateToken; diff --git a/utils/delete-file.d.ts b/utils/delete-file.d.ts deleted file mode 100644 index 1cb7cbe..0000000 --- a/utils/delete-file.d.ts +++ /dev/null @@ -1,46 +0,0 @@ -export = deleteFile; -/** - * @typedef {Object} FunctionReturn - * @property {boolean} success - Did the function run successfully? - * @property {{ - * urlPath: string, - * urlThumbnailPath: string - * } | null} payload - Payload containing the url for the image and its thumbnail - * @property {string} [msg] - An optional message - */ -/** - * # Delete File via API - * @async - * - * @param {Object} params - Single Param object containing params - * @param {String} params.key - *FULL ACCESS API Key - * @param { string } params.url - File URL - * @param { string | number } [params.user_id] - * - * @returns { Promise } - Image Url - */ -declare function deleteFile({ key, url, user_id }: { - key: string; - url: string; - user_id?: string | number; -}): Promise; -declare namespace deleteFile { - export { FunctionReturn }; -} -type FunctionReturn = { - /** - * - Did the function run successfully? - */ - success: boolean; - /** - * - Payload containing the url for the image and its thumbnail - */ - payload: { - urlPath: string; - urlThumbnailPath: string; - } | null; - /** - * - An optional message - */ - msg?: string; -}; diff --git a/utils/delete-file.js b/utils/delete-file.ts similarity index 67% rename from utils/delete-file.js rename to utils/delete-file.ts index a56cb04..872486f 100644 --- a/utils/delete-file.js +++ b/utils/delete-file.ts @@ -1,31 +1,28 @@ -// @ts-check +import grabHostNames from "../package-shared/utils/grab-host-names"; -const http = require("http"); -const https = require("https"); -const grabHostNames = require("../package-shared/utils/grab-host-names"); +interface Return { + success: boolean; + payload: { + urlPath: string; + urlThumbnailPath: string; + } | null; + msg?: string; +} -/** - * @typedef {Object} FunctionReturn - * @property {boolean} success - Did the function run successfully? - * @property {{ - * urlPath: string, - * urlThumbnailPath: string - * } | null} payload - Payload containing the url for the image and its thumbnail - * @property {string} [msg] - An optional message - */ +type Param = { + key: string; + url: string; + user_id?: string | number; +}; /** * # Delete File via API - * @async - * - * @param {Object} params - Single Param object containing params - * @param {String} params.key - *FULL ACCESS API Key - * @param { string } params.url - File URL - * @param { string | number } [params.user_id] - * - * @returns { Promise } - Image Url */ -async function deleteFile({ key, url, user_id }) { +export default async function deleteFile({ + key, + url, + user_id, +}: Param): Promise { const grabedHostNames = grabHostNames(); const { host, port, scheme } = grabedHostNames; @@ -82,8 +79,8 @@ async function deleteFile({ key, url, user_id }) { httpsRequest.end(); }); - return httpResponse; - } catch (/** @type {*} */ error) { + return httpResponse as Return; + } catch (/** @type {*} */ error: any) { console.log("Error deleting file: ", error.message); return { diff --git a/utils/get-schema.d.ts b/utils/get-schema.d.ts deleted file mode 100644 index 6e44e6b..0000000 --- a/utils/get-schema.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -export = getSchema; -/** - * @typedef {Object} GetSchemaReturn - * @property {boolean} success - Did the function run successfully? - * @property {import("../package-shared/types").DSQL_DatabaseSchemaType | import("../package-shared/types").DSQL_TableSchemaType | import("../package-shared/types").DSQL_FieldSchemaType | null} payload - Response payload - */ -/** - * # Get Schema for Database, table, or field * - * @param {import("../package-shared/types").GetSchemaAPIParam} params - * - * @returns { Promise } - Return Object - */ -declare function getSchema({ key, database, field, table, user_id }: import("../package-shared/types").GetSchemaAPIParam): Promise; -declare namespace getSchema { - export { GetSchemaReturn }; -} -type GetSchemaReturn = { - /** - * - Did the function run successfully? - */ - success: boolean; - /** - * - Response payload - */ - payload: import("../package-shared/types").DSQL_DatabaseSchemaType | import("../package-shared/types").DSQL_TableSchemaType | import("../package-shared/types").DSQL_FieldSchemaType | null; -}; diff --git a/utils/get-schema.js b/utils/get-schema.ts similarity index 56% rename from utils/get-schema.js rename to utils/get-schema.ts index 59b568e..023adb9 100644 --- a/utils/get-schema.js +++ b/utils/get-schema.ts @@ -1,22 +1,33 @@ // @ts-check -const http = require("http"); -const https = require("https"); -const grabHostNames = require("../package-shared/utils/grab-host-names"); +import grabHostNames from "../package-shared/utils/grab-host-names"; +import { + DSQL_DatabaseSchemaType, + DSQL_FieldSchemaType, + DSQL_TableSchemaType, + GetSchemaAPIParam, + GetSchemaRequestQuery, +} from "../package-shared/types"; -/** - * @typedef {Object} GetSchemaReturn - * @property {boolean} success - Did the function run successfully? - * @property {import("../package-shared/types").DSQL_DatabaseSchemaType | import("../package-shared/types").DSQL_TableSchemaType | import("../package-shared/types").DSQL_FieldSchemaType | null} payload - Response payload - */ +type GetSchemaReturn = { + success: boolean; + payload?: + | DSQL_DatabaseSchemaType + | DSQL_TableSchemaType + | DSQL_FieldSchemaType + | null; +}; /** * # Get Schema for Database, table, or field * - * @param {import("../package-shared/types").GetSchemaAPIParam} params - * - * @returns { Promise } - Return Object */ -async function getSchema({ key, database, field, table, user_id }) { +export default async function getSchema({ + key, + database, + field, + table, + user_id, +}: GetSchemaAPIParam): Promise { const grabedHostNames = grabHostNames(); const { host, port, scheme } = grabedHostNames; @@ -26,13 +37,10 @@ async function getSchema({ key, database, field, table, user_id }) { * @description make a request to datasquirel.com */ const httpResponse = await new Promise((resolve, reject) => { - /** @type {import("../package-shared/types").GetSchemaRequestQuery} */ - const queryObject = { database, field, table }; + const queryObject: GetSchemaRequestQuery = { database, field, table }; let query = Object.keys(queryObject) - // @ts-ignore - .filter((k) => queryObject[k]) - // @ts-ignore - .map((k) => `${k}=${queryObject[k]}`) + .filter((k) => queryObject[k as keyof GetSchemaRequestQuery]) + .map((k) => `${k}=${queryObject[k as keyof GetSchemaRequestQuery]}`) .join("&"); scheme @@ -67,18 +75,24 @@ async function getSchema({ key, database, field, table, user_id }) { }); response.on("end", function () { - resolve(JSON.parse(str)); + resolve( + JSON.parse(str) as + | DSQL_DatabaseSchemaType + | DSQL_TableSchemaType + | DSQL_FieldSchemaType + ); }); response.on("error", (err) => { - reject(err); + resolve(null); }); } ) .end(); }); - return httpResponse; + return { + success: true, + payload: httpResponse as any, + }; } - -module.exports = getSchema; diff --git a/utils/get.d.ts b/utils/get.d.ts deleted file mode 100644 index b18d2cb..0000000 --- a/utils/get.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -export = get; -/** - * Make a get request to Datasquirel API - * ============================================================================== - * @async - * - * @param {Object} params - Single object passed - * @param {string} [params.key] - API Key - * @param {string} [params.db] - Database Name - * @param {string} params.query - SQL Query - * @param {string[]} [params.queryValues] - An array of query values if using "?" placeholders - * @param {string} [params.tableName] - Name of the table to query - * @param {boolean} [params.useLocal] - Whether to use a remote database instead of API - * @param {string | number} [params.user_id] - User ID - * - * @returns { Promise } - Return Object - */ -declare function get({ key, db, query, queryValues, tableName, useLocal, user_id, }: { - key?: string; - db?: string; - query: string; - queryValues?: string[]; - tableName?: string; - useLocal?: boolean; - user_id?: string | number; -}): Promise; diff --git a/utils/get.js b/utils/get.ts similarity index 58% rename from utils/get.js rename to utils/get.ts index 537a7a9..4e2d71e 100644 --- a/utils/get.js +++ b/utils/get.ts @@ -1,29 +1,27 @@ // @ts-check -const https = require("node:https"); -const path = require("path"); -const fs = require("fs"); -const grabHostNames = require("../package-shared/utils/grab-host-names"); -const apiGet = require("../package-shared/functions/api/query/get"); -const serializeQuery = require("../package-shared/utils/serialize-query"); +import https from "node:https"; +import path from "path"; +import fs from "fs"; +import grabHostNames from "../package-shared/utils/grab-host-names"; +import apiGet from "../package-shared/functions/api/query/get"; +import serializeQuery from "../package-shared/utils/serialize-query"; +import { GetReturn } from "../package-shared/types"; + +type Param = { + key?: string; + db?: string; + query: string; + queryValues?: string[]; + tableName?: string; + useLocal?: boolean; + user_id?: string | number; +}; /** - * Make a get request to Datasquirel API - * ============================================================================== - * @async - * - * @param {Object} params - Single object passed - * @param {string} [params.key] - API Key - * @param {string} [params.db] - Database Name - * @param {string} params.query - SQL Query - * @param {string[]} [params.queryValues] - An array of query values if using "?" placeholders - * @param {string} [params.tableName] - Name of the table to query - * @param {boolean} [params.useLocal] - Whether to use a remote database instead of API - * @param {string | number} [params.user_id] - User ID - * - * @returns { Promise } - Return Object + * # Make a get request to Datasquirel API */ -async function get({ +export default async function get({ key, db, query, @@ -31,7 +29,7 @@ async function get({ tableName, useLocal, user_id, -}) { +}: Param): Promise { const grabedHostNames = grabHostNames(); const { host, port, scheme } = grabedHostNames; @@ -51,7 +49,9 @@ async function get({ useLocal ) { /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ - let dbSchema; + let dbSchema: + | import("../package-shared/types").DSQL_DatabaseSchemaType + | undefined; try { const localDbSchemaPath = path.resolve( @@ -78,14 +78,17 @@ async function get({ */ const httpResponse = await new Promise((resolve, reject) => { /** @type {import("../package-shared/types").GetReqQueryObject} */ - const queryObject = { - db: process.env.DSQL_API_DB_NAME || String(db), - query: String( - query.replace(/\n|\r|\n\r/g, "").replace(/ {2,}/g, " ") - ), - queryValues: queryValues ? JSON.stringify(queryValues) : undefined, - tableName, - }; + const queryObject: import("../package-shared/types").GetReqQueryObject = + { + db: process.env.DSQL_API_DB_NAME || String(db), + query: String( + query.replace(/\n|\r|\n\r/g, "").replace(/ {2,}/g, " ") + ), + queryValues: queryValues + ? JSON.stringify(queryValues) + : undefined, + tableName, + }; const queryString = serializeQuery({ ...queryObject }); @@ -94,7 +97,7 @@ async function get({ }/get${queryString}`; /** @type {https.RequestOptions} */ - const requestObject = { + const requestObject: https.RequestOptions = { method: "GET", headers: { "Content-Type": "application/json", @@ -127,8 +130,8 @@ async function get({ response.on("end", function () { try { - resolve(JSON.parse(str)); - } catch (/** @type {any} */ error) { + resolve(JSON.parse(str) as GetReturn); + } catch (/** @type {any} */ error: any) { reject({ error: error.message, result: str, @@ -138,22 +141,12 @@ async function get({ response.on("error", (err) => { console.log("DSQL get Error,", err.message); - reject(err); + resolve(null); }); } ) .end(); }); - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ - - return httpResponse; + return httpResponse as GetReturn; } - -/** ********************************************** */ -/** ********************************************** */ -/** ********************************************** */ - -module.exports = get; diff --git a/utils/post.d.ts b/utils/post.d.ts deleted file mode 100644 index 2377d8c..0000000 --- a/utils/post.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -export = post; -/** - * # Make a post request to Datasquirel API - * @async - * - * @param {Object} params - Single object passed - * @param {string} [params.key] - FULL ACCESS API Key - * @param {string} [params.database] - Database Name - * @param {import("../package-shared/types").PostDataPayload | string} params.query - SQL query String or Request Object - * @param {any[]} [params.queryValues] - Query Values if using "?" placeholders - * @param {string} [params.tableName] - Name of the table to query - * @param {boolean} [params.useLocal] - Whether to use a remote database instead of API - * @param {boolean} [params.user_id] - User ID - * - * @returns { Promise } - Return Object - */ -declare function post({ key, query, queryValues, database, tableName, useLocal, user_id, }: { - key?: string; - database?: string; - query: import("../package-shared/types").PostDataPayload | string; - queryValues?: any[]; - tableName?: string; - useLocal?: boolean; - user_id?: boolean; -}): Promise; diff --git a/utils/post.js b/utils/post.ts similarity index 72% rename from utils/post.js rename to utils/post.ts index bba67a7..c78f78b 100644 --- a/utils/post.js +++ b/utils/post.ts @@ -1,26 +1,25 @@ // @ts-check -const path = require("path"); -const fs = require("fs"); -const grabHostNames = require("../package-shared/utils/grab-host-names"); -const apiPost = require("../package-shared/functions/api/query/post"); +import path from "path"; +import fs from "fs"; +import grabHostNames from "../package-shared/utils/grab-host-names"; +import apiPost from "../package-shared/functions/api/query/post"; +import { PostDataPayload, PostReturn } from "../package-shared/types"; + +type Param = { + key?: string; + database?: string; + query: PostDataPayload; + queryValues?: any[]; + tableName?: string; + useLocal?: boolean; + user_id?: boolean; +}; /** * # Make a post request to Datasquirel API - * @async - * - * @param {Object} params - Single object passed - * @param {string} [params.key] - FULL ACCESS API Key - * @param {string} [params.database] - Database Name - * @param {import("../package-shared/types").PostDataPayload | string} params.query - SQL query String or Request Object - * @param {any[]} [params.queryValues] - Query Values if using "?" placeholders - * @param {string} [params.tableName] - Name of the table to query - * @param {boolean} [params.useLocal] - Whether to use a remote database instead of API - * @param {boolean} [params.user_id] - User ID - * - * @returns { Promise } - Return Object */ -async function post({ +export default async function post({ key, query, queryValues, @@ -28,7 +27,7 @@ async function post({ tableName, useLocal, user_id, -}) { +}: Param): Promise { const grabedHostNames = grabHostNames(); const { host, port, scheme } = grabedHostNames; @@ -48,7 +47,9 @@ async function post({ useLocal ) { /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ - let dbSchema; + let dbSchema: + | import("../package-shared/types").DSQL_DatabaseSchemaType + | undefined; try { const localDbSchemaPath = path.resolve( @@ -131,7 +132,7 @@ async function post({ response.on("end", function () { try { resolve(JSON.parse(str)); - } catch (/** @type {any} */ error) { + } catch (/** @type {any} */ error: any) { console.log("Route ERROR:", error.message); resolve({ @@ -162,15 +163,5 @@ async function post({ httpsRequest.end(); }); - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ - - return httpResponse; + return httpResponse as PostReturn; } - -/** ********************************************** */ -/** ********************************************** */ -/** ********************************************** */ - -module.exports = post; diff --git a/utils/upload-file.d.ts b/utils/upload-file.d.ts deleted file mode 100644 index 2971671..0000000 --- a/utils/upload-file.d.ts +++ /dev/null @@ -1,56 +0,0 @@ -export = uploadImage; -/** - * @typedef {Object} FunctionReturn - * @property {boolean} success - Did the function run successfully? - * @property {{ - * urlPath: string, - * } | null} payload - Payload containing the url for the image and its thumbnail - * @property {string} [msg] - An optional message - */ -/** - * # Upload File via API - * @async - * - * @param {Object} params - Single Param object containing params - * @param {String} params.key - *FULL ACCESS API Key - * @param {{ - * fileData: string, - * fileName: string, - * mimeType?: string, - * folder?: string, - * isPrivate?: boolean - * }} params.payload - Image Data Eg. - * @param {boolean} [params.user_id] - User ID - * - * @returns { Promise } - Return Object - */ -declare function uploadImage({ key, payload, user_id }: { - key: string; - payload: { - fileData: string; - fileName: string; - mimeType?: string; - folder?: string; - isPrivate?: boolean; - }; - user_id?: boolean; -}): Promise; -declare namespace uploadImage { - export { FunctionReturn }; -} -type FunctionReturn = { - /** - * - Did the function run successfully? - */ - success: boolean; - /** - * - Payload containing the url for the image and its thumbnail - */ - payload: { - urlPath: string; - } | null; - /** - * - An optional message - */ - msg?: string; -}; diff --git a/utils/upload-file.js b/utils/upload-file.ts similarity index 54% rename from utils/upload-file.js rename to utils/upload-file.ts index 20eb695..37f83ed 100644 --- a/utils/upload-file.js +++ b/utils/upload-file.ts @@ -1,36 +1,33 @@ -// @ts-check +import grabHostNames from "../package-shared/utils/grab-host-names"; -const http = require("http"); -const https = require("https"); -const grabHostNames = require("../package-shared/utils/grab-host-names"); +interface Return { + success: boolean; + payload: { + urlPath: string; + } | null; + msg?: string; +} -/** - * @typedef {Object} FunctionReturn - * @property {boolean} success - Did the function run successfully? - * @property {{ - * urlPath: string, - * } | null} payload - Payload containing the url for the image and its thumbnail - * @property {string} [msg] - An optional message - */ +type Param = { + key: string; + payload: { + fileData: string; + fileName: string; + mimeType?: string; + folder?: string; + isPrivate?: boolean; + }; + user_id?: boolean; +}; /** * # Upload File via API - * @async - * - * @param {Object} params - Single Param object containing params - * @param {String} params.key - *FULL ACCESS API Key - * @param {{ - * fileData: string, - * fileName: string, - * mimeType?: string, - * folder?: string, - * isPrivate?: boolean - * }} params.payload - Image Data Eg. - * @param {boolean} [params.user_id] - User ID - * - * @returns { Promise } - Return Object */ -async function uploadImage({ key, payload, user_id }) { +export default async function uploadImage({ + key, + payload, + user_id, +}: Param): Promise { const grabedHostNames = grabHostNames(); const { host, port, scheme } = grabedHostNames; @@ -87,16 +84,8 @@ async function uploadImage({ key, payload, user_id }) { httpsRequest.end(); }); - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ - - return httpResponse; - } catch (/** @type {*} */ error) { - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ - + return httpResponse as Return; + } catch (error: any) { console.log("Error in uploading file: ", error.message); return { @@ -106,9 +95,3 @@ async function uploadImage({ key, payload, user_id }) { }; } } - -/** ********************************************** */ -/** ********************************************** */ -/** ********************************************** */ - -module.exports = uploadImage; diff --git a/utils/upload-image.d.ts b/utils/upload-image.d.ts deleted file mode 100644 index a3d9f2b..0000000 --- a/utils/upload-image.d.ts +++ /dev/null @@ -1,60 +0,0 @@ -export = uploadImage; -/** - * @typedef {Object} FunctionReturn - * @property {boolean} success - Did the function run successfully? - * @property {{ - * urlPath: string, - * urlThumbnailPath: string - * } | null} payload - Payload containing the url for the image and its thumbnail - * @property {string} [msg] - An optional message - */ -/** - * # Upload Image via API - * @async - * - * @param {Object} params - Single Param object containing params - * @param {String} [params.key] - *FULL ACCESS API Key - * @param {{ - * imageData: string, - * imageName: string, - * mimeType?: string, - * thumbnailSize?: number, - * folder?: string, - * isPrivate?: boolean, - * }} params.payload - Image Data Eg. - * @param {boolean} [params.user_id] - User ID - * - * @returns { Promise } - Return Object - */ -declare function uploadImage({ key, payload, user_id }: { - key?: string; - payload: { - imageData: string; - imageName: string; - mimeType?: string; - thumbnailSize?: number; - folder?: string; - isPrivate?: boolean; - }; - user_id?: boolean; -}): Promise; -declare namespace uploadImage { - export { FunctionReturn }; -} -type FunctionReturn = { - /** - * - Did the function run successfully? - */ - success: boolean; - /** - * - Payload containing the url for the image and its thumbnail - */ - payload: { - urlPath: string; - urlThumbnailPath: string; - } | null; - /** - * - An optional message - */ - msg?: string; -}; diff --git a/utils/upload-image.js b/utils/upload-image.ts similarity index 55% rename from utils/upload-image.js rename to utils/upload-image.ts index 25fd128..c7145f8 100644 --- a/utils/upload-image.js +++ b/utils/upload-image.ts @@ -1,36 +1,37 @@ // @ts-check -const grabHostNames = require("../package-shared/utils/grab-host-names"); +import grabHostNames from "../package-shared/utils/grab-host-names"; -/** - * @typedef {Object} FunctionReturn - * @property {boolean} success - Did the function run successfully? - * @property {{ - * urlPath: string, - * urlThumbnailPath: string - * } | null} payload - Payload containing the url for the image and its thumbnail - * @property {string} [msg] - An optional message - */ +interface FunctionReturn { + success: boolean; + payload: { + urlPath: string; + urlThumbnailPath: string; + } | null; + msg?: string; +} + +type Param = { + key?: string; + payload: { + imageData: string; + imageName: string; + mimeType?: string; + thumbnailSize?: number; + folder?: string; + isPrivate?: boolean; + }; + user_id?: boolean; +}; /** * # Upload Image via API - * @async - * - * @param {Object} params - Single Param object containing params - * @param {String} [params.key] - *FULL ACCESS API Key - * @param {{ - * imageData: string, - * imageName: string, - * mimeType?: string, - * thumbnailSize?: number, - * folder?: string, - * isPrivate?: boolean, - * }} params.payload - Image Data Eg. - * @param {boolean} [params.user_id] - User ID - * - * @returns { Promise } - Return Object */ -async function uploadImage({ key, payload, user_id }) { +export default async function uploadImage({ + key, + payload, + user_id, +}: Param): Promise { const grabedHostNames = grabHostNames(); const { host, port, scheme } = grabedHostNames; @@ -87,16 +88,8 @@ async function uploadImage({ key, payload, user_id }) { httpsRequest.end(); }); - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ - - return httpResponse; - } catch (/** @type {*} */ error) { - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ - + return httpResponse as FunctionReturn; + } catch (error: any) { console.log("Error in uploading image: ", error.message); return { @@ -107,8 +100,4 @@ async function uploadImage({ key, payload, user_id }) { } } -/** ********************************************** */ -/** ********************************************** */ -/** ********************************************** */ - module.exports = uploadImage;