@stackframe/stack 2.7.21 → 2.7.23

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.
Files changed (145) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +2 -2
  3. package/dist/admin-app-impl-CTQhv9tV.d.ts +395 -0
  4. package/dist/admin-app-impl-DpyRKp1e.d.mts +395 -0
  5. package/dist/components/selected-team-switcher.d.mts +18 -6
  6. package/dist/components/selected-team-switcher.d.ts +18 -6
  7. package/dist/components/team-icon.d.mts +18 -6
  8. package/dist/components/team-icon.d.ts +18 -6
  9. package/dist/components-page/stack-handler.d.mts +18 -6
  10. package/dist/components-page/stack-handler.d.ts +18 -6
  11. package/dist/esm/lib/stack-app/api-keys/index.js +14 -0
  12. package/dist/esm/lib/stack-app/api-keys/index.js.map +1 -0
  13. package/dist/esm/lib/stack-app/apps/implementations/admin-app-impl.js +291 -0
  14. package/dist/esm/lib/stack-app/apps/implementations/admin-app-impl.js.map +1 -0
  15. package/dist/esm/lib/{stack-app.js → stack-app/apps/implementations/client-app-impl.js} +37 -1109
  16. package/dist/esm/lib/stack-app/apps/implementations/client-app-impl.js.map +1 -0
  17. package/dist/esm/lib/stack-app/apps/implementations/common.js +142 -0
  18. package/dist/esm/lib/stack-app/apps/implementations/common.js.map +1 -0
  19. package/dist/esm/lib/stack-app/apps/implementations/index.js +24 -0
  20. package/dist/esm/lib/stack-app/apps/implementations/index.js.map +1 -0
  21. package/dist/esm/lib/stack-app/apps/implementations/server-app-impl.js +527 -0
  22. package/dist/esm/lib/stack-app/apps/implementations/server-app-impl.js.map +1 -0
  23. package/dist/esm/lib/stack-app/apps/index.js +16 -0
  24. package/dist/esm/lib/stack-app/apps/index.js.map +1 -0
  25. package/dist/esm/lib/stack-app/apps/interfaces/admin-app.js +7 -0
  26. package/dist/esm/lib/stack-app/apps/interfaces/admin-app.js.map +1 -0
  27. package/dist/esm/lib/stack-app/apps/interfaces/client-app.js +7 -0
  28. package/dist/esm/lib/stack-app/apps/interfaces/client-app.js.map +1 -0
  29. package/dist/esm/lib/stack-app/apps/interfaces/server-app.js +7 -0
  30. package/dist/esm/lib/stack-app/apps/interfaces/server-app.js.map +1 -0
  31. package/dist/esm/lib/stack-app/common.js +6 -0
  32. package/dist/esm/lib/stack-app/common.js.map +1 -0
  33. package/dist/esm/lib/stack-app/connected-accounts/index.js +1 -0
  34. package/dist/esm/lib/stack-app/connected-accounts/index.js.map +1 -0
  35. package/dist/esm/lib/stack-app/contact-channels/index.js +39 -0
  36. package/dist/esm/lib/stack-app/contact-channels/index.js.map +1 -0
  37. package/dist/esm/lib/stack-app/email-templates/index.js +11 -0
  38. package/dist/esm/lib/stack-app/email-templates/index.js.map +1 -0
  39. package/dist/esm/lib/stack-app/index.js +16 -0
  40. package/dist/esm/lib/stack-app/index.js.map +1 -0
  41. package/dist/esm/lib/stack-app/permissions/index.js +20 -0
  42. package/dist/esm/lib/stack-app/permissions/index.js.map +1 -0
  43. package/dist/esm/lib/stack-app/project-configs/index.js +1 -0
  44. package/dist/esm/lib/stack-app/project-configs/index.js.map +1 -0
  45. package/dist/esm/lib/stack-app/projects/index.js +57 -0
  46. package/dist/esm/lib/stack-app/projects/index.js.map +1 -0
  47. package/dist/esm/lib/stack-app/teams/index.js +38 -0
  48. package/dist/esm/lib/stack-app/teams/index.js.map +1 -0
  49. package/dist/esm/lib/stack-app/users/index.js +47 -0
  50. package/dist/esm/lib/stack-app/users/index.js.map +1 -0
  51. package/dist/generated/quetzal-translations.d.mts +2 -2
  52. package/dist/generated/quetzal-translations.d.ts +2 -2
  53. package/dist/{lib/stack-app.d.mts → index-C7D6Vt7X.d.mts} +138 -354
  54. package/dist/{lib/stack-app.d.ts → index-DQk7XJpU.d.ts} +138 -354
  55. package/dist/index.d.mts +17 -5
  56. package/dist/index.d.ts +17 -5
  57. package/dist/lib/hooks.d.mts +17 -5
  58. package/dist/lib/hooks.d.ts +17 -5
  59. package/dist/lib/stack-app/api-keys/index.d.mts +40 -0
  60. package/dist/lib/stack-app/api-keys/index.d.ts +40 -0
  61. package/dist/lib/stack-app/api-keys/index.js +39 -0
  62. package/dist/lib/stack-app/api-keys/index.js.map +1 -0
  63. package/dist/lib/stack-app/apps/implementations/admin-app-impl.d.mts +30 -0
  64. package/dist/lib/stack-app/apps/implementations/admin-app-impl.d.ts +30 -0
  65. package/dist/lib/stack-app/apps/implementations/admin-app-impl.js +316 -0
  66. package/dist/lib/stack-app/apps/implementations/admin-app-impl.js.map +1 -0
  67. package/dist/lib/stack-app/apps/implementations/client-app-impl.d.mts +30 -0
  68. package/dist/lib/stack-app/apps/implementations/client-app-impl.d.ts +30 -0
  69. package/dist/lib/{stack-app.js → stack-app/apps/implementations/client-app-impl.js} +75 -1152
  70. package/dist/lib/stack-app/apps/implementations/client-app-impl.js.map +1 -0
  71. package/dist/lib/stack-app/apps/implementations/common.d.mts +45 -0
  72. package/dist/lib/stack-app/apps/implementations/common.d.ts +45 -0
  73. package/dist/lib/stack-app/apps/implementations/common.js +187 -0
  74. package/dist/lib/stack-app/apps/implementations/common.js.map +1 -0
  75. package/dist/lib/stack-app/apps/implementations/index.d.mts +36 -0
  76. package/dist/lib/stack-app/apps/implementations/index.d.ts +36 -0
  77. package/dist/lib/stack-app/apps/implementations/index.js +51 -0
  78. package/dist/lib/stack-app/apps/implementations/index.js.map +1 -0
  79. package/dist/lib/stack-app/apps/implementations/server-app-impl.d.mts +30 -0
  80. package/dist/lib/stack-app/apps/implementations/server-app-impl.d.ts +30 -0
  81. package/dist/lib/stack-app/apps/implementations/server-app-impl.js +552 -0
  82. package/dist/lib/stack-app/apps/implementations/server-app-impl.js.map +1 -0
  83. package/dist/lib/stack-app/apps/index.d.mts +23 -0
  84. package/dist/lib/stack-app/apps/index.d.ts +23 -0
  85. package/dist/lib/stack-app/apps/index.js +37 -0
  86. package/dist/lib/stack-app/apps/index.js.map +1 -0
  87. package/dist/lib/stack-app/apps/interfaces/admin-app.d.mts +23 -0
  88. package/dist/lib/stack-app/apps/interfaces/admin-app.d.ts +23 -0
  89. package/dist/lib/stack-app/apps/interfaces/admin-app.js +32 -0
  90. package/dist/lib/stack-app/apps/interfaces/admin-app.js.map +1 -0
  91. package/dist/lib/stack-app/apps/interfaces/client-app.d.mts +23 -0
  92. package/dist/lib/stack-app/apps/interfaces/client-app.d.ts +23 -0
  93. package/dist/lib/stack-app/apps/interfaces/client-app.js +32 -0
  94. package/dist/lib/stack-app/apps/interfaces/client-app.js.map +1 -0
  95. package/dist/lib/stack-app/apps/interfaces/server-app.d.mts +23 -0
  96. package/dist/lib/stack-app/apps/interfaces/server-app.d.ts +23 -0
  97. package/dist/lib/stack-app/apps/interfaces/server-app.js +32 -0
  98. package/dist/lib/stack-app/apps/interfaces/server-app.js.map +1 -0
  99. package/dist/lib/stack-app/common.d.mts +63 -0
  100. package/dist/lib/stack-app/common.d.ts +63 -0
  101. package/dist/lib/stack-app/common.js +31 -0
  102. package/dist/lib/stack-app/common.js.map +1 -0
  103. package/dist/lib/stack-app/connected-accounts/index.d.mts +13 -0
  104. package/dist/lib/stack-app/connected-accounts/index.d.ts +13 -0
  105. package/dist/lib/stack-app/connected-accounts/index.js +19 -0
  106. package/dist/lib/stack-app/connected-accounts/index.js.map +1 -0
  107. package/dist/lib/stack-app/contact-channels/index.d.mts +38 -0
  108. package/dist/lib/stack-app/contact-channels/index.d.ts +38 -0
  109. package/dist/lib/stack-app/contact-channels/index.js +67 -0
  110. package/dist/lib/stack-app/contact-channels/index.js.map +1 -0
  111. package/dist/lib/stack-app/email-templates/index.d.mts +15 -0
  112. package/dist/lib/stack-app/email-templates/index.d.ts +15 -0
  113. package/dist/lib/stack-app/email-templates/index.js +36 -0
  114. package/dist/lib/stack-app/email-templates/index.js.map +1 -0
  115. package/dist/lib/stack-app/index.d.mts +23 -0
  116. package/dist/lib/stack-app/index.d.ts +23 -0
  117. package/dist/lib/stack-app/index.js +38 -0
  118. package/dist/lib/stack-app/index.js.map +1 -0
  119. package/dist/lib/stack-app/permissions/index.d.mts +21 -0
  120. package/dist/lib/stack-app/permissions/index.d.ts +21 -0
  121. package/dist/lib/stack-app/permissions/index.js +46 -0
  122. package/dist/lib/stack-app/permissions/index.js.map +1 -0
  123. package/dist/lib/stack-app/project-configs/index.d.mts +82 -0
  124. package/dist/lib/stack-app/project-configs/index.d.ts +82 -0
  125. package/dist/lib/stack-app/project-configs/index.js +19 -0
  126. package/dist/lib/stack-app/project-configs/index.js.map +1 -0
  127. package/dist/lib/stack-app/projects/index.d.mts +23 -0
  128. package/dist/lib/stack-app/projects/index.d.ts +23 -0
  129. package/dist/lib/stack-app/projects/index.js +83 -0
  130. package/dist/lib/stack-app/projects/index.js.map +1 -0
  131. package/dist/lib/stack-app/teams/index.d.mts +23 -0
  132. package/dist/lib/stack-app/teams/index.d.ts +23 -0
  133. package/dist/lib/stack-app/teams/index.js +66 -0
  134. package/dist/lib/stack-app/teams/index.js.map +1 -0
  135. package/dist/lib/stack-app/users/index.d.mts +23 -0
  136. package/dist/lib/stack-app/users/index.d.ts +23 -0
  137. package/dist/lib/stack-app/users/index.js +74 -0
  138. package/dist/lib/stack-app/users/index.js.map +1 -0
  139. package/dist/providers/stack-provider-client.d.mts +17 -5
  140. package/dist/providers/stack-provider-client.d.ts +17 -5
  141. package/dist/providers/stack-provider.d.mts +18 -6
  142. package/dist/providers/stack-provider.d.ts +18 -6
  143. package/package.json +4 -4
  144. package/dist/esm/lib/stack-app.js.map +0 -1
  145. package/dist/lib/stack-app.js.map +0 -1
