ts-ag 1.1.26 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,17 +1,19 @@
1
- import { n as readPackageJson, r as writeIfDifferent, t as exists } from "./fs-y6bE7U3-.mjs";
2
- import { t as colorText } from "./cli-CoTTeqrl.mjs";
3
1
  import { parse, stringify } from "devalue";
4
- import * as v from "valibot";
5
- import { parse as parse$1 } from "cookie";
2
+ import { parse as parse$1, parseAsync } from "valibot";
3
+ import { parse as parse$2 } from "cookie";
6
4
  import { Result, ResultAsync } from "neverthrow";
7
- import { AdminGetUserCommand, AdminInitiateAuthCommand, AdminListGroupsForUserCommand, ChangePasswordCommand, CognitoIdentityProviderClient, ConfirmForgotPasswordCommand, ConfirmSignUpCommand, ForgotPasswordCommand, GlobalSignOutCommand, RespondToAuthChallengeCommand, SignUpCommand } from "@aws-sdk/client-cognito-identity-provider";
8
- import { createHmac } from "crypto";
5
+ import { AdminGetUserCommand, AdminInitiateAuthCommand, AdminListGroupsForUserCommand, ChangePasswordCommand, CognitoIdentityProviderClient, ConfirmForgotPasswordCommand, ConfirmSignUpCommand, ForgotPasswordCommand, GetTokensFromRefreshTokenCommand, GlobalSignOutCommand, RespondToAuthChallengeCommand, SignUpCommand } from "@aws-sdk/client-cognito-identity-provider";
6
+ import { createHmac } from "node:crypto";
9
7
  import { GetObjectCommand, HeadObjectCommand, S3Client } from "@aws-sdk/client-s3";
10
8
  import { getSignedUrl as getSignedUrl$1 } from "@aws-sdk/s3-request-presigner";
11
9
  import { DynamoDBToolboxError } from "dynamodb-toolbox";
12
10
  import rehypeParse from "rehype-parse";
13
11
  import { unified } from "unified";
14
12
  import { isEqual, isObject } from "radash";
13
+ import { lstat, mkdir, readFile, writeFile } from "node:fs/promises";
14
+ import { dirname } from "node:path";
15
+ import chalk from "chalk";
16
+ import { styleText } from "node:util";
15
17
  //#region src/lambda/client-types.ts
