zitejs 0.9.8 → 0.9.9

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.
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getFlowId = getFlowId;
4
+ exports.getApiUrl = getApiUrl;
5
+ exports.getAuthPageUrl = getAuthPageUrl;
6
+ exports.getDbToken = getDbToken;
7
+ const env_js_1 = require("../internal/env.js");
8
+ const API_ENVIRONMENTS = {
9
+ production: 'https://api.fillout.com',
10
+ staging: 'https://api.filloutstaging.com',
11
+ local: 'http://localhost:2502',
12
+ };
13
+ const AUTH_PAGE_ENVIRONMENTS = {
14
+ production: 'https://zite.com/auth',
15
+ staging: 'https://zitestaging.com/auth',
16
+ local: 'http://localhost:3000/auth',
17
+ };
18
+ function getFlowId() {
19
+ const id = (0, env_js_1.getEnv)('ZITE_FLOW_ID', 'VITE_ZITE_FLOW_ID') ?? '';
20
+ if (!id) {
21
+ const win = typeof window !== 'undefined' ? window : undefined;
22
+ const config = win?.__ziteConfig;
23
+ if (config?.id)
24
+ return config.id;
25
+ }
26
+ return id;
27
+ }
28
+ function getApiUrl() {
29
+ const env = (0, env_js_1.getEnv)('ZITE_ENV', 'VITE_ZITE_ENV') ?? 'production';
30
+ return (0, env_js_1.getEnv)('ZITE_API_URL', 'VITE_ZITE_API_URL') ?? API_ENVIRONMENTS[env] ?? API_ENVIRONMENTS.production;
31
+ }
32
+ function getAuthPageUrl() {
33
+ const env = (0, env_js_1.getEnv)('ZITE_ENV', 'VITE_ZITE_ENV') ?? 'production';
34
+ return (0, env_js_1.getEnv)('ZITE_AUTH_PAGE_URL', 'VITE_ZITE_AUTH_PAGE_URL') ?? AUTH_PAGE_ENVIRONMENTS[env] ?? AUTH_PAGE_ENVIRONMENTS.production;
35
+ }
36
+ function getDbToken() {
37
+ return (0, env_js_1.getEnv)('ZITE_DB_TOKEN', 'VITE_ZITE_DB_TOKEN') ?? '';
38
+ }
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AUTH_SDK_VERSION = exports.USAGE_TOKEN_QUERY_PARAM = exports.ZITE_SANDBOX_DOMAINS = exports.ZITE_APP_ACTION_HOSTNAME_PREFIX = exports.ZITE_APP_EDITOR_HOSTNAME_PREFIX = void 0;
4
+ exports.ZITE_APP_EDITOR_HOSTNAME_PREFIX = 'zite-editor-';
5
+ exports.ZITE_APP_ACTION_HOSTNAME_PREFIX = 'zite-action-';
6
+ exports.ZITE_SANDBOX_DOMAINS = [
7
+ 'zite-dev-sandbox.com',
8
+ 'zite-dev-app.com',
9
+ 'zite-sandbox.com',
10
+ 'zite-app.com',
11
+ ];
12
+ exports.USAGE_TOKEN_QUERY_PARAM = 'usageToken';
13
+ exports.AUTH_SDK_VERSION = '1.0.0';
@@ -1,2 +1,281 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useAuth = useAuth;
4
+ const react_1 = require("react");
5
+ const react_query_1 = require("@tanstack/react-query");
6
+ const config_js_1 = require("./config.js");
7
+ const constants_js_1 = require("./constants.js");
8
+ const _isLocalEnv = typeof window !== 'undefined' &&
9
+ (window.location.hostname === 'localhost' ||
10
+ window.location.hostname === '127.0.0.1' ||
11
+ window.location.hostname.endsWith('.localhost') ||
12
+ localStorage.getItem('zite.debug.log') === 'true');
13
+ const debugLog = (...args) => {
14
+ if (_isLocalEnv)
15
+ console.log(...args);
16
+ };
17
+ const debugWarn = (...args) => {
18
+ if (_isLocalEnv)
19
+ console.warn(...args);
20
+ };
21
+ debugLog('[zite/auth-sdk] v' + constants_js_1.AUTH_SDK_VERSION + ' initialized', {
22
+ appPublicIdentifier: (0, config_js_1.getFlowId)(),
23
+ });
24
+ const isInternalMode = () => {
25
+ const win = window;
26
+ if (win._ziteIsInternalMode === undefined) {
27
+ const search = new URLSearchParams(window.location.search);
28
+ const isInternalModeParam = search.get('isInternalMode');
29
+ if (isInternalModeParam !== null) {
30
+ win._ziteIsInternalMode = isInternalModeParam === 'true';
31
+ }
32
+ }
33
+ const result = !!win._ziteIsInternalMode;
34
+ debugLog('[zite/auth-sdk] isInternalMode:', result);
35
+ return result;
36
+ };
37
+ const getZiteAppMode = (hostname) => {
38
+ const hostnameParts = hostname.split('.');
39
+ const maybeId = hostnameParts.length > 0 ? hostnameParts[0] : undefined;
40
+ if (maybeId?.startsWith(constants_js_1.ZITE_APP_EDITOR_HOSTNAME_PREFIX))
41
+ return 'preview';
42
+ if (maybeId?.startsWith(constants_js_1.ZITE_APP_ACTION_HOSTNAME_PREFIX))
43
+ return 'preview';
44
+ if (constants_js_1.ZITE_SANDBOX_DOMAINS.some(d => hostname === d || hostname.endsWith('.' + d))) {
45
+ return 'preview';
46
+ }
47
+ return 'live';
48
+ };
49
+ async function getToken(code) {
50
+ const mode = getZiteAppMode(window.location.hostname);
51
+ const flowId = (0, config_js_1.getFlowId)();
52
+ const res = await fetch((0, config_js_1.getApiUrl)() +
53
+ '/v1/zite/public/auth/' +
54
+ flowId +
55
+ '/token?mode=' +
56
+ mode, {
57
+ method: 'POST',
58
+ headers: { 'Content-Type': 'application/json' },
59
+ body: JSON.stringify({ code }),
60
+ });
61
+ if (!res.ok) {
62
+ throw new Error('Failed to get token');
63
+ }
64
+ const { token } = await res.json();
65
+ return token;
66
+ }
67
+ class ZiteAuthenticationError extends Error {
68
+ status;
69
+ constructor(message, status) {
70
+ super(message);
71
+ this.name = 'ZiteAuthenticationError';
72
+ this.status = status;
73
+ Object.setPrototypeOf(this, ZiteAuthenticationError.prototype);
74
+ }
75
+ }
76
+ async function getCurrentUser() {
77
+ const token = localStorage.getItem('zite.auth.token');
78
+ if (!token)
79
+ return null;
80
+ const mode = getZiteAppMode(window.location.hostname);
81
+ const flowId = (0, config_js_1.getFlowId)();
82
+ const res = await fetch((0, config_js_1.getApiUrl)() +
83
+ '/v1/zite/public/auth/' +
84
+ flowId +
85
+ '/me?mode=' +
86
+ mode, {
87
+ method: 'GET',
88
+ headers: { Authorization: 'Bearer ' + token },
89
+ });
90
+ if (res.status === 401) {
91
+ throw new ZiteAuthenticationError('Unauthorized', res.status);
92
+ }
93
+ if (!res.ok)
94
+ return null;
95
+ const { user } = await res.json();
96
+ return user;
97
+ }
98
+ async function getUser() {
99
+ const win = window;
100
+ debugLog('[zite/auth-sdk] getUser called', {
101
+ hasExistingToken: !!localStorage.getItem('zite.auth.token'),
102
+ hasUsageToken: !!win._ziteUsageToken,
103
+ windowIsInternalMode: !!win._ziteIsInternalMode,
104
+ hostname: window.location.hostname,
105
+ });
106
+ const isLocalDev = (window.location.hostname === 'localhost' ||
107
+ window.location.hostname === '127.0.0.1') &&
108
+ !win._ziteIsInternalMode &&
109
+ !win._ziteUsageToken &&
110
+ !localStorage.getItem('zite.auth.token');
111
+ if (isLocalDev) {
112
+ try {
113
+ const rawToken = (0, config_js_1.getDbToken)();
114
+ const jwt = rawToken?.startsWith('zitejwt_')
115
+ ? rawToken.slice(8)
116
+ : rawToken;
117
+ if (jwt) {
118
+ const payload = JSON.parse(atob(jwt.split('.')[1]));
119
+ if (payload.devUser) {
120
+ debugLog('[zite/auth-sdk] local dev mode — user from dev JWT:', payload.devUser.email);
121
+ return payload.devUser;
122
+ }
123
+ }
124
+ }
125
+ catch { }
126
+ debugLog('[zite/auth-sdk] local dev mode — returning fallback mock user');
127
+ return {
128
+ id: 'local-dev',
129
+ email: 'dev@localhost',
130
+ firstName: 'Local',
131
+ lastName: 'Developer',
132
+ };
133
+ }
134
+ const code = new URL(window.location.href).searchParams.get('code');
135
+ if (code) {
136
+ debugLog('[zite/auth-sdk] exchanging code from URL params for token');
137
+ const token = await getToken(code);
138
+ localStorage.setItem('zite.auth.token', token);
139
+ window.history.replaceState({}, '', window.location.pathname);
140
+ }
141
+ if (isInternalMode() && !localStorage.getItem('zite.auth.token')) {
142
+ const usageToken = win._ziteUsageToken;
143
+ debugLog('[zite/auth-sdk] internal mode, no token yet. usageToken present:', !!usageToken);
144
+ if (usageToken) {
145
+ try {
146
+ const mode = getZiteAppMode(window.location.hostname);
147
+ const flowId = (0, config_js_1.getFlowId)();
148
+ debugLog('[zite/auth-sdk] calling /usage-token endpoint', { mode });
149
+ const res = await fetch((0, config_js_1.getApiUrl)() +
150
+ '/v1/zite/public/auth/' +
151
+ flowId +
152
+ '/usage-token?mode=' +
153
+ mode, {
154
+ method: 'POST',
155
+ headers: { 'Content-Type': 'application/json' },
156
+ body: JSON.stringify({
157
+ usageToken,
158
+ redirectUrl: window.location.href,
159
+ }),
160
+ });
161
+ debugLog('[zite/auth-sdk] /usage-token response status:', res.status);
162
+ if (res.ok) {
163
+ const data = await res.json();
164
+ if (data.token) {
165
+ localStorage.setItem('zite.auth.token', data.token);
166
+ debugLog('[zite/auth-sdk] token stored from usage-token response');
167
+ }
168
+ else if (data.redirectUrl) {
169
+ const inlineCode = new URL(data.redirectUrl).searchParams.get('code');
170
+ if (inlineCode) {
171
+ const token = await getToken(inlineCode);
172
+ localStorage.setItem('zite.auth.token', token);
173
+ debugLog('[zite/auth-sdk] token stored from usage-token redirect fallback');
174
+ }
175
+ }
176
+ }
177
+ else {
178
+ debugWarn('[zite/auth-sdk] /usage-token call failed with status:', res.status);
179
+ }
180
+ }
181
+ catch (err) {
182
+ debugWarn('[zite/auth-sdk] /usage-token exchange error:', err);
183
+ }
184
+ }
185
+ }
186
+ else if (isInternalMode()) {
187
+ debugLog('[zite/auth-sdk] internal mode, existing token found — skipping usage-token exchange');
188
+ }
189
+ try {
190
+ debugLog('[zite/auth-sdk] calling getCurrentUser');
191
+ const user = await getCurrentUser();
192
+ if (!user) {
193
+ debugLog('[zite/auth-sdk] getCurrentUser returned null, clearing token');
194
+ localStorage.removeItem('zite.auth.token');
195
+ return null;
196
+ }
197
+ debugLog('[zite/auth-sdk] getUser resolved with user:', user.id);
198
+ return user;
199
+ }
200
+ catch (err) {
201
+ debugWarn('[zite/auth-sdk] getCurrentUser error:', err);
202
+ if (err instanceof ZiteAuthenticationError) {
203
+ localStorage.removeItem('zite.auth.token');
204
+ debugLog('[zite/auth-sdk] cleared token due to auth error (status:', err.status, ')');
205
+ }
206
+ return null;
207
+ }
208
+ }
209
+ function useAuth() {
210
+ const queryClient = (0, react_query_1.useQueryClient)();
211
+ const userQuery = (0, react_query_1.useQuery)({
212
+ queryKey: ['zite.auth.user'],
213
+ queryFn: getUser,
214
+ retry: 3,
215
+ staleTime: Infinity,
216
+ refetchOnWindowFocus: false,
217
+ refetchOnReconnect: false,
218
+ refetchOnMount: false,
219
+ });
220
+ const authErrorThrown = (0, react_1.useRef)(false);
221
+ (0, react_1.useEffect)(() => {
222
+ if (!userQuery.isPending &&
223
+ !userQuery.data &&
224
+ isInternalMode() &&
225
+ !authErrorThrown.current) {
226
+ authErrorThrown.current = true;
227
+ setTimeout(() => {
228
+ throw new ZiteAuthenticationError('Authentication failed in internal mode. The user could not be resolved after loading completed.', 401);
229
+ }, 0);
230
+ }
231
+ }, [userQuery.isPending, userQuery.data]);
232
+ (0, react_1.useEffect)(() => {
233
+ const handler = () => {
234
+ debugLog('[zite/auth-sdk] received zite:auth-sync event, invalidating user query');
235
+ queryClient.invalidateQueries({ queryKey: ['zite.auth.user'] });
236
+ };
237
+ window.addEventListener('zite:auth-sync', handler);
238
+ return () => window.removeEventListener('zite:auth-sync', handler);
239
+ }, [queryClient]);
240
+ const loginWithRedirect = (0, react_1.useCallback)((opts) => {
241
+ if (isInternalMode()) {
242
+ throw new Error('loginWithRedirect is not available in internal mode.');
243
+ }
244
+ const authUrl = (0, config_js_1.getAuthPageUrl)();
245
+ if (!authUrl) {
246
+ throw new Error('loginWithRedirect: AUTH_URL could not be resolved.');
247
+ }
248
+ const url = new URL(authUrl);
249
+ url.searchParams.set('flowPublicIdentifier', (0, config_js_1.getFlowId)());
250
+ if (opts?.redirectUrl)
251
+ url.searchParams.set('redirectUrl', opts.redirectUrl);
252
+ if (opts?.initialView === 'signup')
253
+ url.searchParams.set('mode', 'signup');
254
+ const win = window;
255
+ if (win._ziteUsageToken) {
256
+ url.searchParams.set(constants_js_1.USAGE_TOKEN_QUERY_PARAM, win._ziteUsageToken);
257
+ }
258
+ window.location.href = url.toString();
259
+ }, []);
260
+ const logout = (0, react_1.useCallback)((options) => {
261
+ if (isInternalMode()) {
262
+ throw new Error('logout is not available in internal mode.');
263
+ }
264
+ localStorage.removeItem('zite.auth.token');
265
+ queryClient.setQueryData(['zite.auth.user'], null);
266
+ queryClient.removeQueries({ queryKey: ['zite.auth.user'] });
267
+ if (window.top !== window.self) {
268
+ debugLog('[zite/auth-sdk] sending auth.logout to parent');
269
+ window.parent.postMessage({ type: 'auth.logout', data: {} }, '*');
270
+ }
271
+ if (options?.returnTo) {
272
+ window.location.href = options.returnTo;
273
+ }
274
+ }, [queryClient]);
275
+ return {
276
+ user: userQuery.data ?? undefined,
277
+ isLoading: userQuery.isPending,
278
+ loginWithRedirect,
279
+ logout,
280
+ };
281
+ }
@@ -1,32 +1,22 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createCaller = createCaller;
4
+ const env_js_1 = require("../internal/env.js");
4
5
  const ENVIRONMENTS = {
5
6
  production: 'https://workflows.zite.com',
6
7
  staging: 'https://workflows.zitestaging.com',
7
8
  local: 'http://localhost:2506',
8
9
  };