@@ -1,15 +1,12 @@
1
- // src/lib/stack-app.ts
1
+ // src/lib/stack-app/apps/implementations/client-app-impl.ts
2
2
  import { WebAuthnError, startAuthentication, startRegistration } from "@simplewebauthn/browser";
3
- import { KnownErrors, StackAdminInterface, StackClientInterface, StackServerInterface } from "@stackframe/stack-shared";
4
- import { getProductionModeErrors } from "@stackframe/stack-shared/dist/helpers/production-mode";
3
+ import { KnownErrors, StackClientInterface } from "@stackframe/stack-shared";
5
4
  import { InternalSession } from "@stackframe/stack-shared/dist/sessions";
6
- import { encodeBase64 } from "@stackframe/stack-shared/dist/utils/bytes";
7
- import { AsyncCache } from "@stackframe/stack-shared/dist/utils/caches";
8
5
  import { scrambleDuringCompileTime } from "@stackframe/stack-shared/dist/utils/compile-time";
9
6
  import { isBrowserLike } from "@stackframe/stack-shared/dist/utils/env";
10
- import { StackAssertionError, concatStacktraces, throwErr } from "@stackframe/stack-shared/dist/utils/errors";
7
+ import { StackAssertionError, captureError, throwErr } from "@stackframe/stack-shared/dist/utils/errors";
11
8
  import { DependenciesMap } from "@stackframe/stack-shared/dist/utils/maps";
12
- import { deepPlainEquals, filterUndefined, omit, pick } from "@stackframe/stack-shared/dist/utils/objects";
9
+ import { deepPlainEquals, omit } from "@stackframe/stack-shared/dist/utils/objects";
13
10
  import { neverResolve, runAsynchronously, wait } from "@stackframe/stack-shared/dist/utils/promises";
14
11
  import { suspend, suspendIfSsr } from "@stackframe/stack-shared/dist/utils/react";
15
12
  import { Result } from "@stackframe/stack-shared/dist/utils/results";
@@ -20,137 +17,24 @@ import { generateUuid } from "@stackframe/stack-shared/dist/utils/uuids";
20
17
  import * as cookie from "cookie";
21
18
  import * as NextNavigationUnscrambled from "next/navigation";
22
19
  import React, { useCallback, useMemo } from "react";
23
- import { constructRedirectUrl } from "../utils/url";
24
- import { addNewOAuthProviderOrScope, callOAuthCallback, signInWithOAuth } from "./auth";
25
- import { createBrowserCookieHelper, createCookieHelper, createPlaceholderCookieHelper, deleteCookieClient, getCookieClient, setOrDeleteCookie, setOrDeleteCookieClient } from "./cookie";
20
+ import { constructRedirectUrl } from "../../../../utils/url";
21
+ import { addNewOAuthProviderOrScope, callOAuthCallback, signInWithOAuth } from "../../../auth";
22
+ import { createBrowserCookieHelper, createCookieHelper, createPlaceholderCookieHelper, deleteCookieClient, getCookieClient, setOrDeleteCookie, setOrDeleteCookieClient } from "../../../cookie";
23
+ import { stackAppInternalsSymbol } from "../../common";
24
+ import { contactChannelCreateOptionsToCrud, contactChannelUpdateOptionsToCrud } from "../../contact-channels";
25
+ import { adminProjectCreateOptionsToCrud } from "../../projects";
26
+ import { teamCreateOptionsToCrud, teamUpdateOptionsToCrud } from "../../teams";
27
+ import { userUpdateOptionsToCrud } from "../../users";
28
+ import { clientVersion, createCache, createCacheBySession, createEmptyTokenStore, getBaseUrl, getDefaultProjectId, getDefaultPublishableClientKey, getUrls } from "./common";
29
+ import { useAsyncCache } from "./common";
26
30
  import * as sc from "@stackframe/stack-sc";
27
31
  import { cookies } from "@stackframe/stack-sc";
28
32
  var isReactServer2 = false;
29
33
  isReactServer2 = sc.isReactServer;
30
34
  var NextNavigation = scrambleDuringCompileTime(NextNavigationUnscrambled);
