@scalemule/nextjs 0.0.1 → 0.0.3

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.
@@ -1,6 +1,16 @@
1
1
  import { cookies } from 'next/headers';
2
2
  import 'next/server';
3
3
 
4
+ // src/types/index.ts
5
+ var ScaleMuleApiError = class extends Error {
6
+ constructor(error) {
7
+ super(error.message);
8
+ this.name = "ScaleMuleApiError";
9
+ this.code = error.code;
10
+ this.field = error.field;
11
+ }
12
+ };
13
+
4
14
  // src/server/context.ts
5
15
  function buildClientContextHeaders(context) {
6
16
  const headers = {};
@@ -418,22 +428,27 @@ var ScaleMuleServer = class {
418
428
  headers,
419
429
  body: formData
420
430
  });
421
- const data = await response.json();
431
+ const text = await response.text();
432
+ let responseData = null;
433
+ try {
434
+ responseData = text ? JSON.parse(text) : null;
435
+ } catch {
436
+ }
422
437
  if (!response.ok) {
423
- return {
424
- success: false,
425
- error: data.error || { code: "UPLOAD_FAILED", message: "Upload failed" }
426
- };
438
+ throw new ScaleMuleApiError(
439
+ responseData?.error || { code: "UPLOAD_FAILED", message: text || "Upload failed" }
440
+ );
427
441
  }
442
+ const data = responseData?.data !== void 0 ? responseData.data : responseData;
428
443
  return data;
429
444
  } catch (err) {
430
- return {
431
- success: false,
432
- error: {
433
- code: "UPLOAD_ERROR",
434
- message: err instanceof Error ? err.message : "Upload failed"
435
- }
436
- };
445
+ if (err instanceof ScaleMuleApiError) {
446
+ throw err;
447
+ }
448
+ throw new ScaleMuleApiError({
449
+ code: "UPLOAD_ERROR",
450
+ message: err instanceof Error ? err.message : "Upload failed"
451
+ });
437
452
  }
438
453
  }
439
454
  };
@@ -456,7 +471,7 @@ var ScaleMuleServer = class {
456
471
  * })
457
472
  *
458
473
  * // Store the secret for signature verification