9
- function getEnv(key, viteKey) {
10
- if (typeof process !== 'undefined' && process.env?.[key])
11
- return process.env[key];
12
- try {
13
- // @ts-ignore — import.meta.env is Vite-specific
14
- if (viteKey && typeof import.meta !== 'undefined' && import.meta.env?.[viteKey])
15
- return import.meta.env[viteKey];
16
- }
17
- catch { }
18
- return undefined;
19
- }
20
10
  function getRunnerUrl() {
21
- const env = getEnv('ZITE_ENV', 'VITE_ZITE_ENV') ?? 'production';
22
- return getEnv('ZITE_RUNNER_URL', 'VITE_ZITE_RUNNER_URL') ?? ENVIRONMENTS[env] ?? ENVIRONMENTS.production;
11
+ const env = (0, env_js_1.getEnv)('ZITE_ENV', 'VITE_ZITE_ENV') ?? 'production';
12
+ return (0, env_js_1.getEnv)('ZITE_RUNNER_URL', 'VITE_ZITE_RUNNER_URL') ?? ENVIRONMENTS[env] ?? ENVIRONMENTS.production;
23
13
  }
24
14
  function getToken() {
25
- return getEnv('ZITE_DB_TOKEN', 'VITE_ZITE_DB_TOKEN') ?? '';
15
+ return (0, env_js_1.getEnv)('ZITE_DB_TOKEN', 'VITE_ZITE_DB_TOKEN') ?? '';
26
16
  }