31
- var clientVersion = "js @stackframe/stack@2.7.21";
32
- if (clientVersion.startsWith("STACK_COMPILE_TIME")) {
33
- throw new StackAssertionError("Client version was not replaced. Something went wrong during build!");
34
- }
35
- function getUrls(partial) {
36
- const handler = partial.handler ?? "/handler";
37
- const home = partial.home ?? "/";
38
- const afterSignIn = partial.afterSignIn ?? home;
39
- return {
40
- handler,
41
- signIn: `${handler}/sign-in`,
42
- afterSignIn: home,
43
- signUp: `${handler}/sign-up`,
44
- afterSignUp: afterSignIn,
45
- signOut: `${handler}/sign-out`,
46
- afterSignOut: home,
47
- emailVerification: `${handler}/email-verification`,
48
- passwordReset: `${handler}/password-reset`,
49
- forgotPassword: `${handler}/forgot-password`,
50
- oauthCallback: `${handler}/oauth-callback`,
51
- magicLinkCallback: `${handler}/magic-link-callback`,
52
- home,
53
- accountSettings: `${handler}/account-settings`,
54
- error: `${handler}/error`,
55
- teamInvitation: `${handler}/team-invitation`,
56
- ...filterUndefined(partial)
57
- };
58
- }
59
- function getDefaultProjectId() {
60
- return process.env.NEXT_PUBLIC_STACK_PROJECT_ID || throwErr(new Error("Welcome to Stack Auth! It seems that you haven't provided a project ID. Please create a project on the Stack dashboard at https://app.stack-auth.com and put it in the NEXT_PUBLIC_STACK_PROJECT_ID environment variable."));
61
- }
62
- function getDefaultPublishableClientKey() {
63
- return process.env.NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY || throwErr(new Error("Welcome to Stack Auth! It seems that you haven't provided a publishable client key. Please create an API key for your project on the Stack dashboard at https://app.stack-auth.com and copy your publishable client key into the NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY environment variable."));
64
- }
65
- function getDefaultSecretServerKey() {
66
- return process.env.STACK_SECRET_SERVER_KEY || throwErr(new Error("No secret server key provided. Please copy your key from the Stack dashboard and put your it in the STACK_SECRET_SERVER_KEY environment variable."));
67
- }
68
- function getDefaultSuperSecretAdminKey() {
69
- return process.env.STACK_SUPER_SECRET_ADMIN_KEY || throwErr(new Error("No super secret admin key provided. Please copy your key from the Stack dashboard and put it in the STACK_SUPER_SECRET_ADMIN_KEY environment variable."));
70
- }
71
- function getBaseUrl(userSpecifiedBaseUrl) {
72
- let url;
73
- if (userSpecifiedBaseUrl) {
74
- if (typeof userSpecifiedBaseUrl === "string") {
75
- url = userSpecifiedBaseUrl;
76
- } else {
77
- if (isBrowserLike()) {
78
- url = userSpecifiedBaseUrl.browser;
79
- } else {
80
- url = userSpecifiedBaseUrl.server;
81
- }
82
- }
83
- } else {
84
- if (isBrowserLike()) {
85
- url = process.env.NEXT_PUBLIC_BROWSER_STACK_API_URL;
86
- } else {
87
- url = process.env.NEXT_PUBLIC_SERVER_STACK_API_URL;
88
- }
89
- url = url || process.env.NEXT_PUBLIC_STACK_API_URL || process.env.NEXT_PUBLIC_STACK_URL || defaultBaseUrl;
90
- }
91
- return url.endsWith("/") ? url.slice(0, -1) : url;
92
- }
93
- var defaultBaseUrl = "https://api.stack-auth.com";
94
- function createEmptyTokenStore() {
95
- return new Store({
96
- refreshToken: null,
97
- accessToken: null
98
- });
99
- }
100
- var cachePromiseByComponentId = /* @__PURE__ */ new Map();
101
- function useAsyncCache(cache, dependencies, caller) {
102
- suspendIfSsr(caller);
103
- const id = React.useId();
104
- const subscribe = useCallback((cb) => {
105
- const { unsubscribe } = cache.onStateChange(dependencies, () => {
106
- cachePromiseByComponentId.delete(id);
107
- cb();
108
- });
109
- return unsubscribe;
110
- }, [cache, ...dependencies]);
111
- const getSnapshot = useCallback(() => {
112
- if (!cachePromiseByComponentId.has(id)) {
113
- cachePromiseByComponentId.set(id, cache.getOrWait(dependencies, "read-write"));
114
- }
115
- return cachePromiseByComponentId.get(id);
116
- }, [cache, ...dependencies]);
117
- const promise = React.useSyncExternalStore(
118
- subscribe,
119
- getSnapshot,
120
- () => throwErr(new Error("getServerSnapshot should never be called in useAsyncCache because we restrict to CSR earlier"))
121
- );
122
- const result = React.use(promise);
123
- if (result.status === "error") {
124
- const error = result.error;
125
- if (error instanceof Error && !error.__stackHasConcatenatedStacktraces) {
126
- concatStacktraces(error, new Error());
127
- error.__stackHasConcatenatedStacktraces = true;
128
- }
129
- throw error;
130
- }
131
- return result.data;
132
- }
133
- var stackAppInternalsSymbol = Symbol.for("StackAuth--DO-NOT-USE-OR-YOU-WILL-BE-FIRED--StackAppInternals");
134
- var allClientApps = /* @__PURE__ */ new Map();
135
- var createCache = (fetcher) => {
136
- return new AsyncCache(
137
- async (dependencies) => await Result.fromThrowingAsync(async () => await fetcher(dependencies)),
138
- {}
139
- );
140
- };
141
- var createCacheBySession = (fetcher) => {
142
- return new AsyncCache(
143
- async ([session, ...extraDependencies]) => await Result.fromThrowingAsync(async () => await fetcher(session, extraDependencies)),
144
- {
145
- onSubscribe: ([session], refresh) => {
146
- const handler = session.onInvalidate(() => refresh());
147
- return () => handler.unsubscribe();
148
- }
149
- }
150
- );
151
- };
152
35
  var numberOfAppsCreated = 0;
