@scalemule/nextjs 0.0.1 → 0.0.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.
@@ -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,23 @@ 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
+ const responseData = text ? JSON.parse(text) : null;
422
433
  if (!response.ok) {
423
- return {
424
- success: false,
425
- error: data.error || { code: "UPLOAD_FAILED", message: "Upload failed" }
426
- };
434
+ throw new ScaleMuleApiError(
435
+ responseData?.error || { code: "UPLOAD_FAILED", message: "Upload failed" }
436
+ );
427
437
  }
438
+ const data = responseData?.data !== void 0 ? responseData.data : responseData;
428
439
  return data;
429
440
  } catch (err) {
430
- return {
431
- success: false,
432
- error: {
433
- code: "UPLOAD_ERROR",
434
- message: err instanceof Error ? err.message : "Upload failed"
435
- }
436
- };
441
+ if (err instanceof ScaleMuleApiError) {
442
+ throw err;
443
+ }
444
+ throw new ScaleMuleApiError({
445
+ code: "UPLOAD_ERROR",
446
+ message: err instanceof Error ? err.message : "Upload failed"
447
+ });
437
448
  }
438
449
  }
439
450
  };
@@ -456,7 +467,7 @@ var ScaleMuleServer = class {
456
467
  * })
457
468
  *
458
469
  * // Store the secret for signature verification