459
- * console.log('Webhook secret:', result.data.secret)
474
+ * console.log('Webhook secret:', result.secret)
460
475
  * ```
461
476
  */
462
477
  create: async (data) => {
@@ -611,23 +626,29 @@ var ScaleMuleServer = class {
611
626
  headers,
612
627
  body: options.body ? JSON.stringify(options.body) : void 0
613
628
  });
614
- const data = await response.json();
629
+ const text = await response.text();
630
+ let responseData = null;
631
+ try {
632
+ responseData = text ? JSON.parse(text) : null;
633
+ } catch {
634
+ }
615
635
  if (!response.ok) {
616
- const error = data.error || {
636
+ const error = responseData?.error || {
617
637
  code: `HTTP_${response.status}`,
618
- message: data.message || response.statusText
638
+ message: responseData?.message || text || response.statusText
619
639
  };
620
- return { success: false, error };
640
+ throw new ScaleMuleApiError(error);
621
641
  }
642
+ const data = responseData?.data !== void 0 ? responseData.data : responseData;
622
643
  return data;
623
644
  } catch (err) {
624
- return {
625
- success: false,
626
- error: {
627
- code: "SERVER_ERROR",
628
- message: err instanceof Error ? err.message : "Request failed"
629
- }
630
- };
645
+ if (err instanceof ScaleMuleApiError) {
646
+ throw err;
647
+ }
648
+ throw new ScaleMuleApiError({
649
+ code: "SERVER_ERROR",
650
+ message: err instanceof Error ? err.message : "Request failed"
651
+ });
631
652
  }
632
653
  }
633
654
  };
@@ -793,18 +814,21 @@ function createAuthRoutes(config = {}) {
793
814
  if (!email || !password) {
794
815
  return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
795
816
  }
796
- const result = await sm.auth.register({ email, password, full_name, username, phone });
797
- if (!result.success) {
817
+ let registeredUser;
818
+ try {
819
+ registeredUser = await sm.auth.register({ email, password, full_name, username, phone });
820
+ } catch (err) {
821
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
798
822
  return errorResponse(
799
- result.error?.code || "REGISTER_FAILED",
800
- result.error?.message || "Registration failed",
823
+ apiErr?.code || "REGISTER_FAILED",
824
+ apiErr?.message || "Registration failed",
801
825
  400
802
826
  );
803
827
  }
804
- if (config.onRegister && result.data) {
805
- await config.onRegister({ id: result.data.id, email: result.data.email });
828
+ if (config.onRegister) {
829
+ await config.onRegister({ id: registeredUser.id, email: registeredUser.email });
806
830
  }
807
- return successResponse({ user: result.data, message: "Registration successful" }, 201);
831
+ return successResponse({ user: registeredUser, message: "Registration successful" }, 201);
808
832
  }
809
833
  // ==================== Login ====================
810
834
  case "login": {
@@ -812,9 +836,12 @@ function createAuthRoutes(config = {}) {
812
836
  if (!email || !password) {
813
837
  return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
814
838
  }
815
- const result = await sm.auth.login({ email, password, remember_me });
816
- if (!result.success || !result.data) {
817
- const errorCode = result.error?.code || "LOGIN_FAILED";
839
+ let loginData;
840
+ try {
841
+ loginData = await sm.auth.login({ email, password, remember_me });
842
+ } catch (err) {
843
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
844
+ const errorCode = apiErr?.code || "LOGIN_FAILED";
818
845
  let status = 400;
819
846
  if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
820
847
  if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED", "MFA_REQUIRED"].includes(errorCode)) {
@@ -822,17 +849,17 @@ function createAuthRoutes(config = {}) {
822
849
  }
823
850
  return errorResponse(
824
851
  errorCode,
825
- result.error?.message || "Login failed",
852
+ apiErr?.message || "Login failed",
826
853
  status
827
854
  );
828
855
  }
829
856
  if (config.onLogin) {
830
857
  await config.onLogin({
831
- id: result.data.user.id,
832
- email: result.data.user.email
858
+ id: loginData.user.id,
859
+ email: loginData.user.email
833
860
  });
834
861
  }
835
- return withSession(result.data, { user: result.data.user }, cookieOptions);
862
+ return withSession(loginData, { user: loginData.user }, cookieOptions);
836
863
  }
837
864
  // ==================== Logout ====================
838
865
  case "logout": {
@@ -860,11 +887,13 @@ function createAuthRoutes(config = {}) {
860
887
  if (!token || !new_password) {
861
888
  return errorResponse("VALIDATION_ERROR", "Token and new password required", 400);
862
889
  }
863
- const result = await sm.auth.resetPassword(token, new_password);
864
- if (!result.success) {
890
+ try {
891
+ await sm.auth.resetPassword(token, new_password);
892
+ } catch (err) {
893
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
865
894
  return errorResponse(
866
- result.error?.code || "RESET_FAILED",
867
- result.error?.message || "Password reset failed",
895
+ apiErr?.code || "RESET_FAILED",
896
+ apiErr?.message || "Password reset failed",
868
897
  400
869
898
  );
870
899
  }
@@ -876,11 +905,13 @@ function createAuthRoutes(config = {}) {
876
905
  if (!token) {
877
906
  return errorResponse("VALIDATION_ERROR", "Token required", 400);
878
907
  }
879
- const result = await sm.auth.verifyEmail(token);
880
- if (!result.success) {
908
+ try {
909
+ await sm.auth.verifyEmail(token);
910
+ } catch (err) {
911
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
881
912
  return errorResponse(
882
- result.error?.code || "VERIFY_FAILED",
883
- result.error?.message || "Email verification failed",
913
+ apiErr?.code || "VERIFY_FAILED",
914
+ apiErr?.message || "Email verification failed",
884
915
  400
885
916
  );
886
917
  }
@@ -892,12 +923,14 @@ function createAuthRoutes(config = {}) {
892
923
  const { email } = body;
893
924
  const session = await getSession();
894
925
  if (email) {
895
- const result2 = await sm.auth.resendVerification(email);
896
- if (!result2.success) {
926
+ try {
927
+ await sm.auth.resendVerification(email);
928
+ } catch (err) {
929
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
897
930
  return errorResponse(
898
- result2.error?.code || "RESEND_FAILED",
899
- result2.error?.message || "Failed to resend verification",
900
- result2.error?.code === "RATE_LIMITED" ? 429 : 400
931
+ apiErr?.code || "RESEND_FAILED",
932
+ apiErr?.message || "Failed to resend verification",
933
+ apiErr?.code === "RATE_LIMITED" ? 429 : 400
901
934
  );
902
935
  }
903
936
  return successResponse({ message: "Verification email sent" });
@@ -905,11 +938,13 @@ function createAuthRoutes(config = {}) {
905
938
  if (!session) {
906
939
  return errorResponse("UNAUTHORIZED", "Email or session required", 401);
907
940
  }
908
- const result = await sm.auth.resendVerification(session.sessionToken);
909
- if (!result.success) {
941
+ try {
942
+ await sm.auth.resendVerification(session.sessionToken);
943
+ } catch (err) {
944
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
910
945
  return errorResponse(
911
- result.error?.code || "RESEND_FAILED",
912
- result.error?.message || "Failed to resend verification",
946
+ apiErr?.code || "RESEND_FAILED",
947
+ apiErr?.message || "Failed to resend verification",
913
948
  400
914
949
  );
915
950
  }
@@ -921,15 +956,17 @@ function createAuthRoutes(config = {}) {
921
956
  if (!session) {
922
957
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
923
958
  }
924
- const result = await sm.auth.refresh(session.sessionToken);
925
- if (!result.success || !result.data) {
959
+ let refreshData;
960
+ try {
961
+ refreshData = await sm.auth.refresh(session.sessionToken);
962
+ } catch {
926
963
  return clearSession(
927
964
  { message: "Session expired" },
928
965
  cookieOptions
929
966
  );
930
967
  }
931
968
  return withRefreshedSession(
932
- result.data.session_token,
969
+ refreshData.session_token,
933
970
  session.userId,
934
971
  { message: "Session refreshed" },
935
972
  cookieOptions
@@ -945,15 +982,17 @@ function createAuthRoutes(config = {}) {
945
982
  if (!current_password || !new_password) {
946
983
  return errorResponse("VALIDATION_ERROR", "Current and new password required", 400);
947
984
  }
948
- const result = await sm.user.changePassword(
949
- session.sessionToken,
950
- current_password,
951
- new_password
952
- );
953
- if (!result.success) {
985
+ try {
986
+ await sm.user.changePassword(
987
+ session.sessionToken,
988
+ current_password,
989
+ new_password
990
+ );
991
+ } catch (err) {
992
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
954
993
  return errorResponse(
955
- result.error?.code || "CHANGE_FAILED",
956
- result.error?.message || "Failed to change password",
994
+ apiErr?.code || "CHANGE_FAILED",
995
+ apiErr?.message || "Failed to change password",
957
996
  400
958
997
  );
959
998
  }
@@ -978,14 +1017,16 @@ function createAuthRoutes(config = {}) {
978
1017
  if (!session) {
979
1018
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
980
1019
  }
981
- const result = await sm.auth.me(session.sessionToken);
982
- if (!result.success || !result.data) {
1020
+ let userData;
1021
+ try {
1022
+ userData = await sm.auth.me(session.sessionToken);
1023
+ } catch {
983
1024
  return clearSession(
984
1025
  { error: { code: "SESSION_EXPIRED", message: "Session expired" } },
985
1026
  cookieOptions
986
1027
  );
987
1028
  }
988
- return successResponse({ user: result.data });
1029
+ return successResponse({ user: userData });
989
1030
  }
990
1031
  // ==================== Get Session Status ====================
991
1032
  case "session": {
@@ -1020,11 +1061,13 @@ function createAuthRoutes(config = {}) {
1020
1061
  if (!password) {
1021
1062
  return errorResponse("VALIDATION_ERROR", "Password required", 400);
1022
1063
  }
1023
- const result = await sm.user.deleteAccount(session.sessionToken, password);
1024
- if (!result.success) {
1064
+ try {
1065
+ await sm.user.deleteAccount(session.sessionToken, password);
1066
+ } catch (err) {
1067
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1025
1068
  return errorResponse(
1026
- result.error?.code || "DELETE_FAILED",
1027
- result.error?.message || "Failed to delete account",
1069
+ apiErr?.code || "DELETE_FAILED",
1070
+ apiErr?.message || "Failed to delete account",
1028
1071
  400
1029
1072
  );
1030
1073
  }
@@ -1052,15 +1095,18 @@ function createAuthRoutes(config = {}) {
1052
1095
  }
1053
1096
  const body = await request.json().catch(() => ({}));
1054
1097
  const { full_name, avatar_url } = body;
1055
- const result = await sm.user.update(session.sessionToken, { full_name, avatar_url });
1056
- if (!result.success || !result.data) {
1098
+ let updatedUser;
1099
+ try {
1100
+ updatedUser = await sm.user.update(session.sessionToken, { full_name, avatar_url });
1101
+ } catch (err) {
1102
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1057
1103
  return errorResponse(
1058
- result.error?.code || "UPDATE_FAILED",
1059
- result.error?.message || "Failed to update profile",
1104
+ apiErr?.code || "UPDATE_FAILED",
1105
+ apiErr?.message || "Failed to update profile",
1060
1106
  400
1061
1107
  );
1062
1108
  }
1063
- return successResponse({ user: result.data });
1109
+ return successResponse({ user: updatedUser });
1064
1110
  }
1065
1111
  default:
1066
1112
  return errorResponse("NOT_FOUND", `Unknown endpoint: ${path}`, 404);
@@ -1,6 +1,6 @@
1
- import { S as ServerConfig } from '../webhook-handler-C-5_Ey1T.mjs';
2
- export { a as ScaleMuleServer, d as VideoFailedEvent, V as VideoReadyEvent, f as VideoTranscodedEvent, e as VideoUploadedEvent, W as WebhookEvent, g as WebhookRoutesConfig, c as createServerClient, h as createWebhookHandler, b as createWebhookRoutes, p as parseWebhookEvent, r as registerVideoWebhook, v as verifyWebhookSignature } from '../webhook-handler-C-5_Ey1T.mjs';
3
- import { _ as ClientContext, L as LoginResponse, A as ApiError } from '../index-BkacIKdu.mjs';
1
+ import { S as ServerConfig } from '../webhook-handler-DCSwldKC.mjs';
2
+ export { a as ScaleMuleServer, d as VideoFailedEvent, V as VideoReadyEvent, f as VideoTranscodedEvent, e as VideoUploadedEvent, W as WebhookEvent, g as WebhookRoutesConfig, c as createServerClient, h as createWebhookHandler, b as createWebhookRoutes, p as parseWebhookEvent, r as registerVideoWebhook, v as verifyWebhookSignature } from '../webhook-handler-DCSwldKC.mjs';
3
+ import { $ as ClientContext, L as LoginResponse, A as ApiError } from '../index-9v0SaLgg.mjs';
4
4
  import { NextRequest, NextResponse } from 'next/server';
5
5
 
6
6
  /**
@@ -338,7 +338,7 @@ declare class ScaleMuleError extends Error {
338
338
  }
339
339
  declare function errorCodeToStatus(code: string): number;
340
340
  /**
341
- * Result shape accepted by unwrap().
341
+ * Result shape accepted by unwrap() for backward compatibility.
342
342
  * Compatible with both the base SDK's { data, error } and the
343
343
  * Next.js SDK's { success, data, error } response contracts.
344
344
  */
@@ -348,19 +348,22 @@ type SdkResult<T> = {
348
348
  success?: boolean;
349
349
  };
350
350
  /**
351
- * Convert an SDK result into throw-on-error.
351
+ * Convert an SDK result into throw-on-error, or pass through a raw value.
352
352
  *
353
- * If the result has an error (or success === false), throws a ScaleMuleError
354
- * with the appropriate HTTP status code. Otherwise returns the data, typed
355
- * and non-null.
353
+ * Since SDK methods now throw on error and return data directly,
354
+ * unwrap() acts as a pass-through for direct values. It still supports
355
+ * the legacy { success, data, error } envelope for backward compatibility.
356
356
  *
357
357
  * @example
358
358
  * ```ts
