@molecule/app-svelte 3.3.0 → 3.5.0

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 (164) hide show
  1. package/README.md +2393 -220
  2. package/dist/agent-identity.js +0 -1
  3. package/dist/context.d.ts +101 -1
  4. package/dist/context.d.ts.map +1 -1
  5. package/dist/context.js +199 -3
  6. package/dist/hooks/external-store.d.ts +28 -0
  7. package/dist/hooks/external-store.d.ts.map +1 -0
  8. package/dist/hooks/external-store.js +95 -0
  9. package/dist/hooks/index.d.ts +37 -0
  10. package/dist/hooks/index.d.ts.map +1 -0
  11. package/dist/hooks/index.js +36 -0
  12. package/dist/hooks/live-store.d.ts +68 -0
  13. package/dist/hooks/live-store.d.ts.map +1 -0
  14. package/dist/hooks/live-store.js +76 -0
  15. package/dist/hooks/useAIModels.d.ts +58 -0
  16. package/dist/hooks/useAIModels.d.ts.map +1 -0
  17. package/dist/hooks/useAIModels.js +155 -0
  18. package/dist/hooks/useAsyncState.d.ts +52 -0
  19. package/dist/hooks/useAsyncState.d.ts.map +1 -0
  20. package/dist/hooks/useAsyncState.js +80 -0
  21. package/dist/hooks/useAuth.d.ts +99 -0
  22. package/dist/hooks/useAuth.d.ts.map +1 -0
  23. package/dist/hooks/useAuth.js +88 -0
  24. package/dist/hooks/useCapacitorApp.d.ts +51 -0
  25. package/dist/hooks/useCapacitorApp.d.ts.map +1 -0
  26. package/dist/hooks/useCapacitorApp.js +57 -0
  27. package/dist/hooks/useChangePassword.d.ts +41 -0
  28. package/dist/hooks/useChangePassword.d.ts.map +1 -0
  29. package/dist/hooks/useChangePassword.js +40 -0
  30. package/dist/hooks/useDevice.d.ts +48 -0
  31. package/dist/hooks/useDevice.d.ts.map +1 -0
  32. package/dist/hooks/useDevice.js +37 -0
  33. package/dist/hooks/useEditor.d.ts +65 -0
  34. package/dist/hooks/useEditor.d.ts.map +1 -0
  35. package/dist/hooks/useEditor.js +86 -0
  36. package/dist/hooks/useForm.d.ts +137 -0
  37. package/dist/hooks/useForm.d.ts.map +1 -0
  38. package/dist/hooks/useForm.js +221 -0
  39. package/dist/hooks/useHttp.d.ts +122 -0
  40. package/dist/hooks/useHttp.d.ts.map +1 -0
  41. package/dist/hooks/useHttp.js +220 -0
  42. package/dist/hooks/useLogger.d.ts +52 -0
  43. package/dist/hooks/useLogger.d.ts.map +1 -0
  44. package/dist/hooks/useLogger.js +64 -0
  45. package/dist/hooks/useLogin.d.ts +47 -0
  46. package/dist/hooks/useLogin.d.ts.map +1 -0
  47. package/dist/hooks/useLogin.js +44 -0
  48. package/dist/hooks/useOAuth.d.ts +96 -0
  49. package/dist/hooks/useOAuth.d.ts.map +1 -0
  50. package/dist/hooks/useOAuth.js +363 -0
  51. package/dist/hooks/useOptimisticValue.d.ts +58 -0
  52. package/dist/hooks/useOptimisticValue.d.ts.map +1 -0
  53. package/dist/hooks/useOptimisticValue.js +98 -0
  54. package/dist/hooks/usePasswordReset.d.ts +50 -0
  55. package/dist/hooks/usePasswordReset.d.ts.map +1 -0
  56. package/dist/hooks/usePasswordReset.js +50 -0
  57. package/dist/hooks/usePlatform.d.ts +45 -0
  58. package/dist/hooks/usePlatform.d.ts.map +1 -0
  59. package/dist/hooks/usePlatform.js +35 -0
  60. package/dist/hooks/usePreview.d.ts +54 -0
  61. package/dist/hooks/usePreview.d.ts.map +1 -0
  62. package/dist/hooks/usePreview.js +61 -0
  63. package/dist/hooks/useProfileForm.d.ts +100 -0
  64. package/dist/hooks/useProfileForm.d.ts.map +1 -0
  65. package/dist/hooks/useProfileForm.js +267 -0
  66. package/dist/hooks/usePromise.d.ts +62 -0
  67. package/dist/hooks/usePromise.d.ts.map +1 -0
  68. package/dist/hooks/usePromise.js +105 -0
  69. package/dist/hooks/usePush.d.ts +68 -0
  70. package/dist/hooks/usePush.d.ts.map +1 -0
  71. package/dist/hooks/usePush.js +79 -0
  72. package/dist/hooks/useRouter.d.ts +169 -0
  73. package/dist/hooks/useRouter.d.ts.map +1 -0
  74. package/dist/hooks/useRouter.js +212 -0
  75. package/dist/hooks/useSignup.d.ts +52 -0
  76. package/dist/hooks/useSignup.d.ts.map +1 -0
  77. package/dist/hooks/useSignup.js +42 -0
  78. package/dist/hooks/useStorage.d.ts +133 -0
  79. package/dist/hooks/useStorage.d.ts.map +1 -0
  80. package/dist/hooks/useStorage.js +228 -0
  81. package/dist/hooks/useStore.d.ts +69 -0
  82. package/dist/hooks/useStore.d.ts.map +1 -0
  83. package/dist/hooks/useStore.js +82 -0
  84. package/dist/hooks/useTheme.d.ts +55 -0
  85. package/dist/hooks/useTheme.d.ts.map +1 -0
  86. package/dist/hooks/useTheme.js +102 -0
  87. package/dist/hooks/useTranslation.d.ts +106 -0
  88. package/dist/hooks/useTranslation.d.ts.map +1 -0
  89. package/dist/hooks/useTranslation.js +159 -0
  90. package/dist/hooks/useVerifyPaymentReturn.d.ts +91 -0
  91. package/dist/hooks/useVerifyPaymentReturn.d.ts.map +1 -0
  92. package/dist/hooks/useVerifyPaymentReturn.js +189 -0
  93. package/dist/hooks/useVersion.d.ts +53 -0
  94. package/dist/hooks/useVersion.d.ts.map +1 -0
  95. package/dist/hooks/useVersion.js +70 -0
  96. package/dist/hooks/useWorkspace.d.ts +47 -0
  97. package/dist/hooks/useWorkspace.d.ts.map +1 -0
  98. package/dist/hooks/useWorkspace.js +68 -0
  99. package/dist/index.d.ts +2 -0
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +2 -1
  102. package/dist/session-ready/SessionReady.svelte +20 -0
  103. package/dist/session-ready/SessionReady.svelte.d.ts +5 -0
  104. package/dist/session-ready/SessionReady.svelte.d.ts.map +1 -0
  105. package/dist/session-ready/index.d.ts +7 -0
  106. package/dist/session-ready/index.d.ts.map +1 -0
  107. package/dist/session-ready/index.js +6 -0
  108. package/dist/stores/async-state.js +0 -1
  109. package/dist/stores/auth.js +0 -1
  110. package/dist/stores/capacitor-app.js +0 -1
  111. package/dist/stores/change-password.js +0 -1
  112. package/dist/stores/chat.d.ts.map +1 -1
  113. package/dist/stores/chat.js +3 -10
  114. package/dist/stores/device.js +0 -1
  115. package/dist/stores/forms.js +0 -1
  116. package/dist/stores/http.js +0 -1
  117. package/dist/stores/i18n.d.ts +3 -2
  118. package/dist/stores/i18n.d.ts.map +1 -1
  119. package/dist/stores/i18n.js +2 -3
  120. package/dist/stores/index.js +0 -1
  121. package/dist/stores/logger.js +0 -1
  122. package/dist/stores/login.js +0 -1
  123. package/dist/stores/oauth.js +0 -1
  124. package/dist/stores/password-reset.js +0 -1
  125. package/dist/stores/platform.js +0 -1
  126. package/dist/stores/promise.js +0 -1
  127. package/dist/stores/push.js +0 -1
  128. package/dist/stores/router.js +0 -1
  129. package/dist/stores/signup.js +0 -1
  130. package/dist/stores/state.js +0 -1
  131. package/dist/stores/storage.js +0 -1
  132. package/dist/stores/theme.js +0 -1
  133. package/dist/stores/version.js +0 -1
  134. package/dist/types.d.ts +20 -0
  135. package/dist/types.d.ts.map +1 -1
  136. package/dist/types.js +0 -1
  137. package/package.json +13 -8
  138. package/dist/agent-identity.js.map +0 -1
  139. package/dist/context.js.map +0 -1
  140. package/dist/index.js.map +0 -1
  141. package/dist/stores/async-state.js.map +0 -1
  142. package/dist/stores/auth.js.map +0 -1
  143. package/dist/stores/capacitor-app.js.map +0 -1
  144. package/dist/stores/change-password.js.map +0 -1
  145. package/dist/stores/chat.js.map +0 -1
  146. package/dist/stores/device.js.map +0 -1
  147. package/dist/stores/forms.js.map +0 -1
  148. package/dist/stores/http.js.map +0 -1
  149. package/dist/stores/i18n.js.map +0 -1
  150. package/dist/stores/index.js.map +0 -1
  151. package/dist/stores/logger.js.map +0 -1
  152. package/dist/stores/login.js.map +0 -1
  153. package/dist/stores/oauth.js.map +0 -1
  154. package/dist/stores/password-reset.js.map +0 -1
  155. package/dist/stores/platform.js.map +0 -1
  156. package/dist/stores/promise.js.map +0 -1
  157. package/dist/stores/push.js.map +0 -1
  158. package/dist/stores/router.js.map +0 -1
  159. package/dist/stores/signup.js.map +0 -1
  160. package/dist/stores/state.js.map +0 -1
  161. package/dist/stores/storage.js.map +0 -1
  162. package/dist/stores/theme.js.map +0 -1
  163. package/dist/stores/version.js.map +0 -1
  164. package/dist/types.js.map +0 -1
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Svelte hook for login with async state tracking, porting React's `useLogin`.
3
+ *
4
+ * @module
5
+ */
6
+ import type { Readable } from 'svelte/store';
7
+ import type { AuthResult, LoginCredentials } from '@molecule/app-auth';
8
+ import { type UsePromiseState } from './usePromise.js';
9
+ /** What {@link useLogin} returns: the promise state's value fields as stores plus the action. */
10
+ export interface UseLoginResult<T = unknown> {
11
+ /** The latest call's status. */
12
+ status: Readable<UsePromiseState<AuthResult<T>>['status']>;
13
+ /** The latest call's resolved value. */
14
+ value: Readable<UsePromiseState<AuthResult<T>>['value']>;
15
+ /** The latest call's rejection. */
16
+ error: Readable<UsePromiseState<AuthResult<T>>['error']>;
17
+ /** Runs the login. */
18
+ login: (credentials: LoginCredentials) => Promise<AuthResult<T>>;
19
+ /** Returns the tracker to idle. */
20
+ reset: () => void;
21
+ }
22
+ /**
23
+ * Login with async state tracking, React's `useLogin` in Svelte's idiom:
24
+ * call it during component init under `setMoleculeContext({ auth })`.
25
+ *
26
+ * Registration is available through `const { register } = useAuth()`;
27
+ * call `register({ email, password, name })` to create an account. There is
28
+ * no separate `useRegister` hook; use `usePromise(register)` when a form
29
+ * needs the same pending/error tracking as this login hook.
30
+ *
31
+ * @param T - The user profile the API returns.
32
+ * @returns Login state as stores and the action.
33
+ * @example
34
+ * ```svelte
35
+ * <script>
36
+ * import { useLogin } from '@molecule/app-svelte'
37
+ * const { status, error, login } = useLogin()
38
+ * </script>
39
+ *
40
+ * <button onclick={() => login({ email, password })} disabled={$status === 'pending'}>
41
+ * {$status === 'pending' ? 'Logging in…' : 'Log in'}
42
+ * </button>
43
+ * {#if $error}<p>{$error.message}</p>{/if}
44
+ * ```
45
+ */
46
+ export declare function useLogin<T = unknown>(): UseLoginResult<T>;
47
+ //# sourceMappingURL=useLogin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useLogin.d.ts","sourceRoot":"","sources":["../../src/hooks/useLogin.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AAE5C,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;AAItE,OAAO,EAAc,KAAK,eAAe,EAAwB,MAAM,iBAAiB,CAAA;AAExF,iGAAiG;AACjG,MAAM,WAAW,cAAc,CAAC,CAAC,GAAG,OAAO;IACzC,gCAAgC;IAChC,MAAM,EAAE,QAAQ,CAAC,eAAe,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAA;IAC1D,wCAAwC;IACxC,KAAK,EAAE,QAAQ,CAAC,eAAe,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAA;IACxD,mCAAmC;IACnC,KAAK,EAAE,QAAQ,CAAC,eAAe,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAA;IACxD,sBAAsB;IACtB,KAAK,EAAE,CAAC,WAAW,EAAE,gBAAgB,KAAK,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAA;IAChE,mCAAmC;IACnC,KAAK,EAAE,MAAM,IAAI,CAAA;CAClB;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,QAAQ,CAAC,CAAC,GAAG,OAAO,KAAK,cAAc,CAAC,CAAC,CAAC,CAazD"}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Svelte hook for login with async state tracking, porting React's `useLogin`.
3
+ *
4
+ * @module
5
+ */
6
+ import { useAuthClient } from '../context.js';
7
+ import { promiseFields } from './live-store.js';
8
+ import { usePromise } from './usePromise.js';
9
+ /**
10
+ * Login with async state tracking, React's `useLogin` in Svelte's idiom:
11
+ * call it during component init under `setMoleculeContext({ auth })`.
12
+ *
13
+ * Registration is available through `const { register } = useAuth()`;
14
+ * call `register({ email, password, name })` to create an account. There is
15
+ * no separate `useRegister` hook; use `usePromise(register)` when a form
16
+ * needs the same pending/error tracking as this login hook.
17
+ *
18
+ * @param T - The user profile the API returns.
19
+ * @returns Login state as stores and the action.
20
+ * @example
21
+ * ```svelte
22
+ * <script>
23
+ * import { useLogin } from '@molecule/app-svelte'
24
+ * const { status, error, login } = useLogin()
25
+ * </script>
26
+ *
27
+ * <button onclick={() => login({ email, password })} disabled={$status === 'pending'}>
28
+ * {$status === 'pending' ? 'Logging in…' : 'Log in'}
29
+ * </button>
30
+ * {#if $error}<p>{$error.message}</p>{/if}
31
+ * ```
32
+ */
33
+ export function useLogin() {
34
+ const client = useAuthClient();
35
+ const tracker = usePromise((credentials) => client.login(credentials));
36
+ const fields = promiseFields(tracker);
37
+ return {
38
+ status: fields.status,
39
+ value: fields.value,
40
+ error: fields.error,
41
+ login: fields.call,
42
+ reset: fields.reset,
43
+ };
44
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Svelte hook for OAuth authentication, porting React's `useOAuth`.
3
+ *
4
+ * Supports two initiation modes that share ONE callback path:
5
+ * - {@link UseOAuthReturn.redirect} — full-page redirect (the default).
6
+ * - {@link UseOAuthReturn.loginViaPopup} — opens the provider in a popup so the
7
+ * opener page never navigates. On completion the popup relays the result to
8
+ * the opener via a STRICTLY-validated `postMessage` and closes itself; the
9
+ * opener establishes the session in place.
10
+ *
11
+ * Security model for the popup relay (see inline notes at each gate):
12
+ * - The popup posts ONLY to its own origin (`targetOrigin = location.origin`),
13
+ * never `'*'`, so the bearer token can never be delivered to another origin.
14
+ * - The opener accepts a result ONLY when ALL hold: `event.origin === location.origin`,
15
+ * `event.source === thePopupWindowWeOpened`, and `event.data.type` matches our
16
+ * private message type. Anything else is ignored.
17
+ * - The popup-relay path is gated on `window.name === OAUTH_POPUP_WINDOW_NAME`
18
+ * AND `window.opener`, so an ordinary full-page callback is completely
19
+ * unaffected.
20
+ * - The opener tears down its listener + timers on result, on user-close, and on
21
+ * a hard timeout, so no stale handler lingers.
22
+ *
23
+ * Unmounting does not cancel a flow that has started. A popup result or a
24
+ * callback exchange that settles afterwards still establishes the session on
25
+ * the shared auth client, because the user did sign in. `onSuccess` and
26
+ * `onError` are not called after unmount: they belong to the unmounted view.
27
+ *
28
+ * @module
29
+ */
30
+ /**
31
+ * Return type for useOAuth hook.
32
+ */
33
+ export interface UseOAuthReturn {
34
+ /** The configured provider names. */
35
+ providers: string[];
36
+ /** Builds the provider's initiation URL (provider encoded as one path segment). */
37
+ getOAuthUrl: (provider: string) => string;
38
+ /** Full-page redirect to the provider (default). The opener page navigates away. */
39
+ redirect: (provider: string) => void;
40
+ /**
41
+ * Open the provider in a popup so the opener page does NOT navigate. On success
42
+ * the session is established in the opener in place and `config.onSuccess` fires;
43
+ * on failure `config.onError` fires. Falls back to a full-page {@link redirect}
44
+ * when the popup is blocked.
45
+ */
46
+ loginViaPopup: (provider: string) => void;
47
+ }
48
+ /**
49
+ * OAuth configuration override options.
50
+ */
51
+ export interface UseOAuthConfig {
52
+ /** Base URL for the API server (e.g. "https://api.example.com"). */
53
+ baseURL?: string;
54
+ /** List of supported OAuth provider names (e.g. ["google", "github"]). */
55
+ oauthProviders?: string[];
56
+ /** Path prefix for OAuth routes (defaults to "/oauth"). */
57
+ oauthEndpoint?: string;
58
+ /** Path for the OAuth login POST endpoint (defaults to "/users/log-in/oauth"). */
59
+ loginEndpoint?: string;
60
+ /** Callback after successful OAuth login. */
61
+ onSuccess?: () => void;
62
+ /** Callback on OAuth login failure. */
63
+ onError?: (error: string) => void;
64
+ /**
65
+ * How the page leaves for the provider: {@link UseOAuthReturn.redirect} and the
66
+ * blocked-popup fallback call it with the provider URL. Defaults to a full-page
67
+ * navigation (`window.location.href = url`); pass an in-app browser opener on
68
+ * native, or a router's external navigation.
69
+ */
70
+ navigate?: (url: string) => void;
71
+ }
72
+ /**
73
+ * OAuth authentication, React's `useOAuth` in Svelte's idiom: call it during
74
+ * component init under `setMoleculeContext({ auth })`. Reads OAuth
75
+ * configuration and provides helpers to build OAuth URLs and start a login
76
+ * (full-page or popup). Automatically handles OAuth callbacks by detecting
77
+ * `code` and `state` URL parameters and exchanging them for a session — and,
78
+ * when the callback is running inside a popup we opened, relaying the result
79
+ * to the opener instead.
80
+ *
81
+ * @param config - Optional OAuth configuration override.
82
+ * @returns OAuth helpers: providers, getOAuthUrl, redirect, and loginViaPopup.
83
+ * @example
84
+ * ```svelte
85
+ * <script>
86
+ * import { useOAuth } from '@molecule/app-svelte'
87
+ * const { providers, loginViaPopup } = useOAuth()
88
+ * </script>
89
+ *
90
+ * {#each providers as provider}
91
+ * <button onclick={() => loginViaPopup(provider)}>Login with {provider}</button>
92
+ * {/each}
93
+ * ```
94
+ */
95
+ export declare function useOAuth(config?: UseOAuthConfig): UseOAuthReturn;
96
+ //# sourceMappingURL=useOAuth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useOAuth.d.ts","sourceRoot":"","sources":["../../src/hooks/useOAuth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAuCH;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,qCAAqC;IACrC,SAAS,EAAE,MAAM,EAAE,CAAA;IACnB,mFAAmF;IACnF,WAAW,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,MAAM,CAAA;IACzC,oFAAoF;IACpF,QAAQ,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAA;IACpC;;;;;OAKG;IACH,aAAa,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAA;CAC1C;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,oEAAoE;IACpE,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,0EAA0E;IAC1E,cAAc,CAAC,EAAE,MAAM,EAAE,CAAA;IACzB,2DAA2D;IAC3D,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,kFAAkF;IAClF,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,6CAA6C;IAC7C,SAAS,CAAC,EAAE,MAAM,IAAI,CAAA;IACtB,uCAAuC;IACvC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;IACjC;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAA;CACjC;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,QAAQ,CAAC,MAAM,CAAC,EAAE,cAAc,GAAG,cAAc,CAiThE"}
@@ -0,0 +1,363 @@
1
+ /**
2
+ * Svelte hook for OAuth authentication, porting React's `useOAuth`.
3
+ *
4
+ * Supports two initiation modes that share ONE callback path:
5
+ * - {@link UseOAuthReturn.redirect} — full-page redirect (the default).
6
+ * - {@link UseOAuthReturn.loginViaPopup} — opens the provider in a popup so the
7
+ * opener page never navigates. On completion the popup relays the result to
8
+ * the opener via a STRICTLY-validated `postMessage` and closes itself; the
9
+ * opener establishes the session in place.
10
+ *
11
+ * Security model for the popup relay (see inline notes at each gate):
12
+ * - The popup posts ONLY to its own origin (`targetOrigin = location.origin`),
13
+ * never `'*'`, so the bearer token can never be delivered to another origin.
14
+ * - The opener accepts a result ONLY when ALL hold: `event.origin === location.origin`,
15
+ * `event.source === thePopupWindowWeOpened`, and `event.data.type` matches our
16
+ * private message type. Anything else is ignored.
17
+ * - The popup-relay path is gated on `window.name === OAUTH_POPUP_WINDOW_NAME`
18
+ * AND `window.opener`, so an ordinary full-page callback is completely
19
+ * unaffected.
20
+ * - The opener tears down its listener + timers on result, on user-close, and on
21
+ * a hard timeout, so no stale handler lingers.
22
+ *
23
+ * Unmounting does not cancel a flow that has started. A popup result or a
24
+ * callback exchange that settles afterwards still establishes the session on
25
+ * the shared auth client, because the user did sign in. `onSuccess` and
26
+ * `onError` are not called after unmount: they belong to the unmounted view.
27
+ *
28
+ * @module
29
+ */
30
+ import { onDestroy } from 'svelte';
31
+ import { t } from '@molecule/app-i18n';
32
+ import { useAuthClient } from '../context.js';
33
+ /** What `onError` gets when the server gives no reason of its own. */
34
+ const oauthFailed = () => t('svelte.error.oauthFailed', undefined, { defaultValue: 'OAuth login failed' });
35
+ /**
36
+ * `window.open` name for the OAuth popup. The callback page relays its result to
37
+ * the opener ONLY when its own `window.name` equals this AND `window.opener`
38
+ * exists — so a normal (full-page) callback never takes the relay path.
39
+ */
40
+ const OAUTH_POPUP_WINDOW_NAME = 'molecule-oauth-popup';
41
+ /** Private `postMessage` type for the popup→opener result relay. */
42
+ const OAUTH_RESULT_MESSAGE_TYPE = 'molecule:oauth-result';
43
+ /** Hard cap on how long the opener waits for the popup before giving up. */
44
+ const OAUTH_POPUP_TIMEOUT_MS = 5 * 60 * 1000;
45
+ /**
46
+ * OAuth authentication, React's `useOAuth` in Svelte's idiom: call it during
47
+ * component init under `setMoleculeContext({ auth })`. Reads OAuth
48
+ * configuration and provides helpers to build OAuth URLs and start a login
49
+ * (full-page or popup). Automatically handles OAuth callbacks by detecting
50
+ * `code` and `state` URL parameters and exchanging them for a session — and,
51
+ * when the callback is running inside a popup we opened, relaying the result
52
+ * to the opener instead.
53
+ *
54
+ * @param config - Optional OAuth configuration override.
55
+ * @returns OAuth helpers: providers, getOAuthUrl, redirect, and loginViaPopup.
56
+ * @example
57
+ * ```svelte
58
+ * <script>
59
+ * import { useOAuth } from '@molecule/app-svelte'
60
+ * const { providers, loginViaPopup } = useOAuth()
61
+ * </script>
62
+ *
63
+ * {#each providers as provider}
64
+ * <button onclick={() => loginViaPopup(provider)}>Login with {provider}</button>
65
+ * {/each}
66
+ * ```
67
+ */
68
+ export function useOAuth(config) {
69
+ const authClient = useAuthClient();
70
+ // Whether the component is mounted, read when a flow settles.
71
+ let mounted = true;
72
+ onDestroy(() => {
73
+ mounted = false;
74
+ });
75
+ const providers = config?.oauthProviders ?? [];
76
+ const baseURL = config?.baseURL ?? '';
77
+ const oauthEndpoint = config?.oauthEndpoint ?? '/oauth';
78
+ const loginEndpoint = config?.loginEndpoint ?? '/users/log-in/oauth';
79
+ const getOAuthUrl = (provider) => {
80
+ // Encode the provider as a single path segment so a (future) caller passing an
81
+ // untrusted value can never inject a path/query/scheme into the opened URL —
82
+ // defense-in-depth on top of the upstream static provider allowlist. Plain
83
+ // provider names ('github', 'google') pass through unchanged.
84
+ return `${baseURL}${oauthEndpoint}/${encodeURIComponent(provider)}`;
85
+ };
86
+ /** Stash which provider initiated the flow so the callback knows it's ours. */
87
+ const stashProvider = (provider) => {
88
+ try {
89
+ sessionStorage.setItem('oauth_provider', provider);
90
+ }
91
+ catch (_error) {
92
+ /* SSR-safe — sessionStorage is unavailable in SSR/sandboxed environments */
93
+ }
94
+ };
95
+ /**
96
+ * Append the current page's PATH as `redirect_to` so the api's initiation
97
+ * endpoint (`GET /users/oauth/:provider`) builds a provider `redirect_uri`
98
+ * that lands the callback back on THIS page — the one with `useOAuth`
99
+ * mounted (e.g. `/login`) — instead of the app root, where nothing may be
100
+ * listening for the `code` param. Path only (no origin/query): the server
101
+ * validates it as a same-origin absolute path, so it can never become an
102
+ * open redirect. Servers that predate the param simply ignore it.
103
+ */
104
+ const withReturnPath = (url) => {
105
+ const path = typeof window !== 'undefined' ? window.location.pathname : '';
106
+ if (!path || path === '/')
107
+ return url;
108
+ return `${url}${url.includes('?') ? '&' : '?'}redirect_to=${encodeURIComponent(path)}`;
109
+ };
110
+ /**
111
+ * Establish the authenticated session from an exchange result: seed the access
112
+ * token + user and let `initialize()` flip `authenticated`. Mirrors what
113
+ * `authClient.login()` does for password login. Returns whether a user was set
114
+ * (a result with no user is not a real session).
115
+ */
116
+ const establishSession = async (token, user) => {
117
+ // Seed the token via the auth client's configured token storage adapter
118
+ // (in-memory by default) — NOT localStorage directly.
119
+ if (token)
120
+ authClient.setAccessToken(token);
121
+ if (user && typeof user === 'object') {
122
+ authClient.setUser(user);
123
+ await authClient.initialize();
124
+ return true;
125
+ }
126
+ return false;
127
+ };
128
+ const navigateOption = config?.navigate;
129
+ /** Leaves the page for the provider: the `navigate` option, else a full-page navigation. */
130
+ const leaveFor = (url) => {
131
+ if (navigateOption)
132
+ navigateOption(url);
133
+ else
134
+ window.location.href = url;
135
+ };
136
+ const redirect = (provider) => {
137
+ stashProvider(provider);
138
+ leaveFor(withReturnPath(getOAuthUrl(provider)));
139
+ };
140
+ // The currently-open OAuth popup, so a second click focuses it instead of
141
+ // stacking a second flow (the relay gates already fail safe, but one window is
142
+ // cleaner and avoids an orphaned listener until the timeout reaps it).
143
+ let activePopup = null;
144
+ const loginViaPopup = (provider) => {
145
+ // A flow is already open — focus it rather than starting another.
146
+ if (activePopup && !activePopup.closed) {
147
+ try {
148
+ activePopup.focus();
149
+ }
150
+ catch (_error) {
151
+ /* best-effort focus */
152
+ }
153
+ return;
154
+ }
155
+ stashProvider(provider);
156
+ const url = withReturnPath(getOAuthUrl(provider));
157
+ // A named popup. We intentionally do NOT pass `noopener` — the popup needs
158
+ // `window.opener` to relay its result back.
159
+ const features = 'popup=yes,width=520,height=680,menubar=no,toolbar=no,location=yes';
160
+ const popup = window.open(url, OAUTH_POPUP_WINDOW_NAME, features);
161
+ // Popup blocked (or unavailable) → fall back to a full-page redirect so login
162
+ // still works. No listener is registered in this branch.
163
+ if (!popup) {
164
+ leaveFor(url);
165
+ return;
166
+ }
167
+ activePopup = popup;
168
+ let settled = false;
169
+ const timers = {};
170
+ const cleanup = () => {
171
+ window.removeEventListener('message', onMessage);
172
+ if (timers.closed)
173
+ clearInterval(timers.closed);
174
+ if (timers.timeout)
175
+ clearTimeout(timers.timeout);
176
+ if (activePopup === popup)
177
+ activePopup = null;
178
+ };
179
+ const onMessage = (event) => {
180
+ // SECURITY — accept the result ONLY from our own origin, ONLY from the exact
181
+ // popup window we opened, and ONLY when it carries our private type. Any one
182
+ // failing means a forged / unrelated message: ignore it silently. This is
183
+ // what prevents a malicious page from injecting a session.
184
+ if (event.origin !== window.location.origin)
185
+ return;
186
+ if (event.source !== popup)
187
+ return;
188
+ const data = event.data;
189
+ if (!data || typeof data !== 'object' || data.type !== OAUTH_RESULT_MESSAGE_TYPE)
190
+ return;
191
+ if (settled)
192
+ return;
193
+ settled = true;
194
+ cleanup();
195
+ try {
196
+ popup.close();
197
+ }
198
+ catch (_error) {
199
+ /* already closed — nothing to do */
200
+ }
201
+ if (data.ok) {
202
+ void establishSession(data.token, data.user).then((ok) => {
203
+ if (!mounted)
204
+ return;
205
+ if (ok)
206
+ config?.onSuccess?.();
207
+ else
208
+ config?.onError?.(oauthFailed());
209
+ });
210
+ }
211
+ else if (mounted) {
212
+ config?.onError?.(typeof data.error === 'string' ? data.error : oauthFailed());
213
+ }
214
+ };
215
+ window.addEventListener('message', onMessage);
216
+ // The user closed the popup without completing — silently stop waiting (no
217
+ // error toast for a deliberate cancel) and release the listener.
218
+ timers.closed = setInterval(() => {
219
+ if (popup.closed && !settled) {
220
+ settled = true;
221
+ cleanup();
222
+ }
223
+ }, 500);
224
+ // Hard safety timeout so a wedged popup never leaks a listener forever.
225
+ timers.timeout = setTimeout(() => {
226
+ if (!settled) {
227
+ settled = true;
228
+ cleanup();
229
+ try {
230
+ popup.close();
231
+ }
232
+ catch (_error) {
233
+ /* best-effort */
234
+ }
235
+ }
236
+ }, OAUTH_POPUP_TIMEOUT_MS);
237
+ };
238
+ // Handle OAuth callback — detect code + state in URL params (React's mount
239
+ // effect; the exchange starts at init and outlives the component).
240
+ {
241
+ const params = new URLSearchParams(window.location.search);
242
+ const code = params.get('code');
243
+ const state = params.get('state');
244
+ if (code) {
245
+ // Retrieve the provider that initiated the flow
246
+ let provider = null;
247
+ try {
248
+ provider = sessionStorage.getItem('oauth_provider');
249
+ }
250
+ catch (_error) {
251
+ /* SSR-safe — sessionStorage is unavailable in SSR/sandboxed environments */
252
+ }
253
+ if (provider) {
254
+ // Are we the OAuth popup we opened? Relay the result to the opener instead of
255
+ // establishing the session in this (about-to-close) window. Gated on BOTH the
256
+ // window name AND window.opener so a normal full-page callback never relays.
257
+ const inPopup = typeof window !== 'undefined' &&
258
+ !!window.opener &&
259
+ window.name === OAUTH_POPUP_WINDOW_NAME;
260
+ // Clean up URL (remove code/state params) and sessionStorage
261
+ const cleanUrl = new URL(window.location.href);
262
+ cleanUrl.searchParams.delete('code');
263
+ cleanUrl.searchParams.delete('state');
264
+ window.history.replaceState({}, '', cleanUrl.toString());
265
+ try {
266
+ sessionStorage.removeItem('oauth_provider');
267
+ }
268
+ catch (_error) {
269
+ /* SSR-safe — sessionStorage is unavailable in SSR/sandboxed environments */
270
+ }
271
+ /** Relay a result to the opener (popup path) — origin-pinned, never `'*'`. */
272
+ const relayToOpener = (message) => {
273
+ try {
274
+ // targetOrigin is our OWN origin: the browser delivers the message (and the
275
+ // token it carries) ONLY if the opener is still on this origin. Never '*'.
276
+ window.opener?.postMessage(message, window.location.origin);
277
+ }
278
+ catch (_error) {
279
+ /* opener gone / cross-origin — the opener's close-poll will recover */
280
+ }
281
+ try {
282
+ window.close();
283
+ }
284
+ catch (_error) {
285
+ /* best-effort */
286
+ }
287
+ };
288
+ // Exchange code for session
289
+ const exchangeCode = async () => {
290
+ try {
291
+ const response = await fetch(`${baseURL}${loginEndpoint}`, {
292
+ method: 'POST',
293
+ headers: { 'Content-Type': 'application/json' },
294
+ credentials: 'include', // Send cookies (oauth_state) for state validation
295
+ body: JSON.stringify({
296
+ server: provider,
297
+ code,
298
+ state: state || undefined,
299
+ redirect_uri: window.location.origin,
300
+ }),
301
+ });
302
+ if (!response.ok) {
303
+ // A body that is not JSON: report the generic failure.
304
+ const data = await response
305
+ .json()
306
+ .catch((_error) => ({ error: oauthFailed() }));
307
+ const error = data.error || oauthFailed();
308
+ if (inPopup) {
309
+ relayToOpener({ type: OAUTH_RESULT_MESSAGE_TYPE, ok: false, error });
310
+ return;
311
+ }
312
+ if (mounted)
313
+ config?.onError?.(error);
314
+ return;
315
+ }
316
+ // A body that is not JSON carries no user; the token comes from the header.
317
+ const data = await response.json().catch((_error) => null);
318
+ // Store the token from the response
319
+ const authHeader = response.headers.get('authorization') || response.headers.get('set-authorization');
320
+ const token = authHeader ? authHeader.replace('Bearer ', '') : null;
321
+ // The authenticated user is `props` (molecule resource convention) or `user`
322
+ // (generic AuthResult).
323
+ const user = data && typeof data === 'object'
324
+ ? (data.props ??
325
+ data.user ??
326
+ null)
327
+ : null;
328
+ if (inPopup) {
329
+ // Relay to the opener — it (same origin) establishes the session in place.
330
+ // Do NOT establish it here; this window is about to close.
331
+ relayToOpener({ type: OAUTH_RESULT_MESSAGE_TYPE, ok: true, token, user });
332
+ return;
333
+ }
334
+ // Full-page callback: establish the session here, then fire onSuccess.
335
+ const ok = await establishSession(token, user);
336
+ if (!mounted)
337
+ return;
338
+ if (ok)
339
+ config?.onSuccess?.();
340
+ else
341
+ config?.onError?.(oauthFailed());
342
+ }
343
+ catch (err) {
344
+ const error = err instanceof Error ? err.message : oauthFailed();
345
+ if (inPopup) {
346
+ relayToOpener({ type: OAUTH_RESULT_MESSAGE_TYPE, ok: false, error });
347
+ return;
348
+ }
349
+ if (mounted)
350
+ config?.onError?.(error);
351
+ }
352
+ };
353
+ void exchangeCode();
354
+ }
355
+ }
356
+ }
357
+ return {
358
+ providers,
359
+ getOAuthUrl,
360
+ redirect,
361
+ loginViaPopup,
362
+ };
363
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Svelte hook for a server-backed value that the UI changes at once and saves
3
+ * in order, porting React's `useOptimisticValue`.
4
+ *
5
+ * @module
6
+ */
7
+ import { type Readable } from 'svelte/store';
8
+ import type { OptimisticValueOptions } from '@molecule/app-state';
9
+ /**
10
+ * What {@link useOptimisticValue} returns: the state to render as readable
11
+ * stores and the two ways to change it (the same names React returns).
12
+ *
13
+ * @template T - The value type.
14
+ */
15
+ export interface UseOptimisticValueResult<T> {
16
+ /** The value to render. */
17
+ value: Readable<T>;
18
+ /** Whether a save is running or waiting. */
19
+ pending: Readable<boolean>;
20
+ /** The failure of the newest change. */
21
+ error: Readable<unknown>;
22
+ /** Shows `next` at once and saves it, after any save already running. */
23
+ set: (next: T) => void;
24
+ /** Like `set`, computed from the value shown now (`update((on) => !on)`). */
25
+ update: (change: (current: T) => T) => void;
26
+ }
27
+ /**
28
+ * A server-backed value — a favorite, follow, like or bookmark button, a
29
+ * rating, a quantity, a setting switch — that changes on the first render
30
+ * after a tap and is saved one change at a time, in order. See
31
+ * `createOptimisticValue` in `@molecule/app-state`, under React's hook name.
32
+ *
33
+ * A new server `value` is taken only when it differs (by `equals`) from the
34
+ * one the hook last received, and only while nothing is being saved, so a
35
+ * refetch of older data never flips the button mid-save. The latest `commit`
36
+ * and `onError` are always used. Give the component a `key` per record, so one
37
+ * record's pending change never shows on another. Keep related fields, such as
38
+ * a favorite flag and its count, in the SAME value. Let commit reject on
39
+ * failure: a catch that returns old data hides the failure.
40
+ *
41
+ * @param options - The server's current value and how to save a change.
42
+ * @returns The value to render, whether a save is pending, the newest failure,
43
+ * and `set`/`update`.
44
+ * @example
45
+ * ```svelte
46
+ * <script>
47
+ * import { useOptimisticValue } from '@molecule/app-svelte'
48
+ * const star = useOptimisticValue({
49
+ * value: { starred: repository.starred, stars: repository.stars },
50
+ * commit: async (next) => { /* save and return the server's value * },
51
+ * })
52
+ * </script>
53
+ *
54
+ * <button aria-pressed={$star.value.starred} onclick={() => star.update((on) => ({ ...on, starred: !on.starred }))}>
55
+ * ```
56
+ */
57
+ export declare const useOptimisticValue: <T>(options: OptimisticValueOptions<T>) => UseOptimisticValueResult<T>;
58
+ //# sourceMappingURL=useOptimisticValue.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useOptimisticValue.d.ts","sourceRoot":"","sources":["../../src/hooks/useOptimisticValue.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,KAAK,QAAQ,EAAY,MAAM,cAAc,CAAA;AAEtD,OAAO,KAAK,EAEV,sBAAsB,EAEvB,MAAM,qBAAqB,CAAA;AAuB5B;;;;;GAKG;AACH,MAAM,WAAW,wBAAwB,CAAC,CAAC;IACzC,2BAA2B;IAC3B,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAA;IAClB,4CAA4C;IAC5C,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAA;IAC1B,wCAAwC;IACxC,KAAK,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAA;IACxB,yEAAyE;IACzE,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,CAAA;IACtB,6EAA6E;IAC7E,MAAM,EAAE,CAAC,MAAM,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,KAAK,IAAI,CAAA;CAC5C;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,eAAO,MAAM,kBAAkB,GAAI,CAAC,EAClC,SAAS,sBAAsB,CAAC,CAAC,CAAC,KACjC,wBAAwB,CAAC,CAAC,CA2D5B,CAAA"}