16
18
  const HTTPMethods = [
17
19
  "GET",
@@ -31,8 +33,8 @@ const bodyMethods = [
31
33
  ];
32
34
  const queryMethods = ["GET", "DELETE"];
33
35
  async function _apiRequest(path, method, input, schema, environment, apiUrl, headers) {
34
- if (schema) if (schema.async === true) await v.parseAsync(schema, input);
35
- else v.parse(schema, input);
36
+ if (schema) if (schema.async === true) await parseAsync(schema, input);
37
+ else parse$1(schema, input);
36
38
  let url = `${apiUrl}${apiUrl.endsWith("/") ? "" : "/"}${path}`;
37
39
  if (queryMethods.includes(method)) {
38
40
  const params = new URLSearchParams();
@@ -114,36 +116,48 @@ function wrapHandler(handler) {
114
116
  * The separation means that they can be returned from functions that are certainly run inside a lambda fucntion but theyre not the actual return of the lambda.
115
117
  * Im not sure it this is optimal behaviour and if not we will migrate to only using the errorResponse function
116
118
  */
117
- const error_lambda_badRequest = (message, fieldName, fieldValue) => ({
118
- type: "badRequest",
119
- message,
120
- fieldName,
121
- fieldValue
122
- });
123
- const error_lambda_unauthorized = (message) => ({
124
- type: "unauthorized",
125
- message
126
- });
127
- const error_lambda_forbidden = (message) => ({
128
- type: "forbidden",
129
- message
130
- });
131
- const error_lambda_notFound = (message, fieldName, fieldValue) => ({
132
- type: "notFound",
133
- message,
134
- fieldName,
135
- fieldValue
136
- });
137
- const error_lambda_conflict = (message, fieldName, fieldValue) => ({
138
- type: "conflict",
139
- message,
140
- fieldName,
141
- fieldValue
142
- });
143
- const error_lambda_internal = (message) => ({
144
- type: "internal",
145
- message
146
- });
119
+ function error_lambda_badRequest(message, fieldName, fieldValue) {
120
+ return {
121
+ type: "badRequest",
122
+ message,
123
+ fieldName,
124
+ fieldValue
125
+ };
126
+ }
127
+ function error_lambda_unauthorized(message) {
128
+ return {
129
+ type: "unauthorized",
130
+ message
131
+ };
132
+ }
133
+ function error_lambda_forbidden(message) {
134
+ return {
135
+ type: "forbidden",
136
+ message
137
+ };
138
+ }
139
+ function error_lambda_notFound(message, fieldName, fieldValue) {
140
+ return {
141
+ type: "notFound",
142
+ message,
143
+ fieldName,
144
+ fieldValue
145
+ };
146
+ }
147
+ function error_lambda_conflict(message, fieldName, fieldValue) {
148
+ return {
149
+ type: "conflict",
150
+ message,
151
+ fieldName,
152
+ fieldValue
153
+ };
154
+ }
155
+ function error_lambda_internal(message) {
156
+ return {
157
+ type: "internal",
158
+ message
159
+ };
160
+ }
147
161
  //#endregion
148
162
  //#region src/lambda/response.ts
149
163
  function field(obj) {
@@ -244,15 +258,17 @@ function response_ok(body, headers, cookies) {
244
258
  /**
245
259
  * Wraps cookies parse along with the api gateway event with neverthrow
246
260
  */
247
- const getCookies = Result.fromThrowable((event) => {
248
- if (!("headers" in event) || !event.headers) throw new Error("No headers in event");
249
- const cookieString = Array.isArray(event.cookies) && event.cookies.length > 0 ? event.cookies.join("; ") : event.headers.Cookie || event.headers.cookie;
250
- if (!cookieString) throw new Error("No cookies found in event");
251
- return parse$1(cookieString);
252
- }, (e) => {
253
- if (e instanceof Error) return error_lambda_unauthorized(e.message);
254
- return error_lambda_unauthorized("Invalid Cookies");
255
- });
261
+ function getCookies(event) {
262
+ return Result.fromThrowable(() => {
263
+ if (!("headers" in event) || !event.headers) throw new Error("No headers in event");
264
+ const cookieString = Array.isArray(event.cookies) && event.cookies.length > 0 ? event.cookies.join("; ") : event.headers.Cookie || event.headers.cookie;
265
+ if (!cookieString) throw new Error("No cookies found in event");
266
+ return parse$2(cookieString);
267
+ }, (e) => {
268
+ if (e instanceof Error) return error_lambda_unauthorized(e.message);
269
+ return error_lambda_unauthorized("Invalid Cookies");
270
+ })();
271
+ }
256
272
  //#endregion
257
273
  //#region src/cognito/client.ts
258
274
  /**
@@ -447,20 +463,22 @@ function isRecord$2(value) {
447
463
  /**
448
464
  * Performs an AdminGetUserCommand and extracts the user attributes into an object
449
465
  */
450
- const getUserDetails = ResultAsync.fromThrowable(async (a) => {
451
- console.log("getUserDetails: Getting details for user: ", a.username);
452
- const res = await getCognitoClient().send(new AdminGetUserCommand({
453
- UserPoolId: a.userPoolId,
454
- Username: a.username
455
- }));
456
- return {
457
- ...res,
458
- UserAttributes: extractAttributes(res.UserAttributes)
459
- };
460
- }, (e) => {
461
- console.error("getUserDetails:error:", e);
462
- return error_cognito(e);
463
- });
466
+ function getUserDetails(a) {
467
+ return ResultAsync.fromThrowable(async () => {
468
+ console.log("getUserDetails: Getting details for user: ", a.username);
469
+ const res = await getCognitoClient().send(new AdminGetUserCommand({
470
+ UserPoolId: a.userPoolId,
471
+ Username: a.username
472
+ }));
473
+ return {
474
+ ...res,
475
+ UserAttributes: extractAttributes(res.UserAttributes)
476
+ };
477
+ }, (e) => {
478
+ console.error("getUserDetails:error:", e);
479
+ return error_cognito(e);
480
+ })();
481
+ }
464
482
  /**
465
483
  * @returns An object of attributes with their names as keys and values as values.
466
484
  */
@@ -474,16 +492,18 @@ function extractAttributes(attrs) {
474
492
  /**
475
493
  * Performs an AdminGetUserCommand and extracts the user attributes into an object
476
494
  */
477
- const getUserGroups = ResultAsync.fromThrowable(async (a) => {
478
- console.log("getUserGroups: Getting groups for user: ", a.username);
479
- return await getCognitoClient().send(new AdminListGroupsForUserCommand({
480
- UserPoolId: a.userPoolId,
481
- Username: a.username
482
- }));
483
- }, (e) => {
484
- console.error("getUserGroups:error:", e);
485
- return error_cognito(e);
486
- });
495
+ function getUserGroups(a) {
496
+ return ResultAsync.fromThrowable(async () => {
497
+ console.log("getUserGroups: Getting groups for user: ", a.username);
498
+ return await getCognitoClient().send(new AdminListGroupsForUserCommand({
499
+ UserPoolId: a.userPoolId,
500
+ Username: a.username
501
+ }));
502
+ }, (e) => {
503
+ console.error("getUserGroups:error:", e);
504
+ return error_cognito(e);
505
+ })();
506
+ }
487
507
  //#endregion
488
508
  //#region src/cognito/password.ts
489
509
  /**
@@ -504,16 +524,18 @@ function computeSecretHash(username, clientId, clientSecret) {
504
524
  * @param oldPassword - Current password.
505
525
  * @param newPassword - New password to set.
506
526
  */
507
- const changePassword = ResultAsync.fromThrowable(async (accessToken, oldPassword, newPassword) => {
508
- return getCognitoClient().send(new ChangePasswordCommand({
509
- AccessToken: accessToken,
510
- PreviousPassword: oldPassword,
511
- ProposedPassword: newPassword
512
- }));
513
- }, (e) => {
514
- console.error("ChangePasswordCommand error", e);
515
- return error_cognito(e);
516
- });
527
+ function changePassword(accessToken, oldPassword, newPassword) {
528
+ return ResultAsync.fromThrowable(async () => {
529
+ return getCognitoClient().send(new ChangePasswordCommand({
530
+ AccessToken: accessToken,
531
+ PreviousPassword: oldPassword,
532
+ ProposedPassword: newPassword
533
+ }));
534
+ }, (e) => {
535
+ console.error("ChangePasswordCommand error", e);
536
+ return error_cognito(e);
537
+ })();
538
+ }
517
539
  /**
518
540
  * Completes a forgot-password flow by submitting the confirmation code and new password.
519
541
  *
@@ -523,18 +545,20 @@ const changePassword = ResultAsync.fromThrowable(async (accessToken, oldPassword
523
545
  * @param a.clientId - Cognito app client ID.
524
546
  * @param a.clientSecret - Cognito app client secret.
525
547
  */
526
- const confirmForgotPassword = ResultAsync.fromThrowable((a) => {
527
- return getCognitoClient().send(new ConfirmForgotPasswordCommand({
528
- ClientId: a.clientId,
529
- Username: a.username,
530
- ConfirmationCode: a.confirmationCode,
531
- Password: a.newPassword,
532
- SecretHash: computeSecretHash(a.username, a.clientId, a.clientSecret)
533
- }));
534
- }, (e) => {
535
- console.error("ConfirmForgotPasswordCommand error", e);
536
- return error_cognito(e);
537
- });
548
+ function confirmForgotPassword(a) {
549
+ return ResultAsync.fromThrowable(() => {
550
+ return getCognitoClient().send(new ConfirmForgotPasswordCommand({
551
+ ClientId: a.clientId,
552
+ Username: a.username,
553
+ ConfirmationCode: a.confirmationCode,
554
+ Password: a.newPassword,
555
+ SecretHash: computeSecretHash(a.username, a.clientId, a.clientSecret)
556
+ }));
557
+ }, (e) => {
558
+ console.error("ConfirmForgotPasswordCommand error", e);
559
+ return error_cognito(e);
560
+ })();
561
+ }
538
562
  /**
539
563
  * Confirms a user's signup using the confirmation code sent by Cognito.
540
564
  *
@@ -543,17 +567,19 @@ const confirmForgotPassword = ResultAsync.fromThrowable((a) => {
543
567
  * @param a.clientId - Cognito app client ID.
544
568
  * @param a.clientSecret - Cognito app client secret.
545
569
  */
546
- const confirmSignup = ResultAsync.fromThrowable((a) => {
547
- return getCognitoClient().send(new ConfirmSignUpCommand({
548
- ClientId: a.clientId,
549
- Username: a.username,
550
- ConfirmationCode: a.confirmationCode,
551
- SecretHash: computeSecretHash(a.username, a.clientId, a.clientSecret)
552
- }));
553
- }, (e) => {
554
- console.error("ConfirmSignUpCommand error", e);
555
- return error_cognito(e);
556
- });
570
+ function confirmSignup(a) {
571
+ return ResultAsync.fromThrowable(() => {
572
+ return getCognitoClient().send(new ConfirmSignUpCommand({
573
+ ClientId: a.clientId,
574
+ Username: a.username,
575
+ ConfirmationCode: a.confirmationCode,
576
+ SecretHash: computeSecretHash(a.username, a.clientId, a.clientSecret)
577
+ }));
578
+ }, (e) => {
579
+ console.error("ConfirmSignUpCommand error", e);
580
+ return error_cognito(e);
581
+ })();
582
+ }
557
583
  /**
558
584
  * Starts a forgot-password flow by sending a reset code to the user.
559
585
  *
@@ -561,16 +587,18 @@ const confirmSignup = ResultAsync.fromThrowable((a) => {
561
587
  * @param a.clientId - Cognito app client ID.
562
588
  * @param a.clientSecret - Cognito app client secret.
563
589
  */
564
- const forgotPassword = ResultAsync.fromThrowable((a) => {
565
- return getCognitoClient().send(new ForgotPasswordCommand({
566
- ClientId: a.clientId,
567
- Username: a.username,
568
- SecretHash: computeSecretHash(a.username, a.clientId, a.clientSecret)
569
- }));
570
- }, (e) => {
571
- console.error("ForgotPasswordCommand error", e);
572
- return error_cognito(e);
573
- });
590
+ function forgotPassword(a) {
591
+ return ResultAsync.fromThrowable(() => {
592
+ return getCognitoClient().send(new ForgotPasswordCommand({
593
+ ClientId: a.clientId,
594
+ Username: a.username,
595
+ SecretHash: computeSecretHash(a.username, a.clientId, a.clientSecret)
596
+ }));
597
+ }, (e) => {
598
+ console.error("ForgotPasswordCommand error", e);
599
+ return error_cognito(e);
600
+ })();
601
+ }
574
602
  /**
575
603
  * Signs a user in with ADMIN_USER_PASSWORD_AUTH.
576
604
  *
@@ -580,21 +608,34 @@ const forgotPassword = ResultAsync.fromThrowable((a) => {
580
608
  * @param a.clientSecret - Cognito app client secret.
581
609
  * @param a.userPoolId - Cognito user pool ID.
582
610
  */
583
- const login = ResultAsync.fromThrowable((a) => {
584
- return getCognitoClient().send(new AdminInitiateAuthCommand({
585
- AuthFlow: "ADMIN_USER_PASSWORD_AUTH",
586
- ClientId: a.clientId,
587
- UserPoolId: a.userPoolId,
588
- AuthParameters: {
589
- USERNAME: a.username,
590
- PASSWORD: a.password,
591
- SECRET_HASH: computeSecretHash(a.username, a.clientId, a.clientSecret)
592
- }
593
- }));
594
- }, (e) => {
595
- console.error("AdminInitiateAuthCommand error", e);
596
- return error_cognito(e);
597
- });
611
+ function login(a) {
612
+ return ResultAsync.fromThrowable(() => {
613
+ return getCognitoClient().send(new AdminInitiateAuthCommand({
614
+ AuthFlow: "ADMIN_USER_PASSWORD_AUTH",
615
+ ClientId: a.clientId,
616
+ UserPoolId: a.userPoolId,
617
+ AuthParameters: {
618
+ USERNAME: a.username,
619
+ PASSWORD: a.password,
620
+ SECRET_HASH: computeSecretHash(a.username, a.clientId, a.clientSecret)
621
+ }
622
+ }));
623
+ }, (e) => {
624
+ console.error("AdminInitiateAuthCommand error", e);
625
+ return error_cognito(e);
626
+ })();
627
+ }
628
+ /**
629
+ * Sends a GetTokensFromRefreshTokenCommand
630
+ */
631
+ function refreshTokens(a) {
632
+ return ResultAsync.fromThrowable(() => {
633
+ return getCognitoClient().send(new GetTokensFromRefreshTokenCommand(a));
634
+ }, (e) => {
635
+ console.error("refreshTokens: GetTokensFromRefreshTokenCommand error", e);
636
+ return error_cognito(e);
637
+ })();
638
+ }
598
639
  /**
599
640
  * Exchanges a refresh token for new tokens.
600
641
  *
@@ -604,31 +645,35 @@ const login = ResultAsync.fromThrowable((a) => {
604
645
  * @param a.clientSecret - Cognito app client secret.
605
646
  * @param a.userPoolId - Cognito user pool ID.
606
647
  */
607
- const refreshTokens = ResultAsync.fromThrowable((a) => {
608
- return getCognitoClient().send(new AdminInitiateAuthCommand({
609
- AuthFlow: "REFRESH_TOKEN_AUTH",
610
- ClientId: a.clientId,
611
- UserPoolId: a.userPoolId,
612
- AuthParameters: {
613
- REFRESH_TOKEN: a.refreshToken,
614
- SECRET_HASH: computeSecretHash(a.username, a.clientId, a.clientSecret)
615
- }
616
- }));
617
- }, (e) => {
618
- console.error("refreshTokens: AdminInitiateAuthCommand error", e);
619
- return error_cognito(e);
620
- });
648
+ function refreshTokensAuth(a) {
649
+ return ResultAsync.fromThrowable(() => {
650
+ return getCognitoClient().send(new AdminInitiateAuthCommand({
651
+ AuthFlow: "REFRESH_TOKEN_AUTH",
652
+ ClientId: a.clientId,
653
+ UserPoolId: a.userPoolId,
654
+ AuthParameters: {
655
+ REFRESH_TOKEN: a.refreshToken,
656
+ SECRET_HASH: computeSecretHash(a.username, a.clientId, a.clientSecret)
657
+ }
658
+ }));
659
+ }, (e) => {
660
+ console.error("refreshTokens: AdminInitiateAuthCommand error", e);
661
+ return error_cognito(e);
662
+ })();
663
+ }
621
664
  /**
622
665
  * Globally signs out a user by invalidating all refresh tokens.
623
666
  *
624
667
  * @param accessToken - Access token for the authenticated user.
625
668
  */
626
- const logout = ResultAsync.fromThrowable((accessToken) => {
627
- return getCognitoClient().send(new GlobalSignOutCommand({ AccessToken: accessToken }));
628
- }, (e) => {
629
- console.error("GlobalSignOutCommand error", e);
630
- return error_cognito(e);
631
- });
669
+ function logout(accessToken) {
670
+ return ResultAsync.fromThrowable(() => {
671
+ return getCognitoClient().send(new GlobalSignOutCommand({ AccessToken: accessToken }));
672
+ }, (e) => {
673
+ console.error("GlobalSignOutCommand error", e);
674
+ return error_cognito(e);
675
+ })();
676
+ }
632
677
  /**
633
678
  * Completes a NEW_PASSWORD_REQUIRED challenge for users who must set a new password.
634
679
  *
@@ -638,21 +683,23 @@ const logout = ResultAsync.fromThrowable((accessToken) => {
638
683
  * @param a.clientId - Cognito app client ID.
639
684
  * @param a.clientSecret - Cognito app client secret.
640
685
  */
641
- const resetPassword = ResultAsync.fromThrowable((a) => {
642
- return getCognitoClient().send(new RespondToAuthChallengeCommand({
643
- ChallengeName: "NEW_PASSWORD_REQUIRED",
644
- ClientId: a.clientId,
645
- Session: a.session,
646
- ChallengeResponses: {
647
- SECRET_HASH: computeSecretHash(a.username, a.clientId, a.clientSecret),
648
- NEW_PASSWORD: a.newPassword,
649
- USERNAME: a.username
650
- }
651
- }));
652
- }, (e) => {
653
- console.error("RespondToAuthChallengeCommand error", e);
654
- return error_cognito(e);
655
- });
686
+ function resetPassword(a) {
687
+ return ResultAsync.fromThrowable(() => {
688
+ return getCognitoClient().send(new RespondToAuthChallengeCommand({
689
+ ChallengeName: "NEW_PASSWORD_REQUIRED",
690
+ ClientId: a.clientId,
691
+ Session: a.session,
692
+ ChallengeResponses: {
693
+ SECRET_HASH: computeSecretHash(a.username, a.clientId, a.clientSecret),
694
+ NEW_PASSWORD: a.newPassword,
695
+ USERNAME: a.username
696
+ }
697
+ }));
698
+ }, (e) => {
699
+ console.error("RespondToAuthChallengeCommand error", e);
700
+ return error_cognito(e);
701
+ })();
702
+ }
656
703
  /**
657
704
  * Registers a new user with Cognito and optional custom attributes.
658
705
  *
@@ -662,28 +709,30 @@ const resetPassword = ResultAsync.fromThrowable((a) => {
662
709
  * @param a.clientSecret - Cognito app client secret.
663
710
  * @param a.<attribute> - Any additional user attributes to set.
664
711
  */
665
- const signUp = ResultAsync.fromThrowable((a) => {
666
- const cognitoClient = getCognitoClient();
667
- const secretHash = computeSecretHash(a.username, a.clientId, a.clientSecret);
668
- return cognitoClient.send(new SignUpCommand({
669
- ClientId: a.clientId,
670
- Username: a.username,
671
- Password: a.password,
672
- SecretHash: secretHash,
673
- UserAttributes: Object.entries(a).filter(([key]) => ![
674
- "username",
675
- "password",
676
- "clientId",
677
- "clientSecret"
678
- ].includes(key)).map(([key, value]) => ({
679
- Name: key,
680
- Value: value
681
- }))
682
- }));
683
- }, (e) => {
684
- console.error("SignUpCommand error", e);
685
- return error_cognito(e);
686
- });
712
+ function signUp(a) {
713
+ return ResultAsync.fromThrowable(() => {
714
+ const cognitoClient = getCognitoClient();
715
+ const secretHash = computeSecretHash(a.username, a.clientId, a.clientSecret);
716
+ return cognitoClient.send(new SignUpCommand({
717
+ ClientId: a.clientId,
718
+ Username: a.username,
719
+ Password: a.password,
720
+ SecretHash: secretHash,
721
+ UserAttributes: Object.entries(a).filter(([key]) => ![
722
+ "username",
723
+ "password",
724
+ "clientId",
725
+ "clientSecret"
726
+ ].includes(key)).map(([key, value]) => ({
727
+ Name: key,
728
+ Value: value
729
+ }))
730
+ }));
731
+ }, (e) => {
732
+ console.error("SignUpCommand error", e);
733
+ return error_cognito(e);
734
+ })();
735
+ }
687
736
  /**
688
737
  * Exchanges an OAuth2 authorization code for Cognito tokens using the token endpoint.
689
738
  * See https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html for request/response fields and grant details.
@@ -695,30 +744,32 @@ const signUp = ResultAsync.fromThrowable((a) => {
695
744
  * @param a.cognitoDomain - Cognito domain URL (e.g., your-domain.auth.region.amazoncognito.com).
696
745
  * @returns Parsed token payload containing `access_token`, `id_token`, `refresh_token`, token type, and expiry.
697
746
  */
698
- const verifyOAuthToken = ResultAsync.fromThrowable(async (a) => {
699
- const basicAuth = Buffer.from(`${a.clientId}:${a.clientSecret}`).toString("base64");
700
- const params = new URLSearchParams();
701
- params.append("grant_type", "authorization_code");
702
- params.append("code", a.code);
703
- params.append("redirect_uri", a.redirectUri);
704
- console.log("verifyOAuthToken: params", params.toString());
705
- const tokenRes = await fetch(`https://${a.cognitoDomain}/oauth2/token`, {
706
- method: "POST",
707
- headers: {
708
- "Content-Type": "application/x-www-form-urlencoded",
709
- Authorization: `Basic ${basicAuth}`
710
- },
711
- body: params.toString()
712
- });
713
- if (!tokenRes.ok) {
714
- console.error("verifyOAuthToken: token exchange failed", await tokenRes.text());
715
- throw Object.assign(/* @__PURE__ */ new Error("OAuth token exchange failed"), { name: "NotAuthorizedException" });
716
- }
717
- return await tokenRes.json();
718
- }, (e) => {
719
- console.error("verifyOAuthToken:error", e);
720
- return error_cognito(e);
721
- });
747
+ function verifyOAuthToken(a) {
748
+ return ResultAsync.fromThrowable(async () => {
749
+ const basicAuth = Buffer.from(`${a.clientId}:${a.clientSecret}`).toString("base64");
750
+ const params = new URLSearchParams();
751
+ params.append("grant_type", "authorization_code");
752
+ params.append("code", a.code);
753
+ params.append("redirect_uri", a.redirectUri);
754
+ console.log("verifyOAuthToken: params", params.toString());
755
+ const tokenRes = await fetch(`https://${a.cognitoDomain}/oauth2/token`, {
756
+ method: "POST",
757
+ headers: {
758
+ "Content-Type": "application/x-www-form-urlencoded",
759
+ Authorization: `Basic ${basicAuth}`
760
+ },
761
+ body: params.toString()
762
+ });
763
+ if (!tokenRes.ok) {
764
+ console.error("verifyOAuthToken: token exchange failed", await tokenRes.text());
765
+ throw Object.assign(/* @__PURE__ */ new Error("OAuth token exchange failed"), { name: "NotAuthorizedException" });
766
+ }
767
+ return await tokenRes.json();
768
+ }, (e) => {
769
+ console.error("verifyOAuthToken:error", e);
770
+ return error_cognito(e);
771
+ })();
772
+ }
722
773
  /**
723
774
  * Exchanges an OAuth2 refresh token for Cognito tokens using the oauth token endpoint.
724
775
  * See https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html for request/response fields and grant details.
@@ -729,29 +780,31 @@ const verifyOAuthToken = ResultAsync.fromThrowable(async (a) => {
729
780
  * @param a.cognitoDomain - Cognito domain URL (e.g., your-domain.auth.region.amazoncognito.com).
730
781
  * @returns Parsed token payload containing `access_token`, `id_token`, `refresh_token`, token type, and expiry.
731
782
  */
732
- const refreshOAuthToken = ResultAsync.fromThrowable(async (a) => {
733
- const basicAuth = Buffer.from(`${a.clientId}:${a.clientSecret}`).toString("base64");
734
- const params = new URLSearchParams();
735
- params.append("grant_type", "refresh_token");
736
- params.append("refresh_token", a.refreshToken);
737
- console.log("refreshOAuthToken: params", params.toString());
738
- const tokenRes = await fetch(`https://${a.cognitoDomain}/oauth2/token`, {
739
- method: "POST",
740
- headers: {
741
- "Content-Type": "application/x-www-form-urlencoded",
742
- Authorization: `Basic ${basicAuth}`
743
- },
744
- body: params.toString()
745
- });
746
- if (!tokenRes.ok) {
747
- console.error("refreshOAuthToken: token exchange failed", await tokenRes.text());
748
- throw Object.assign(/* @__PURE__ */ new Error("OAuth token refresh failed"), { name: "NotAuthorizedException" });
749
- }
750
- return await tokenRes.json();
751
- }, (e) => {
752
- console.error("refreshOAuthToken:error", e);
753
- return error_cognito(e);
754
- });
783
+ function refreshOAuthToken(a) {
784
+ return ResultAsync.fromThrowable(async () => {
785
+ const basicAuth = Buffer.from(`${a.clientId}:${a.clientSecret}`).toString("base64");
786
+ const params = new URLSearchParams();
787
+ params.append("grant_type", "refresh_token");
788
+ params.append("refresh_token", a.refreshToken);
789
+ console.log("refreshOAuthToken: params", params.toString());
790
+ const tokenRes = await fetch(`https://${a.cognitoDomain}/oauth2/token`, {
791
+ method: "POST",
792
+ headers: {
793
+ "Content-Type": "application/x-www-form-urlencoded",
794
+ Authorization: `Basic ${basicAuth}`
795
+ },
796
+ body: params.toString()
797
+ });
798
+ if (!tokenRes.ok) {
799
+ console.error("refreshOAuthToken: token exchange failed", await tokenRes.text());
800
+ throw Object.assign(/* @__PURE__ */ new Error("OAuth token refresh failed"), { name: "NotAuthorizedException" });
801
+ }
802
+ return await tokenRes.json();
803
+ }, (e) => {
804
+ console.error("refreshOAuthToken:error", e);
805
+ return error_cognito(e);
806
+ })();
807
+ }
755
808
  //#endregion
756
809
  //#region src/s3/client.ts
757
810
  /**
@@ -941,10 +994,12 @@ function getHttpStatusCode$1(error) {
941
994
  }
942
995
  //#endregion
943
996
  //#region src/s3/signedUrl.ts
944
- const getSignedUrl = ResultAsync.fromThrowable(getSignedUrl$1, (e) => {
945
- console.error("getSignedUrl: Failed to get signed url", e);
946
- error_s3(e);
947
- });
997
+ function getSignedUrl(...args) {
998
+ return ResultAsync.fromThrowable(getSignedUrl$1, (e) => {
999
+ console.error("getSignedUrl: Failed to get signed url", e);
1000
+ return error_s3(e);
1001
+ })(...args);
1002
+ }
948
1003
  //#endregion
949
1004
  //#region src/s3/object.ts
950
1005
  /**
@@ -954,23 +1009,25 @@ const getSignedUrl = ResultAsync.fromThrowable(getSignedUrl$1, (e) => {
954
1009
  * @param {string} key - The key of the object to retrieve.
955
1010
  * @returns {Promise<Buffer>} A promise that resolves to the object data as a Buffer.
956
1011
  */
957
- const getObject = ResultAsync.fromThrowable(async (bucketName, key) => {
958
- const s3 = getS3();
959
- const cmd = new GetObjectCommand({
960
- Bucket: bucketName,
961
- Key: key
962
- });
963
- const stream = (await s3.send(cmd)).Body;
964
- return new Promise((resolve, reject) => {
965
- const chunks = [];
966
- stream.on("data", (chunk) => chunks.push(chunk));
967
- stream.on("end", () => resolve(Buffer.concat(chunks)));
968
- stream.on("error", reject);
969
- });
970
- }, (e) => {
971
- console.error(`getObjectt: Error getting object from S3: ${e}`);
972
- return error_s3(e);
973
- });
1012
+ function getObject(bucketName, key) {
1013
+ return ResultAsync.fromThrowable(async () => {
1014
+ const s3 = getS3();
1015
+ const cmd = new GetObjectCommand({
1016
+ Bucket: bucketName,
1017
+ Key: key
1018
+ });
1019
+ const stream = (await s3.send(cmd)).Body;
1020
+ return new Promise((resolve, reject) => {
1021
+ const chunks = [];
1022
+ stream.on("data", (chunk) => chunks.push(chunk));
1023
+ stream.on("end", () => resolve(Buffer.concat(chunks)));
1024
+ stream.on("error", reject);
1025
+ });
1026
+ }, (e) => {
1027
+ console.error(`getObjectt: Error getting object from S3: ${e}`);
1028
+ return error_s3(e);
1029
+ })();
1030
+ }
974
1031
  /**
975
1032
  * Convenience function to get an object from S3 and return it as a string.
976
1033
  */
@@ -984,22 +1041,24 @@ function getObjectString(bucketName, key) {
984
1041
  * @param {string} key - The key of the object to retrieve.
985
1042
  * @returns {Promise<Buffer>} A promise that resolves to a boolean.
986
1043
  */
987
- const objectExists = ResultAsync.fromThrowable(async (bucketName, key) => {
988
- const s3 = getS3();
989
- try {
990
- const cmd = new HeadObjectCommand({
991
- Bucket: bucketName,
992
- Key: key
993
- });
994
- return (await s3.send(cmd)).$metadata.httpStatusCode === 200;
995
- } catch (e) {
996
- if (is_s3_notFound(e)) return false;
997
- throw e;
998
- }
999
- }, (e) => {
1000
- console.error(`objectExists: Error getting object head from S3: ${e}`);
1001
- return error_s3(e);
1002
- });
1044
+ function objectExists(bucketName, key) {
1045
+ return ResultAsync.fromThrowable(async () => {
1046
+ const s3 = getS3();
1047
+ try {
1048
+ const cmd = new HeadObjectCommand({
1049
+ Bucket: bucketName,
1050
+ Key: key
1051
+ });
1052
+ return (await s3.send(cmd)).$metadata.httpStatusCode === 200;
1053
+ } catch (e) {
1054
+ if (is_s3_notFound(e)) return false;
1055
+ throw e;
1056
+ }
1057
+ }, (e) => {
1058
+ console.error(`objectExists: Error getting object head from S3: ${e}`);
1059
+ return error_s3(e);
1060
+ })();
1061
+ }
1003
1062
  //#endregion
1004
1063
  //#region src/dynamo/errors.ts
1005
1064
  const defaultErrors$1 = {
@@ -1563,6 +1622,43 @@ function pruneToShape(source, shape) {
1563
1622
  }
1564
1623
  }
1565
1624
  //#endregion
1566
- export { HTTPMethods, changePassword, colorText, computeSecretHash, confirmForgotPassword, confirmSignup, createApiRequest, deepDiff, error_cognito, error_dynamo, error_lambda_badRequest, error_lambda_conflict, error_lambda_forbidden, error_lambda_fromCognito, error_lambda_fromDynamo, error_lambda_fromS3, error_lambda_fromSes, error_lambda_internal, error_lambda_notFound, error_lambda_unauthorized, error_s3, error_ses, exists, extractAttributes, extractToc, forgotPassword, getByPath, getCognitoClient, getCookies, getErrorName, getObject, getObjectString, getS3, getSchemaByPath, getSignedUrl, getUserDetails, getUserGroups, isRecord, isSchema, is_s3_notFound, login, logout, objectExists, parseRaw, pruneToShape, readPackageJson, refreshOAuthToken, refreshTokens, resetPassword, response_error, response_ok, response_valibotError, setByPath, signUp, unwrap, verifyOAuthToken, wrapHandler, writeIfDifferent };
1625
+ //#region src/utils/fs.ts
1626
+ /**
1627
+ * @returns true if a filepath exists
1628
+ */
1629
+ async function exists(filePath) {
1630
+ try {
1631
+ await lstat(filePath);
1632
+ return true;
1633
+ } catch {
1634
+ return false;
1635
+ }
1636
+ }
1637
+ /**
1638
+ * Writes data to a filepath if it is different
1639
+ * @returns true if the file is written to
1640
+ */
1641
+ async function writeIfDifferent(filePath, newData) {
1642
+ const directory = dirname(filePath);
1643
+ if (!await exists(directory)) await mkdir(directory, { recursive: true });
1644
+ if (await exists(filePath)) {
1645
+ if (await readFile(filePath, "utf8") === newData) return false;
1646
+ }
1647
+ await writeFile(filePath, newData, "utf8");
1648
+ console.log(chalk.green("Writing to"), filePath);
1649
+ return true;
1650
+ }
1651
+ /**
1652
+ * @returns the json object packageJson or undefined if it doesnt exist
1653
+ */
1654
+ async function readPackageJson(filePath) {
1655
+ if (!await exists(filePath)) return void 0;
1656
+ return JSON.parse(await readFile(filePath, { encoding: "utf-8" }));
1657
+ }
1658
+ //#endregion
1659
+ //#region src/utils/cli.ts
1660
+ const colorText = (format, text) => styleText(format, String(text), { validateStream: false });
1661
+ //#endregion
1662
+ export { HTTPMethods, changePassword, colorText, computeSecretHash, confirmForgotPassword, confirmSignup, createApiRequest, deepDiff, error_cognito, error_dynamo, error_lambda_badRequest, error_lambda_conflict, error_lambda_forbidden, error_lambda_fromCognito, error_lambda_fromDynamo, error_lambda_fromS3, error_lambda_fromSes, error_lambda_internal, error_lambda_notFound, error_lambda_unauthorized, error_s3, error_ses, exists, extractAttributes, extractToc, forgotPassword, getByPath, getCognitoClient, getCookies, getErrorName, getObject, getObjectString, getS3, getSchemaByPath, getSignedUrl, getUserDetails, getUserGroups, isRecord, isSchema, is_s3_notFound, login, logout, objectExists, parseRaw, pruneToShape, readPackageJson, refreshOAuthToken, refreshTokens, refreshTokensAuth, resetPassword, response_error, response_ok, response_valibotError, setByPath, signUp, unwrap, verifyOAuthToken, wrapHandler, writeIfDifferent };
1567
1663
 
1568
1664
  //# sourceMappingURL=index.mjs.map