153
- var _StackClientAppImpl = class __StackClientAppImpl {
36
+ var allClientApps = /* @__PURE__ */ new Map();
37
+ var __StackClientAppImplIncomplete = class __StackClientAppImplIncomplete {
154
38
  constructor(_options) {
155
39
  this._options = _options;
156
40
  this._uniqueIdentifier = void 0;
@@ -236,6 +120,9 @@ var _StackClientAppImpl = class __StackClientAppImpl {
236
120
  * - So different token stores are separated and don't leak information between each other, eg. if the same user sends two requests to the same server they should get a different session object
237
121
  */
238
122
  this._sessionsByTokenStoreAndSessionKey = /* @__PURE__ */ new WeakMap();
123
+ if (!__StackClientAppImplIncomplete.LazyStackAdminAppImpl.value) {
124
+ throw new StackAssertionError("Admin app implementation not initialized. Did you import the _StackClientApp from stack-app/apps/implementations/index.ts? You can't import it directly from ./apps/implementations/client-app-impl.ts as that causes a circular dependency (see the comment at _LazyStackAdminAppImpl for more details).");
125
+ }
239
126
  if ("interface" in _options) {
240
127
  this._interface = _options.interface;
241
128
  } else {
@@ -695,12 +582,12 @@ var _StackClientAppImpl = class __StackClientAppImpl {
695
582
  let attResp;
696
583
  try {
697
584
  attResp = await startRegistration({ optionsJSON: options_json });
698
- debugger;
699
585
  } catch (error) {
700
586
  if (error instanceof WebAuthnError) {
701
587
  return Result.error(new KnownErrors.PasskeyWebAuthnError(error.message, error.name));
702
588
  } else {
703
- return Result.error(new KnownErrors.PasskeyRegistrationFailed("Failed to start passkey registration"));
589
+ captureError("passkey-registration-failed", error);
590
+ return Result.error(new KnownErrors.PasskeyRegistrationFailed("Failed to start passkey registration due to unknown error"));
704
591
  }
705
592
  }
706
593
  const registrationResult = await app._interface.registerPasskey({ credential: attResp, code }, session);
@@ -897,7 +784,7 @@ var _StackClientAppImpl = class __StackClientAppImpl {
897
784
  }
898
785
  _getOwnedAdminApp(forProjectId, session) {
899
786
  if (!this._ownedAdminApps.has([session, forProjectId])) {
900
- this._ownedAdminApps.set([session, forProjectId], new _StackAdminAppImpl({
787
+ this._ownedAdminApps.set([session, forProjectId], new __StackClientAppImplIncomplete.LazyStackAdminAppImpl.value({
901
788
  baseUrl: this._interface.options.getBaseUrl(),
902
789
  projectId: forProjectId,
903
790
  tokenStore: null,
@@ -942,9 +829,10 @@ var _StackClientAppImpl = class __StackClientAppImpl {
942
829
  if (typeof this._redirectMethod === "object") {
943
830
  return this._redirectMethod.useNavigate();
944
831
  } else if (this._redirectMethod === "window") {
945
- return () => window.location.assign;
832
+ return (to) => window.location.assign(to);
946
833
  } else if (this._redirectMethod === "nextjs") {
947
- return NextNavigation.useRouter().push;
834
+ const router = NextNavigation.useRouter();
835
+ return (to) => router.push(to);
948
836
  } else {
949
837
  return (to) => {
950
838
  };
@@ -1397,7 +1285,7 @@ var _StackClientAppImpl = class __StackClientAppImpl {
1397
1285
  }
1398
1286
  return clientApp;
1399
1287
  }
1400
- return new __StackClientAppImpl({
1288
+ return new __StackClientAppImplIncomplete({
1401
1289
  ...json,
1402
1290
  checkString: providedCheckString
1403
1291
  });
@@ -1435,976 +1323,16 @@ var _StackClientAppImpl = class __StackClientAppImpl {
1435
1323
  };
1436
1324
  }
1437
1325
  };
1438
- var _StackServerAppImpl = class extends _StackClientAppImpl {
1439
- constructor(options) {
1440
- super("interface" in options ? {
1441
- interface: options.interface,
1442
- tokenStore: options.tokenStore,
1443
- urls: options.urls,
1444
- oauthScopesOnSignIn: options.oauthScopesOnSignIn
1445
- } : {
1446
- interface: new StackServerInterface({
1447
- getBaseUrl: () => getBaseUrl(options.baseUrl),
1448
- projectId: options.projectId ?? getDefaultProjectId(),
1449
- clientVersion,
1450
- publishableClientKey: options.publishableClientKey ?? getDefaultPublishableClientKey(),
1451
- secretServerKey: options.secretServerKey ?? getDefaultSecretServerKey()
1452
- }),
1453
- baseUrl: options.baseUrl,
1454
- projectId: options.projectId,
1455
- publishableClientKey: options.publishableClientKey,
1456
- tokenStore: options.tokenStore,
1457
- urls: options.urls ?? {},
1458
- oauthScopesOnSignIn: options.oauthScopesOnSignIn ?? {},
1459
- redirectMethod: options.redirectMethod
1460
- });
1461
- // TODO override the client user cache to use the server user cache, so we save some requests
1462
- this._currentServerUserCache = createCacheBySession(async (session) => {
1463
- if (session.isKnownToBeInvalid()) {
1464
- return null;
1465
- }
1466
- return await this._interface.getServerUserByToken(session);
1467
- });
1468
- this._serverUsersCache = createCache(async ([cursor, limit, orderBy, desc, query]) => {
1469
- return await this._interface.listServerUsers({ cursor, limit, orderBy, desc, query });
1470
- });
1471
- this._serverUserCache = createCache(async ([userId]) => {
1472
- const user = await this._interface.getServerUserById(userId);
1473
- return Result.or(user, null);
1474
- });
1475
- this._serverTeamsCache = createCache(async ([userId]) => {
1476
- return await this._interface.listServerTeams({ userId });
1477
- });
1478
- this._serverTeamUserPermissionsCache = createCache(async ([teamId, userId, recursive]) => {
1479
- return await this._interface.listServerTeamPermissions({ teamId, userId, recursive }, null);
1480
- });
1481
- this._serverUserOAuthConnectionAccessTokensCache = createCache(
1482
- async ([userId, providerId, scope]) => {
1483
- try {
1484
- const result = await this._interface.createServerProviderAccessToken(userId, providerId, scope || "");
1485
- return { accessToken: result.access_token };
1486
- } catch (err) {
1487
- if (!(err instanceof KnownErrors.OAuthConnectionDoesNotHaveRequiredScope || err instanceof KnownErrors.OAuthConnectionNotConnectedToUser)) {
1488
- throw err;
1489
- }
1490
- }
1491
- return null;
1492
- }
1493
- );
1494
- this._serverUserOAuthConnectionCache = createCache(
1495
- async ([userId, providerId, scope, redirect]) => {
1496
- return await this._getUserOAuthConnectionCacheFn({
1497
- getUser: async () => Result.orThrow(await this._serverUserCache.getOrWait([userId], "write-only")),
1498
- getOrWaitOAuthToken: async () => Result.orThrow(await this._serverUserOAuthConnectionAccessTokensCache.getOrWait([userId, providerId, scope || ""], "write-only")),
1499
- useOAuthToken: () => useAsyncCache(this._serverUserOAuthConnectionAccessTokensCache, [userId, providerId, scope || ""], "user.useConnectedAccount()"),
1500
- providerId,
1501
- scope,
1502
- redirect,
1503
- session: null
1504
- });
1505
- }
1506
- );
1507
- this._serverTeamMemberProfilesCache = createCache(
1508
- async ([teamId]) => {
1509
- return await this._interface.listServerTeamMemberProfiles({ teamId });
1510
- }
1511
- );
1512
- this._serverTeamInvitationsCache = createCache(
1513
- async ([teamId]) => {
1514
- return await this._interface.listServerTeamInvitations({ teamId });
1515
- }
1516
- );
1517
- this._serverUserTeamProfileCache = createCache(
1518
- async ([teamId, userId]) => {
1519
- return await this._interface.getServerTeamMemberProfile({ teamId, userId });
1520
- }
1521
- );
1522
- this._serverContactChannelsCache = createCache(
1523
- async ([userId]) => {
1524
- return await this._interface.listServerContactChannels(userId);
1525
- }
1526
- );
1527
- }
1528
- async _updateServerUser(userId, update) {
1529
- const result = await this._interface.updateServerUser(userId, serverUserUpdateOptionsToCrud(update));
1530
- await this._refreshUsers();
1531
- return result;
1532
- }
1533
- _serverEditableTeamProfileFromCrud(crud) {
1534
- const app = this;
1535
- return {
1536
- displayName: crud.display_name,
1537
- profileImageUrl: crud.profile_image_url,
1538
- async update(update) {
1539
- await app._interface.updateServerTeamMemberProfile({
1540
- teamId: crud.team_id,
1541
- userId: crud.user_id,
1542
- profile: {
1543
- display_name: update.displayName,
1544
- profile_image_url: update.profileImageUrl
1545
- }
1546
- });
1547
- await app._serverUserTeamProfileCache.refresh([crud.team_id, crud.user_id]);
1548
- }
1549
- };
1550
- }
1551
- _serverContactChannelFromCrud(userId, crud) {
1552
- const app = this;
1553
- return {
1554
- id: crud.id,
1555
- value: crud.value,
1556
- type: crud.type,
1557
- isVerified: crud.is_verified,
1558
- isPrimary: crud.is_primary,
1559
- usedForAuth: crud.used_for_auth,
1560
- async sendVerificationEmail(options) {
1561
- if (!options?.callbackUrl && !await app._getCurrentUrl()) {
1562
- throw new Error("Cannot send verification email without a callback URL from the server or without a redirect method. Make sure you pass the `callbackUrl` option: `sendVerificationEmail({ callbackUrl: ... })`");
1563
- }
1564
- await app._interface.sendServerContactChannelVerificationEmail(userId, crud.id, options?.callbackUrl ?? constructRedirectUrl(app.urls.emailVerification));
1565
- },
1566
- async update(data) {
1567
- await app._interface.updateServerContactChannel(userId, crud.id, serverContactChannelUpdateOptionsToCrud(data));
1568
- },
1569
- async delete() {
1570
- await app._interface.deleteServerContactChannel(userId, crud.id);
1571
- }
1572
- };
1573
- }
1574
- _serverUserFromCrud(crud) {
1575
- const app = this;
1576
- async function getConnectedAccount(id, options) {
1577
- const scopeString = options?.scopes?.join(" ");
1578
- return Result.orThrow(await app._serverUserOAuthConnectionCache.getOrWait([crud.id, id, scopeString || "", options?.or === "redirect"], "write-only"));
1579
- }
1580
- function useConnectedAccount(id, options) {
1581
- const scopeString = options?.scopes?.join(" ");
1582
- return useAsyncCache(app._serverUserOAuthConnectionCache, [crud.id, id, scopeString || "", options?.or === "redirect"], "user.useConnectedAccount()");
1583
- }
1584
- return {
1585
- ...super._createBaseUser(crud),
1586
- lastActiveAt: new Date(crud.last_active_at_millis),
1587
- serverMetadata: crud.server_metadata,
1588
- async setPrimaryEmail(email, options) {
1589
- await app._updateServerUser(crud.id, { primaryEmail: email, primaryEmailVerified: options?.verified });
1590
- },
1591
- async grantPermission(scope, permissionId) {
1592
- await app._interface.grantServerTeamUserPermission(scope.id, crud.id, permissionId);
1593
- for (const recursive of [true, false]) {
1594
- await app._serverTeamUserPermissionsCache.refresh([scope.id, crud.id, recursive]);
1595
- }
1596
- },
1597
- async revokePermission(scope, permissionId) {
1598
- await app._interface.revokeServerTeamUserPermission(scope.id, crud.id, permissionId);
1599
- for (const recursive of [true, false]) {
1600
- await app._serverTeamUserPermissionsCache.refresh([scope.id, crud.id, recursive]);
1601
- }
1602
- },
1603
- async delete() {
1604
- const res = await app._interface.deleteServerServerUser(crud.id);
1605
- await app._refreshUsers();
1606
- return res;
1607
- },
1608
- async createSession(options) {
1609
- const tokens = await app._interface.createServerUserSession(crud.id, options.expiresInMillis ?? 1e3 * 60 * 60 * 24 * 365);
1610
- return {
1611
- async getTokens() {
1612
- return tokens;
1613
- }
1614
- };
1615
- },
1616
- async setDisplayName(displayName) {
1617
- return await this.update({ displayName });
1618
- },
1619
- async setClientMetadata(metadata) {
1620
- return await this.update({ clientMetadata: metadata });
1621
- },
1622
- async setClientReadOnlyMetadata(metadata) {
1623
- return await this.update({ clientReadOnlyMetadata: metadata });
1624
- },
1625
- async setServerMetadata(metadata) {
1626
- return await this.update({ serverMetadata: metadata });
1627
- },
1628
- async setSelectedTeam(team) {
1629
- return await this.update({ selectedTeamId: team?.id ?? null });
1630
- },
1631
- getConnectedAccount,
1632
- useConnectedAccount,
1633
- selectedTeam: crud.selected_team ? app._serverTeamFromCrud(crud.selected_team) : null,
1634
- async getTeam(teamId) {
1635
- const teams = await this.listTeams();
1636
- return teams.find((t) => t.id === teamId) ?? null;
1637
- },
1638
- useTeam(teamId) {
1639
- const teams = this.useTeams();
1640
- return useMemo(() => {
1641
- return teams.find((t) => t.id === teamId) ?? null;
1642
- }, [teams, teamId]);
1643
- },
1644
- async listTeams() {
1645
- const teams = Result.orThrow(await app._serverTeamsCache.getOrWait([crud.id], "write-only"));
1646
- return teams.map((t) => app._serverTeamFromCrud(t));
1647
- },
1648
- useTeams() {
1649
- const teams = useAsyncCache(app._serverTeamsCache, [crud.id], "user.useTeams()");
1650
- return useMemo(() => teams.map((t) => app._serverTeamFromCrud(t)), [teams]);
1651
- },
1652
- createTeam: async (data) => {
1653
- const team = await app._interface.createServerTeam(serverTeamCreateOptionsToCrud({
1654
- creatorUserId: crud.id,
1655
- ...data
1656
- }));
1657
- await app._serverTeamsCache.refresh([void 0]);
1658
- return app._serverTeamFromCrud(team);
1659
- },
1660
- leaveTeam: async (team) => {
1661
- await app._interface.leaveServerTeam({ teamId: team.id, userId: crud.id });
1662
- },
1663
- async listPermissions(scope, options) {
1664
- const recursive = options?.recursive ?? true;
1665
- const permissions = Result.orThrow(await app._serverTeamUserPermissionsCache.getOrWait([scope.id, crud.id, recursive], "write-only"));
1666
- return permissions.map((crud2) => app._serverPermissionFromCrud(crud2));
1667
- },
1668
- usePermissions(scope, options) {
1669
- const recursive = options?.recursive ?? true;
1670
- const permissions = useAsyncCache(app._serverTeamUserPermissionsCache, [scope.id, crud.id, recursive], "user.usePermissions()");
1671
- return useMemo(() => permissions.map((crud2) => app._serverPermissionFromCrud(crud2)), [permissions]);
1672
- },
1673
- async getPermission(scope, permissionId) {
1674
- const permissions = await this.listPermissions(scope);
1675
- return permissions.find((p) => p.id === permissionId) ?? null;
1676
- },
1677
- usePermission(scope, permissionId) {
1678
- const permissions = this.usePermissions(scope);
1679
- return useMemo(() => permissions.find((p) => p.id === permissionId) ?? null, [permissions, permissionId]);
1680
- },
1681
- async hasPermission(scope, permissionId) {
1682
- return await this.getPermission(scope, permissionId) !== null;
1683
- },
1684
- async update(update) {
1685
- await app._updateServerUser(crud.id, update);
1686
- },
1687
- async sendVerificationEmail() {
1688
- return await app._checkFeatureSupport("sendVerificationEmail() on ServerUser", {});
1689
- },
1690
- async updatePassword(options) {
1691
- const result = await this.update({ password: options.newPassword });
1692
- await app._serverUserCache.refresh([crud.id]);
1693
- return result;
1694
- },
1695
- async setPassword(options) {
1696
- const result = await this.update(options);
1697
- await app._serverUserCache.refresh([crud.id]);
1698
- return result;
1699
- },
1700
- async getTeamProfile(team) {
1701
- const result = Result.orThrow(await app._serverUserTeamProfileCache.getOrWait([team.id, crud.id], "write-only"));
1702
- return app._serverEditableTeamProfileFromCrud(result);
1703
- },
1704
- useTeamProfile(team) {
1705
- const result = useAsyncCache(app._serverUserTeamProfileCache, [team.id, crud.id], "user.useTeamProfile()");
1706
- return useMemo(() => app._serverEditableTeamProfileFromCrud(result), [result]);
1707
- },
1708
- async listContactChannels() {
1709
- const result = Result.orThrow(await app._serverContactChannelsCache.getOrWait([crud.id], "write-only"));
1710
- return result.map((data) => app._serverContactChannelFromCrud(crud.id, data));
1711
- },
1712
- useContactChannels() {
1713
- const result = useAsyncCache(app._serverContactChannelsCache, [crud.id], "user.useContactChannels()");
1714
- return useMemo(() => result.map((data) => app._serverContactChannelFromCrud(crud.id, data)), [result]);
1715
- },
1716
- createContactChannel: async (data) => {
1717
- const contactChannel = await app._interface.createServerContactChannel(serverContactChannelCreateOptionsToCrud(crud.id, data));
1718
- await app._serverContactChannelsCache.refresh([crud.id]);
1719
- return app._serverContactChannelFromCrud(crud.id, contactChannel);
1720
- }
1721
- };
1722
- }
1723
- _serverTeamUserFromCrud(crud) {
1724
- return {
1725
- ...this._serverUserFromCrud(crud.user),
1726
- teamProfile: {
1727
- displayName: crud.display_name,
1728
- profileImageUrl: crud.profile_image_url
1729
- }
1730
- };
1731
- }
1732
- _serverTeamInvitationFromCrud(crud) {
1733
- return {
1734
- id: crud.id,
1735
- recipientEmail: crud.recipient_email,
1736
- expiresAt: new Date(crud.expires_at_millis),
1737
- revoke: async () => {
1738
- await this._interface.revokeServerTeamInvitation(crud.id, crud.team_id);
1739
- }
1740
- };
1741
- }
1742
- _currentUserFromCrud(crud, session) {
1743
- const app = this;
1744
- const currentUser = {
1745
- ...this._serverUserFromCrud(crud),
1746
- ...this._createAuth(session),
1747
- ...this._isInternalProject() ? this._createInternalUserExtra(session) : {}
1748
- };
1749
- Object.freeze(currentUser);
1750
- return currentUser;
1751
- }
1752
- _serverTeamFromCrud(crud) {
1753
- const app = this;
1754
- return {
1755
- id: crud.id,
1756
- displayName: crud.display_name,
1757
- profileImageUrl: crud.profile_image_url,
1758
- createdAt: new Date(crud.created_at_millis),
1759
- clientMetadata: crud.client_metadata,
1760
- clientReadOnlyMetadata: crud.client_read_only_metadata,
1761
- serverMetadata: crud.server_metadata,
1762
- async update(update) {
1763
- await app._interface.updateServerTeam(crud.id, serverTeamUpdateOptionsToCrud(update));
1764
- await app._serverTeamsCache.refresh([void 0]);
1765
- },
1766
- async delete() {
1767
- await app._interface.deleteServerTeam(crud.id);
1768
- await app._serverTeamsCache.refresh([void 0]);
1769
- },
1770
- async listUsers() {
1771
- const result = Result.orThrow(await app._serverTeamMemberProfilesCache.getOrWait([crud.id], "write-only"));
1772
- return result.map((u) => app._serverTeamUserFromCrud(u));
1773
- },
1774
- useUsers() {
1775
- const result = useAsyncCache(app._serverTeamMemberProfilesCache, [crud.id], "team.useUsers()");
1776
- return useMemo(() => result.map((u) => app._serverTeamUserFromCrud(u)), [result]);
1777
- },
1778
- async addUser(userId) {
1779
- await app._interface.addServerUserToTeam({
1780
- teamId: crud.id,
1781
- userId
1782
- });
1783
- await app._serverTeamMemberProfilesCache.refresh([crud.id]);
1784
- },
1785
- async removeUser(userId) {
1786
- await app._interface.removeServerUserFromTeam({
1787
- teamId: crud.id,
1788
- userId
1789
- });
1790
- await app._serverTeamMemberProfilesCache.refresh([crud.id]);
1791
- },
1792
- async inviteUser(options) {
1793
- if (!options.callbackUrl && !await app._getCurrentUrl()) {
1794
- throw new Error("Cannot invite user without a callback URL from the server or without a redirect method. Make sure you pass the `callbackUrl` option: `inviteUser({ email, callbackUrl: ... })`");
1795
- }
1796
- await app._interface.sendServerTeamInvitation({
1797
- teamId: crud.id,
1798
- email: options.email,
1799
- callbackUrl: options.callbackUrl ?? constructRedirectUrl(app.urls.teamInvitation)
1800
- });
1801
- await app._serverTeamInvitationsCache.refresh([crud.id]);
1802
- },
1803
- async listInvitations() {
1804
- const result = Result.orThrow(await app._serverTeamInvitationsCache.getOrWait([crud.id], "write-only"));
1805
- return result.map((crud2) => app._serverTeamInvitationFromCrud(crud2));
1806
- },
1807
- useInvitations() {
1808
- const result = useAsyncCache(app._serverTeamInvitationsCache, [crud.id], "team.useInvitations()");
1809
- return useMemo(() => result.map((crud2) => app._serverTeamInvitationFromCrud(crud2)), [result]);
1810
- }
1811
- };
1812
- }
1813
- async createUser(options) {
1814
- const crud = await this._interface.createServerUser(serverUserCreateOptionsToCrud(options));
1815
- await this._refreshUsers();
1816
- return this._serverUserFromCrud(crud);
1817
- }
1818
- async getUser(options) {
1819
- if (typeof options === "string") {
1820
- return await this.getServerUserById(options);
1821
- } else {
1822
- this._ensurePersistentTokenStore(options?.tokenStore);
1823
- const session = await this._getSession(options?.tokenStore);
1824
- const crud = Result.orThrow(await this._currentServerUserCache.getOrWait([session], "write-only"));
1825
- if (crud === null) {
1826
- switch (options?.or) {
1827
- case "redirect": {
1828
- await this.redirectToSignIn({ replace: true });
1829
- break;
1830
- }
1831
- case "throw": {
1832
- throw new Error("User is not signed in but getUser was called with { or: 'throw' }");
1833
- }
1834
- default: {
1835
- return null;
1836
- }
1837
- }
1838
- }
1839
- return crud && this._currentUserFromCrud(crud, session);
1840
- }
1841
- }
1842
- async getServerUser() {
1843
- console.warn("stackServerApp.getServerUser is deprecated; use stackServerApp.getUser instead");
1844
- return await this.getUser();
1845
- }
1846
- async getServerUserById(userId) {
1847
- const crud = Result.orThrow(await this._serverUserCache.getOrWait([userId], "write-only"));
1848
- return crud && this._serverUserFromCrud(crud);
1849
- }
1850
- useUser(options) {
1851
- if (typeof options === "string") {
1852
- return this.useUserById(options);
1853
- } else {
1854
- this._ensurePersistentTokenStore(options?.tokenStore);
1855
- const session = this._useSession(options?.tokenStore);
1856
- const crud = useAsyncCache(this._currentServerUserCache, [session], "useUser()");
1857
- if (crud === null) {
1858
- switch (options?.or) {
1859
- case "redirect": {
1860
- runAsynchronously(this.redirectToSignIn({ replace: true }));
1861
- suspend();
1862
- throw new StackAssertionError("suspend should never return");
1863
- }
1864
- case "throw": {
1865
- throw new Error("User is not signed in but useUser was called with { or: 'throw' }");
1866
- }
1867
- case void 0:
1868
- case "return-null": {
1869
- }
1870
- }
1871
- }
1872
- return useMemo(() => {
1873
- return crud && this._currentUserFromCrud(crud, session);
1874
- }, [crud, session, options?.or]);
1875
- }
1876
- }
1877
- useUserById(userId) {
1878
- const crud = useAsyncCache(this._serverUserCache, [userId], "useUserById()");
1879
- return useMemo(() => {
1880
- return crud && this._serverUserFromCrud(crud);
1881
- }, [crud]);
1882
- }
1883
- async listUsers(options) {
1884
- const crud = Result.orThrow(await this._serverUsersCache.getOrWait([options?.cursor, options?.limit, options?.orderBy, options?.desc, options?.query], "write-only"));
1885
- const result = crud.items.map((j) => this._serverUserFromCrud(j));
1886
- result.nextCursor = crud.pagination?.next_cursor ?? null;
1887
- return result;
1888
- }
1889
- useUsers(options) {
1890
- const crud = useAsyncCache(this._serverUsersCache, [options?.cursor, options?.limit, options?.orderBy, options?.desc, options?.query], "useServerUsers()");
1891
- const result = crud.items.map((j) => this._serverUserFromCrud(j));
1892
- result.nextCursor = crud.pagination?.next_cursor ?? null;
1893
- return result;
1894
- }
1895
- _serverPermissionFromCrud(crud) {
1896
- return {
1897
- id: crud.id
1898
- };
1899
- }
1900
- _serverTeamPermissionDefinitionFromCrud(crud) {
1901
- return {
1902
- id: crud.id,
1903
- description: crud.description,
1904
- containedPermissionIds: crud.contained_permission_ids
1905
- };
1906
- }
1907
- async listTeams() {
1908
- const teams = Result.orThrow(await this._serverTeamsCache.getOrWait([void 0], "write-only"));
1909
- return teams.map((t) => this._serverTeamFromCrud(t));
1910
- }
1911
- async createTeam(data) {
1912
- const team = await this._interface.createServerTeam(serverTeamCreateOptionsToCrud(data));
1913
- await this._serverTeamsCache.refresh([void 0]);
1914
- return this._serverTeamFromCrud(team);
1915
- }
1916
- useTeams() {
1917
- const teams = useAsyncCache(this._serverTeamsCache, [void 0], "useServerTeams()");
1918
- return useMemo(() => {
1919
- return teams.map((t) => this._serverTeamFromCrud(t));
1920
- }, [teams]);
1921
- }
1922
- async getTeam(teamId) {
1923
- const teams = await this.listTeams();
1924
- return teams.find((t) => t.id === teamId) ?? null;
1925
- }
1926
- useTeam(teamId) {
1927
- const teams = this.useTeams();
1928
- return useMemo(() => {
1929
- return teams.find((t) => t.id === teamId) ?? null;
1930
- }, [teams, teamId]);
1931
- }
1932
- async _refreshSession(session) {
1933
- await Promise.all([
1934
- super._refreshUser(session),
1935
- this._currentServerUserCache.refresh([session])
1936
- ]);
1937
- }
1938
- async _refreshUsers() {
1939
- await Promise.all([
1940
- super._refreshUsers(),
1941
- this._serverUserCache.refreshWhere(() => true),
1942
- this._serverUsersCache.refreshWhere(() => true),
1943
- this._serverContactChannelsCache.refreshWhere(() => true)
1944
- ]);
1945
- }
1946
- };
1947
- var _StackAdminAppImpl = class extends _StackServerAppImpl {
1948
- constructor(options) {
1949
- super({
1950
- interface: new StackAdminInterface({
1951
- getBaseUrl: () => getBaseUrl(options.baseUrl),
1952
- projectId: options.projectId ?? getDefaultProjectId(),
1953
- clientVersion,
1954
- ..."projectOwnerSession" in options ? {
1955
- projectOwnerSession: options.projectOwnerSession
1956
- } : {
1957
- publishableClientKey: options.publishableClientKey ?? getDefaultPublishableClientKey(),
1958
- secretServerKey: options.secretServerKey ?? getDefaultSecretServerKey(),
1959
- superSecretAdminKey: options.superSecretAdminKey ?? getDefaultSuperSecretAdminKey()
1960
- }
1961
- }),
1962
- baseUrl: options.baseUrl,
1963
- projectId: options.projectId,
1964
- tokenStore: options.tokenStore,
1965
- urls: options.urls,
1966
- oauthScopesOnSignIn: options.oauthScopesOnSignIn,
1967
- redirectMethod: options.redirectMethod
1968
- });
1969
- this._adminProjectCache = createCache(async () => {
1970
- return await this._interface.getProject();
1971
- });
1972
- this._apiKeysCache = createCache(async () => {
1973
- return await this._interface.listApiKeys();
1974
- });
1975
- this._adminEmailTemplatesCache = createCache(async () => {
1976
- return await this._interface.listEmailTemplates();
1977
- });
1978
- this._adminTeamPermissionDefinitionsCache = createCache(async () => {
1979
- return await this._interface.listPermissionDefinitions();
1980
- });
1981
- this._svixTokenCache = createCache(async () => {
1982
- return await this._interface.getSvixToken();
1983
- });
1984
- this._metricsCache = createCache(async () => {
1985
- return await this._interface.getMetrics();
1986
- });
1987
- }
1988
- _adminOwnedProjectFromCrud(data, onRefresh) {
1989
- if (this._tokenStoreInit !== null) {
1990
- throw new StackAssertionError("Owned apps must always have tokenStore === null \u2014 did you not create this project with app._createOwnedApp()?");
1991
- ;
1992
- }
1993
- return {
1994
- ...this._adminProjectFromCrud(data, onRefresh),
1995
- app: this
1996
- };
1997
- }
1998
- _adminProjectFromCrud(data, onRefresh) {
1999
- if (data.id !== this.projectId) {
2000
- throw new StackAssertionError(`The project ID of the provided project JSON (${data.id}) does not match the project ID of the app (${this.projectId})!`);
2001
- }
2002
- const app = this;
2003
- return {
2004
- id: data.id,
2005
- displayName: data.display_name,
2006
- description: data.description,
2007
- createdAt: new Date(data.created_at_millis),
2008
- userCount: data.user_count,
2009
- isProductionMode: data.is_production_mode,
2010
- config: {
2011
- id: data.config.id,
2012
- signUpEnabled: data.config.sign_up_enabled,
2013
- credentialEnabled: data.config.credential_enabled,
2014
- magicLinkEnabled: data.config.magic_link_enabled,
2015
- passkeyEnabled: data.config.passkey_enabled,
2016
- clientTeamCreationEnabled: data.config.client_team_creation_enabled,
2017
- clientUserDeletionEnabled: data.config.client_user_deletion_enabled,
2018
- allowLocalhost: data.config.allow_localhost,
2019
- oauthProviders: data.config.oauth_providers.map((p) => p.type === "shared" ? {
2020
- id: p.id,
2021
- enabled: p.enabled,
2022
- type: "shared"
2023
- } : {
2024
- id: p.id,
2025
- enabled: p.enabled,
2026
- type: "standard",
2027
- clientId: p.client_id ?? throwErr("Client ID is missing"),
2028
- clientSecret: p.client_secret ?? throwErr("Client secret is missing"),
2029
- facebookConfigId: p.facebook_config_id,
2030
- microsoftTenantId: p.microsoft_tenant_id
2031
- }),
2032
- emailConfig: data.config.email_config.type === "shared" ? {
2033
- type: "shared"
2034
- } : {
2035
- type: "standard",
2036
- host: data.config.email_config.host ?? throwErr("Email host is missing"),
2037
- port: data.config.email_config.port ?? throwErr("Email port is missing"),
2038
- username: data.config.email_config.username ?? throwErr("Email username is missing"),
2039
- password: data.config.email_config.password ?? throwErr("Email password is missing"),
2040
- senderName: data.config.email_config.sender_name ?? throwErr("Email sender name is missing"),
2041
- senderEmail: data.config.email_config.sender_email ?? throwErr("Email sender email is missing")
2042
- },
2043
- domains: data.config.domains.map((d) => ({
2044
- domain: d.domain,
2045
- handlerPath: d.handler_path
2046
- })),
2047
- createTeamOnSignUp: data.config.create_team_on_sign_up,
2048
- teamCreatorDefaultPermissions: data.config.team_creator_default_permissions,
2049
- teamMemberDefaultPermissions: data.config.team_member_default_permissions
2050
- },
2051
- async update(update) {
2052
- await app._interface.updateProject(adminProjectUpdateOptionsToCrud(update));
2053
- await onRefresh();
2054
- },
2055
- async delete() {
2056
- await app._interface.deleteProject();
2057
- },
2058
- async getProductionModeErrors() {
2059
- return getProductionModeErrors(data);
2060
- },
2061
- useProductionModeErrors() {
2062
- return getProductionModeErrors(data);
2063
- }
2064
- };
2065
- }
2066
- _adminEmailTemplateFromCrud(data) {
2067
- return {
2068
- type: data.type,
2069
- subject: data.subject,
2070
- content: data.content,
2071
- isDefault: data.is_default
2072
- };
2073
- }
2074
- async getProject() {
2075
- return this._adminProjectFromCrud(
2076
- Result.orThrow(await this._adminProjectCache.getOrWait([], "write-only")),
2077
- () => this._refreshProject()
2078
- );
2079
- }
2080
- useProject() {
2081
- const crud = useAsyncCache(this._adminProjectCache, [], "useProjectAdmin()");
2082
- return useMemo(() => this._adminProjectFromCrud(
2083
- crud,
2084
- () => this._refreshProject()
2085
- ), [crud]);
2086
- }
2087
- _createApiKeyBaseFromCrud(data) {
2088
- const app = this;
2089
- return {
2090
- id: data.id,
2091
- description: data.description,
2092
- expiresAt: new Date(data.expires_at_millis),
2093
- manuallyRevokedAt: data.manually_revoked_at_millis ? new Date(data.manually_revoked_at_millis) : null,
2094
- createdAt: new Date(data.created_at_millis),
2095
- isValid() {
2096
- return this.whyInvalid() === null;
2097
- },
2098
- whyInvalid() {
2099
- if (this.expiresAt.getTime() < Date.now()) return "expired";
2100
- if (this.manuallyRevokedAt) return "manually-revoked";
2101
- return null;
2102
- },
2103
- async revoke() {
2104
- const res = await app._interface.revokeApiKeyById(data.id);
2105
- await app._refreshApiKeys();
2106
- return res;
2107
- }
2108
- };
2109
- }
2110
- _createApiKeyFromCrud(data) {
2111
- return {
2112
- ...this._createApiKeyBaseFromCrud(data),
2113
- publishableClientKey: data.publishable_client_key ? { lastFour: data.publishable_client_key.last_four } : null,
2114
- secretServerKey: data.secret_server_key ? { lastFour: data.secret_server_key.last_four } : null,
2115
- superSecretAdminKey: data.super_secret_admin_key ? { lastFour: data.super_secret_admin_key.last_four } : null
2116
- };
2117
- }
2118
- _createApiKeyFirstViewFromCrud(data) {
2119
- return {
2120
- ...this._createApiKeyBaseFromCrud(data),
2121
- publishableClientKey: data.publishable_client_key,
2122
- secretServerKey: data.secret_server_key,
2123
- superSecretAdminKey: data.super_secret_admin_key
2124
- };
2125
- }
2126
- async listApiKeys() {
2127
- const crud = Result.orThrow(await this._apiKeysCache.getOrWait([], "write-only"));
2128
- return crud.map((j) => this._createApiKeyFromCrud(j));
2129
- }
2130
- useApiKeys() {
2131
- const crud = useAsyncCache(this._apiKeysCache, [], "useApiKeys()");
2132
- return useMemo(() => {
2133
- return crud.map((j) => this._createApiKeyFromCrud(j));
2134
- }, [crud]);
2135
- }
2136
- async createApiKey(options) {
2137
- const crud = await this._interface.createApiKey(apiKeyCreateOptionsToCrud(options));
2138
- await this._refreshApiKeys();
2139
- return this._createApiKeyFirstViewFromCrud(crud);
2140
- }
2141
- useEmailTemplates() {
2142
- const crud = useAsyncCache(this._adminEmailTemplatesCache, [], "useEmailTemplates()");
2143
- return useMemo(() => {
2144
- return crud.map((j) => this._adminEmailTemplateFromCrud(j));
2145
- }, [crud]);
2146
- }
2147
- async listEmailTemplates() {
2148
- const crud = Result.orThrow(await this._adminEmailTemplatesCache.getOrWait([], "write-only"));
2149
- return crud.map((j) => this._adminEmailTemplateFromCrud(j));
2150
- }
2151
- async updateEmailTemplate(type, data) {
2152
- await this._interface.updateEmailTemplate(type, adminEmailTemplateUpdateOptionsToCrud(data));
2153
- await this._adminEmailTemplatesCache.refresh([]);
2154
- }
2155
- async resetEmailTemplate(type) {
2156
- await this._interface.resetEmailTemplate(type);
2157
- await this._adminEmailTemplatesCache.refresh([]);
2158
- }
2159
- async createTeamPermissionDefinition(data) {
2160
- const crud = await this._interface.createPermissionDefinition(serverTeamPermissionDefinitionCreateOptionsToCrud(data));
2161
- await this._adminTeamPermissionDefinitionsCache.refresh([]);
2162
- return this._serverTeamPermissionDefinitionFromCrud(crud);
2163
- }
2164
- async updateTeamPermissionDefinition(permissionId, data) {
2165
- await this._interface.updatePermissionDefinition(permissionId, serverTeamPermissionDefinitionUpdateOptionsToCrud(data));
2166
- await this._adminTeamPermissionDefinitionsCache.refresh([]);
2167
- }
2168
- async deleteTeamPermissionDefinition(permissionId) {
2169
- await this._interface.deletePermissionDefinition(permissionId);
2170
- await this._adminTeamPermissionDefinitionsCache.refresh([]);
2171
- }
2172
- async listTeamPermissionDefinitions() {
2173
- const crud = Result.orThrow(await this._adminTeamPermissionDefinitionsCache.getOrWait([], "write-only"));
2174
- return crud.map((p) => this._serverTeamPermissionDefinitionFromCrud(p));
2175
- }
2176
- useTeamPermissionDefinitions() {
2177
- const crud = useAsyncCache(this._adminTeamPermissionDefinitionsCache, [], "usePermissions()");
2178
- return useMemo(() => {
2179
- return crud.map((p) => this._serverTeamPermissionDefinitionFromCrud(p));
2180
- }, [crud]);
2181
- }
2182
- useSvixToken() {
2183
- const crud = useAsyncCache(this._svixTokenCache, [], "useSvixToken()");
2184
- return crud.token;
2185
- }
2186
- async _refreshProject() {
2187
- await Promise.all([
2188
- super._refreshProject(),
2189
- this._adminProjectCache.refresh([])
2190
- ]);
2191
- }
2192
- async _refreshApiKeys() {
2193
- await this._apiKeysCache.refresh([]);
2194
- }
2195
- get [stackAppInternalsSymbol]() {
2196
- return {
2197
- ...super[stackAppInternalsSymbol],
2198
- useMetrics: () => {
2199
- return useAsyncCache(this._metricsCache, [], "useMetrics()");
2200
- }
2201
- };
2202
- }
2203
- async sendTestEmail(options) {
2204
- const response = await this._interface.sendTestEmail({
2205
- recipient_email: options.recipientEmail,
2206
- email_config: {
2207
- ...pick(options.emailConfig, ["host", "port", "username", "password"]),
2208
- sender_email: options.emailConfig.senderEmail,
2209
- sender_name: options.emailConfig.senderName
2210
- }
2211
- });
2212
- if (response.success) {
2213
- return Result.ok(void 0);
2214
- } else {
2215
- return Result.error({ errorMessage: response.error_message ?? throwErr("Email test error not specified") });
2216
- }
2217
- }
2218
- };
2219
- function contactChannelCreateOptionsToCrud(userId, options) {
2220
- return {
2221
- value: options.value,
2222
- type: options.type,
2223
- used_for_auth: options.usedForAuth,
2224
- user_id: userId
2225
- };
2226
- }
2227
- function contactChannelUpdateOptionsToCrud(options) {
2228
- return {
2229
- value: options.value,
2230
- used_for_auth: options.usedForAuth,
2231
- is_primary: options.isPrimary
2232
- };
2233
- }
2234
- function serverContactChannelUpdateOptionsToCrud(options) {
2235
- return {
2236
- value: options.value,
2237
- is_verified: options.isVerified,
2238
- used_for_auth: options.usedForAuth
2239
- };
2240
- }
2241
- function serverContactChannelCreateOptionsToCrud(userId, options) {
2242
- return {
2243
- type: options.type,
2244
- value: options.value,
2245
- is_verified: options.isVerified,
2246
- user_id: userId,
2247
- used_for_auth: options.usedForAuth
2248
- };
2249
- }
2250
- function userUpdateOptionsToCrud(options) {
2251
- return {
2252
- display_name: options.displayName,
2253
- client_metadata: options.clientMetadata,
2254
- selected_team_id: options.selectedTeamId,
2255
- totp_secret_base64: options.totpMultiFactorSecret != null ? encodeBase64(options.totpMultiFactorSecret) : options.totpMultiFactorSecret,
2256
- profile_image_url: options.profileImageUrl,
2257
- otp_auth_enabled: options.otpAuthEnabled,
2258
- passkey_auth_enabled: options.passkeyAuthEnabled
2259
- };
2260
- }
2261
- function serverUserUpdateOptionsToCrud(options) {
2262
- return {
2263
- display_name: options.displayName,
2264
- primary_email: options.primaryEmail,
2265
- client_metadata: options.clientMetadata,
2266
- client_read_only_metadata: options.clientReadOnlyMetadata,
2267
- server_metadata: options.serverMetadata,
2268
- selected_team_id: options.selectedTeamId,
2269
- primary_email_auth_enabled: options.primaryEmailAuthEnabled,
2270
- primary_email_verified: options.primaryEmailVerified,
2271
- password: options.password,
2272
- profile_image_url: options.profileImageUrl,
2273
- totp_secret_base64: options.totpMultiFactorSecret != null ? encodeBase64(options.totpMultiFactorSecret) : options.totpMultiFactorSecret
2274
- };
2275
- }
2276
- function serverUserCreateOptionsToCrud(options) {
2277
- return {
2278
- primary_email: options.primaryEmail,
2279
- password: options.password,
2280
- otp_auth_enabled: options.otpAuthEnabled,
2281
- primary_email_auth_enabled: options.primaryEmailAuthEnabled,
2282
- display_name: options.displayName,
2283
- primary_email_verified: options.primaryEmailVerified,
2284
- client_metadata: options.clientMetadata,
2285
- client_read_only_metadata: options.clientReadOnlyMetadata,
2286
- server_metadata: options.serverMetadata
2287
- };
2288
- }
2289
- function adminProjectUpdateOptionsToCrud(options) {
2290
- return {
2291
- display_name: options.displayName,
2292
- description: options.description,
2293
- is_production_mode: options.isProductionMode,
2294
- config: {
2295
- domains: options.config?.domains?.map((d) => ({
2296
- domain: d.domain,
2297
- handler_path: d.handlerPath
2298
- })),
2299
- oauth_providers: options.config?.oauthProviders?.map((p) => ({
2300
- id: p.id,
2301
- enabled: p.enabled,
2302
- type: p.type,
2303
- ...p.type === "standard" && {
2304
- client_id: p.clientId,
2305
- client_secret: p.clientSecret,
2306
- facebook_config_id: p.facebookConfigId,
2307
- microsoft_tenant_id: p.microsoftTenantId
2308
- }
2309
- })),
2310
- email_config: options.config?.emailConfig && (options.config.emailConfig.type === "shared" ? {
2311
- type: "shared"
2312
- } : {
2313
- type: "standard",
2314
- host: options.config.emailConfig.host,
2315
- port: options.config.emailConfig.port,
2316
- username: options.config.emailConfig.username,
2317
- password: options.config.emailConfig.password,
2318
- sender_name: options.config.emailConfig.senderName,
2319
- sender_email: options.config.emailConfig.senderEmail
2320
- }),
2321
- sign_up_enabled: options.config?.signUpEnabled,
2322
- credential_enabled: options.config?.credentialEnabled,
2323
- magic_link_enabled: options.config?.magicLinkEnabled,
2324
- passkey_enabled: options.config?.passkeyEnabled,
2325
- allow_localhost: options.config?.allowLocalhost,
2326
- create_team_on_sign_up: options.config?.createTeamOnSignUp,
2327
- client_team_creation_enabled: options.config?.clientTeamCreationEnabled,
2328
- client_user_deletion_enabled: options.config?.clientUserDeletionEnabled,
2329
- team_creator_default_permissions: options.config?.teamCreatorDefaultPermissions,
2330
- team_member_default_permissions: options.config?.teamMemberDefaultPermissions
2331
- }
2332
- };
2333
- }
2334
- function adminProjectCreateOptionsToCrud(options) {
2335
- return {
2336
- ...adminProjectUpdateOptionsToCrud(options),
2337
- display_name: options.displayName
2338
- };
2339
- }
2340
- function apiKeyCreateOptionsToCrud(options) {
2341
- return {
2342
- description: options.description,
2343
- expires_at_millis: options.expiresAt.getTime(),
2344
- has_publishable_client_key: options.hasPublishableClientKey,
2345
- has_secret_server_key: options.hasSecretServerKey,
2346
- has_super_secret_admin_key: options.hasSuperSecretAdminKey
2347
- };
2348
- }
2349
- function teamUpdateOptionsToCrud(options) {
2350
- return {
2351
- display_name: options.displayName,
2352
- profile_image_url: options.profileImageUrl,
2353
- client_metadata: options.clientMetadata
2354
- };
2355
- }
2356
- function teamCreateOptionsToCrud(options, creatorUserId) {
2357
- return {
2358
- display_name: options.displayName,
2359
- profile_image_url: options.profileImageUrl,
2360
- creator_user_id: creatorUserId
2361
- };
2362
- }
2363
- function serverTeamCreateOptionsToCrud(options) {
2364
- return {
2365
- display_name: options.displayName,
2366
- profile_image_url: options.profileImageUrl,
2367
- creator_user_id: options.creatorUserId
2368
- };
2369
- }
2370
- function serverTeamUpdateOptionsToCrud(options) {
2371
- return {
2372
- display_name: options.displayName,
2373
- profile_image_url: options.profileImageUrl,
2374
- client_metadata: options.clientMetadata,
2375
- client_read_only_metadata: options.clientReadOnlyMetadata,
2376
- server_metadata: options.serverMetadata
2377
- };
2378
- }
2379
- function serverTeamPermissionDefinitionCreateOptionsToCrud(options) {
2380
- return {
2381
- id: options.id,
2382
- description: options.description,
2383
- contained_permission_ids: options.containedPermissionIds
2384
- };
2385
- }
2386
- function serverTeamPermissionDefinitionUpdateOptionsToCrud(options) {
2387
- return {
2388
- id: options.id,
2389
- description: options.description,
2390
- contained_permission_ids: options.containedPermissionIds
2391
- };
2392
- }
2393
- var StackClientApp = _StackClientAppImpl;
2394
- var StackServerApp = _StackServerAppImpl;
2395
- var StackAdminApp = _StackAdminAppImpl;
2396
- function adminEmailTemplateUpdateOptionsToCrud(options) {
2397
- return {
2398
- subject: options.subject,
2399
- content: options.content
2400
- };
2401
- }
1326
+ /**
1327
+ * There is a circular dependency between the admin app and the client app, as the former inherits from the latter and
1328
+ * the latter needs to use the former when creating a new instance of an internal project.
1329
+ *
1330
+ * To break it, we set the admin app here lazily instead of importing it directly. This variable is set by ./index.ts,
1331
+ * which imports both this file and ./admin-app-impl.ts.
1332
+ */
1333
+ __StackClientAppImplIncomplete.LazyStackAdminAppImpl = { value: void 0 };
1334
+ var _StackClientAppImplIncomplete = __StackClientAppImplIncomplete;
2402
1335
  export {
2403
- StackAdminApp,
2404
- StackClientApp,
2405
- StackServerApp,
2406
- serverTeamPermissionDefinitionCreateOptionsToCrud,
2407
- serverTeamPermissionDefinitionUpdateOptionsToCrud,
2408
- stackAppInternalsSymbol
1336
+ _StackClientAppImplIncomplete
2409
1337
  };
2410
- //# sourceMappingURL=stack-app.js.map
1338
+ //# sourceMappingURL=client-app-impl.js.map