Compare commits

...
287 Commits
Author SHA1 Message Date
tben 3d0ee2e688 Updates 2026-02-22 14:21:03 +01:00
tben 0e44676226 Updates 2026-02-21 22:18:18 +01:00
tben a68e42beab Updates 2026-02-21 06:54:01 +01:00
tben 3d4ee58d01 Updates 2026-02-21 03:22:24 +01:00
tben ac489ce443 Updates 2026-02-21 02:34:48 +01:00
tben 0da68e30b8 Updates 2026-02-19 04:52:04 +01:00
tben 0a1993494d Updates 2026-02-13 18:59:28 +01:00
tben 194e4dcad0 Updates 2026-02-13 18:58:11 +01:00
tben 70908a2019 Updates 2026-02-13 18:56:14 +01:00
tben cf2cbe452b Updates 2026-02-13 18:53:31 +01:00
tben 16cc7bede5 Updates 2026-02-11 10:49:21 +01:00
tben 5847bd34ab Updates 2026-02-11 07:42:34 +01:00
tben af2749a922 Updates 2026-02-11 07:38:59 +01:00
tben fd83f6ab1b Updates 2026-02-11 07:36:42 +01:00
tben 2741214db8 Updates 2026-02-11 07:20:01 +01:00
tben 35ad577ead Updates 2026-02-11 07:18:18 +01:00
tben e1ca42137a Updates 2026-02-11 07:00:24 +01:00
tben a90706de5d Updates 2026-02-11 06:56:43 +01:00
tben 80df059135 Updates 2026-02-11 06:30:50 +01:00
tben 09fff9881e Updates 2026-02-11 05:14:25 +01:00
tben b25316485b Updates 2026-02-11 05:08:45 +01:00
tben 7345010391 Updates 2026-02-11 05:05:32 +01:00
tben 42caaecb18 Updates 2026-01-30 08:02:32 +01:00
tben b6fa30a3f2 Updates 2026-01-30 07:55:55 +01:00
tben 7169e467cc Updates 2026-01-25 05:36:26 +01:00
tben cda056311b Updates 2026-01-25 05:14:56 +01:00
tben acccc26c38 Updates 2026-01-17 05:20:00 +01:00
tben 664cb3a3d8 Updates 2026-01-15 07:54:35 +01:00
tben b50e100732 Updates 2026-01-14 11:01:08 +01:00
tben 0a03405598 Updates 2026-01-11 06:21:48 +01:00
tben 18a9409aec Updates 2026-01-09 13:03:34 +01:00
tben 1c20286c8c Updates 2026-01-09 13:02:54 +01:00
tben a915be704b Updates 2026-01-09 12:59:05 +01:00
tben a10524da95 Updates 2026-01-06 18:26:37 +01:00
tben ea40a1a8c2 Updates 2026-01-05 14:36:29 +01:00
tben 9402c859f7 Updates 2026-01-05 14:11:17 +01:00
tben 58984214fc Updates 2026-01-05 13:49:54 +01:00
tben 8bcb35a8f0 Updates 2026-01-05 13:40:23 +01:00
tben 18e29fa413 Updates 2026-01-04 12:41:19 +01:00
tben def2f2f057 Updates 2026-01-03 05:37:24 +01:00
tben 290dfe303c Updates 2026-01-03 05:34:24 +01:00
tben f0d44092e5 Updates 2026-01-02 06:19:04 +01:00
tben a8128c23ab Updates 2026-01-01 09:56:54 +01:00
tben b07153673e Updates 2026-01-01 09:52:53 +01:00
tben bd507eb9ea Updates 2026-01-01 09:50:07 +01:00
tben d109388af5 Updates 2026-01-01 09:47:08 +01:00
tben d985503688 Updates 2026-01-01 09:24:55 +01:00
tben 8277ff3e41 Updates 2026-01-01 09:22:51 +01:00
tben b8e5d45762 Updates 2025-12-31 12:18:18 +01:00
tben 515db80a79 Updates 2025-12-31 10:37:42 +01:00
tben 05733b4ade Updates 2025-12-31 10:30:01 +01:00
tben f7a2d6e03a Updates 2025-12-31 10:28:52 +01:00
tben 276a0db83b Updates 2025-12-30 18:00:20 +01:00
tben 637ca6ea54 Updates 2025-12-29 11:55:46 +01:00
tben 19eb7bf222 Updates 2025-12-29 06:50:11 +01:00
tben 863906f3e6 Updates 2025-12-29 06:37:52 +01:00
tben b10bcb4d46 Updates 2025-12-29 06:35:37 +01:00
tben 83eb4b976f Updates 2025-12-28 18:41:03 +01:00
tben d9f0f74481 Updates 2025-12-28 10:33:52 +01:00
tben 49276d4cb3 Updates 2025-12-27 16:40:30 +01:00
tben 0dc8f3c787 Updates 2025-12-27 16:06:23 +01:00
tben 27887ded41 Updates 2025-12-26 13:16:11 +01:00
tben f1e0aa9fc4 Updates 2025-12-26 12:21:27 +01:00
tben 5caa604b8f Updates 2025-12-26 12:08:45 +01:00
tben f95cf21ffd Updates 2025-12-26 10:33:46 +01:00
tben 0e5b5fea6e Updates 2025-12-26 09:37:33 +01:00
tben d7cef41552 Updates 2025-12-26 09:13:47 +01:00
tben b02399c64d Updates 2025-12-26 06:37:30 +01:00
tben 98aaa94b80 Updates 2025-12-26 06:20:46 +01:00
tben cfcd08680f Updates 2025-12-22 07:18:57 +01:00
tben 0d9f313dc0 Updates 2025-12-16 11:19:06 +01:00
tben 14ea760373 Updates 2025-12-13 16:33:58 +01:00
tben c88fb13375 Updates 2025-12-11 09:18:22 +01:00
tben f91aff421c Updates 2025-12-05 06:33:20 +01:00
tben 57f06a631f Updates 2025-12-03 21:31:18 +01:00
tben 9ab5543c5c Bugfix 2025-12-03 11:45:32 +01:00
tben 4a6da06580 Bugfix 2025-12-03 10:52:19 +01:00
tben c6d1ac7793 Bugfix 2025-12-03 10:15:11 +01:00
tben 77fca5e47c Updates 2025-12-03 10:11:21 +01:00
tben 3346486b6b Updates 2025-12-03 10:07:34 +01:00
tben 672e011cd8 Updates 2025-12-03 09:46:11 +01:00
tben 7959014721 Updates 2025-12-03 06:21:14 +01:00
tben 0858b18344 Updates 2025-11-22 14:35:13 +01:00
tben 8eebe3215a Updates 2025-11-17 11:12:19 +01:00
tben 5fcfc4dc2c Updates 2025-11-13 07:18:15 +01:00
tben 22434ee656 Updates 2025-11-13 06:53:31 +01:00
tben d2fe98b4b8 Updates 2025-11-13 06:52:52 +01:00
tben 57e67f5c51 Updates 2025-11-13 06:42:09 +01:00
tben 957709f79d Updates 2025-11-13 06:29:24 +01:00
tben 66f207416d Updates 2025-11-13 06:27:29 +01:00
tben 90c36f2345 Updates 2025-11-13 06:16:55 +01:00
tben e6b4b09277 Updates 2025-10-21 12:08:50 +01:00
tben b81948d2c1 Updates 2025-09-21 09:10:33 +01:00
archben 557bbb30bd Updates 2025-09-21 09:04:58 +01:00
archben 0fcd92ab3e Updates 2025-09-21 09:02:19 +01:00
Benjamin Toby d646b4e93a Updates 2025-09-03 13:46:08 +01:00
Benjamin Toby c5954f6ba2 Updates 2025-09-03 13:41:05 +01:00
Benjamin Toby 5c3324105e Updates 2025-09-03 13:38:54 +01:00
Benjamin Toby c34d256891 Updates 2025-09-03 13:27:04 +01:00
Benjamin Toby 97f480c208 Updates 2025-09-03 13:18:06 +01:00
Benjamin Toby 1086b35b9d Updates 2025-08-26 12:24:07 +01:00
Benjamin Toby 2336b71703 Updates 2025-08-26 11:37:28 +01:00
Benjamin Toby 82bea3efd0 Updates 2025-08-14 15:16:35 +01:00
Benjamin Toby e8269a8b5e Updates 2025-08-13 11:42:07 +01:00
Benjamin Toby 56198e8ac5 Updates 2025-08-13 11:16:45 +01:00
Benjamin Toby 700a704abd Updates 2025-08-13 11:16:28 +01:00
Benjamin Toby a1e56bb1b0 Updates 2025-08-06 06:37:43 +01:00
Benjamin Toby 689f885d9d Updates 2025-08-05 18:46:53 +01:00
Benjamin Toby eb98148533 Updates 2025-08-05 15:27:07 +01:00
Benjamin Toby 43a741f9ac Updates 2025-08-05 13:56:51 +01:00
Benjamin Toby ab13c68c8e Updates 2025-08-04 08:20:32 +01:00
Benjamin Toby 71a8431de5 Updates 2025-08-02 17:14:46 +01:00
Benjamin Toby 9ca64cf25e Updates 2025-08-02 07:44:30 +01:00
Benjamin Toby 1f375fe94f Updates 2025-08-02 07:40:35 +01:00
Benjamin Toby 8ac8b8eb51 Updates 2025-07-28 07:23:45 +01:00
Benjamin Toby a429436939 Updates 2025-07-20 07:00:09 +01:00
Benjamin Toby 3437be2c08 Updates 2025-07-19 07:58:18 +01:00
Benjamin Toby 3cf76f5155 Updates 2025-07-19 07:15:51 +01:00
Benjamin Toby 5a4d4448a5 Updates 2025-07-18 19:44:23 +01:00
Benjamin Toby 05d6d13ef0 Updates 2025-07-18 19:35:02 +01:00
Benjamin Toby 20a390e4a8 Updates 2025-07-18 18:34:04 +01:00
Benjamin Toby a53b6e6974 Bugfixes 2025-07-11 06:37:39 +01:00
Benjamin Toby 9ce8bf2c90 update Types 2025-07-11 06:08:55 +01:00
Benjamin Toby c7e02a3061 Updates 2025-07-10 18:13:29 +01:00
Benjamin Toby caa26217a0 Updates 2025-07-10 17:29:34 +01:00
Benjamin Toby 5cb8a067c0 Updates 2025-07-10 17:20:11 +01:00
Benjamin Toby 166bde51c7 Updates 2025-07-10 17:15:50 +01:00
Benjamin Toby f9725a1d6f Updates 2025-07-10 12:13:03 +01:00
Benjamin Toby 5ab079f687 Updates 2025-07-10 11:48:20 +01:00
Benjamin Toby a131764e1e Updates 2025-07-09 22:11:20 +01:00
Benjamin Toby c593404263 Updates 2025-07-09 21:53:27 +01:00
Benjamin Toby da87fe6491 Updates 2025-07-09 21:50:07 +01:00
Benjamin Toby e8787a2ef8 Updates 2025-07-09 21:40:50 +01:00
Benjamin Toby 03abe33d22 Updates 2025-07-09 21:24:33 +01:00
Benjamin Toby 382da38bb0 Updates 2025-07-09 20:42:01 +01:00
Benjamin Toby c37d105dee Updates 2025-07-09 20:30:45 +01:00
Benjamin Toby ccb5605b58 Updates 2025-07-07 09:14:37 +01:00
Benjamin Toby 6acf0f2cd6 Updates 2025-07-06 17:00:35 +01:00
Benjamin Toby b38ddc9f21 Updates 2025-07-06 15:32:28 +01:00
Benjamin Toby 3597b11342 Updates 2025-07-05 18:17:35 +01:00
Benjamin Toby fcc668d3a1 Updates 2025-07-05 17:39:29 +01:00
Benjamin Toby ad904622eb Updates 2025-07-05 17:27:26 +01:00
Benjamin Toby d80d876ac1 Updates 2025-07-05 16:53:58 +01:00
Benjamin Toby 23d1b28354 Updates 2025-07-05 16:42:24 +01:00
Benjamin Toby 56a58c225e Updates 2025-07-05 16:24:04 +01:00
Benjamin Toby a2d8fba8d7 Updates 2025-07-05 16:15:26 +01:00
Benjamin Toby 728183b827 Roll Back compile version 2025-07-05 16:14:11 +01:00
Benjamin Toby 4f4eb44a98 Bugfix 2025-07-05 15:52:10 +01:00
Benjamin Toby 321683e7c8 Bugfix 2025-07-05 15:30:37 +01:00
Benjamin Toby 3730e4722e Updates 2025-07-05 15:16:31 +01:00
Benjamin Toby 7e8bb37c09 Updates 2025-07-05 14:59:30 +01:00
Benjamin Toby 6e334c2525 Updates 2025-06-04 08:46:39 +01:00
Benjamin Toby 881128fcea Updates 2025-06-04 08:44:33 +01:00
Benjamin Toby 761348de08 Updates 2025-06-04 08:43:16 +01:00
Benjamin Toby 1364074c2c Updates 2025-06-01 16:27:26 +01:00
Benjamin Toby 4a083fe73b Updates 2025-06-01 16:13:56 +01:00
Benjamin Toby 8639c9f34d Updates 2025-06-01 12:32:16 +01:00
Benjamin Toby cd96c11817 Updates 2025-06-01 12:14:49 +01:00
Benjamin Toby 9b7c98cff6 Updates 2025-06-01 11:39:56 +01:00
Benjamin Toby b28b05956b Updates 2025-06-01 07:06:45 +01:00
Benjamin Toby a68d1c1d3f Updates 2025-06-01 07:05:45 +01:00
Benjamin Toby b3353b8b70 Updates 2025-05-22 10:05:54 +01:00
Benjamin Toby 2618d472dc Updates 2025-05-22 10:04:18 +01:00
Benjamin Toby 0fc2c7fb3e Updates 2025-05-21 09:34:49 +01:00
Benjamin Toby 4adb5af430 Updates 2025-05-15 08:41:24 +01:00
Benjamin Toby 04a56b5bc3 Updates 2025-05-13 13:00:02 +01:00
Benjamin Toby a90989cea7 Updates 2025-05-12 10:49:30 +01:00
Benjamin Toby 674af34355 Updates 2025-05-12 10:47:47 +01:00
Benjamin Toby 07c2186b98 Updates 2025-05-06 06:12:42 +01:00
Benjamin Toby fe2b34d0ee Updates 2025-05-05 15:36:57 +01:00
Benjamin Toby 181501296a Updates 2025-05-05 15:34:42 +01:00
Benjamin Toby cd4a2f7902 Updates 2025-05-04 21:13:21 +01:00
Benjamin Toby cc29a3c107 Updates 2025-05-04 19:13:19 +01:00
Benjamin Toby 8d855ce94d Updates 2025-05-04 19:09:02 +01:00
Benjamin Toby 9ea903a401 Updates 2025-05-04 18:49:34 +01:00
Benjamin Toby e4c6c995ef Updates 2025-05-04 17:52:51 +01:00
Benjamin Toby c71c1c29ca Updates 2025-04-23 14:45:44 +01:00
Benjamin Toby e7b7cf0314 Updates 2025-04-23 14:40:16 +01:00
Benjamin Toby daad62141e Updates 2025-04-23 14:35:42 +01:00
Benjamin Toby 22f4372cbf Updates 2025-04-23 14:29:17 +01:00
Benjamin Toby 18cbf9b2f4 Updates 2025-04-23 14:27:27 +01:00
Benjamin Toby 2ad17ae682 Updates 2025-04-23 14:21:14 +01:00
Benjamin Toby d78e44c98d Updates 2025-04-23 13:45:48 +01:00
Benjamin Toby cd6bfdfc67 Updates 2025-04-23 13:20:44 +01:00
Benjamin Toby 6593047efd Updates 2025-04-18 12:06:15 +01:00
Benjamin Toby 8d38f99bf1 Updates 2025-04-18 12:05:10 +01:00
Benjamin Toby fb0bc4b753 Updates 2025-04-17 12:07:46 +01:00
Benjamin Toby 7c04884a00 Updates 2025-04-17 11:50:49 +01:00
Benjamin Toby 656eb27b8c Updates 2025-04-17 11:47:02 +01:00
Benjamin Toby ee23d71b66 Updates 2025-04-17 11:42:53 +01:00
Benjamin Toby ba1a4aeeb8 Bugfix 2025-04-17 11:33:05 +01:00
Benjamin Toby d41d28104f Bugfix 2025-04-17 11:27:45 +01:00
Benjamin Toby a9c0dd4b63 Updates 2025-04-17 11:24:53 +01:00
Benjamin Toby 870de51f5d Updates 2025-04-17 11:15:21 +01:00
Benjamin Toby c24afca519 Updates 2025-04-17 11:11:29 +01:00
Benjamin Toby 6e32bbb4e0 Updates 2025-04-17 10:49:34 +01:00
Benjamin Toby bcaaaae347 Updates 2025-04-16 12:55:44 +01:00
Benjamin Toby cd224b24df Updates 2025-04-16 12:53:11 +01:00
Benjamin Toby fe97939faf Updates 2025-03-31 07:43:38 +01:00
Benjamin Toby 2091c823c8 Updates 2025-03-25 09:33:18 +01:00
Benjamin Toby e3c98388c6 Updates 2025-03-23 08:03:10 +01:00
Benjamin Toby fecb9a1df6 Updates 2025-03-23 08:02:44 +01:00
Benjamin Toby fbe4f7e5e6 Updates 2025-03-23 07:53:17 +01:00
Benjamin Toby e829ebd2ed Update Cookie Expiry Logic 2025-03-23 07:52:28 +01:00
Benjamin Toby 870bc7fd17 Updates 2025-03-17 09:46:04 +01:00
Benjamin Toby 34f843bc84 Updates 2025-03-17 08:48:58 +01:00
Benjamin Toby ec4d0428bb Updates 2025-03-12 07:22:04 +01:00
Benjamin Toby c192d9cd13 Updates 2025-03-04 20:55:59 +01:00
Benjamin Toby d4cb764a18 Updates 2025-02-19 20:33:56 +01:00
Benjamin Toby e9bb9fb07f Updates 2025-02-19 20:01:50 +01:00
Benjamin Toby c08db13f3d Bugfix 2025-02-19 08:42:23 +01:00
Benjamin Toby 2e0b6d0a70 Updates 2025-02-19 08:39:03 +01:00
Benjamin Toby 8b3553fcd5 Updates 2025-02-13 08:18:46 +01:00
Benjamin Toby b578843c6d Bugfix 2025-02-12 12:39:02 +01:00
Benjamin Toby 12296a3e75 Bugfix 2025-02-12 12:29:41 +01:00
Benjamin Toby dbc68e54c6 Updates 2025-02-12 12:22:19 +01:00
Benjamin Toby 5819017a97 Updates 2025-02-12 12:13:28 +01:00
Benjamin Toby e089f84ef4 Bugfix 2025-02-12 12:12:11 +01:00
Benjamin Toby ca65327527 Bugfix 2025-02-12 12:00:53 +01:00
Benjamin Toby e6702c7f82 Bugfix 2025-02-12 11:55:36 +01:00
Benjamin Toby 95318307fe Bugfix 2025-02-12 11:52:25 +01:00
Benjamin Toby a2961d6b89 Bugfix 2025-02-09 14:03:21 +01:00
Benjamin Toby 5e3476ad15 Updates 2025-02-09 13:54:01 +01:00
Benjamin Toby 3358412028 Updates 2025-02-07 14:14:00 +01:00
Benjamin Toby 6d4ccb63a3 Updates 2025-02-07 14:06:53 +01:00
Benjamin Toby b8fbbd3afb Updates 2025-02-07 13:58:34 +01:00
Benjamin Toby 64ee344ba1 Google Login Bugfix 2025-02-05 19:45:02 +01:00
Benjamin Toby 06de31dcb2 Updates 2025-02-05 19:34:03 +01:00
Benjamin Toby 1acdad97a2 Bugfix 2025-01-27 16:21:55 +01:00
Benjamin Toby e41224bab7 Remove Logs 2025-01-27 11:35:45 +01:00
Benjamin Toby 97fc8f42c2 Bugfix 2025-01-26 07:36:41 +01:00
Benjamin Toby 38abc55870 Bugfix 2025-01-26 07:12:19 +01:00
Benjamin Toby 94d15ecb30 Update Types 2025-01-26 07:03:38 +01:00
Benjamin Toby 7188fe6e2c Updates 2025-01-26 06:45:19 +01:00
Benjamin Toby ff5550ec85 Updates 2025-01-26 05:58:25 +01:00
Benjamin Toby b6a3e002fb Updates 2025-01-26 05:50:37 +01:00
Benjamin Toby 8ecef72efc Updates 2025-01-25 15:45:27 +01:00
Benjamin Toby 4fe8921bc6 Updates 2025-01-25 14:45:22 +01:00
Benjamin Toby 483ea16d4d Updates 2025-01-25 14:28:26 +01:00
Benjamin Toby ebf3618667 Updates 2025-01-25 14:25:20 +01:00
Benjamin Toby e82bcd0824 Updates 2025-01-25 14:20:25 +01:00
Benjamin Toby 1db9c3a2e7 Updates 2025-01-21 18:43:03 +01:00
Benjamin Toby 9f773de1a1 Bugfix 2025-01-21 08:24:29 +01:00
Benjamin Toby 4aa69791c1 Updates 2025-01-20 09:49:32 +01:00
Benjamin Toby d89ded9d43 Updates 2025-01-20 09:28:30 +01:00
Benjamin Toby 8d809412bb Updates 2025-01-20 09:19:34 +01:00
Benjamin Toby 7d0f3e12f3 Remove all 'useLocal' params 2025-01-20 09:12:43 +01:00
Benjamin Toby 16191975f9 Updates 2025-01-20 08:50:36 +01:00
Benjamin Toby c210e6ca46 Updates 2025-01-20 08:42:35 +01:00
Benjamin Toby 3695a75919 Updates 2025-01-20 08:26:15 +01:00
Benjamin Toby fdd3913f4f Updates 2025-01-20 08:12:01 +01:00
Benjamin Toby 3dd1d08a5b Updates 2025-01-20 07:43:04 +01:00
Benjamin Toby dfe6fb3177 Updates 2025-01-20 07:31:16 +01:00
Benjamin Toby c947567311 Updates 2025-01-17 10:23:41 +01:00
Benjamin Toby a44526aeed Updates 2025-01-16 10:05:11 +01:00
Benjamin Toby 982149f759 Updates 2025-01-15 23:11:00 +01:00
Benjamin Toby b18ec506b3 Updates 2025-01-15 22:59:16 +01:00
Benjamin Toby a2feec6f5b Updates 2025-01-15 22:30:01 +01:00
Benjamin Toby 342056060b Updates 2025-01-15 22:04:09 +01:00
Benjamin Toby 967cbae93f Updates 2025-01-15 21:54:43 +01:00
Benjamin Toby e13a14ab5c Updates 2025-01-15 21:51:05 +01:00
Benjamin Toby 785b15aad5 Updates 2025-01-15 08:47:54 +01:00
Benjamin Toby 8394963f0b Updates 2025-01-15 05:52:00 +01:00
Benjamin Toby 60cccc9d9f Updates 2025-01-14 16:58:05 +01:00
Benjamin Toby 82152082f3 Updates 2025-01-14 16:50:40 +01:00
Benjamin Toby 9cd2707157 Updates 2025-01-14 16:03:51 +01:00
Benjamin Toby fc9839fd0c Updates 2025-01-14 15:59:48 +01:00
Benjamin Toby 49716e8c5c Updates 2025-01-14 15:33:49 +01:00
Benjamin Toby 62bb1fd6d4 Updates 2025-01-14 14:58:44 +01:00
Benjamin Toby f181b79ef7 Updates 2025-01-14 14:51:22 +01:00
Benjamin Toby 09bfbd4214 Updates 2025-01-14 14:45:32 +01:00
Benjamin Toby 20754d5cae Updates 2025-01-14 14:19:50 +01:00
Benjamin Toby 0731e8cb6c Updates 2025-01-14 11:53:57 +01:00
Benjamin Toby 03d4fdc270 Updates 2025-01-14 11:33:30 +01:00
Benjamin Toby d55fe64d47 Updates 2025-01-14 11:14:50 +01:00
Benjamin Toby edd555c088 Updates 2025-01-14 10:59:09 +01:00
Benjamin Toby 0cd3eb418c Updates 2025-01-14 10:49:37 +01:00
Benjamin Toby 2118a55ab6 Updates 2025-01-14 09:07:00 +01:00
Benjamin Toby 7551749784 Updates 2025-01-14 08:41:57 +01:00
Benjamin Toby 285d3b8369 Updates 2025-01-14 08:01:19 +01:00
Benjamin Toby 87c7b4a83b Updates 2025-01-14 00:03:47 +01:00
Benjamin Toby d586de0639 Updates 2025-01-14 00:01:02 +01:00
Benjamin Toby 8f00f333aa Updates 2025-01-12 18:47:28 +01:00
Benjamin Toby 186cc76ffb Updates 2025-01-12 18:19:20 +01:00
Benjamin Toby a3561da53d Updates 2025-01-10 20:35:05 +01:00
Benjamin Toby 9192dae0b5 First TS builds 2025-01-10 20:16:48 +01:00
Benjamin Toby eb0992f28d Refactor Code to typescript 2025-01-10 20:10:28 +01:00
1035 changed files with 42459 additions and 17270 deletions
-1
View File
@@ -90,7 +90,6 @@ out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
Executable
BIN
View File
Binary file not shown.
-7
View File
@@ -1,7 +0,0 @@
declare function _exports({ clientId, redirectUrl, setLoading, scopes }: {
clientId: string;
redirectUrl: string;
setLoading?: (arg0: boolean) => void;
scopes?: string[];
}): void;
export = _exports;
-36
View File
@@ -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);
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
};
+24
View File
@@ -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);
}
-19
View File
@@ -1,19 +0,0 @@
declare namespace _exports {
export { GoogleGetAccessTokenFunctionParams };
}
declare function _exports(params: GoogleGetAccessTokenFunctionParams): Promise<string>;
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<React.SetStateAction<boolean>>;
};
@@ -1,33 +1,22 @@
// @ts-check
interface GoogleGetAccessTokenFunctionParams {
clientId: string;
triggerPrompt?: boolean;
setLoading?: React.Dispatch<React.SetStateAction<boolean>>;
}
/**
* @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<React.SetStateAction<boolean>>} [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<string>} - Access Token String
*/
module.exports = async function getAccessToken(params) {
export default async function getAccessToken(
params: GoogleGetAccessTokenFunctionParams
): Promise<string> {
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);
}
});
-2
View File
@@ -1,2 +0,0 @@
declare function _exports(params: object | null): Promise<boolean>;
export = _exports;
-146
View File
@@ -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<boolean>} - 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;
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
};
+104
View File
@@ -0,0 +1,104 @@
import getCsrfHeaderName from "../../package-shared/actions/get-csrf-header-name";
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?: {
googleClientId?: any;
}): Promise<boolean> {
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(getCsrfHeaderName());
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;
}
}
+21
View File
@@ -0,0 +1,21 @@
import getCsrfHeaderName from "../../package-shared/actions/get-csrf-header-name";
import { APILoginFunctionReturn } from "../../package-shared/types";
/**
* Client Setup After Login
* ===============================================================================
* @description This function sets local storage variables like `csrf` after a user
* is logged in. Use this in conjunction with the `datasquirel.user.loginUser`
* function
*/
export default function postLogin(res: APILoginFunctionReturn): boolean {
try {
if (!res.payload) return false;
if (!res.payload.csrf_k) return false;
localStorage.setItem(getCsrfHeaderName(), res.payload.csrf_k);
localStorage.setItem("user", JSON.stringify(res.payload));
return true;
} catch (error) {
return false;
}
}
+60
View File
@@ -0,0 +1,60 @@
import {
APIResponseObject,
ClientCrudFetchParams,
PostInsertReturn,
} from "../../package-shared/types";
import serializeQuery from "../../package-shared/utils/serialize-query";
import fetchApi from "../fetch";
export default async function clientCrudFetch<
T extends { [k: string]: any } = { [k: string]: any },
P = string,
R extends { [k: string]: any } = { [k: string]: any }
>({
table,
basePath,
body,
query,
targetId,
method = "GET",
apiOrigin,
headers,
...options
}: ClientCrudFetchParams<T, P>) {
try {
let pathname = basePath || ``;
pathname += `/${String(table)}`;
if (targetId) {
pathname += `/${String(targetId)}`;
}
if (query) {
pathname = `${pathname}${serializeQuery(query)}`;
}
pathname = pathname.replace(/\/{2,}/g, "/");
pathname = apiOrigin
? `${apiOrigin}/${pathname}`.replace(/([^:]\/)\/+/g, "$1")
: pathname;
const res = await fetchApi<
any,
APIResponseObject<PostInsertReturn | R[]>
>(pathname, {
method,
body,
headers,
...options,
});
return res;
} catch (error: any) {
return {
success: false,
msg: `API ERROR => ${error.message}`,
};
}
}
-5
View File
@@ -1,5 +0,0 @@
export = clientFetch;
declare function clientFetch(url: string, options?: import("../../package-shared/types").FetchApiOptions, csrf?: boolean): Promise<any>;
declare namespace clientFetch {
export { clientFetch as fetchApi };
}
-95
View File
@@ -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;
+87
View File
@@ -0,0 +1,87 @@
import _ from "lodash";
import {
DSQLClientFetchHeader,
DSQLFetchApiOptions,
} from "../../package-shared/types";
import serializeQuery from "../../package-shared/utils/serialize-query";
/**
* # Fetch API
*/
export default async function fetchApi<
T extends { [k: string]: any } = { [k: string]: any },
R extends any = any,
>(url: string, options?: DSQLFetchApiOptions<T>): Promise<R> {
let data;
let finalHeaders = {
"Content-Type": "application/json",
} as DSQLClientFetchHeader;
if (options?.csrfKey && options.csrfValue) {
finalHeaders[options.csrfKey] = options.csrfValue;
}
let finalURL = url;
if (options?.query) {
finalURL += serializeQuery(options.query);
}
if (typeof options === "string") {
try {
let fetchData;
switch (options) {
case "post":
fetchData = await fetch(finalURL, {
method: options,
headers: finalHeaders,
} as RequestInit);
data = fetchData.json();
break;
default:
fetchData = await fetch(finalURL);
data = fetchData.json();
break;
}
} catch (error: any) {
console.log("FetchAPI error #1:", error.message);
data = null;
}
} else if (typeof options === "object") {
let fetchData;
let fetchOptions: RequestInit = {};
try {
fetchOptions.method = options.method;
if (options.method.match(/post|put|delete|patch/i)) {
if (options.body && typeof options.body == "object") {
fetchOptions.body = JSON.stringify(options.body);
}
}
fetchOptions.headers = _.merge(finalHeaders, options.headers || {});
fetchOptions = _.merge(fetchOptions, options.fetchOptions);
fetchData = await fetch(finalURL, fetchOptions);
data = fetchData.json();
} catch (error: any) {
console.log("FetchAPI error #2:", error.message);
data = null;
}
} else {
try {
let fetchData = await fetch(finalURL);
data = await fetchData.json();
} catch (error: any) {
console.log("FetchAPI error #3:", error.message);
data = null;
}
}
return data;
}
-38
View File
@@ -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");
-67
View File
@@ -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;
+68
View File
@@ -0,0 +1,68 @@
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";
import postLogin from "./auth/post-login";
import deserializeQuery from "../package-shared/utils/deserialize-query";
import debugLog from "../package-shared/utils/logging/debug-log";
import clientCrudFetch from "./crud-fetch";
const media = {
imageInputToBase64,
imageInputFileToBase64,
inputFileToBase64,
};
/**
* User Auth Object
*/
const auth = {
google: {
getAccessToken: getAccessToken,
},
github: {
getAccessToken: getGithubAccessToken,
},
logout,
postLogin,
};
const utils = {
deserializeQuery,
serializeQuery,
serializeCookies,
EJSON,
numberfy,
slugify,
debugLog,
};
/**
* Fetch
*/
const fetch = {
fetchApi,
clientFetch,
};
/**
* Main Export
*/
const datasquirelClient = {
media,
auth,
fetch,
utils,
clientCrudFetch,
};
export default datasquirelClient;
-8
View File
@@ -1,8 +0,0 @@
declare function _exports({ imageInputFile, maxWidth, imagePreviewNode, }: {
imageInputFile: {
name: string;
};
maxWidth?: number;
imagePreviewNode?: HTMLImageElement;
}): Promise<any>;
export = _exports;
@@ -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<import("../../types/general.td").ImageInputFileToBase64FunctionReturn> } - Return Object
* # Image input File top Base64
*/
module.exports = async function imageInputFileToBase64({
export default async function imageInputFileToBase64({
imageInputFile,
maxWidth,
imagePreviewNode,
}) {
}: Param): Promise<ImageInputFileToBase64FunctionReturn> {
/**
* 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,
};
}
};
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
}
-14
View File
@@ -1,14 +0,0 @@
declare namespace _exports {
export { FunctionReturn };
}
declare function _exports({ imageInput, maxWidth, mimeType, }: {
imageInput: HTMLInputElement;
maxWidth?: number;
mimeType?: [string];
}): Promise<FunctionReturn>;
export = _exports;
type FunctionReturn = {
imageBase64: string;
imageBase64Full: string;
imageName: string;
};
-115
View File
@@ -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<FunctionReturn> } - 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,
};
}
};
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
+104
View File
@@ -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<FunctionReturn> {
/**
* 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 {};
}
}
-19
View File
@@ -1,19 +0,0 @@
declare namespace _exports {
export { FunctionReturn };
}
declare function _exports({ inputFile, allowedRegex }: {
inputFile: {
name: string;
size: number;
type: string;
};
allowedRegex?: RegExp;
}): Promise<FunctionReturn>;
export = _exports;
type FunctionReturn = {
fileBase64: string;
fileBase64Full: string;
fileName: string;
fileSize: number;
fileType: string;
};
-96
View File
@@ -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<FunctionReturn> } - 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,
};
}
};
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
+68
View File
@@ -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<FunctionReturn> {
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,
};
}
}
-2
View File
@@ -1,2 +0,0 @@
declare function _exports(): {} | null;
export = _exports;
-65
View File
@@ -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;
};
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
+34
View File
@@ -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;
}
+1 -1
View File
@@ -28,4 +28,4 @@ const colors = {
BgGray: "\x1b[100m",
};
module.exports = colors;
export default colors;
+13
View File
@@ -0,0 +1,13 @@
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;
export {};
+15
View File
@@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = getAccessToken;
/**
* Login with Github Function
* ===============================================================================
* @description This function uses github api to login a user with datasquirel
*/
function getAccessToken({ clientId, redirectUrl, setLoading, scopes, }) {
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);
}
+18
View File
@@ -0,0 +1,18 @@
interface GoogleGetAccessTokenFunctionParams {
clientId: string;
triggerPrompt?: boolean;
setLoading?: React.Dispatch<React.SetStateAction<boolean>>;
}
/**
* Login with Google Function
* ===============================================================================
* @description This function uses google identity api to login a user with datasquirel
*/
export default function getAccessToken(params: GoogleGetAccessTokenFunctionParams): Promise<string>;
/**
* # Google Login Function
*/
export declare function googleLogin({ google, clientId, setLoading, triggerPrompt, }: GoogleGetAccessTokenFunctionParams & {
google: any;
}): Promise<unknown>;
export {};
+71
View File
@@ -0,0 +1,71 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = getAccessToken;
exports.googleLogin = googleLogin;
let interval;
/**
* Login with Google Function
* ===============================================================================
* @description This function uses google identity api to login a user with datasquirel
*/
function getAccessToken(params) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
(_a = params.setLoading) === null || _a === void 0 ? void 0 : _a.call(params, true);
const response = (yield new Promise((resolve, reject) => {
interval = setInterval(() => {
// @ts-ignore
let google = window.google;
if (google) {
window.clearInterval(interval);
resolve(googleLogin(Object.assign(Object.assign({}, params), { google })));
}
}, 500);
}));
(_b = params.setLoading) === null || _b === void 0 ? void 0 : _b.call(params, false);
return response;
});
}
/**
* # Google Login Function
*/
function googleLogin({ google, clientId, setLoading, triggerPrompt, }) {
setTimeout(() => {
setLoading === null || setLoading === void 0 ? void 0 : setLoading(false);
}, 3000);
return new Promise((resolve, reject) => {
/**
* # Callback Function
* @param {import("../../../package-shared/types").GoogleAccessTokenObject} response
*/
function handleCredentialResponse(response) {
resolve(response.access_token);
}
const googleAuth = google.accounts.oauth2.initTokenClient({
client_id: clientId,
scope: "email profile",
callback: handleCredentialResponse,
});
googleAuth.requestAccessToken();
if (triggerPrompt) {
google.accounts.id.prompt(triggerGooglePromptCallback);
}
/**
* Google prompt notification callback
* ========================================================
* @param {import("../../../package-shared/types").GoogleIdentityPromptNotification} notification
*/
function triggerGooglePromptCallback(notification) {
console.log(notification);
}
});
}
+8
View File
@@ -0,0 +1,8 @@
/**
* Login with Google Function
* ===============================================================================
* @description This function uses google identity api to login a user with datasquirel
*/
export default function logout(params?: {
googleClientId?: any;
}): Promise<boolean>;
+103
View File
@@ -0,0 +1,103 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = logout;
const get_csrf_header_name_1 = __importDefault(require("../../package-shared/actions/get-csrf-header-name"));
const parseClientCookies_1 = __importDefault(require("../utils/parseClientCookies"));
/**
* Login with Google Function
* ===============================================================================
* @description This function uses google identity api to login a user with datasquirel
*/
function logout(params) {
return __awaiter(this, void 0, void 0, function* () {
try {
const localUser = localStorage.getItem("user");
let targetUser;
try {
targetUser = JSON.parse(localUser || "");
}
catch (error) {
console.log(error);
}
if (!targetUser) {
return false;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const cookies = (0, parseClientCookies_1.default)();
const socialId = (cookies === null || cookies === void 0 ? void 0 : 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((0, get_csrf_header_name_1.default)());
document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const response = yield new Promise((resolve, reject) => {
if (socialId && !(socialId === null || socialId === void 0 ? void 0 : socialId.match(/^null$/i))) {
const googleClientId = params === null || params === void 0 ? void 0 : 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) => {
console.log(done.error);
resolve(true);
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
};
}
else {
resolve(true);
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
else {
resolve(true);
}
});
return response;
}
catch (error) {
return false;
}
});
}
+9
View File
@@ -0,0 +1,9 @@
import { APILoginFunctionReturn } from "../../package-shared/types";
/**
* Client Setup After Login
* ===============================================================================
* @description This function sets local storage variables like `csrf` after a user
* is logged in. Use this in conjunction with the `datasquirel.user.loginUser`
* function
*/
export default function postLogin(res: APILoginFunctionReturn): boolean;
+28
View File
@@ -0,0 +1,28 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = postLogin;
const get_csrf_header_name_1 = __importDefault(require("../../package-shared/actions/get-csrf-header-name"));
/**
* Client Setup After Login
* ===============================================================================
* @description This function sets local storage variables like `csrf` after a user
* is logged in. Use this in conjunction with the `datasquirel.user.loginUser`
* function
*/
function postLogin(res) {
try {
if (!res.payload)
return false;
if (!res.payload.csrf_k)
return false;
localStorage.setItem((0, get_csrf_header_name_1.default)(), res.payload.csrf_k);
localStorage.setItem("user", JSON.stringify(res.payload));
return true;
}
catch (error) {
return false;
}
}
+10
View File
@@ -0,0 +1,10 @@
import { APIResponseObject, ClientCrudFetchParams, PostInsertReturn } from "../../package-shared/types";
export default function clientCrudFetch<T extends {
[k: string]: any;
} = {
[k: string]: any;
}, P = string, R extends {
[k: string]: any;
} = {
[k: string]: any;
}>({ table, basePath, body, query, targetId, method, apiOrigin, headers, ...options }: ClientCrudFetchParams<T, P>): Promise<APIResponseObject<PostInsertReturn | R[]>>;
+57
View File
@@ -0,0 +1,57 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = clientCrudFetch;
const serialize_query_1 = __importDefault(require("../../package-shared/utils/serialize-query"));
const fetch_1 = __importDefault(require("../fetch"));
function clientCrudFetch(_a) {
return __awaiter(this, void 0, void 0, function* () {
var { table, basePath, body, query, targetId, method = "GET", apiOrigin, headers } = _a, options = __rest(_a, ["table", "basePath", "body", "query", "targetId", "method", "apiOrigin", "headers"]);
try {
let pathname = basePath || ``;
pathname += `/${String(table)}`;
if (targetId) {
pathname += `/${String(targetId)}`;
}
if (query) {
pathname = `${pathname}${(0, serialize_query_1.default)(query)}`;
}
pathname = pathname.replace(/\/{2,}/g, "/");
pathname = apiOrigin
? `${apiOrigin}/${pathname}`.replace(/([^:]\/)\/+/g, "$1")
: pathname;
const res = yield (0, fetch_1.default)(pathname, Object.assign({ method,
body,
headers }, options));
return res;
}
catch (error) {
return {
success: false,
msg: `API ERROR => ${error.message}`,
};
}
});
}
+9
View File
@@ -0,0 +1,9 @@
import { DSQLFetchApiOptions } from "../../package-shared/types";
/**
* # Fetch API
*/
export default function fetchApi<T extends {
[k: string]: any;
} = {
[k: string]: any;
}, R extends any = any>(url: string, options?: DSQLFetchApiOptions<T>): Promise<R>;
+88
View File
@@ -0,0 +1,88 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = fetchApi;
const lodash_1 = __importDefault(require("lodash"));
const serialize_query_1 = __importDefault(require("../../package-shared/utils/serialize-query"));
/**
* # Fetch API
*/
function fetchApi(url, options) {
return __awaiter(this, void 0, void 0, function* () {
let data;
let finalHeaders = {
"Content-Type": "application/json",
};
if ((options === null || options === void 0 ? void 0 : options.csrfKey) && options.csrfValue) {
finalHeaders[options.csrfKey] = options.csrfValue;
}
let finalURL = url;
if (options === null || options === void 0 ? void 0 : options.query) {
finalURL += (0, serialize_query_1.default)(options.query);
}
if (typeof options === "string") {
try {
let fetchData;
switch (options) {
case "post":
fetchData = yield fetch(finalURL, {
method: options,
headers: finalHeaders,
});
data = fetchData.json();
break;
default:
fetchData = yield fetch(finalURL);
data = fetchData.json();
break;
}
}
catch (error) {
console.log("FetchAPI error #1:", error.message);
data = null;
}
}
else if (typeof options === "object") {
let fetchData;
let fetchOptions = {};
try {
fetchOptions.method = options.method;
if (options.method.match(/post|put|delete|patch/i)) {
if (options.body && typeof options.body == "object") {
fetchOptions.body = JSON.stringify(options.body);
}
}
fetchOptions.headers = lodash_1.default.merge(finalHeaders, options.headers || {});
fetchOptions = lodash_1.default.merge(fetchOptions, options.fetchOptions);
fetchData = yield fetch(finalURL, fetchOptions);
data = fetchData.json();
}
catch (error) {
console.log("FetchAPI error #2:", error.message);
data = null;
}
}
else {
try {
let fetchData = yield fetch(finalURL);
data = yield fetchData.json();
}
catch (error) {
console.log("FetchAPI error #3:", error.message);
data = null;
}
}
return data;
});
}
+57
View File
@@ -0,0 +1,57 @@
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 serializeQuery from "../package-shared/utils/serialize-query";
import serializeCookies from "../package-shared/utils/serialize-cookies";
import numberfy from "../package-shared/utils/numberfy";
import slugify from "../package-shared/utils/slugify";
import postLogin from "./auth/post-login";
import deserializeQuery from "../package-shared/utils/deserialize-query";
import debugLog from "../package-shared/utils/logging/debug-log";
import clientCrudFetch from "./crud-fetch";
/**
* Main Export
*/
declare const datasquirelClient: {
media: {
imageInputToBase64: typeof imageInputToBase64;
imageInputFileToBase64: typeof imageInputFileToBase64;
inputFileToBase64: typeof inputFileToBase64;
};
auth: {
google: {
getAccessToken: typeof getAccessToken;
};
github: {
getAccessToken: typeof getGithubAccessToken;
};
logout: typeof logout;
postLogin: typeof postLogin;
};
fetch: {
fetchApi: typeof fetchApi;
clientFetch: typeof fetchApi;
};
utils: {
deserializeQuery: typeof deserializeQuery;
serializeQuery: typeof serializeQuery;
serializeCookies: typeof serializeCookies;
EJSON: {
parse: (string: string | null | number, reviver?: (this: any, key: string, value: any) => any) => {
[s: string]: any;
} | {
[s: string]: any;
}[] | undefined;
stringify: (value: any, replacer?: ((this: any, key: string, value: any) => any) | null, space?: string | number) => string | undefined;
};
numberfy: typeof numberfy;
slugify: typeof slugify;
debugLog: typeof debugLog;
};
clientCrudFetch: typeof clientCrudFetch;
};
export default datasquirelClient;
+67
View File
@@ -0,0 +1,67 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const imageInputFileToBase64_1 = __importDefault(require("./media/imageInputFileToBase64"));
const imageInputToBase64_1 = __importDefault(require("./media/imageInputToBase64"));
const inputFileToBase64_1 = __importDefault(require("./media/inputFileToBase64"));
const getAccessToken_1 = __importDefault(require("./auth/google/getAccessToken"));
const getAccessToken_2 = __importDefault(require("./auth/github/getAccessToken"));
const logout_1 = __importDefault(require("./auth/logout"));
const fetch_1 = __importDefault(require("./fetch"));
const fetch_2 = __importDefault(require("./fetch"));
const serialize_query_1 = __importDefault(require("../package-shared/utils/serialize-query"));
const serialize_cookies_1 = __importDefault(require("../package-shared/utils/serialize-cookies"));
const ejson_1 = __importDefault(require("../package-shared/utils/ejson"));
const numberfy_1 = __importDefault(require("../package-shared/utils/numberfy"));
const slugify_1 = __importDefault(require("../package-shared/utils/slugify"));
const post_login_1 = __importDefault(require("./auth/post-login"));
const deserialize_query_1 = __importDefault(require("../package-shared/utils/deserialize-query"));
const debug_log_1 = __importDefault(require("../package-shared/utils/logging/debug-log"));
const crud_fetch_1 = __importDefault(require("./crud-fetch"));
const media = {
imageInputToBase64: imageInputToBase64_1.default,
imageInputFileToBase64: imageInputFileToBase64_1.default,
inputFileToBase64: inputFileToBase64_1.default,
};
/**
* User Auth Object
*/
const auth = {
google: {
getAccessToken: getAccessToken_1.default,
},
github: {
getAccessToken: getAccessToken_2.default,
},
logout: logout_1.default,
postLogin: post_login_1.default,
};
const utils = {
deserializeQuery: deserialize_query_1.default,
serializeQuery: serialize_query_1.default,
serializeCookies: serialize_cookies_1.default,
EJSON: ejson_1.default,
numberfy: numberfy_1.default,
slugify: slugify_1.default,
debugLog: debug_log_1.default,
};
/**
* Fetch
*/
const fetch = {
fetchApi: fetch_1.default,
clientFetch: fetch_2.default,
};
/**
* Main Export
*/
const datasquirelClient = {
media,
auth,
fetch,
utils,
clientCrudFetch: crud_fetch_1.default,
};
exports.default = datasquirelClient;
+14
View File
@@ -0,0 +1,14 @@
import imageInputFileToBase64 from "./imageInputFileToBase64";
import imageInputToBase64 from "./imageInputToBase64";
/**
* ==========================
* Main Export
* ==========================
*/
declare const datasquirelClient: {
media: {
imageInputToBase64: typeof imageInputToBase64;
imageInputFileToBase64: typeof imageInputFileToBase64;
};
};
export default datasquirelClient;
+34
View File
@@ -0,0 +1,34 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const imageInputFileToBase64_1 = __importDefault(require("./imageInputFileToBase64"));
const imageInputToBase64_1 = __importDefault(require("./imageInputToBase64"));
/**
* ==========================
* Media Functions Object
* ==========================
*/
const media = {
imageInputToBase64: imageInputToBase64_1.default,
imageInputFileToBase64: imageInputFileToBase64_1.default,
};
/**
* ==========================
* Media Functions Object
* ==========================
*/
const auth = {
imageInputToBase64: imageInputToBase64_1.default,
imageInputFileToBase64: imageInputFileToBase64_1.default,
};
/**
* ==========================
* Main Export
* ==========================
*/
const datasquirelClient = {
media: media,
};
exports.default = datasquirelClient;
+11
View File
@@ -0,0 +1,11 @@
import { ImageInputFileToBase64FunctionReturn } from "../../package-shared/types";
type Param = {
imageInputFile: File;
maxWidth?: number;
imagePreviewNode?: HTMLImageElement;
};
/**
* # Image input File top Base64
*/
export default function imageInputFileToBase64({ imageInputFile, maxWidth, imagePreviewNode, }: Param): Promise<ImageInputFileToBase64FunctionReturn>;
export {};
+92
View File
@@ -0,0 +1,92 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = imageInputFileToBase64;
/**
* # Image input File top Base64
*/
function imageInputFileToBase64(_a) {
return __awaiter(this, arguments, void 0, function* ({ imageInputFile, maxWidth, imagePreviewNode, }) {
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
try {
let imageName = imageInputFile.name.replace(/\..*/, "");
let imageDataBase64;
let imageSize;
let canvas = document.createElement("canvas");
const MIME_TYPE = imageInputFile.type;
const QUALITY = 0.95;
const MAX_WIDTH = maxWidth ? maxWidth : null;
const file = imageInputFile;
const blobURL = URL.createObjectURL(file);
const img = new Image();
/** ********************* Add source to new image */
img.src = blobURL;
imageDataBase64 = yield new Promise((res, rej) => {
/** ********************* Handle Errors in loading image */
img.onerror = function () {
URL.revokeObjectURL(this.src);
console.log("Cannot load image");
};
/** ********************* Handle new image when loaded */
img.onload = function (e) {
const imgEl = e.target;
URL.revokeObjectURL(imgEl.src);
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 === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
if (imagePreviewNode) {
imagePreviewNode.src = srcEncoded;
}
res(srcEncoded);
};
});
imageSize = yield new Promise((res, rej) => {
canvas.toBlob((blob) => {
res(blob === null || blob === void 0 ? void 0 : blob.size);
}, MIME_TYPE, QUALITY);
});
return {
imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""),
imageBase64Full: imageDataBase64,
imageName: imageName,
imageSize: imageSize,
};
}
catch (error) {
console.log("Image Processing Error! =>", error.message);
return {
imageBase64: undefined,
imageBase64Full: undefined,
imageName: undefined,
imageSize: undefined,
};
}
});
}
+15
View File
@@ -0,0 +1,15 @@
type FunctionReturn = {
imageBase64?: string;
imageBase64Full?: string;
imageName?: string;
};
type Param = {
imageInput: HTMLInputElement;
maxWidth?: number;
mimeType?: string;
};
/**
* # Image Input Element to Base 64
*/
export default function imageInputToBase64({ imageInput, maxWidth, mimeType, }: Param): Promise<FunctionReturn>;
export {};
+90
View File
@@ -0,0 +1,90 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = imageInputToBase64;
/**
* # Image Input Element to Base 64
*/
function imageInputToBase64(_a) {
return __awaiter(this, arguments, void 0, function* ({ imageInput, maxWidth, mimeType, }) {
var _b, _c;
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
try {
let imagePreviewNode = document.querySelector(`[data-imagepreview='image']`);
let imageName = (_b = imageInput.files) === null || _b === void 0 ? void 0 : _b[0].name.replace(/\..*/, "");
let imageDataBase64;
const MIME_TYPE = mimeType ? mimeType : "image/jpeg";
const QUALITY = 0.95;
const MAX_WIDTH = maxWidth ? maxWidth : null;
const file = (_c = imageInput.files) === null || _c === void 0 ? void 0 : _c[0];
const blobURL = file ? URL.createObjectURL(file) : undefined;
const img = new Image();
if (blobURL) {
img.src = blobURL;
imageDataBase64 = yield 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;
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 === null || ctx === void 0 ? void 0 : 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;
_imgEl.src = srcEncoded;
});
}
res(srcEncoded);
};
});
return {
imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""),
imageBase64Full: imageDataBase64,
imageName: imageName,
};
}
else {
return {};
}
}
catch ( /** @type {*} */error) {
console.log("Image Processing Error! =>", error.message);
return {};
}
});
}
+21
View File
@@ -0,0 +1,21 @@
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 function inputFileToBase64({ inputFile, allowedRegex, }: Param): Promise<FunctionReturn>;
export {};
+59
View File
@@ -0,0 +1,59 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = inputFileToBase64;
/**
* 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.
*/
function inputFileToBase64(_a) {
return __awaiter(this, arguments, void 0, function* ({ inputFile, allowedRegex, }) {
var _b;
const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/;
if (!((_b = inputFile === null || inputFile === void 0 ? void 0 : inputFile.type) === null || _b === void 0 ? void 0 : _b.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 = yield new Promise((resolve, reject) => {
var reader = new FileReader();
reader.readAsDataURL(inputFile);
reader.onload = function () {
var _a;
resolve((_a = reader.result) === null || _a === void 0 ? void 0 : _a.toString());
};
reader.onerror = function (/** @type {*} */ error) {
console.log("Error: ", error.message);
};
});
return {
fileBase64: fileData === null || fileData === void 0 ? void 0 : fileData.replace(/.*?base64,/, ""),
fileBase64Full: fileData,
fileName: fileName,
fileSize: inputFile.size,
fileType: inputFile.type,
};
}
catch (error) {
console.log("File Processing Error! =>", error.message);
return {
fileName: inputFile.name,
};
}
});
}
+8
View File
@@ -0,0 +1,8 @@
/**
* 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;
+31
View File
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
/**
* Parse request cookies
* ============================================================================== *
* @description This function takes in a request object and returns the cookies as a JS object
*/
function default_1() {
/**
* Check inputs
*
* @description Check inputs
*/
const cookieString = document.cookie;
if (!cookieString || typeof cookieString !== "string") {
return null;
}
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;
}
});
return cookieObject;
}
+28
View File
@@ -0,0 +1,28 @@
declare const colors: {
Reset: string;
Bright: string;
Dim: string;
Underscore: string;
Blink: string;
Reverse: string;
Hidden: string;
FgBlack: string;
FgRed: string;
FgGreen: string;
FgYellow: string;
FgBlue: string;
FgMagenta: string;
FgCyan: string;
FgWhite: string;
FgGray: string;
BgBlack: string;
BgRed: string;
BgGreen: string;
BgYellow: string;
BgBlue: string;
BgMagenta: string;
BgCyan: string;
BgWhite: string;
BgGray: string;
};
export default colors;
+30
View File
@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const colors = {
Reset: "\x1b[0m",
Bright: "\x1b[1m",
Dim: "\x1b[2m",
Underscore: "\x1b[4m",
Blink: "\x1b[5m",
Reverse: "\x1b[7m",
Hidden: "\x1b[8m",
FgBlack: "\x1b[30m",
FgRed: "\x1b[31m",
FgGreen: "\x1b[32m",
FgYellow: "\x1b[33m",
FgBlue: "\x1b[34m",
FgMagenta: "\x1b[35m",
FgCyan: "\x1b[36m",
FgWhite: "\x1b[37m",
FgGray: "\x1b[90m",
BgBlack: "\x1b[40m",
BgRed: "\x1b[41m",
BgGreen: "\x1b[42m",
BgYellow: "\x1b[43m",
BgBlue: "\x1b[44m",
BgMagenta: "\x1b[45m",
BgCyan: "\x1b[46m",
BgWhite: "\x1b[47m",
BgGray: "\x1b[100m",
};
exports.default = colors;
+2
View File
@@ -0,0 +1,2 @@
#! /usr/bin/env node
export default function run(): Promise<void>;
+115
View File
@@ -0,0 +1,115 @@
#! /usr/bin/env node
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = run;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
require("dotenv").config({
path: path_1.default.resolve(process.cwd(), ".env"),
});
const index_1 = __importDefault(require("../index"));
const console_colors_1 = __importDefault(require("../console-colors"));
const createDbFromSchema_1 = __importDefault(require("../package-shared/shell/createDbFromSchema"));
if (!fs_1.default.existsSync(path_1.default.resolve(process.cwd(), ".env"))) {
console.log(".env file not found");
process.exit();
}
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC, } = process.env;
if (!(DSQL_HOST === null || DSQL_HOST === void 0 ? void 0 : DSQL_HOST.match(/./))) {
console.log("DSQL_HOST is required in your `.env` file");
process.exit();
}
if (!(DSQL_USER === null || DSQL_USER === void 0 ? void 0 : DSQL_USER.match(/./))) {
console.log("DSQL_USER is required in your `.env` file");
process.exit();
}
if (!(DSQL_PASS === null || DSQL_PASS === void 0 ? void 0 : DSQL_PASS.match(/./))) {
console.log("DSQL_PASS is required in your `.env` file");
process.exit();
}
const dbSchemaLocalFilePath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
function run() {
return __awaiter(this, void 0, void 0, function* () {
let schemaData;
if (DSQL_KEY && (DSQL_REF_DB_NAME === null || DSQL_REF_DB_NAME === void 0 ? void 0 : DSQL_REF_DB_NAME.match(/./))) {
const dbSchemaDataResponse = yield index_1.default.getSchema({
key: DSQL_KEY,
database: DSQL_REF_DB_NAME || undefined,
});
if (!dbSchemaDataResponse.payload ||
Array.isArray(dbSchemaDataResponse.payload)) {
console.log("DSQL_KEY+DSQL_REF_DB_NAME => Error in fetching DB schema");
console.log(dbSchemaDataResponse);
process.exit();
}
let fetchedDbSchemaObject = dbSchemaDataResponse.payload;
if (DSQL_DB_NAME)
fetchedDbSchemaObject.dbFullName = DSQL_DB_NAME;
schemaData = [fetchedDbSchemaObject];
}
else if (DSQL_KEY) {
const dbSchemaDataResponse = yield index_1.default.getSchema({
key: DSQL_KEY,
database: DSQL_REF_DB_NAME || undefined,
});
if (!dbSchemaDataResponse.payload ||
!Array.isArray(dbSchemaDataResponse.payload)) {
console.log("DSQL_KEY => Error in fetching DB schema");
console.log(dbSchemaDataResponse);
process.exit();
}
let fetchedDbSchemaObject = dbSchemaDataResponse.payload;
// fetchedDbSchemaObject.forEach((db, index) => {
// db.dbFullName = db.dbFullName?.replace(/^datasquirel_user_\d+_/, "");
// });
schemaData = fetchedDbSchemaObject;
}
else if (fs_1.default.existsSync(dbSchemaLocalFilePath)) {
schemaData = [
JSON.parse(fs_1.default.readFileSync(dbSchemaLocalFilePath, "utf8")),
];
}
else {
console.log("No source for DB Schema. Please provide a local `dsql.schema.json` file, or provide `DSQL_KEY` and `DSQL_REF_DB_NAME` environment variables.");
process.exit();
}
if (!schemaData) {
console.log("No schema found");
process.exit();
}
if (DSQL_FULL_SYNC === null || DSQL_FULL_SYNC === void 0 ? void 0 : DSQL_FULL_SYNC.match(/true/i)) {
fs_1.default.writeFileSync(dbSchemaLocalFilePath, JSON.stringify(schemaData[0], null, 4), "utf8");
}
console.log(` - ${console_colors_1.default.FgBlue}Info:${console_colors_1.default.Reset} Now generating and mapping databases ...`);
yield (0, createDbFromSchema_1.default)({
dbSchemaData: schemaData,
});
console.log(` - ${console_colors_1.default.FgGreen}Success:${console_colors_1.default.Reset} Databases created Successfully!`);
});
}
let interval;
if (fs_1.default.existsSync(dbSchemaLocalFilePath) && !(DSQL_KEY === null || DSQL_KEY === void 0 ? void 0 : DSQL_KEY.match(/....../))) {
fs_1.default.watchFile(dbSchemaLocalFilePath, { interval: 1000 }, (curr, prev) => {
console.log(` - ${console_colors_1.default.FgBlue}Info:${console_colors_1.default.Reset} Syncing Databases Locally ...`);
run();
});
}
else if (DSQL_KEY === null || DSQL_KEY === void 0 ? void 0 : DSQL_KEY.match(/....../)) {
interval = setInterval(() => {
console.log(` - ${console_colors_1.default.FgMagenta}Info:${console_colors_1.default.Reset} Syncing Databases from the cloud ...`);
run();
}, 20000);
}
run();
+2
View File
@@ -0,0 +1,2 @@
#! /usr/bin/env node
export {};
+52
View File
@@ -0,0 +1,52 @@
#! /usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a, _b, _c;
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const child_process_1 = require("child_process");
const grab_db_names_1 = __importDefault(require("../package-shared/utils/grab-db-names"));
require("dotenv").config({
path: path_1.default.resolve(process.cwd(), ".env"),
});
const mysqlPath = ((_a = process.platform) === null || _a === void 0 ? void 0 : _a.match(/win/i))
? "'" + "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysql.exe" + "'"
: "mysql";
const mysqlDumpPath = ((_b = process.platform) === null || _b === void 0 ? void 0 : _b.match(/win/i))
? "'" +
"C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqldump.exe" +
"'"
: "mysqldump";
const { DSQL_USER, DSQL_PASS } = process.env;
const { dbFullName } = (0, grab_db_names_1.default)();
const dumpFilePathArg = process.argv.indexOf("--file");
if (dumpFilePathArg < 0) {
console.log("Please provide a dump file path using `--file` argument");
process.exit();
}
const dumpFilePath = process.argv[dumpFilePathArg + 1];
if (!(dbFullName === null || dbFullName === void 0 ? void 0 : dbFullName.match(/./))) {
console.log("DSQL_DB_NAME is required in your `.env` file");
process.exit();
}
if (!(DSQL_USER === null || DSQL_USER === void 0 ? void 0 : DSQL_USER.match(/./)) || !(DSQL_PASS === null || DSQL_PASS === void 0 ? void 0 : DSQL_PASS.match(/./))) {
console.log("DSQL_USER and DSQL_PASS are required in your `.env` file");
process.exit();
}
try {
let execSyncOptions = {
cwd: process.cwd(),
};
// if (process.platform.match(/win/i)) execSyncOptions.shell = "bash.exe";
const dump = (0, child_process_1.execSync)(`${mysqlPath} -u ${DSQL_USER} -p${DSQL_PASS} ${dbFullName} < ${dumpFilePath}`, execSyncOptions);
console.log("Dumped successfully", dump.toString());
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
catch (error) {
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `MariaDB Dump Error`, error);
console.log("Dump Error: ", error.message);
}
+2
View File
@@ -0,0 +1,2 @@
#! /usr/bin/env node
export {};
+139
View File
@@ -0,0 +1,139 @@
#! /usr/bin/env node
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importStar(require("fs"));
const __1 = __importDefault(require(".."));
const db_schema_to_type_1 = __importDefault(require("../package-shared/functions/dsql/db-schema-to-type"));
const path_1 = __importDefault(require("path"));
const debug_log_1 = __importDefault(require("../package-shared/utils/logging/debug-log"));
const app_names_1 = require("../package-shared/dict/app-names");
const configFileName = app_names_1.AppNames["SchemaToTypeDefConfigFileName"];
const configFilePath = path_1.default.join(process.cwd(), configFileName);
if (!fs_1.default.existsSync(configFilePath)) {
(0, debug_log_1.default)({
log: `Config File doesn't exist. Please add a '${app_names_1.AppNames["SchemaToTypeDefConfigFileName"]}' in the working directory with relevant configurations.`,
addTime: true,
type: "error",
});
process.exit(1);
}
const config = JSON.parse((0, fs_1.readFileSync)(path_1.default.join(process.cwd(), configFileName), "utf-8"));
if (!config.database) {
(0, debug_log_1.default)({
log: `Config File needs a 'database' value.`,
addTime: true,
type: "error",
});
process.exit(1);
}
if (!config.outDir && !config.outFile) {
(0, debug_log_1.default)({
log: `Config File needs a 'outDir' or 'outFile' value.`,
addTime: true,
type: "error",
});
process.exit(1);
}
if (!config.apiConnectionConfig) {
(0, debug_log_1.default)({
log: `Config File needs a 'apiConnectionConfig' value. This value needs an 'apiKey' value.`,
addTime: true,
type: "error",
});
process.exit(1);
}
if (!config.apiConnectionConfig.apiKey) {
(0, debug_log_1.default)({
log: `Config value 'apiConnectionConfig' needs an 'apiKey' value.`,
addTime: true,
type: "error",
});
process.exit(1);
}
(() => __awaiter(void 0, void 0, void 0, function* () {
try {
if (config.debug) {
(0, debug_log_1.default)({
log: config,
label: "Config",
addTime: true,
});
}
const schemaRes = yield __1.default.api.schema.get({
dbName: config.database || "",
apiConnectionConfig: config.apiConnectionConfig,
});
const dbSchema = schemaRes.singleRes;
if (config.debug) {
(0, debug_log_1.default)({
log: schemaRes,
label: "schema",
addTime: true,
});
}
if (!dbSchema)
throw new Error("No schema found");
const definitions = (0, db_schema_to_type_1.default)({ dbSchema });
const finalOutfile = path_1.default.resolve(process.cwd(), config.outDir ? config.outDir + "/dsql.ts" : config.outFile || "");
const ourfileDir = path_1.default.dirname(finalOutfile);
if (!fs_1.default.existsSync(ourfileDir)) {
fs_1.default.mkdirSync(ourfileDir, { recursive: true });
}
fs_1.default.writeFileSync(finalOutfile, (definitions === null || definitions === void 0 ? void 0 : definitions.join("\n\n")) || "", "utf-8");
}
catch (error) {
(0, debug_log_1.default)({
log: error.message,
label: "Error",
title: "Schema to Typedef",
addTime: true,
type: "error",
});
process.exit(1);
}
}))();
+172
View File
@@ -0,0 +1,172 @@
declare global {
var ERROR_CALLBACK: ErrorCallback | undefined;
}
import get from "./package-shared/actions/get";
import post from "./package-shared/actions/post";
import getSchema from "./package-shared/actions/get-schema";
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 connDbHandler from "./package-shared/utils/db/conn-db-handler";
import encrypt from "./package-shared/functions/dsql/encrypt";
import decrypt from "./package-shared/functions/dsql/decrypt";
import hashPassword from "./package-shared/functions/dsql/hashPassword";
import dsqlCrud from "./package-shared/utils/data-fetching/crud";
import dsqlMethodCrud from "./package-shared/utils/data-fetching/method-crud";
import debugLog from "./package-shared/utils/logging/debug-log";
import { ErrorCallback } from "./package-shared/types";
import parseEnv from "./package-shared/utils/parse-env";
import dbHandler from "./package-shared/functions/backend/dbHandler";
import httpsRequest from "./package-shared/functions/backend/httpsRequest";
import handleNodemailer from "./package-shared/functions/backend/handleNodemailer";
import grabDSQLConnection from "./package-shared/utils/grab-dsql-connection";
import grabDSQLConnectionConfig from "./package-shared/utils/grab-dsql-connection-config";
import purgeDefaultFields from "./package-shared/utils/purge-default-fields";
import apiCrudHandler from "./package-shared/api-paths";
/**
* Main Export
*/
declare const datasquirel: {
/**
* API Actions
*/
api: {
crud: {
get: typeof import("./package-shared/api/crud/get").default;
insert: typeof import("./package-shared/api/crud/post").default;
update: typeof import("./package-shared/api/crud/put").default;
delete: typeof import("./package-shared/api/crud/delete").default;
options: () => Promise<void>;
};
media: {
get: typeof import("./package-shared/api/media/get").default;
add: typeof import("./package-shared/api/media/post").default;
delete: typeof import("./package-shared/api/media/delete").default;
};
user: {
auth: {
login: typeof import("./package-shared/actions/users/login-user").default;
get: typeof import("./package-shared/actions/users/get-user").default;
signup: typeof import("./package-shared/actions/users/add-user").default;
sendEmailCode: typeof import("./package-shared/actions/users/send-email-code").default;
update: typeof import("./package-shared/actions/users/update-user").default;
resetPassword: typeof import("./package-shared/actions/users/reset-password").default;
googleLogin: typeof import("./package-shared/actions/users/social/google-auth").default;
logout: typeof import("./package-shared/actions/users/logout-user").default;
auth: typeof import("./package-shared/actions/users/user-auth").default;
validateTempEmailCode: typeof import("./package-shared/actions/users/validate-temp-email-code").default;
};
};
schema: {
get: typeof import("./package-shared/api/schema/get").default;
};
};
/**
* Get Action
*/
get: typeof get;
/**
* Post Action
*/
post: typeof post;
user: {
auth: {
login: (_: import("./package-shared/types").LoginUserParam) => Promise<import("./package-shared/types").APIResponseObject>;
get: (_: import("./package-shared/types").GetUserParams) => Promise<import("./package-shared/types").APIResponseObject>;
signup: (_: import("./package-shared/types").AddUserParams) => Promise<import("./package-shared/types").APIResponseObject>;
sendEmailCode: (_: import("./package-shared/types").SendEmailCodeParams) => Promise<import("./package-shared/types").APIResponseObject>;
update: (_: import("./package-shared/types").UpdateUserParams) => Promise<import("./package-shared/types").APIResponseObject>;
resetPassword: (_: import("./package-shared/types").ResetPasswordParams) => Promise<import("./package-shared/types").APIResponseObject>;
googleLogin: (_: import("./package-shared/types").GoogleAuthParams) => Promise<import("./package-shared/types").APIResponseObject>;
logout: typeof import("./package-shared/actions/users/logout-user").default;
auth: typeof import("./package-shared/actions/users/user-auth").default;
validateTempEmailCode: typeof import("./package-shared/actions/users/validate-temp-email-code").default;
githubLoginFn: typeof import("./package-shared/functions/api/social-login/githubLogin").default;
};
};
getSchema: typeof getSchema;
client: {
media: {
imageInputToBase64: typeof import("./client/media/imageInputToBase64").default;
imageInputFileToBase64: typeof import("./client/media/imageInputFileToBase64").default;
inputFileToBase64: typeof import("./client/media/inputFileToBase64").default;
};
auth: {
google: {
getAccessToken: typeof import("./client/auth/google/getAccessToken").default;
};
github: {
getAccessToken: typeof import("./client/auth/github/getAccessToken").default;
};
logout: typeof import("./client/auth/logout").default;
postLogin: typeof import("./client/auth/post-login").default;
};
fetch: {
fetchApi: typeof import("./client/fetch").default;
clientFetch: typeof import("./client/fetch").default;
};
utils: {
deserializeQuery: typeof import("./package-shared/utils/deserialize-query").default;
serializeQuery: typeof import("./package-shared/utils/serialize-query").default;
serializeCookies: typeof import("./package-shared/utils/serialize-cookies").default;
EJSON: {
parse: (string: string | null | number, reviver?: (this: any, key: string, value: any) => any) => {
[s: string]: any;
} | {
[s: string]: any;
}[] | undefined;
stringify: (value: any, replacer?: ((this: any, key: string, value: any) => any) | null, space?: string | number) => string | undefined;
};
numberfy: typeof import("./package-shared/utils/numberfy").default;
slugify: typeof import("./package-shared/utils/slugify").default;
debugLog: typeof debugLog;
};
clientCrudFetch: typeof import("./client/crud-fetch").default;
};
sql: {
sqlGenerator: typeof sqlGenerator;
sqlInsertGenerator: typeof sqlInsertGenerator;
sqlDeleteGenerator: typeof sqlDeleteGenerator;
trim: typeof trimSql;
};
utils: {
crypto: {
encrypt: typeof encrypt;
decrypt: typeof decrypt;
hashPassword: typeof hashPassword;
};
parseCookies: typeof parseCookies;
connDbHandler: typeof connDbHandler;
debugLog: typeof debugLog;
parseEnv: typeof parseEnv;
httpsRequest: typeof httpsRequest;
httpRequest: typeof httpsRequest;
grabDSQLConnection: typeof grabDSQLConnection;
grabDSQLConnectionConfig: typeof grabDSQLConnectionConfig;
purgeDefaultFields: typeof purgeDefaultFields;
};
/**
* Run Crud actions `get`, `insert`, `update`, `delete`
* @description *Requires global variables `DSQL_USE_LOCAL` and `DSQL_DB_CONN`
*/
crud: typeof dsqlCrud;
/**
* Run Crud based on request Methods `GET`, `POST`, `PUT`, `PATCH`
* @description *Requires global variables `DSQL_USE_LOCAL` and `DSQL_DB_CONN`
*/
methodCrud: typeof dsqlMethodCrud;
/**
* General Database Handler
*/
dbHandler: typeof dbHandler;
/**
* Handle Mail
*/
mail: {
mailer: typeof handleNodemailer;
};
apiCrudHandler: typeof apiCrudHandler;
};
export default datasquirel;
+111
View File
@@ -0,0 +1,111 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const get_1 = __importDefault(require("./package-shared/actions/get"));
const post_1 = __importDefault(require("./package-shared/actions/post"));
const get_schema_1 = __importDefault(require("./package-shared/actions/get-schema"));
const client_1 = __importDefault(require("./client"));
const sql_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-generator"));
const sql_insert_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-insert-generator"));
const sql_delete_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-delete-generator"));
const trim_sql_1 = __importDefault(require("./package-shared/utils/trim-sql"));
const parseCookies_1 = __importDefault(require("./package-shared/utils/backend/parseCookies"));
const conn_db_handler_1 = __importDefault(require("./package-shared/utils/db/conn-db-handler"));
const encrypt_1 = __importDefault(require("./package-shared/functions/dsql/encrypt"));
const decrypt_1 = __importDefault(require("./package-shared/functions/dsql/decrypt"));
const hashPassword_1 = __importDefault(require("./package-shared/functions/dsql/hashPassword"));
const crud_1 = __importDefault(require("./package-shared/utils/data-fetching/crud"));
const method_crud_1 = __importDefault(require("./package-shared/utils/data-fetching/method-crud"));
const debug_log_1 = __importDefault(require("./package-shared/utils/logging/debug-log"));
const parse_env_1 = __importDefault(require("./package-shared/utils/parse-env"));
const crud_2 = __importDefault(require("./package-shared/api/crud"));
const user_1 = __importDefault(require("./package-shared/api/user"));
const local_user_1 = __importDefault(require("./package-shared/api/user/local-user"));
const media_1 = __importDefault(require("./package-shared/api/media"));
const dbHandler_1 = __importDefault(require("./package-shared/functions/backend/dbHandler"));
const httpsRequest_1 = __importDefault(require("./package-shared/functions/backend/httpsRequest"));
const handleNodemailer_1 = __importDefault(require("./package-shared/functions/backend/handleNodemailer"));
const grab_dsql_connection_1 = __importDefault(require("./package-shared/utils/grab-dsql-connection"));
const grab_dsql_connection_config_1 = __importDefault(require("./package-shared/utils/grab-dsql-connection-config"));
const schema_1 = __importDefault(require("./package-shared/api/schema"));
const purge_default_fields_1 = __importDefault(require("./package-shared/utils/purge-default-fields"));
const api_paths_1 = __importDefault(require("./package-shared/api-paths"));
/**
* API Functions Object
*/
const api = {
crud: crud_2.default,
media: media_1.default,
user: user_1.default,
schema: schema_1.default,
};
/**
* SQL Utils
*/
const sql = {
sqlGenerator: sql_generator_1.default,
sqlInsertGenerator: sql_insert_generator_1.default,
sqlDeleteGenerator: sql_delete_generator_1.default,
trim: trim_sql_1.default,
};
/**
* Main Export
*/
const datasquirel = {
/**
* API Actions
*/
api,
/**
* Get Action
*/
get: get_1.default,
/**
* Post Action
*/
post: post_1.default,
user: local_user_1.default,
getSchema: get_schema_1.default,
client: client_1.default,
sql,
utils: {
crypto: {
encrypt: encrypt_1.default,
decrypt: decrypt_1.default,
hashPassword: hashPassword_1.default,
},
parseCookies: parseCookies_1.default,
connDbHandler: conn_db_handler_1.default,
debugLog: debug_log_1.default,
parseEnv: parse_env_1.default,
httpsRequest: httpsRequest_1.default,
httpRequest: httpsRequest_1.default,
grabDSQLConnection: grab_dsql_connection_1.default,
grabDSQLConnectionConfig: grab_dsql_connection_config_1.default,
purgeDefaultFields: purge_default_fields_1.default,
},
/**
* Run Crud actions `get`, `insert`, `update`, `delete`
* @description *Requires global variables `DSQL_USE_LOCAL` and `DSQL_DB_CONN`
*/
crud: crud_1.default,
/**
* Run Crud based on request Methods `GET`, `POST`, `PUT`, `PATCH`
* @description *Requires global variables `DSQL_USE_LOCAL` and `DSQL_DB_CONN`
*/
methodCrud: method_crud_1.default,
/**
* General Database Handler
*/
dbHandler: dbHandler_1.default,
/**
* Handle Mail
*/
mail: {
mailer: handleNodemailer_1.default,
},
apiCrudHandler: api_paths_1.default,
};
exports.default = datasquirel;
+18
View File
@@ -0,0 +1,18 @@
interface Return {
success: boolean;
payload: {
urlPath: string;
urlThumbnailPath: string;
} | null;
msg?: string;
}
type Param = {
key: string;
url: string;
user_id?: string | number;
};
/**
* # Delete File via API
*/
export default function deleteFile({ key, url, user_id, }: Param): Promise<Return>;
export {};
+76
View File
@@ -0,0 +1,76 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = deleteFile;
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
/**
* # Delete File via API
*/
function deleteFile(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, url, user_id, }) {
const grabedHostNames = (0, grab_host_names_1.default)();
const { host, port, scheme } = grabedHostNames;
try {
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = yield new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({ url: url });
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/query/${user_id || grabedHostNames.user_id}/delete-file`,
},
/**
* 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);
});
});
httpsRequest.write(reqPayload);
httpsRequest.end();
});
return httpResponse;
}
catch ( /** @type {*} */error) {
console.log("Error deleting file: ", error.message);
return {
success: false,
payload: null,
msg: error.message,
};
}
});
}
+1
View File
@@ -0,0 +1 @@
export default function getCsrfHeaderName(): string;
+6
View File
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = getCsrfHeaderName;
function getCsrfHeaderName() {
return "x-dsql-csrf-key";
}
+10
View File
@@ -0,0 +1,10 @@
import { DSQL_DatabaseSchemaType, DSQL_FieldSchemaType, DSQL_TableSchemaType, GetSchemaAPIParam } from "../types";
type GetSchemaReturn = {
success: boolean;
payload?: DSQL_DatabaseSchemaType | DSQL_TableSchemaType | DSQL_FieldSchemaType | null;
};
/**
* # Get Schema for Database, table, or field *
*/
export default function getSchema({ key, database, field, table, user_id, env, }: GetSchemaAPIParam): Promise<GetSchemaReturn>;
export {};
+69
View File
@@ -0,0 +1,69 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = getSchema;
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
/**
* # Get Schema for Database, table, or field *
*/
function getSchema(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, database, field, table, user_id, env, }) {
const grabedHostNames = (0, grab_host_names_1.default)({ env });
const { host, port, scheme } = grabedHostNames;
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = yield new Promise((resolve, reject) => {
const queryObject = { database, field, table };
let query = Object.keys(queryObject)
.filter((k) => queryObject[k])
.map((k) => `${k}=${queryObject[k]}`)
.join("&");
scheme
.request({
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/query/${user_id || grabedHostNames.user_id}/get-schema` + ((query === null || query === void 0 ? void 0 : query.match(/./)) ? `?${query}` : ""),
},
/**
* 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) => {
resolve(null);
});
})
.end();
});
return httpResponse;
});
}
+24
View File
@@ -0,0 +1,24 @@
import { APIResponseObject, DsqlCrudQueryObject } from "../types";
type Param<T extends {
[k: string]: any;
} = {
[k: string]: any;
}> = {
key?: string;
database: string;
query: DsqlCrudQueryObject<T>;
table?: string;
debug?: boolean;
useLocal?: boolean;
apiVersion?: string;
};
export type ApiGetParams = Param;
/**
* # Make a get request to Datasquirel API
*/
export default function get<T extends {
[k: string]: any;
} = {
[k: string]: any;
}>({ key, database, query, table, debug, useLocal, apiVersion, }: Param<T>): Promise<APIResponseObject>;
export {};
+101
View File
@@ -0,0 +1,101 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = get;
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
const serialize_query_1 = __importDefault(require("../utils/serialize-query"));
const debug_log_1 = __importDefault(require("../utils/logging/debug-log"));
const crud_1 = __importDefault(require("../utils/data-fetching/crud"));
const grab_api_key_1 = __importDefault(require("../utils/grab-api-key"));
/**
* # Make a get request to Datasquirel API
*/
function get(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, database, query, table, debug, useLocal, apiVersion = "v1", }) {
const grabedHostNames = (0, grab_host_names_1.default)();
const { host, port, scheme } = grabedHostNames;
function debugFn(log, label) {
(0, debug_log_1.default)({ log, addTime: true, title: "apiGet", label });
}
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
if (useLocal) {
const result = yield (0, crud_1.default)({
action: "get",
table: table || "",
dbFullName: database,
query,
});
return result;
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = yield new Promise((resolve, reject) => {
const queryString = (0, serialize_query_1.default)(query);
if (debug) {
debugFn(queryString, "queryString");
}
let path = `/api/${apiVersion}/crud/${database}/${table}`;
if (debug) {
debugFn(path, "path");
}
const requestObject = {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: (0, grab_api_key_1.default)(key),
},
port,
hostname: host,
path,
};
scheme
.request(requestObject,
/**
* 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) {
reject({
error: error.message,
result: str,
});
}
});
response.on("error", (err) => {
console.log("DSQL get Error,", err.message);
resolve(null);
});
})
.end();
});
return httpResponse;
});
}
+16
View File
@@ -0,0 +1,16 @@
import { PostDataPayload, PostReturn } from "../types";
type Param = {
key?: string;
database?: string;
query: string | PostDataPayload;
queryValues?: any[];
tableName?: string;
user_id?: boolean;
useLocal?: boolean;
debug?: boolean;
};
/**
* # Make a post request to Datasquirel API
*/
export default function post({ key, query, queryValues, database, tableName, user_id, useLocal, debug, }: Param): Promise<PostReturn>;
export {};
+132
View File
@@ -0,0 +1,132 @@
"use strict";
// @ts-check
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = post;
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
const post_1 = __importDefault(require("../functions/api/query/post"));
const debug_log_1 = __importDefault(require("../utils/logging/debug-log"));
/**
* # Make a post request to Datasquirel API
*/
function post(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, query, queryValues, database, tableName, user_id, useLocal, debug, }) {
const grabedHostNames = (0, grab_host_names_1.default)();
const { host, port, scheme } = grabedHostNames;
if (debug) {
(0, debug_log_1.default)({
log: grabedHostNames,
addTime: true,
label: "grabedHostNames",
});
}
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
if (useLocal) {
if (debug) {
(0, debug_log_1.default)({
log: "Using Local DB ...",
addTime: true,
});
}
return yield (0, post_1.default)({
dbFullName: database || "",
query,
queryValues,
tableName,
debug,
});
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = yield new Promise((resolve, reject) => {
const reqPayloadString = JSON.stringify({
query,
queryValues,
database: process.env.DSQL_API_DB_NAME || database,
tableName: tableName ? tableName : null,
}).replace(/\n|\r|\n\r/gm, "");
try {
JSON.parse(reqPayloadString);
}
catch (error) {
console.log("Error Parsing HTTP response for post action: ", error.message);
return {
success: false,
payload: null,
error: "Query object is invalid. Please Check query data values",
};
}
const reqPayload = reqPayloadString;
const requPath = `/api/query/${user_id || grabedHostNames.user_id}/post`;
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: requPath,
},
/**
* 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("Route ERROR:", error.message);
resolve({
success: false,
payload: null,
error: error.message,
errPayload: str,
});
}
});
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);
});
httpsRequest.end();
});
return httpResponse;
});
}
+24
View File
@@ -0,0 +1,24 @@
interface Return {
success: boolean;
payload: {
urlPath: string;
} | null;
msg?: string;
}
type Param = {
key: string;
payload: {
fileData: string;
fileName: string;
mimeType?: string;
folder?: string;
isPrivate?: boolean;
};
user_id?: string | number;
useDefault?: boolean;
};
/**
* # Upload File via API
*/
export default function uploadImage({ key, payload, user_id, useDefault, }: Param): Promise<Return>;
export {};
+76
View File
@@ -0,0 +1,76 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = uploadImage;
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
/**
* # Upload File via API
*/
function uploadImage(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, payload, user_id, useDefault, }) {
const grabedHostNames = (0, grab_host_names_1.default)({ useDefault });
const { host, port, scheme } = grabedHostNames;
try {
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = yield new Promise((resolve, reject) => {
const reqPayload = JSON.stringify(payload);
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/query/${user_id || grabedHostNames.user_id}/add-file`,
},
/**
* 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);
});
});
httpsRequest.write(reqPayload);
httpsRequest.end();
});
return httpResponse;
}
catch (error) {
console.log("Error in uploading file: ", error.message);
return {
success: false,
payload: null,
msg: error.message,
};
}
});
}
+27
View File
@@ -0,0 +1,27 @@
export interface DSQLUploadImageFunctionReturn {
success: boolean;
payload: DSQLUploadImagePayload | null;
msg?: string;
}
export interface DSQLUploadImagePayload {
urlPath: string;
urlThumbnailPath: string;
}
type Param = {
key?: string;
payload: {
imageData: string;
imageName: string;
mimeType?: string;
thumbnailSize?: number;
folder?: string;
isPrivate?: boolean;
};
user_id?: string | number;
useDefault?: boolean;
};
/**
* # Upload Image via API
*/
export default function uploadImage({ key, payload, user_id, useDefault, }: Param): Promise<DSQLUploadImageFunctionReturn>;
export {};
+76
View File
@@ -0,0 +1,76 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = uploadImage;
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
/**
* # Upload Image via API
*/
function uploadImage(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, payload, user_id, useDefault, }) {
const grabedHostNames = (0, grab_host_names_1.default)({ useDefault });
const { host, port, scheme } = grabedHostNames;
try {
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = yield new Promise((resolve, reject) => {
const reqPayload = JSON.stringify(payload);
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/query/${user_id || grabedHostNames.user_id}/add-image`,
},
/**
* 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);
});
});
httpsRequest.write(reqPayload);
httpsRequest.end();
});
return httpResponse;
}
catch (error) {
console.log("Error in uploading image: ", error.message);
return {
success: false,
payload: null,
msg: error.message,
};
}
});
}
+5
View File
@@ -0,0 +1,5 @@
import { AddUserParams, APIResponseObject } from "../../types";
/**
* # Add User to Database
*/
export default function addUser({ apiKey, payload, database, encryptionKey, useLocal, verify, apiVersion, dsqlUserID, }: AddUserParams): Promise<APIResponseObject>;
+55
View File
@@ -0,0 +1,55 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = addUser;
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
const api_create_user_1 = __importDefault(require("../../functions/api/users/api-create-user"));
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
const query_dsql_api_1 = __importDefault(require("../../functions/api/query-dsql-api"));
/**
* # Add User to Database
*/
function addUser(_a) {
return __awaiter(this, arguments, void 0, function* ({ apiKey, payload, database, encryptionKey, useLocal, verify, apiVersion = "v1", dsqlUserID, }) {
const grabedHostNames = (0, grab_host_names_1.default)();
const { host, port, scheme } = grabedHostNames;
const apiAddUserParams = {
database,
encryptionKey,
payload,
verify,
dsqlUserID,
};
if (useLocal) {
return yield (0, api_create_user_1.default)(apiAddUserParams);
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = yield (0, query_dsql_api_1.default)({
path: (0, grab_api_path_1.default)({
paradigm: "auth",
action: "signup",
database,
apiVersion,
}),
apiKey,
body: apiAddUserParams,
method: "POST",
});
return httpResponse;
});
}
+13
View File
@@ -0,0 +1,13 @@
import { UpdateUserFunctionReturn } from "../../types";
type Param = {
apiKey?: string;
database: string;
deletedUserId: string | number;
useLocal?: boolean;
apiVersion?: string;
};
/**
* # Update User
*/
export default function deleteUser({ apiKey, database, deletedUserId, useLocal, apiVersion, }: Param): Promise<UpdateUserFunctionReturn>;
export {};
+84
View File
@@ -0,0 +1,84 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = deleteUser;
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
const api_delete_user_1 = __importDefault(require("../../functions/api/users/api-delete-user"));
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
/**
* # Update User
*/
function deleteUser(_a) {
return __awaiter(this, arguments, void 0, function* ({ apiKey, database, deletedUserId, useLocal, apiVersion = "v1", }) {
const grabedHostNames = (0, grab_host_names_1.default)();
const { host, port, scheme } = grabedHostNames;
if (useLocal) {
return yield (0, api_delete_user_1.default)({
dbFullName: database,
deletedUserId,
});
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = (yield new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
database,
deletedUserId,
});
const finalAPIKey = apiKey ||
process.env.DSQL_API_KEY ||
process.env.DSQL_FULL_ACCESS_API_KEY;
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: finalAPIKey,
},
port,
hostname: host,
path: (0, grab_api_path_1.default)({
paradigm: "auth",
action: "delete",
database,
apiVersion,
userID: deletedUserId,
}),
},
/**
* 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);
});
});
httpsRequest.write(reqPayload);
httpsRequest.end();
}));
return httpResponse;
});
}
+20
View File
@@ -0,0 +1,20 @@
import http from "http";
type Param = {
request?: http.IncomingMessage;
cookieString?: string;
encryptionKey: string;
encryptionSalt: string;
database: string;
};
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, cookieString, }: Param): Return;
export {};
+75
View File
@@ -0,0 +1,75 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = getToken;
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
const parseCookies_1 = __importDefault(require("../../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
*/
function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
try {
/**
* Grab the payload
*
* @description Grab the payload
*/
const cookies = (0, parseCookies_1.default)({ request, cookieString });
const keynames = (0, get_auth_cookie_names_1.default)();
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 = (0, decrypt_1.default)({
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) {
console.log("Error Getting Token:", error.message);
/**
* Return User Object
*
* @description Return User Object
*/
return {
key: undefined,
csrf: undefined,
};
}
}
+5
View File
@@ -0,0 +1,5 @@
import { APIResponseObject, GetUserParams } from "../../types";
/**
* # Get User
*/
export default function getUser({ apiKey, userId, database, fields, useLocal, apiVersion, dbUserId, selectAll, }: GetUserParams): Promise<APIResponseObject>;
+106
View File
@@ -0,0 +1,106 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = getUser;
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
const api_get_user_1 = __importDefault(require("../../functions/api/users/api-get-user"));
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
/**
* # Get User
*/
function getUser(_a) {
return __awaiter(this, arguments, void 0, function* ({ apiKey, userId, database, fields, useLocal, apiVersion = "v1", dbUserId, selectAll, }) {
/**
* Initialize
*/
const defaultFields = [
"id",
"first_name",
"last_name",
"email",
"username",
"image",
"image_thumbnail",
"verification_status",
"date_created",
"date_created_code",
"date_created_timestamp",
"date_updated",
"date_updated_code",
"date_updated_timestamp",
];
const updatedFields = fields && fields[0] ? [...defaultFields, ...fields] : defaultFields;
const grabedHostNames = (0, grab_host_names_1.default)();
const { host, port, scheme } = grabedHostNames;
const getUserParams = {
userId,
fields: [...new Set(updatedFields)],
database,
dbUserId,
selectAll,
};
if (useLocal) {
return yield (0, api_get_user_1.default)(getUserParams);
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = yield new Promise((resolve, reject) => {
const reqPayload = JSON.stringify(getUserParams);
const finalAPIKey = apiKey ||
process.env.DSQL_API_KEY ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_READ_ONLY_API_KEY;
const httpsRequest = scheme.request({
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: finalAPIKey,
},
port,
hostname: host,
path: (0, grab_api_path_1.default)({
paradigm: "auth",
action: "get",
database,
apiVersion,
userID: userId,
}),
},
/**
* 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);
});
});
httpsRequest.write(reqPayload);
httpsRequest.end();
});
return httpResponse;
});
}
+5
View File
@@ -0,0 +1,5 @@
import { APIResponseObject, LoginUserParam } from "../../types";
/**
* # Login A user
*/
export default function loginUser({ apiKey, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, useLocal, apiVersion, }: LoginUserParam): Promise<APIResponseObject>;
+119
View File
@@ -0,0 +1,119 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = loginUser;
const api_login_1 = __importDefault(require("../../functions/api/users/api-login"));
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
const grab_cookie_expirt_date_1 = __importDefault(require("../../utils/grab-cookie-expirt-date"));
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
const query_dsql_api_1 = __importDefault(require("../../functions/api/query-dsql-api"));
const post_login_response_handler_1 = __importDefault(require("../../functions/backend/auth/post-login-response-handler"));
function debugFn(log, label) {
(0, debug_log_1.default)({ log, addTime: true, title: "loginUser", label });
}
/**
* # Login A user
*/
function loginUser(_a) {
return __awaiter(this, arguments, void 0, function* ({ apiKey, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, useLocal, apiVersion = "v1", }) {
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
const defaultTempLoginFieldName = "temp_login_code";
const emailLoginTempCodeFieldName = email_login
? temp_code_field
? temp_code_field
: defaultTempLoginFieldName
: undefined;
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
console.log("Encryption key is invalid");
return {
success: false,
payload: null,
msg: "Encryption key is invalid",
};
}
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
console.log("Encryption salt is invalid");
return {
success: false,
payload: null,
msg: "Encryption salt is invalid",
};
}
/**
* Initialize HTTP response variable
*/
let httpResponse = {
success: false,
};
const apiLoginParams = {
database,
email: payload.email,
username: payload.username,
password: payload.password,
skipPassword,
encryptionKey: finalEncryptionKey,
additionalFields,
email_login,
email_login_code,
email_login_field: emailLoginTempCodeFieldName,
token,
dbUserId,
debug,
};
/**
* Check for local DB settings
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
if (useLocal) {
httpResponse = yield (0, api_login_1.default)(apiLoginParams);
}
else {
httpResponse = yield (0, query_dsql_api_1.default)({
path: (0, grab_api_path_1.default)({
paradigm: "auth",
action: "login",
database,
apiVersion,
}),
apiKey,
body: apiLoginParams,
method: "POST",
});
}
if (debug) {
debugFn(httpResponse, "httpResponse");
}
/**
* # Send Response
*/
if (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) {
(0, post_login_response_handler_1.default)({
database,
httpResponse,
cleanupTokens,
debug,
encryptionKey,
encryptionSalt,
response,
secureCookie,
skipWriteAuthFile,
token,
});
}
return httpResponse;
});
}
+24
View File
@@ -0,0 +1,24 @@
import http from "http";
type Param = {
encryptedUserString?: string;
request?: http.IncomingMessage & {
[s: string]: any;
};
response?: http.ServerResponse & {
[s: string]: any;
};
cookieString?: string;
database?: string;
dsqlUserId?: string | number;
debug?: boolean;
};
type Return = {
success: boolean;
msg: string;
cookieNames?: any;
};
/**
* # Logout user
*/
export default function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, debug, }: Param): Return;
export {};
+88
View File
@@ -0,0 +1,88 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = logoutUser;
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
const ejson_1 = __importDefault(require("../../utils/ejson"));
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
/**
* # Logout user
*/
function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, debug, }) {
/**
* Check Encryption Keys
*
* @description Check Encryption Keys
*/
try {
const cookieNames = (0, get_auth_cookie_names_1.default)({
database,
});
function debugFn(log, label) {
(0, debug_log_1.default)({ log, addTime: true, title: "logoutUser", label });
}
if (debug) {
debugFn(cookieNames, "cookieNames");
}
const authKeyName = cookieNames.keyCookieName;
const csrfName = cookieNames.csrfCookieName;
const oneTimeCodeName = cookieNames.oneTimeCodeName;
const decryptedUserJSON = (() => {
try {
if (request) {
const cookiesObject = (0, parseCookies_1.default)({
request,
cookieString,
});
return (0, decrypt_1.default)({
encryptedString: cookiesObject[authKeyName],
});
}
else if (encryptedUserString) {
return (0, decrypt_1.default)({
encryptedString: encryptedUserString,
});
}
else {
return undefined;
}
}
catch (error) {
console.log("Error getting decrypted User JSON to logout:", error.message);
return undefined;
}
})();
if (debug) {
debugFn(decryptedUserJSON, "decryptedUserJSON");
}
if (!decryptedUserJSON)
throw new Error("Invalid User");
const userObject = ejson_1.default.parse(decryptedUserJSON);
if (!(userObject === null || userObject === void 0 ? void 0 : userObject.csrf_k))
throw new Error("Invalid User. Please check key");
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
`${authKeyName}=null;max-age=0`,
`${csrfName}=null;max-age=0`,
`${oneTimeCodeName}=null;max-age=0`,
]);
const csrf = userObject.csrf_k;
(0, write_auth_files_1.deleteAuthFile)(csrf);
return {
success: true,
msg: "User Logged Out",
cookieNames,
};
}
catch (error) {
console.log("Logout Error:", error.message);
return {
success: false,
msg: "Logout Failed",
};
}
}
+5
View File
@@ -0,0 +1,5 @@
import { APIResponseObject, ResetPasswordParams } from "../../types";
/**
* # Reset User Password
*/
export default function resetPassword(params: ResetPasswordParams): Promise<APIResponseObject>;
+40
View File
@@ -0,0 +1,40 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = resetPassword;
const query_dsql_api_1 = __importDefault(require("../../functions/api/query-dsql-api"));
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
const api_reset_user_password_1 = __importDefault(require("../../functions/api/users/api-reset-user-password"));
/**
* # Reset User Password
*/
function resetPassword(params) {
return __awaiter(this, void 0, void 0, function* () {
if (params.useLocal) {
return yield (0, api_reset_user_password_1.default)(params);
}
const httpResponse = yield (0, query_dsql_api_1.default)({
path: (0, grab_api_path_1.default)({
paradigm: "auth",
action: "reset-password",
database: params.database,
apiVersion: params.apiVersion,
}),
apiKey: params.apiKey,
body: params,
method: "POST",
});
return httpResponse;
});
}
@@ -0,0 +1,5 @@
import { APIResponseObject, SendEmailCodeParams } from "../../types";
/**
* # Send Email Code to a User
*/
export default function sendEmailCode(params: SendEmailCodeParams): Promise<APIResponseObject>;
+62
View File
@@ -0,0 +1,62 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = sendEmailCode;
const api_send_email_code_1 = __importDefault(require("../../functions/api/users/api-send-email-code"));
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
const query_dsql_api_1 = __importDefault(require("../../functions/api/query-dsql-api"));
/**
* # Send Email Code to a User
*/
function sendEmailCode(params) {
return __awaiter(this, void 0, void 0, function* () {
const { apiKey, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, response, extraCookies, useLocal, apiVersion, html, } = params;
const defaultTempLoginFieldName = "temp_login_code";
const emailLoginTempCodeFieldName = temp_code_field_name
? temp_code_field_name
: defaultTempLoginFieldName;
const emailHtml = html ||
`<p>Please use this code to login</p>\n<h2>{{code}}</h2>\n<p>Please note that this code expires after 15 minutes</p>`;
const apiSendEmailCodeParams = {
database,
email,
email_login_field: emailLoginTempCodeFieldName,
html: emailHtml,
mail_domain,
mail_password,
mail_port,
mail_username,
sender,
response,
extraCookies,
};
if (useLocal) {
return yield (0, api_send_email_code_1.default)(apiSendEmailCodeParams);
}
else {
const httpResponse = yield (0, query_dsql_api_1.default)({
path: (0, grab_api_path_1.default)({
paradigm: "auth",
action: "send-email-code",
database,
apiVersion,
}),
apiKey,
body: apiSendEmailCodeParams,
method: "POST",
});
return httpResponse;
}
});
}
@@ -0,0 +1,35 @@
import http from "http";
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;
secureCookie?: boolean;
};
/**
* # SERVER FUNCTION: Login with google Function
*/
export default function githubAuth({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, secureCookie, }: Param): Promise<FunctionReturn | undefined>;
export {};
+174
View File
@@ -0,0 +1,174 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = githubAuth;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const encrypt_1 = __importDefault(require("../../../functions/dsql/encrypt"));
const grab_host_names_1 = __importDefault(require("../../../utils/grab-host-names"));
const api_github_login_1 = __importDefault(require("../../../functions/api/users/social/api-github-login"));
const grab_cookie_expirt_date_1 = __importDefault(require("../../../utils/grab-cookie-expirt-date"));
const grab_db_names_1 = __importDefault(require("../../../utils/grab-db-names"));
/**
* # SERVER FUNCTION: Login with google Function
*/
function githubAuth(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, secureCookie, }) {
/**
* Check inputs
*
* @description Check inputs
*/
const grabedHostNames = (0, grab_host_names_1.default)();
const { host, port, scheme } = grabedHostNames;
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
if (!code || (code === null || code === void 0 ? void 0 : code.match(/ /))) {
return {
success: false,
user: null,
msg: "Please enter Github Access Token",
};
}
if (!database || (database === null || database === void 0 ? void 0 : database.match(/ /))) {
return {
success: false,
user: null,
msg: "Please provide database slug name you want to access",
};
}
if (!clientId || (clientId === null || clientId === void 0 ? void 0 : clientId.match(/ /))) {
return {
success: false,
user: null,
msg: "Please enter Github OAUTH client ID",
};
}
/**
* Initialize HTTP response variable
*/
let httpResponse;
/**
* 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 === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./))) {
/** @type {import("../../../types").DSQL_DatabaseSchemaType | undefined | undefined} */
let dbSchema;
try {
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
}
catch (error) { }
const { dbFullName } = (0, grab_db_names_1.default)({ dbName: database });
httpResponse = yield (0, api_github_login_1.default)({
code,
email: email || undefined,
clientId,
clientSecret,
additionalFields,
database: dbFullName,
additionalData,
});
}
else {
/**
* Make https request
*
* @description make a request to datasquirel.com
* @type {FunctionReturn} - Https response object
*/
httpResponse = (yield new Promise((resolve, reject) => {
const reqPayload = JSON.stringify({
code,
email,
clientId,
clientSecret,
database,
additionalFields,
additionalData,
});
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}/github-login`,
},
/**
* 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("Github Auth Error:", error.message);
resolve({
success: false,
user: null,
msg: "Something went wrong",
});
}
});
response.on("error", (err) => {
reject(err);
});
});
httpsRequest.write(reqPayload);
httpsRequest.end();
}));
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.user)) {
let encryptedPayload = (0, encrypt_1.default)({
data: JSON.stringify(httpResponse.user),
encryptionKey,
encryptionSalt,
});
const { user, dsqlUserId } = httpResponse;
const authKeyName = `datasquirel_${dsqlUserId}_${database}_auth_key`;
const csrfName = `datasquirel_${dsqlUserId}_${database}_csrf`;
response.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
`${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
]);
}
return httpResponse;
});
}
@@ -0,0 +1,5 @@
import { APIResponseObject, GoogleAuthParams } from "../../../types";
/**
* # SERVER FUNCTION: Login with google Function
*/
export default function googleAuth({ apiKey, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, debug, secureCookie, loginOnly, useLocal, apiVersion, skipWriteAuthFile, cleanupTokens, }: GoogleAuthParams): Promise<APIResponseObject>;
+108
View File
@@ -0,0 +1,108 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = googleAuth;
const api_google_login_1 = __importDefault(require("../../../functions/api/users/social/api-google-login"));
const query_dsql_api_1 = __importDefault(require("../../../functions/api/query-dsql-api"));
const grab_api_path_1 = __importDefault(require("../../../utils/backend/users/grab-api-path"));
const post_login_response_handler_1 = __importDefault(require("../../../functions/backend/auth/post-login-response-handler"));
/**
* # SERVER FUNCTION: Login with google Function
*/
function googleAuth(_a) {
return __awaiter(this, arguments, void 0, function* ({ apiKey, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, debug, secureCookie, loginOnly, useLocal, apiVersion, skipWriteAuthFile, cleanupTokens, }) {
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
console.log("Encryption key is invalid");
return {
success: false,
payload: null,
msg: "Encryption key is invalid",
};
}
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
console.log("Encryption salt is invalid");
return {
success: false,
payload: null,
msg: "Encryption salt is invalid",
};
}
/**
* Check inputs
*
* @description Check inputs
*/
if (!token || (token === null || token === void 0 ? void 0 : token.match(/ /))) {
return {
success: false,
payload: null,
msg: "Please enter Google Access Token",
};
}
/**
* Initialize HTTP response variable
*/
let httpResponse = {
success: false,
};
const googleAuthParams = {
token,
additionalFields,
additionalData,
debug,
loginOnly,
database,
};
if (useLocal) {
if (debug) {
console.log(`Google login with Local Paradigm ...`);
}
httpResponse = yield (0, api_google_login_1.default)(googleAuthParams);
}
else {
httpResponse = yield (0, query_dsql_api_1.default)({
path: (0, grab_api_path_1.default)({
paradigm: "auth",
action: "google-login",
database,
apiVersion,
}),
apiKey,
body: googleAuthParams,
method: "POST",
});
}
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.singleRes) && database) {
(0, post_login_response_handler_1.default)({
database,
httpResponse,
cleanupTokens,
debug,
encryptionKey,
encryptionSalt,
response,
secureCookie,
skipWriteAuthFile,
});
}
return httpResponse;
});
}
+8
View File
@@ -0,0 +1,8 @@
import { APIResponseObject, UpdateUserParams } from "../../types";
import { DSQL_DATASQUIREL_USERS } from "../../types/dsql";
/**
* # Update User
*/
export default function updateUser<T extends DSQL_DATASQUIREL_USERS = DSQL_DATASQUIREL_USERS & {
[k: string]: any;
}>({ payload, database, updatedUserId, useLocal, apiKey, apiVersion, dbUserId, }: UpdateUserParams<T>): Promise<APIResponseObject>;

Some files were not shown because too many files have changed in this diff Show More