27
17
  function createCaller(endpoint, name, flowId) {
28
18
  return async (input) => {
29
- const appId = flowId ?? getEnv('ZITE_FLOW_ID', 'VITE_ZITE_FLOW_ID') ?? '';
19
+ const appId = flowId ?? (0, env_js_1.getEnv)('ZITE_FLOW_ID', 'VITE_ZITE_FLOW_ID') ?? '';
30
20
  const res = await fetch(getRunnerUrl() + '/public/' + appId + '/api/' + name, {
31
21
  method: 'POST',
32
22
  headers: {
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getEnv = getEnv;
4
+ function getEnv(key, viteKey) {
5
+ if (typeof process !== 'undefined' && process.env?.[key])
6
+ return process.env[key];
7
+ try {
8
+ // @ts-ignore — import.meta.env is Vite-specific
9
+ if (viteKey && typeof import.meta !== 'undefined' && import.meta.env?.[viteKey])
10
+ return import.meta.env[viteKey];
11
+ }
12
+ catch { }
13
+ return undefined;
14
+ }
@@ -3,28 +3,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createCaller = void 0;
4
4
  exports.wrapSdkCall = wrapSdkCall;
5
5
  exports.createTableClient = createTableClient;
6
+ const env_js_1 = require("../internal/env.js");
6
7
  const ENVIRONMENTS = {
7
8
  production: 'https://workflows.zite.com',
8
9
  staging: 'https://workflows.zitestaging.com',
9
10
  local: 'http://localhost:2506',
10
11
  };
11
- function getEnv(key, viteKey) {
12
- if (typeof process !== 'undefined' && process.env?.[key])
13
- return process.env[key];
14
- try {
15
- // @ts-ignore — import.meta.env is Vite-specific
16
- if (viteKey && typeof import.meta !== 'undefined' && import.meta.env?.[viteKey])
17
- return import.meta.env[viteKey];
18
- }
19
- catch { }
20
- return undefined;
21
- }
22
12
  function getRunnerUrl() {
23
- const env = getEnv('ZITE_ENV', 'VITE_ZITE_ENV') ?? 'production';
24
- return getEnv('ZITE_RUNNER_URL', 'VITE_ZITE_RUNNER_URL') ?? ENVIRONMENTS[env] ?? ENVIRONMENTS.production;
13
+ const env = (0, env_js_1.getEnv)('ZITE_ENV', 'VITE_ZITE_ENV') ?? 'production';
14
+ return (0, env_js_1.getEnv)('ZITE_RUNNER_URL', 'VITE_ZITE_RUNNER_URL') ?? ENVIRONMENTS[env] ?? ENVIRONMENTS.production;
25
15
  }
26
16
  function getToken() {
27
- return getEnv('ZITE_DB_TOKEN', 'VITE_ZITE_DB_TOKEN') ?? '';
17
+ return (0, env_js_1.getEnv)('ZITE_DB_TOKEN', 'VITE_ZITE_DB_TOKEN') ?? '';
28
18
  }
29
19
  async function wrapSdkCall(integrationId, className, methodName, params) {
30
20
  const res = await fetch(`${getRunnerUrl()}/sdk/execute`, {
@@ -0,0 +1,4 @@
1
+ export declare function getFlowId(): string;
2
+ export declare function getApiUrl(): string;
3
+ export declare function getAuthPageUrl(): string;
4
+ export declare function getDbToken(): string;
@@ -0,0 +1,32 @@
1
+ import { getEnv } from '../internal/env.js';
2
+ const API_ENVIRONMENTS = {
3
+ production: 'https://api.fillout.com',
4
+ staging: 'https://api.filloutstaging.com',
5
+ local: 'http://localhost:2502',
6
+ };
7
+ const AUTH_PAGE_ENVIRONMENTS = {
8
+ production: 'https://zite.com/auth',
9
+ staging: 'https://zitestaging.com/auth',
10
+ local: 'http://localhost:3000/auth',
11
+ };
12
+ export function getFlowId() {
13
+ const id = getEnv('ZITE_FLOW_ID', 'VITE_ZITE_FLOW_ID') ?? '';
14
+ if (!id) {
15
+ const win = typeof window !== 'undefined' ? window : undefined;
16
+ const config = win?.__ziteConfig;
17
+ if (config?.id)
18
+ return config.id;
19
+ }
20
+ return id;
21
+ }
22
+ export function getApiUrl() {
23
+ const env = getEnv('ZITE_ENV', 'VITE_ZITE_ENV') ?? 'production';
24
+ return getEnv('ZITE_API_URL', 'VITE_ZITE_API_URL') ?? API_ENVIRONMENTS[env] ?? API_ENVIRONMENTS.production;
25
+ }
26
+ export function getAuthPageUrl() {
27
+ const env = getEnv('ZITE_ENV', 'VITE_ZITE_ENV') ?? 'production';
28
+ return getEnv('ZITE_AUTH_PAGE_URL', 'VITE_ZITE_AUTH_PAGE_URL') ?? AUTH_PAGE_ENVIRONMENTS[env] ?? AUTH_PAGE_ENVIRONMENTS.production;
29
+ }
30
+ export function getDbToken() {
31
+ return getEnv('ZITE_DB_TOKEN', 'VITE_ZITE_DB_TOKEN') ?? '';
32
+ }
@@ -0,0 +1,5 @@
1
+ export declare const ZITE_APP_EDITOR_HOSTNAME_PREFIX = "zite-editor-";
2
+ export declare const ZITE_APP_ACTION_HOSTNAME_PREFIX = "zite-action-";
3
+ export declare const ZITE_SANDBOX_DOMAINS: readonly ["zite-dev-sandbox.com", "zite-dev-app.com", "zite-sandbox.com", "zite-app.com"];
4
+ export declare const USAGE_TOKEN_QUERY_PARAM = "usageToken";
5
+ export declare const AUTH_SDK_VERSION = "1.0.0";
@@ -0,0 +1,10 @@
1
+ export const ZITE_APP_EDITOR_HOSTNAME_PREFIX = 'zite-editor-';
2
+ export const ZITE_APP_ACTION_HOSTNAME_PREFIX = 'zite-action-';
3
+ export const ZITE_SANDBOX_DOMAINS = [
4
+ 'zite-dev-sandbox.com',
5
+ 'zite-dev-app.com',
6
+ 'zite-sandbox.com',
7
+ 'zite-app.com',
8
+ ];
9
+ export const USAGE_TOKEN_QUERY_PARAM = 'usageToken';
10
+ export const AUTH_SDK_VERSION = '1.0.0';
@@ -1 +1,18 @@
1
- export {};
1
+ export type User = {
2
+ id: string;
3
+ email: string;
4
+ firstName?: string;
5
+ lastName?: string;
6
+ [key: string]: unknown;
7
+ };
8
+ export declare function useAuth(): {
9
+ user: User | undefined;
10
+ isLoading: boolean;
11
+ loginWithRedirect: (opts?: {
12
+ redirectUrl?: string;
13
+ initialView?: 'login' | 'signup';
14
+ }) => void;
15
+ logout: (options?: {
16
+ returnTo?: string;
17
+ }) => void;
18
+ };
@@ -1 +1,278 @@
1
- export {};
1
+ import { useCallback, useEffect, useRef } from 'react';
2
+ import { useQuery, useQueryClient } from '@tanstack/react-query';
3
+ import { getFlowId, getApiUrl, getAuthPageUrl, getDbToken } from './config.js';
4
+ import { ZITE_APP_EDITOR_HOSTNAME_PREFIX, ZITE_APP_ACTION_HOSTNAME_PREFIX, ZITE_SANDBOX_DOMAINS, USAGE_TOKEN_QUERY_PARAM, AUTH_SDK_VERSION, } from './constants.js';
5
+ const _isLocalEnv = typeof window !== 'undefined' &&
6
+ (window.location.hostname === 'localhost' ||
7
+ window.location.hostname === '127.0.0.1' ||
8
+ window.location.hostname.endsWith('.localhost') ||
9
+ localStorage.getItem('zite.debug.log') === 'true');
10
+ const debugLog = (...args) => {
11
+ if (_isLocalEnv)
12
+ console.log(...args);
13
+ };
14
+ const debugWarn = (...args) => {
15
+ if (_isLocalEnv)
16
+ console.warn(...args);
17
+ };
18
+ debugLog('[zite/auth-sdk] v' + AUTH_SDK_VERSION + ' initialized', {
19
+ appPublicIdentifier: getFlowId(),
20
+ });
21
+ const isInternalMode = () => {
22
+ const win = window;
23
+ if (win._ziteIsInternalMode === undefined) {
24
+ const search = new URLSearchParams(window.location.search);
25
+ const isInternalModeParam = search.get('isInternalMode');
26
+ if (isInternalModeParam !== null) {
27
+ win._ziteIsInternalMode = isInternalModeParam === 'true';
28
+ }
29
+ }
30
+ const result = !!win._ziteIsInternalMode;
31
+ debugLog('[zite/auth-sdk] isInternalMode:', result);
32
+ return result;
33
+ };
34
+ const getZiteAppMode = (hostname) => {
35
+ const hostnameParts = hostname.split('.');
36
+ const maybeId = hostnameParts.length > 0 ? hostnameParts[0] : undefined;
37
+ if (maybeId?.startsWith(ZITE_APP_EDITOR_HOSTNAME_PREFIX))
38
+ return 'preview';
39
+ if (maybeId?.startsWith(ZITE_APP_ACTION_HOSTNAME_PREFIX))
40
+ return 'preview';
41
+ if (ZITE_SANDBOX_DOMAINS.some(d => hostname === d || hostname.endsWith('.' + d))) {
42
+ return 'preview';
43
+ }
44
+ return 'live';
45
+ };
46
+ async function getToken(code) {
47
+ const mode = getZiteAppMode(window.location.hostname);
48
+ const flowId = getFlowId();
49
+ const res = await fetch(getApiUrl() +
50
+ '/v1/zite/public/auth/' +
51
+ flowId +
52
+ '/token?mode=' +
53
+ mode, {
54
+ method: 'POST',
55
+ headers: { 'Content-Type': 'application/json' },
56
+ body: JSON.stringify({ code }),
57
+ });
58
+ if (!res.ok) {
59
+ throw new Error('Failed to get token');
60
+ }
61
+ const { token } = await res.json();
62
+ return token;
63
+ }
64
+ class ZiteAuthenticationError extends Error {
65
+ status;
66
+ constructor(message, status) {
67
+ super(message);
68
+ this.name = 'ZiteAuthenticationError';
69
+ this.status = status;
70
+ Object.setPrototypeOf(this, ZiteAuthenticationError.prototype);
71
+ }
72
+ }
73
+ async function getCurrentUser() {
74
+ const token = localStorage.getItem('zite.auth.token');
75
+ if (!token)
76
+ return null;
77
+ const mode = getZiteAppMode(window.location.hostname);
78
+ const flowId = getFlowId();
79
+ const res = await fetch(getApiUrl() +
80
+ '/v1/zite/public/auth/' +
81
+ flowId +
82
+ '/me?mode=' +
83
+ mode, {
84
+ method: 'GET',
85
+ headers: { Authorization: 'Bearer ' + token },
86
+ });
87
+ if (res.status === 401) {
88
+ throw new ZiteAuthenticationError('Unauthorized', res.status);
89
+ }
90
+ if (!res.ok)
91
+ return null;
92
+ const { user } = await res.json();
93
+ return user;
94
+ }
95
+ async function getUser() {
96
+ const win = window;
97
+ debugLog('[zite/auth-sdk] getUser called', {
98
+ hasExistingToken: !!localStorage.getItem('zite.auth.token'),
99
+ hasUsageToken: !!win._ziteUsageToken,
100
+ windowIsInternalMode: !!win._ziteIsInternalMode,
101
+ hostname: window.location.hostname,
102
+ });
103
+ const isLocalDev = (window.location.hostname === 'localhost' ||
104
+ window.location.hostname === '127.0.0.1') &&
105
+ !win._ziteIsInternalMode &&
106
+ !win._ziteUsageToken &&
107
+ !localStorage.getItem('zite.auth.token');
108
+ if (isLocalDev) {
109
+ try {
110
+ const rawToken = getDbToken();
111
+ const jwt = rawToken?.startsWith('zitejwt_')
112
+ ? rawToken.slice(8)
113
+ : rawToken;
114
+ if (jwt) {
115
+ const payload = JSON.parse(atob(jwt.split('.')[1]));
116
+ if (payload.devUser) {
117
+ debugLog('[zite/auth-sdk] local dev mode — user from dev JWT:', payload.devUser.email);
118
+ return payload.devUser;
119
+ }
120
+ }
121
+ }
122
+ catch { }
123
+ debugLog('[zite/auth-sdk] local dev mode — returning fallback mock user');
124
+ return {
125
+ id: 'local-dev',
126
+ email: 'dev@localhost',
127
+ firstName: 'Local',
128
+ lastName: 'Developer',
129
+ };
130
+ }
131
+ const code = new URL(window.location.href).searchParams.get('code');
132
+ if (code) {
133
+ debugLog('[zite/auth-sdk] exchanging code from URL params for token');
134
+ const token = await getToken(code);
135
+ localStorage.setItem('zite.auth.token', token);
136
+ window.history.replaceState({}, '', window.location.pathname);
137
+ }
138
+ if (isInternalMode() && !localStorage.getItem('zite.auth.token')) {
139
+ const usageToken = win._ziteUsageToken;
140
+ debugLog('[zite/auth-sdk] internal mode, no token yet. usageToken present:', !!usageToken);
141
+ if (usageToken) {
142
+ try {
143
+ const mode = getZiteAppMode(window.location.hostname);
144
+ const flowId = getFlowId();
145
+ debugLog('[zite/auth-sdk] calling /usage-token endpoint', { mode });
146
+ const res = await fetch(getApiUrl() +
147
+ '/v1/zite/public/auth/' +
148
+ flowId +
149
+ '/usage-token?mode=' +
150
+ mode, {
151
+ method: 'POST',
152
+ headers: { 'Content-Type': 'application/json' },
153
+ body: JSON.stringify({
154
+ usageToken,
155
+ redirectUrl: window.location.href,
156
+ }),
157
+ });
158
+ debugLog('[zite/auth-sdk] /usage-token response status:', res.status);
159
+ if (res.ok) {
160
+ const data = await res.json();
161
+ if (data.token) {
162
+ localStorage.setItem('zite.auth.token', data.token);
163
+ debugLog('[zite/auth-sdk] token stored from usage-token response');
164
+ }
165
+ else if (data.redirectUrl) {
166
+ const inlineCode = new URL(data.redirectUrl).searchParams.get('code');
167
+ if (inlineCode) {
168
+ const token = await getToken(inlineCode);
169
+ localStorage.setItem('zite.auth.token', token);
170
+ debugLog('[zite/auth-sdk] token stored from usage-token redirect fallback');
171
+ }
172
+ }
173
+ }
174
+ else {
175
+ debugWarn('[zite/auth-sdk] /usage-token call failed with status:', res.status);
176
+ }
177
+ }
178
+ catch (err) {
179
+ debugWarn('[zite/auth-sdk] /usage-token exchange error:', err);
180
+ }
181
+ }
182
+ }
183
+ else if (isInternalMode()) {
184
+ debugLog('[zite/auth-sdk] internal mode, existing token found — skipping usage-token exchange');
185
+ }
186
+ try {
187
+ debugLog('[zite/auth-sdk] calling getCurrentUser');
188
+ const user = await getCurrentUser();
189
+ if (!user) {
190
+ debugLog('[zite/auth-sdk] getCurrentUser returned null, clearing token');
191
+ localStorage.removeItem('zite.auth.token');
192
+ return null;
193
+ }
194
+ debugLog('[zite/auth-sdk] getUser resolved with user:', user.id);
195
+ return user;
196
+ }
197
+ catch (err) {
198
+ debugWarn('[zite/auth-sdk] getCurrentUser error:', err);
199
+ if (err instanceof ZiteAuthenticationError) {
200
+ localStorage.removeItem('zite.auth.token');
201
+ debugLog('[zite/auth-sdk] cleared token due to auth error (status:', err.status, ')');
202
+ }
203
+ return null;
204
+ }
205
+ }
206
+ export function useAuth() {
207
+ const queryClient = useQueryClient();
208
+ const userQuery = useQuery({
209
+ queryKey: ['zite.auth.user'],
210
+ queryFn: getUser,
211
+ retry: 3,
212
+ staleTime: Infinity,
213
+ refetchOnWindowFocus: false,
214
+ refetchOnReconnect: false,
215
+ refetchOnMount: false,
216
+ });
217
+ const authErrorThrown = useRef(false);
218
+ useEffect(() => {
219
+ if (!userQuery.isPending &&
220
+ !userQuery.data &&
221
+ isInternalMode() &&
222
+ !authErrorThrown.current) {
223
+ authErrorThrown.current = true;
224
+ setTimeout(() => {
225
+ throw new ZiteAuthenticationError('Authentication failed in internal mode. The user could not be resolved after loading completed.', 401);
226
+ }, 0);
227
+ }
228
+ }, [userQuery.isPending, userQuery.data]);
229
+ useEffect(() => {
230
+ const handler = () => {
231
+ debugLog('[zite/auth-sdk] received zite:auth-sync event, invalidating user query');
232
+ queryClient.invalidateQueries({ queryKey: ['zite.auth.user'] });
233
+ };
234
+ window.addEventListener('zite:auth-sync', handler);
235
+ return () => window.removeEventListener('zite:auth-sync', handler);
236
+ }, [queryClient]);
237
+ const loginWithRedirect = useCallback((opts) => {
238
+ if (isInternalMode()) {
239
+ throw new Error('loginWithRedirect is not available in internal mode.');
240
+ }
241
+ const authUrl = getAuthPageUrl();
242
+ if (!authUrl) {
243
+ throw new Error('loginWithRedirect: AUTH_URL could not be resolved.');
244
+ }
245
+ const url = new URL(authUrl);
246
+ url.searchParams.set('flowPublicIdentifier', getFlowId());
247
+ if (opts?.redirectUrl)
248
+ url.searchParams.set('redirectUrl', opts.redirectUrl);
249
+ if (opts?.initialView === 'signup')
250
+ url.searchParams.set('mode', 'signup');
251
+ const win = window;
252
+ if (win._ziteUsageToken) {
253
+ url.searchParams.set(USAGE_TOKEN_QUERY_PARAM, win._ziteUsageToken);
254
+ }
255
+ window.location.href = url.toString();
256
+ }, []);
257
+ const logout = useCallback((options) => {
258
+ if (isInternalMode()) {
259
+ throw new Error('logout is not available in internal mode.');
260
+ }
261
+ localStorage.removeItem('zite.auth.token');
262
+ queryClient.setQueryData(['zite.auth.user'], null);
263
+ queryClient.removeQueries({ queryKey: ['zite.auth.user'] });
264
+ if (window.top !== window.self) {
265
+ debugLog('[zite/auth-sdk] sending auth.logout to parent');
266
+ window.parent.postMessage({ type: 'auth.logout', data: {} }, '*');
267
+ }
268
+ if (options?.returnTo) {
269
+ window.location.href = options.returnTo;
270
+ }
271
+ }, [queryClient]);
272
+ return {
273
+ user: userQuery.data ?? undefined,
274
+ isLoading: userQuery.isPending,
275
+ loginWithRedirect,
276
+ logout,
277
+ };
278
+ }
@@ -1,19 +1,9 @@
1
+ import { getEnv } from '../internal/env.js';
1
2
  const ENVIRONMENTS = {
2
3
  production: 'https://workflows.zite.com',
3
4
  staging: 'https://workflows.zitestaging.com',
4
5
  local: 'http://localhost:2506',
5
6
  };
6
- function getEnv(key, viteKey) {
7
- if (typeof process !== 'undefined' && process.env?.[key])
8
- return process.env[key];
9
- try {
10
- // @ts-ignore — import.meta.env is Vite-specific
11
- if (viteKey && typeof import.meta !== 'undefined' && import.meta.env?.[viteKey])
12
- return import.meta.env[viteKey];
13
- }
14
- catch { }
15
- return undefined;
16
- }
17
7
  function getRunnerUrl() {
18
8
  const env = getEnv('ZITE_ENV', 'VITE_ZITE_ENV') ?? 'production';
19
9
  return getEnv('ZITE_RUNNER_URL', 'VITE_ZITE_RUNNER_URL') ?? ENVIRONMENTS[env] ?? ENVIRONMENTS.production;
@@ -0,0 +1 @@
1
+ export declare function getEnv(key: string, viteKey?: string): string | undefined;
@@ -0,0 +1,11 @@
1
+ export function getEnv(key, viteKey) {
2
+ if (typeof process !== 'undefined' && process.env?.[key])
3
+ return process.env[key];
4
+ try {
5
+ // @ts-ignore — import.meta.env is Vite-specific
6
+ if (viteKey && typeof import.meta !== 'undefined' && import.meta.env?.[viteKey])
7
+ return import.meta.env[viteKey];
8
+ }
9
+ catch { }
10
+ return undefined;
11
+ }
@@ -1,19 +1,9 @@
1
+ import { getEnv } from '../internal/env.js';
1
2
  const ENVIRONMENTS = {
2
3
  production: 'https://workflows.zite.com',
3
4
  staging: 'https://workflows.zitestaging.com',
4
5
  local: 'http://localhost:2506',
5
6
  };
6
- function getEnv(key, viteKey) {
7
- if (typeof process !== 'undefined' && process.env?.[key])
8
- return process.env[key];
9
- try {
10
- // @ts-ignore — import.meta.env is Vite-specific
11
- if (viteKey && typeof import.meta !== 'undefined' && import.meta.env?.[viteKey])
12
- return import.meta.env[viteKey];
13
- }
14
- catch { }
15
- return undefined;
16
- }
17
7
  function getRunnerUrl() {
18
8
  const env = getEnv('ZITE_ENV', 'VITE_ZITE_ENV') ?? 'production';
19
9
  return getEnv('ZITE_RUNNER_URL', 'VITE_ZITE_RUNNER_URL') ?? ENVIRONMENTS[env] ?? ENVIRONMENTS.production;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zitejs",
3
- "version": "0.9.8",
3
+ "version": "0.9.9",
4
4
  "description": "The Zite framework — build apps on Zite Database",
5
5
  "type": "module",
6
6
  "main": "./dist/cjs/runtime/index.js",
@@ -27,6 +27,11 @@
27
27
  "import": "./dist/esm/runtime/index.js",
28
28
  "require": "./dist/cjs/runtime/index.js"
29
29
  },
30
+ "./auth": {
31
+ "types": "./dist/esm/auth/index.d.ts",
32
+ "import": "./dist/esm/auth/index.js",
33
+ "require": "./dist/cjs/auth/index.js"
34
+ },
30
35
  "./backend": {
31
36
  "types": "./dist/esm/backend/index.d.ts",
32
37
  "import": "./dist/esm/backend/index.js",
@@ -64,14 +69,19 @@
64
69
  "dist"
65
70
  ],
66
71
  "peerDependencies": {
72
+ "@tanstack/react-query": ">=5",
67
73
  "react": ">=18"
68
74
  },
69
75
  "peerDependenciesMeta": {
70
76
  "react": {
71
77
  "optional": true
78
+ },
79
+ "@tanstack/react-query": {
80
+ "optional": true
72
81
  }
73
82
  },
74
83
  "devDependencies": {
84
+ "@tanstack/react-query": "^5.100.14",
75
85
  "@types/node": "^25.9.1",
76
86
  "@types/react": "^19.0.0",
77
87
  "react": "^19.0.0",