359
- * const user = unwrap(await sm.auth.me(token))
360
- * const snaps = unwrap(await sm.data.query('snaps', { ... }))
359
+ * // New style (SDK methods throw on error, return T directly):
360
+ * const user = await sm.auth.me(token)
361
+ *
362
+ * // Legacy style (still works with unwrap):
363
+ * const user = unwrap(legacyResult)
361
364
  * ```
362
365
  */
363
- declare function unwrap<T>(result: SdkResult<T>): T;
366
+ declare function unwrap<T>(result: T | SdkResult<T>): T;
364
367
 
365
368
  /**
366
369
  * API Route Handler Wrapper
@@ -1,6 +1,6 @@
1
- import { S as ServerConfig } from '../webhook-handler-BPNqhuwL.js';
2
- export { a as ScaleMuleServer, d as VideoFailedEvent, V as VideoReadyEvent, f as VideoTranscodedEvent, e as VideoUploadedEvent, W as WebhookEvent, g as WebhookRoutesConfig, c as createServerClient, h as createWebhookHandler, b as createWebhookRoutes, p as parseWebhookEvent, r as registerVideoWebhook, v as verifyWebhookSignature } from '../webhook-handler-BPNqhuwL.js';
3
- import { _ as ClientContext, L as LoginResponse, A as ApiError } from '../index-BkacIKdu.js';
1
+ import { S as ServerConfig } from '../webhook-handler-Ymeice_x.js';
2
+ export { a as ScaleMuleServer, d as VideoFailedEvent, V as VideoReadyEvent, f as VideoTranscodedEvent, e as VideoUploadedEvent, W as WebhookEvent, g as WebhookRoutesConfig, c as createServerClient, h as createWebhookHandler, b as createWebhookRoutes, p as parseWebhookEvent, r as registerVideoWebhook, v as verifyWebhookSignature } from '../webhook-handler-Ymeice_x.js';
3
+ import { $ as ClientContext, L as LoginResponse, A as ApiError } from '../index-9v0SaLgg.js';
4
4
  import { NextRequest, NextResponse } from 'next/server';
5
5
 
6
6
  /**
@@ -338,7 +338,7 @@ declare class ScaleMuleError extends Error {
338
338
  }
339
339
  declare function errorCodeToStatus(code: string): number;
340
340
  /**
341
- * Result shape accepted by unwrap().
341
+ * Result shape accepted by unwrap() for backward compatibility.
342
342
  * Compatible with both the base SDK's { data, error } and the
343
343
  * Next.js SDK's { success, data, error } response contracts.
344
344
  */
@@ -348,19 +348,22 @@ type SdkResult<T> = {
348
348
  success?: boolean;
349
349
  };
350
350
  /**
351
- * Convert an SDK result into throw-on-error.
351
+ * Convert an SDK result into throw-on-error, or pass through a raw value.
352
352
  *
353
- * If the result has an error (or success === false), throws a ScaleMuleError
354
- * with the appropriate HTTP status code. Otherwise returns the data, typed
355
- * and non-null.
353
+ * Since SDK methods now throw on error and return data directly,
354
+ * unwrap() acts as a pass-through for direct values. It still supports
355
+ * the legacy { success, data, error } envelope for backward compatibility.
356
356
  *
357
357
  * @example
358
358
  * ```ts
359
- * const user = unwrap(await sm.auth.me(token))
360
- * const snaps = unwrap(await sm.data.query('snaps', { ... }))
359
+ * // New style (SDK methods throw on error, return T directly):
360
+ * const user = await sm.auth.me(token)
361
+ *
362
+ * // Legacy style (still works with unwrap):
363
+ * const user = unwrap(legacyResult)
361
364
  * ```
362
365
  */
363
- declare function unwrap<T>(result: SdkResult<T>): T;
366
+ declare function unwrap<T>(result: T | SdkResult<T>): T;
364
367
 
365
368
  /**
366
369
  * API Route Handler Wrapper