459
- * console.log('Webhook secret:', result.data.secret)
470
+ * console.log('Webhook secret:', result.secret)
460
471
  * ```
461
472
  */
462
473
  create: async (data) => {
@@ -611,23 +622,25 @@ var ScaleMuleServer = class {
611
622
  headers,
612
623
  body: options.body ? JSON.stringify(options.body) : void 0
613
624
  });
614
- const data = await response.json();
625
+ const text = await response.text();
626
+ const responseData = text ? JSON.parse(text) : null;
615
627
  if (!response.ok) {
616
- const error = data.error || {
628
+ const error = responseData?.error || {
617
629
  code: `HTTP_${response.status}`,
618
- message: data.message || response.statusText
630
+ message: responseData?.message || response.statusText
619
631
  };
620
- return { success: false, error };
632
+ throw new ScaleMuleApiError(error);
621
633
  }
634
+ const data = responseData?.data !== void 0 ? responseData.data : responseData;
622
635
  return data;
623
636
  } catch (err) {
624
- return {
625
- success: false,
626
- error: {
627
- code: "SERVER_ERROR",
628
- message: err instanceof Error ? err.message : "Request failed"
629
- }
630
- };
637
+ if (err instanceof ScaleMuleApiError) {
638
+ throw err;
639
+ }
640
+ throw new ScaleMuleApiError({
641
+ code: "SERVER_ERROR",
642
+ message: err instanceof Error ? err.message : "Request failed"
643
+ });
631
644
  }
632
645
  }
633
646
  };
@@ -793,18 +806,21 @@ function createAuthRoutes(config = {}) {
793
806
  if (!email || !password) {
794
807
  return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
795
808
  }
796
- const result = await sm.auth.register({ email, password, full_name, username, phone });
797
- if (!result.success) {
809
+ let registeredUser;
810
+ try {
811
+ registeredUser = await sm.auth.register({ email, password, full_name, username, phone });
812
+ } catch (err) {
813
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
798
814
  return errorResponse(
799
- result.error?.code || "REGISTER_FAILED",
800
- result.error?.message || "Registration failed",
815
+ apiErr?.code || "REGISTER_FAILED",
816
+ apiErr?.message || "Registration failed",
801
817
  400
802
818
  );
803
819
  }
804
- if (config.onRegister && result.data) {
805
- await config.onRegister({ id: result.data.id, email: result.data.email });
820
+ if (config.onRegister) {
821
+ await config.onRegister({ id: registeredUser.id, email: registeredUser.email });
806
822
  }
807
- return successResponse({ user: result.data, message: "Registration successful" }, 201);
823
+ return successResponse({ user: registeredUser, message: "Registration successful" }, 201);
808
824
  }
809
825
  // ==================== Login ====================
810
826
  case "login": {
@@ -812,9 +828,12 @@ function createAuthRoutes(config = {}) {
812
828
  if (!email || !password) {
813
829
  return errorResponse("VALIDATION_ERROR", "Email and password required", 400);
814
830
  }
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";
831
+ let loginData;
832
+ try {
833
+ loginData = await sm.auth.login({ email, password, remember_me });
834
+ } catch (err) {
835
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
836
+ const errorCode = apiErr?.code || "LOGIN_FAILED";
818
837
  let status = 400;
819
838
  if (errorCode === "INVALID_CREDENTIALS" || errorCode === "UNAUTHORIZED") status = 401;
820
839
  if (["EMAIL_NOT_VERIFIED", "PHONE_NOT_VERIFIED", "ACCOUNT_LOCKED", "ACCOUNT_DISABLED", "MFA_REQUIRED"].includes(errorCode)) {
@@ -822,17 +841,17 @@ function createAuthRoutes(config = {}) {
822
841
  }
823
842
  return errorResponse(
824
843
  errorCode,
825
- result.error?.message || "Login failed",
844
+ apiErr?.message || "Login failed",
826
845
  status
827
846
  );
828
847
  }
829
848
  if (config.onLogin) {
830
849
  await config.onLogin({
831
- id: result.data.user.id,
832
- email: result.data.user.email
850
+ id: loginData.user.id,
851
+ email: loginData.user.email
833
852
  });
834
853
  }
835
- return withSession(result.data, { user: result.data.user }, cookieOptions);
854
+ return withSession(loginData, { user: loginData.user }, cookieOptions);
836
855
  }
837
856
  // ==================== Logout ====================
838
857
  case "logout": {
@@ -860,11 +879,13 @@ function createAuthRoutes(config = {}) {
860
879
  if (!token || !new_password) {
861
880
  return errorResponse("VALIDATION_ERROR", "Token and new password required", 400);
862
881
  }
863
- const result = await sm.auth.resetPassword(token, new_password);
864
- if (!result.success) {
882
+ try {
883
+ await sm.auth.resetPassword(token, new_password);
884
+ } catch (err) {
885
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
865
886
  return errorResponse(
866
- result.error?.code || "RESET_FAILED",
867
- result.error?.message || "Password reset failed",
887
+ apiErr?.code || "RESET_FAILED",
888
+ apiErr?.message || "Password reset failed",
868
889
  400
869
890
  );
870
891
  }
@@ -876,11 +897,13 @@ function createAuthRoutes(config = {}) {
876
897
  if (!token) {
877
898
  return errorResponse("VALIDATION_ERROR", "Token required", 400);
878
899
  }
879
- const result = await sm.auth.verifyEmail(token);
880
- if (!result.success) {
900
+ try {
901
+ await sm.auth.verifyEmail(token);
902
+ } catch (err) {
903
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
881
904
  return errorResponse(
882
- result.error?.code || "VERIFY_FAILED",
883
- result.error?.message || "Email verification failed",
905
+ apiErr?.code || "VERIFY_FAILED",
906
+ apiErr?.message || "Email verification failed",
884
907
  400
885
908
  );
886
909
  }
@@ -892,12 +915,14 @@ function createAuthRoutes(config = {}) {
892
915
  const { email } = body;
893
916
  const session = await getSession();
894
917
  if (email) {
895
- const result2 = await sm.auth.resendVerification(email);
896
- if (!result2.success) {
918
+ try {
919
+ await sm.auth.resendVerification(email);
920
+ } catch (err) {
921
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
897
922
  return errorResponse(
898
- result2.error?.code || "RESEND_FAILED",
899
- result2.error?.message || "Failed to resend verification",
900
- result2.error?.code === "RATE_LIMITED" ? 429 : 400
923
+ apiErr?.code || "RESEND_FAILED",
924
+ apiErr?.message || "Failed to resend verification",
925
+ apiErr?.code === "RATE_LIMITED" ? 429 : 400
901
926
  );
902
927
  }
903
928
  return successResponse({ message: "Verification email sent" });
@@ -905,11 +930,13 @@ function createAuthRoutes(config = {}) {
905
930
  if (!session) {
906
931
  return errorResponse("UNAUTHORIZED", "Email or session required", 401);
907
932
  }
908
- const result = await sm.auth.resendVerification(session.sessionToken);
909
- if (!result.success) {
933
+ try {
934
+ await sm.auth.resendVerification(session.sessionToken);
935
+ } catch (err) {
936
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
910
937
  return errorResponse(
911
- result.error?.code || "RESEND_FAILED",
912
- result.error?.message || "Failed to resend verification",
938
+ apiErr?.code || "RESEND_FAILED",
939
+ apiErr?.message || "Failed to resend verification",
913
940
  400
914
941
  );
915
942
  }
@@ -921,15 +948,17 @@ function createAuthRoutes(config = {}) {
921
948
  if (!session) {
922
949
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
923
950
  }
924
- const result = await sm.auth.refresh(session.sessionToken);
925
- if (!result.success || !result.data) {
951
+ let refreshData;
952
+ try {
953
+ refreshData = await sm.auth.refresh(session.sessionToken);
954
+ } catch {
926
955
  return clearSession(
927
956
  { message: "Session expired" },
928
957
  cookieOptions
929
958
  );
930
959
  }
931
960
  return withRefreshedSession(
932
- result.data.session_token,
961
+ refreshData.session_token,
933
962
  session.userId,
934
963
  { message: "Session refreshed" },
935
964
  cookieOptions
@@ -945,15 +974,17 @@ function createAuthRoutes(config = {}) {
945
974
  if (!current_password || !new_password) {
946
975
  return errorResponse("VALIDATION_ERROR", "Current and new password required", 400);
947
976
  }
948
- const result = await sm.user.changePassword(
949
- session.sessionToken,
950
- current_password,
951
- new_password
952
- );
953
- if (!result.success) {
977
+ try {
978
+ await sm.user.changePassword(
979
+ session.sessionToken,
980
+ current_password,
981
+ new_password
982
+ );
983
+ } catch (err) {
984
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
954
985
  return errorResponse(
955
- result.error?.code || "CHANGE_FAILED",
956
- result.error?.message || "Failed to change password",
986
+ apiErr?.code || "CHANGE_FAILED",
987
+ apiErr?.message || "Failed to change password",
957
988
  400
958
989
  );
959
990
  }
@@ -978,14 +1009,16 @@ function createAuthRoutes(config = {}) {
978
1009
  if (!session) {
979
1010
  return errorResponse("UNAUTHORIZED", "Authentication required", 401);
980
1011
  }
981
- const result = await sm.auth.me(session.sessionToken);
982
- if (!result.success || !result.data) {
1012
+ let userData;
1013
+ try {
1014
+ userData = await sm.auth.me(session.sessionToken);
1015
+ } catch {
983
1016
  return clearSession(
984
1017
  { error: { code: "SESSION_EXPIRED", message: "Session expired" } },
985
1018
  cookieOptions
986
1019
  );
987
1020
  }
988
- return successResponse({ user: result.data });
1021
+ return successResponse({ user: userData });
989
1022
  }
990
1023
  // ==================== Get Session Status ====================
991
1024
  case "session": {
@@ -1020,11 +1053,13 @@ function createAuthRoutes(config = {}) {
1020
1053
  if (!password) {
1021
1054
  return errorResponse("VALIDATION_ERROR", "Password required", 400);
1022
1055
  }
1023
- const result = await sm.user.deleteAccount(session.sessionToken, password);
1024
- if (!result.success) {
1056
+ try {
1057
+ await sm.user.deleteAccount(session.sessionToken, password);
1058
+ } catch (err) {
1059
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1025
1060
  return errorResponse(
1026
- result.error?.code || "DELETE_FAILED",
1027
- result.error?.message || "Failed to delete account",
1061
+ apiErr?.code || "DELETE_FAILED",
1062
+ apiErr?.message || "Failed to delete account",
1028
1063
  400
1029
1064
  );
1030
1065
  }
@@ -1052,15 +1087,18 @@ function createAuthRoutes(config = {}) {
1052
1087
  }
1053
1088
  const body = await request.json().catch(() => ({}));
1054
1089
  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) {
1090
+ let updatedUser;
1091
+ try {
1092
+ updatedUser = await sm.user.update(session.sessionToken, { full_name, avatar_url });
1093
+ } catch (err) {
1094
+ const apiErr = err instanceof ScaleMuleApiError ? err : null;
1057
1095
  return errorResponse(
1058
- result.error?.code || "UPDATE_FAILED",
1059
- result.error?.message || "Failed to update profile",
1096
+ apiErr?.code || "UPDATE_FAILED",
1097
+ apiErr?.message || "Failed to update profile",
1060
1098
  400
1061
1099
  );
1062
1100
  }
1063
- return successResponse({ user: result.data });
1101
+ return successResponse({ user: updatedUser });
1064
1102
  }
1065
1103
  default:
1066
1104
  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