ts-ag 1.2.0 → 1.2.2

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