@kerne/react 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,238 +1,186 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.tsx
21
- var index_exports = {};
22
- __export(index_exports, {
23
- KerneClient: () => KerneClient,
24
- KerneProvider: () => KerneProvider,
25
- createKerneClient: () => createKerneClient,
26
- useAuth: () => useAuth,
27
- useBilling: () => useBilling,
28
- useKerne: () => useKerne
29
- });
30
- module.exports = __toCommonJS(index_exports);
31
- var import_react = require("react");
32
- var import_server = require("@kerne/server");
33
- var import_jsx_runtime = require("react/jsx-runtime");
34
- var DEFAULT_STORAGE_KEY = "kerne_auth";
35
- var KerneClient = class {
36
- kerne;
37
- storage;
38
- storageKey;
39
- onAuthChange;
40
- currentUser = null;
41
- currentToken = null;
42
- constructor(config) {
43
- this.storage = config.storage ?? (typeof window !== "undefined" ? localStorage : null);
44
- this.storageKey = config.storageKey ?? DEFAULT_STORAGE_KEY;
45
- this.onAuthChange = config.onAuthChange;
46
- this.kerne = new import_server.Kerne({
47
- baseUrl: config.baseUrl,
48
- appId: config.appId,
49
- timeout: config.timeout
50
- });
51
- this.loadSession();
52
- }
53
- loadSession() {
54
- if (!this.storage) return;
55
- try {
56
- const data = this.storage.getItem(this.storageKey);
57
- if (data) {
58
- const { user, token, expires_at } = JSON.parse(data);
59
- if (new Date(expires_at) > /* @__PURE__ */ new Date()) {
60
- this.currentUser = user;
61
- this.currentToken = token;
62
- this.kerne = this.kerne.withToken(token);
63
- } else {
64
- this.storage.removeItem(this.storageKey);
65
- }
66
- }
67
- } catch {
68
- this.storage.removeItem(this.storageKey);
69
- }
70
- }
71
- saveSession(response) {
72
- this.currentUser = response.user;
73
- this.currentToken = response.token;
74
- this.kerne = this.kerne.withToken(response.token);
75
- if (this.storage) {
76
- this.storage.setItem(this.storageKey, JSON.stringify(response));
77
- }
78
- this.onAuthChange?.(response.user);
79
- }
80
- clearSession() {
81
- this.currentUser = null;
82
- this.currentToken = null;
83
- if (this.storage) {
84
- this.storage.removeItem(this.storageKey);
85
- }
86
- this.onAuthChange?.(null);
87
- }
88
- get user() {
89
- return this.currentUser;
90
- }
91
- get token() {
92
- return this.currentToken;
93
- }
94
- get isAuthenticated() {
95
- return this.currentToken !== null;
96
- }
97
- get client() {
98
- return this.kerne;
99
- }
100
- get projects() {
101
- return this.kerne.projects;
102
- }
103
- async register(params) {
104
- const [firstName, ...lastNameParts] = (params.name || "").split(" ");
105
- const lastName = lastNameParts.join(" ");
106
- const response = await this.kerne.auth.signup({
107
- email: params.email,
108
- password: params.password,
109
- first_name: firstName,
110
- last_name: lastName || void 0
111
- });
112
- this.saveSession(response);
113
- return response;
114
- }
115
- async login(params) {
116
- const response = await this.kerne.auth.login({
117
- email: params.email,
118
- password: params.password
119
- });
120
- this.saveSession(response);
121
- return response;
122
- }
123
- async refreshToken() {
124
- if (!this.currentToken) return null;
125
- const response = await this.kerne.auth.refreshToken({
126
- refresh_token: this.currentToken
127
- });
128
- this.saveSession(response);
129
- return response;
130
- }
131
- logout() {
132
- this.clearSession();
133
- }
134
- async refreshUser() {
135
- if (!this.currentToken) return null;
136
- try {
137
- const user = await this.kerne.users.me();
138
- this.currentUser = user;
139
- this.onAuthChange?.(user);
140
- return user;
141
- } catch {
142
- this.clearSession();
143
- return null;
144
- }
145
- }
146
- async checkEntitlement(featureKey, requested) {
147
- try {
148
- const check = await this.kerne.billing.checkEntitlement(featureKey, requested);
149
- return check.has_access;
150
- } catch {
151
- return false;
152
- }
153
- }
154
- async createCheckout(planId, options) {
155
- const { url } = await this.kerne.billing.createCheckout(planId, {
156
- success_url: options?.successUrl,
157
- cancel_url: options?.cancelUrl
158
- });
159
- return url;
160
- }
161
- async openCheckout(planId, options) {
162
- const url = await this.createCheckout(planId, options);
163
- if (typeof window !== "undefined") {
164
- window.location.href = url;
165
- }
166
- }
167
- async createPortal(returnUrl) {
168
- const { url } = await this.kerne.billing.createPortal({ return_url: returnUrl });
169
- return url;
170
- }
171
- async openPortal(returnUrl) {
172
- const url = await this.createPortal(returnUrl);
173
- if (typeof window !== "undefined") {
174
- window.location.href = url;
175
- }
176
- }
177
- };
178
- function createKerneClient(config) {
179
- return new KerneClient(config);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;"use client";
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+ var _chunk3PROPZWWcjs = require('./chunk-3PROPZWW.cjs');
21
+
22
+ // src/components.tsx
23
+ var _react = require('react'); var _react2 = _interopRequireDefault(_react);
24
+ var _jsxruntime = require('react/jsx-runtime');
25
+ function Authenticated({ children, fallback = null }) {
26
+ const { isAuthenticated } = _chunk3PROPZWWcjs.useAuth.call(void 0, );
27
+ return isAuthenticated ? children : fallback;
180
28
  }
181
- var KerneContext = (0, import_react.createContext)(null);
182
- function KerneProvider({ children, ...config }) {
183
- const [user, setUser] = (0, import_react.useState)(null);
184
- const client = (0, import_react.useMemo)(() => {
185
- return new KerneClient({
186
- ...config,
187
- onAuthChange: (u) => {
188
- setUser(u);
189
- config.onAuthChange?.(u);
190
- }
29
+ function Unauthenticated({ children, fallback = null }) {
30
+ const { isAuthenticated } = _chunk3PROPZWWcjs.useAuth.call(void 0, );
31
+ return !isAuthenticated ? children : fallback;
32
+ }
33
+ function AuthLoading({ children }) {
34
+ const client = _chunk3PROPZWWcjs.useClient.call(void 0, );
35
+ return client.isLoading ? children : null;
36
+ }
37
+ function HasSubscription({ children, fallback = null }) {
38
+ const client = _chunk3PROPZWWcjs.useClient.call(void 0, );
39
+ const [hasSubscription, setHasSubscription] = _react2.default.useState(null);
40
+ _react2.default.useEffect(() => {
41
+ client.getSubscription().then((sub) => {
42
+ setHasSubscription(sub !== null && ["ACTIVE", "TRIALING"].includes(sub.status));
43
+ }).catch(() => {
44
+ setHasSubscription(false);
191
45
  });
192
- }, [config.appId, config.baseUrl]);
193
- (0, import_react.useEffect)(() => {
194
- setUser(client.user);
195
46
  }, [client]);
196
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(KerneContext.Provider, { value: client, children });
47
+ if (hasSubscription === null) return null;
48
+ return hasSubscription ? children : fallback;
197
49
  }
198
- function useKerne() {
199
- const context = (0, import_react.useContext)(KerneContext);
200
- if (!context) {
201
- throw new Error("useKerne must be used within a KerneProvider");
202
- }
203
- return context;
50
+ function Allows({
51
+ children,
52
+ featureKey,
53
+ minimum,
54
+ fallback = null
55
+ }) {
56
+ const client = _chunk3PROPZWWcjs.useClient.call(void 0, );
57
+ const [allowed, setAllowed] = _react2.default.useState(null);
58
+ _react2.default.useEffect(() => {
59
+ client.allows(featureKey, minimum).then((result) => {
60
+ setAllowed(result);
61
+ }).catch(() => {
62
+ setAllowed(false);
63
+ });
64
+ }, [client, featureKey, minimum]);
65
+ if (allowed === null) return null;
66
+ return allowed ? children : fallback;
204
67
  }
205
- function useAuth() {
206
- const client = useKerne();
207
- const [user, setUser] = (0, import_react.useState)(client.user);
208
- (0, import_react.useEffect)(() => {
209
- setUser(client.user);
210
- }, [client.user]);
211
- return {
212
- user,
213
- isAuthenticated: client.isAuthenticated,
214
- login: client.login.bind(client),
215
- register: client.register.bind(client),
216
- logout: client.logout.bind(client),
217
- refreshUser: client.refreshUser.bind(client)
218
- };
68
+ function Protected({
69
+ children,
70
+ auth = true,
71
+ featureKey,
72
+ authFallback = null,
73
+ billingFallback = null
74
+ }) {
75
+ const { isAuthenticated } = _chunk3PROPZWWcjs.useAuth.call(void 0, );
76
+ if (auth && !isAuthenticated) {
77
+ return authFallback;
78
+ }
79
+ if (featureKey) {
80
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, Allows, { featureKey, fallback: billingFallback, children });
81
+ }
82
+ return children;
219
83
  }
220
- function useBilling() {
221
- const client = useKerne();
84
+
85
+ // src/error-boundary.tsx
86
+
87
+
88
+ var KerneErrorBoundary = (_class = class extends _react.Component {
89
+ constructor(props) {
90
+ super(props);_class.prototype.__init.call(this);;
91
+ this.state = { error: null, hasError: false };
92
+ }
93
+ static getDerivedStateFromError(error) {
94
+ return { error, hasError: true };
95
+ }
96
+ componentDidCatch(error, errorInfo) {
97
+ const kerneError = error;
98
+ _optionalChain([this, 'access', _4 => _4.props, 'access', _5 => _5.onError, 'optionalCall', _6 => _6(kerneError, errorInfo)]);
99
+ if (process.env.NODE_ENV === "development") {
100
+ console.error("[KerneSDK] Error caught by boundary:", kerneError);
101
+ console.error("[KerneSDK] Component stack:", errorInfo.componentStack);
102
+ }
103
+ }
104
+ __init() {this.reset = () => {
105
+ _optionalChain([this, 'access', _7 => _7.props, 'access', _8 => _8.onReset, 'optionalCall', _9 => _9()]);
106
+ this.setState({ error: null, hasError: false });
107
+ }}
108
+ render() {
109
+ if (this.state.hasError && this.state.error) {
110
+ const { fallback } = this.props;
111
+ const { error } = this.state;
112
+ if (fallback) {
113
+ if (typeof fallback === "function") {
114
+ return fallback(error, this.reset);
115
+ }
116
+ return fallback;
117
+ }
118
+ return /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, "div", { style: { padding: "20px", textAlign: "center" }, children: [
119
+ /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "h2", { style: { color: "#dc2626", marginBottom: "10px" }, children: "Something went wrong" }),
120
+ /* @__PURE__ */ _jsxruntime.jsx.call(void 0, "p", { style: { color: "#6b7280", marginBottom: "20px" }, children: error.message || "An unexpected error occurred" }),
121
+ error.code && /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, "p", { style: { color: "#9ca3af", fontSize: "12px", marginBottom: "20px" }, children: [
122
+ "Error code: ",
123
+ error.code
124
+ ] }),
125
+ /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
126
+ "button",
127
+ {
128
+ onClick: this.reset,
129
+ style: {
130
+ padding: "10px 20px",
131
+ backgroundColor: "#3b82f6",
132
+ color: "white",
133
+ border: "none",
134
+ borderRadius: "6px",
135
+ cursor: "pointer"
136
+ },
137
+ children: "Try again"
138
+ }
139
+ )
140
+ ] });
141
+ }
142
+ return this.props.children;
143
+ }
144
+ }, _class);
145
+ function useKerneError() {
146
+ const [error, setError] = _react2.default.useState(null);
147
+ const handleError = _react2.default.useCallback((err) => {
148
+ setError(err);
149
+ }, []);
150
+ const clearError = _react2.default.useCallback(() => {
151
+ setError(null);
152
+ }, []);
222
153
  return {
223
- checkEntitlement: client.checkEntitlement.bind(client),
224
- createCheckout: client.createCheckout.bind(client),
225
- openCheckout: client.openCheckout.bind(client),
226
- createPortal: client.createPortal.bind(client),
227
- openPortal: client.openPortal.bind(client)
154
+ error,
155
+ hasError: error !== null,
156
+ handleError,
157
+ clearError
228
158
  };
229
159
  }
230
- // Annotate the CommonJS export names for ESM import in node:
231
- 0 && (module.exports = {
232
- KerneClient,
233
- KerneProvider,
234
- createKerneClient,
235
- useAuth,
236
- useBilling,
237
- useKerne
238
- });
160
+
161
+
162
+
163
+
164
+
165
+
166
+
167
+
168
+
169
+
170
+
171
+
172
+
173
+
174
+
175
+
176
+
177
+
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+ exports.Allows = Allows; exports.AuthLoading = AuthLoading; exports.Authenticated = Authenticated; exports.HasSubscription = HasSubscription; exports.KerneClient = _chunk3PROPZWWcjs.KerneClient; exports.KerneContext = _chunk3PROPZWWcjs.KerneContext; exports.KerneErrorBoundary = KerneErrorBoundary; exports.KerneProvider = _chunk3PROPZWWcjs.KerneProvider; exports.Protected = Protected; exports.Unauthenticated = Unauthenticated; exports.defaultLocalization = _chunk3PROPZWWcjs.defaultLocalization; exports.useAccess = _chunk3PROPZWWcjs.useAccess; exports.useAuth = _chunk3PROPZWWcjs.useAuth; exports.useAuthConfig = _chunk3PROPZWWcjs.useAuthConfig; exports.useCheckout = _chunk3PROPZWWcjs.useCheckout; exports.useClient = _chunk3PROPZWWcjs.useClient; exports.useEntitlements = _chunk3PROPZWWcjs.useEntitlements; exports.useInvitation = _chunk3PROPZWWcjs.useInvitation; exports.useKerneError = useKerneError; exports.usePlans = _chunk3PROPZWWcjs.usePlans; exports.usePortal = _chunk3PROPZWWcjs.usePortal; exports.useSubscription = _chunk3PROPZWWcjs.useSubscription; exports.useUsage = _chunk3PROPZWWcjs.useUsage; exports.useUser = _chunk3PROPZWWcjs.useUser; exports.useWaitlist = _chunk3PROPZWWcjs.useWaitlist;