@godxjp/sdk 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,78 @@
1
+ # @godxjp/sdk
2
+
3
+ Shared frontend infrastructure for GoDX products.
4
+
5
+ Published for use by GoDX applications. The source repository is private; this package is the distribution.
6
+
7
+ ## Two layers, two owners
8
+
9
+ Entries are split by **who owns the contract**, not by what happens to be duplicated. Duplication alone is not a reason to share code; a contract that two sides must agree on is.
10
+
11
+ | Entry | Contents | Cadence |
12
+ | --- | --- | --- |
13
+ | `.` — not yet published | Platform contracts: permission DTO, tenant-scoped channel names | Binds every product at once |
14
+ | `./laravel` | House conventions for Laravel + React: HTTP client, `ApiError` | Moves faster |
15
+ | `./realtime` | Realtime seam: configuration, connection status, channel listeners | Moves faster |
16
+
17
+ `.` is deliberately **absent from `exports`** until the contracts it would carry are agreed. An empty entry published for the sake of symmetry is the thing to avoid.
18
+
19
+ ## `./laravel`
20
+
21
+ ```ts
22
+ import { createClient, ApiError } from '@godxjp/sdk/laravel';
23
+
24
+ export const apiClient = createClient({
25
+ baseUrl: '/api/app/v1',
26
+ signInUrl: (returnTo) => `/login?return=${encodeURIComponent(returnTo)}`,
27
+ });
28
+
29
+ // A public API whose visitor has nowhere to sign in: omit `signInUrl`,
30
+ // and a 401 is simply reported.
31
+ export const publicApiClient = createClient({ baseUrl: '/api' });
32
+ ```
33
+
34
+ Authentication is the session cookie, so a write sends the `XSRF-TOKEN` cookie back as the `X-XSRF-TOKEN` header, exactly as Laravel expects. Also handled: `key[]=a&key[]=b` for array query values and `1`/`0` for booleans, `204` resolving to `undefined`, `419` as an expired session, an unreachable server as `status: 0`, and upload progress over `XMLHttpRequest` because `fetch` cannot report it.
35
+
36
+ A cancellation stays an `AbortError` and is never converted to an `ApiError` — TanStack Query tells a cancelled query from a failed one by exactly that.
37
+
38
+ ## `./realtime`
39
+
40
+ ```ts
41
+ import {
42
+ configureRealtime,
43
+ isRealtimeConfigured,
44
+ useChannelEvent,
45
+ useRealtimeStatus,
46
+ useUserNotification,
47
+ } from '@godxjp/sdk/realtime';
48
+ ```
49
+
50
+ **Why the seam exists:** the transport underneath is expected to change. Putting the seam in first makes a later move one adapter in one package, rather than every listening component in every product.
51
+
52
+ So nothing from the transport appears in this API — no Echo type, no Pusher connection state, no channel object. A consumer able to name the underlying client has already defeated the point.
53
+
54
+ ### Three words, not six
55
+
56
+ ```ts
57
+ type RealtimeStatus = 'connecting' | 'connected' | 'unavailable';
58
+ ```
59
+
60
+ `connecting` is the first state of **every** page load and says nothing yet — a screen must not start polling here, or every visit doubles its requests for the first second. `unavailable` means the client actually tried and is not live; that is the only state a fallback may fire on. The transport's `failed`, `unavailable` and `disconnected` all land there, because a screen has the same job in all three.
61
+
62
+ An unrecognised state maps to `unavailable`, never `connected`. Guessing toward live would switch a polling fallback **off** and freeze the screen — the exact failure the fallback exists to prevent.
63
+
64
+ ### Configured is not connected
65
+
66
+ `isRealtimeConfigured()` answers only "did `configureRealtime` run", and stays true for the life of the tab. Ask `useRealtimeStatus()` when you need to know whether anything is actually arriving. Reading the former as the latter leaves a screen frozen on whatever it loaded with while the server is down.
67
+
68
+ ### `useUserNotification` is separate on purpose
69
+
70
+ Laravel broadcasts every notification under one framework event name, so subscribing by a custom name succeeds and then never fires — a failure that presents as "connected but nothing happens". Naming the two cases apart is what stops the next person reaching for the wrong one.
71
+
72
+ ## Peer dependencies
73
+
74
+ `./realtime` needs `@laravel/echo-react` and `react`. Both are optional peers: an application using only `./laravel` installs neither.
75
+
76
+ ## Licence
77
+
78
+ Apache-2.0.
@@ -0,0 +1,72 @@
1
+ /**
2
+ * A request to a Laravel JSON API that did not succeed.
3
+ *
4
+ * Lives apart from `api-client.ts` (which re-exports it) so a query layer can
5
+ * recognise a failure — server-side field errors, the retry policy — without
6
+ * importing the module that issues requests.
7
+ *
8
+ * `status` is 0 when the server was never reached. It is also the field
9
+ * `@godxjp/ui/query`'s `classifyQueryError` reads, so `DataState` picks the
10
+ * right recovery (sign in, no access, retry) with no adapter.
11
+ */
12
+ declare class ApiError extends Error {
13
+ readonly status: number;
14
+ /** Laravel's `{errors: {field: string[]}}`, first message per key; `{}` when absent. */
15
+ readonly errors: Record<string, string>;
16
+ constructor(status: number, message: string, errors?: Record<string, string>);
17
+ }
18
+
19
+ /**
20
+ * The one place a consumer calls `fetch` (or, for an upload that reports
21
+ * progress, `XMLHttpRequest`).
22
+ *
23
+ * Authentication is the `web` session cookie, so a write carries the
24
+ * `XSRF-TOKEN` cookie back as `X-XSRF-TOKEN`, exactly as Laravel expects.
25
+ *
26
+ * THE PACKAGE DOES NOT KNOW WHERE SIGNING IN LIVES. The host passes
27
+ * `signInUrl`; a client without one simply reports the 401. That is the only
28
+ * difference from the implementation this was lifted from (godx-task), where
29
+ * the sign-in route was imported directly and a boolean chose whether to use
30
+ * it — which tied the client to one app's route file.
31
+ */
32
+ type QueryValue = string | number | boolean | null | undefined;
33
+ type ApiQuery = Record<string, QueryValue | QueryValue[]>;
34
+ type RequestOptions = {
35
+ signal?: AbortSignal;
36
+ };
37
+ type GetOptions = RequestOptions & {
38
+ query?: ApiQuery;
39
+ };
40
+ type WriteOptions = RequestOptions & {
41
+ /**
42
+ * Upload progress, 0–100. `fetch` cannot report it, so a request that asks
43
+ * for progress goes out over `XMLHttpRequest` instead — same headers, same
44
+ * answers, same errors.
45
+ */
46
+ onUploadProgress?: (percent: number) => void;
47
+ };
48
+ type ClientConfig = {
49
+ /** Prefixed to every path, e.g. `/api/app/v1`. */
50
+ baseUrl: string;
51
+ /**
52
+ * Where to send the browser on a 401, given the path to come back to.
53
+ * Omitted for a public API whose visitor has nowhere to sign in.
54
+ */
55
+ signInUrl?: (returnTo: string) => string;
56
+ };
57
+ type ApiClient = {
58
+ get: <T>(path: string, options?: GetOptions) => Promise<T>;
59
+ post: <T>(path: string, body?: Body, options?: WriteOptions) => Promise<T>;
60
+ put: <T>(path: string, body?: Body, options?: WriteOptions) => Promise<T>;
61
+ patch: <T>(path: string, body?: Body, options?: WriteOptions) => Promise<T>;
62
+ delete: <T>(path: string, options?: GetOptions) => Promise<T>;
63
+ };
64
+ /** `FormData` goes out as multipart untouched; anything else is JSON-encoded. */
65
+ type Body = FormData | object;
66
+ /** Laravel reads `key[]=a&key[]=b` as an array and '1'/'0' as booleans. */
67
+ declare function queryString(query: ApiQuery | undefined): string;
68
+ /** First message per key — the one a field shows (`$errors->first()`). */
69
+ declare function flattenErrors(errors: unknown): Record<string, string>;
70
+ declare function createClient(config: ClientConfig): ApiClient;
71
+
72
+ export { type ApiClient, ApiError, type ApiQuery, type ClientConfig, type GetOptions, type WriteOptions, createClient, flattenErrors, queryString };
@@ -0,0 +1,182 @@
1
+ // src/laravel/api-error.ts
2
+ var ApiError = class extends Error {
3
+ status;
4
+ /** Laravel's `{errors: {field: string[]}}`, first message per key; `{}` when absent. */
5
+ errors;
6
+ constructor(status, message, errors = {}) {
7
+ super(message);
8
+ this.name = "ApiError";
9
+ this.status = status;
10
+ this.errors = errors;
11
+ }
12
+ };
13
+
14
+ // src/laravel/api-client.ts
15
+ var SESSION_EXPIRED = "Your session has expired. Reload the page and try again.";
16
+ var UNREACHABLE = "Could not reach the server. Check your connection and try again.";
17
+ var redirectingToSignIn = false;
18
+ function readCookie(name) {
19
+ const prefix = `${name}=`;
20
+ const entry = document.cookie.split("; ").find((cookie) => cookie.startsWith(prefix));
21
+ return entry === void 0 ? void 0 : decodeURIComponent(entry.slice(prefix.length));
22
+ }
23
+ function queryString(query) {
24
+ if (query === void 0) {
25
+ return "";
26
+ }
27
+ const params = new URLSearchParams();
28
+ const encode = (value) => {
29
+ if (value === null || value === void 0) {
30
+ return void 0;
31
+ }
32
+ if (typeof value === "boolean") {
33
+ return value ? "1" : "0";
34
+ }
35
+ return String(value);
36
+ };
37
+ for (const [key, value] of Object.entries(query)) {
38
+ if (Array.isArray(value)) {
39
+ for (const item of value) {
40
+ const encoded2 = encode(item);
41
+ if (encoded2 !== void 0) {
42
+ params.append(`${key}[]`, encoded2);
43
+ }
44
+ }
45
+ continue;
46
+ }
47
+ const encoded = encode(value);
48
+ if (encoded !== void 0) {
49
+ params.append(key, encoded);
50
+ }
51
+ }
52
+ const text = params.toString();
53
+ return text === "" ? "" : `?${text}`;
54
+ }
55
+ function flattenErrors(errors) {
56
+ if (errors === null || typeof errors !== "object") {
57
+ return {};
58
+ }
59
+ const flat = {};
60
+ for (const [key, messages] of Object.entries(errors)) {
61
+ const first = Array.isArray(messages) ? messages[0] : messages;
62
+ if (typeof first === "string") {
63
+ flat[key] = first;
64
+ }
65
+ }
66
+ return flat;
67
+ }
68
+ function redirectToSignIn(signInUrl) {
69
+ if (redirectingToSignIn) {
70
+ return;
71
+ }
72
+ redirectingToSignIn = true;
73
+ const { pathname, search } = window.location;
74
+ window.location.assign(signInUrl(`${pathname}${search}`));
75
+ }
76
+ function send(url, init, onUploadProgress) {
77
+ if (onUploadProgress === void 0) {
78
+ return fetch(url, { ...init, credentials: "same-origin" }).then(
79
+ async (response) => ({
80
+ status: response.status,
81
+ statusText: response.statusText,
82
+ text: await response.text()
83
+ })
84
+ );
85
+ }
86
+ return new Promise((resolve, reject) => {
87
+ const xhr = new XMLHttpRequest();
88
+ const abort = () => xhr.abort();
89
+ xhr.open(init.method, url);
90
+ for (const [name, value] of Object.entries(init.headers)) {
91
+ xhr.setRequestHeader(name, value);
92
+ }
93
+ xhr.upload.onprogress = (event) => {
94
+ if (event.lengthComputable && event.total > 0) {
95
+ onUploadProgress(
96
+ Math.round(event.loaded / event.total * 100)
97
+ );
98
+ }
99
+ };
100
+ xhr.onload = () => {
101
+ init.signal?.removeEventListener("abort", abort);
102
+ resolve({
103
+ status: xhr.status,
104
+ statusText: xhr.statusText,
105
+ text: xhr.responseText
106
+ });
107
+ };
108
+ xhr.onerror = () => reject(new TypeError("Network request failed"));
109
+ xhr.onabort = () => reject(new DOMException("The request was aborted.", "AbortError"));
110
+ if (init.signal?.aborted) {
111
+ reject(new DOMException("The request was aborted.", "AbortError"));
112
+ return;
113
+ }
114
+ init.signal?.addEventListener("abort", abort, { once: true });
115
+ xhr.send(init.body ?? null);
116
+ });
117
+ }
118
+ async function request(config, method, path, body, { signal, query, onUploadProgress }) {
119
+ const headers = {
120
+ Accept: "application/json",
121
+ "X-Requested-With": "XMLHttpRequest"
122
+ };
123
+ const xsrfToken = readCookie("XSRF-TOKEN");
124
+ if (xsrfToken !== void 0) {
125
+ headers["X-XSRF-TOKEN"] = xsrfToken;
126
+ }
127
+ let payload;
128
+ if (body instanceof FormData) {
129
+ payload = body;
130
+ } else if (body !== void 0) {
131
+ headers["Content-Type"] = "application/json";
132
+ payload = JSON.stringify(body);
133
+ }
134
+ let response;
135
+ try {
136
+ response = await send(
137
+ `${config.baseUrl}${path}${queryString(query)}`,
138
+ { method, headers, body: payload, signal },
139
+ onUploadProgress
140
+ );
141
+ } catch (error) {
142
+ if (signal?.aborted) {
143
+ throw error;
144
+ }
145
+ throw new ApiError(0, UNREACHABLE);
146
+ }
147
+ if (response.status === 204) {
148
+ return void 0;
149
+ }
150
+ let json = void 0;
151
+ try {
152
+ json = response.text === "" ? void 0 : JSON.parse(response.text);
153
+ } catch {
154
+ }
155
+ if (response.status >= 200 && response.status < 300) {
156
+ return json;
157
+ }
158
+ const bag = json ?? {};
159
+ if (response.status === 401 && config.signInUrl !== void 0) {
160
+ redirectToSignIn(config.signInUrl);
161
+ }
162
+ if (response.status === 419) {
163
+ throw new ApiError(419, SESSION_EXPIRED);
164
+ }
165
+ throw new ApiError(
166
+ response.status,
167
+ typeof bag.message === "string" && bag.message !== "" ? bag.message : response.statusText,
168
+ flattenErrors(bag.errors)
169
+ );
170
+ }
171
+ function createClient(config) {
172
+ return {
173
+ get: (path, options = {}) => request(config, "GET", path, void 0, options),
174
+ post: (path, body, options = {}) => request(config, "POST", path, body, options),
175
+ put: (path, body, options = {}) => request(config, "PUT", path, body, options),
176
+ patch: (path, body, options = {}) => request(config, "PATCH", path, body, options),
177
+ /** `query` for what identifies the targets (`?ids[]=1&ids[]=2`). */
178
+ delete: (path, options = {}) => request(config, "DELETE", path, void 0, options)
179
+ };
180
+ }
181
+
182
+ export { ApiError, createClient, flattenErrors, queryString };
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The realtime seam.
3
+ *
4
+ * WHY THIS EXISTS AT ALL: the transport under it is expected to change. The
5
+ * decision on file (`godx-task:debate/realtime-reverb-vs-centrifugo`) keeps
6
+ * Reverb for now and puts this seam in first, so a later move to another
7
+ * server is one adapter in one package rather than six files in each of four
8
+ * products.
9
+ *
10
+ * SO NOTHING FROM THE TRANSPORT MAY APPEAR HERE. No Echo type, no Pusher
11
+ * connection state, no channel object. A consumer that can name `pusher-js`
12
+ * has already defeated the point.
13
+ */
14
+ /**
15
+ * What the connection can tell a screen, in three words rather than Pusher's
16
+ * six.
17
+ *
18
+ * `connecting` is the first state of every page load and says NOTHING yet — a
19
+ * screen must not fall back to polling on it. `unavailable` means the client
20
+ * actually tried and is not live, which is the only state a fallback may fire
21
+ * on. Pusher's `failed`, `unavailable` and `disconnected` all land there,
22
+ * because a screen has the same job in all three.
23
+ */
24
+ type RealtimeStatus = 'connecting' | 'connected' | 'unavailable';
25
+ /** What the host must hand over to reach its own server. */
26
+ type RealtimeConfig = {
27
+ /** The app key the server issued. */
28
+ key: string;
29
+ host: string;
30
+ port: number;
31
+ /** `https` turns on TLS and the `wss` transport. */
32
+ scheme: 'http' | 'https';
33
+ };
34
+ /**
35
+ * Map a transport's own vocabulary onto ours.
36
+ *
37
+ * Exported because it is the ONE piece of this module with behaviour worth
38
+ * pinning, and a hook is an awkward place to pin it from.
39
+ */
40
+ declare function toRealtimeStatus(raw: string | null | undefined): RealtimeStatus;
41
+
42
+ /**
43
+ * The Echo/Pusher adapter — today's transport, and the only file in this
44
+ * package that may import it.
45
+ */
46
+ /**
47
+ * Wire the connection once, for the life of the tab.
48
+ *
49
+ * The host reads its own server's details wherever it keeps them (a meta tag,
50
+ * an API call) and passes them in. The SDK does not guess: `import.meta.env`
51
+ * belongs to whoever runs the bundler, and four products do not share one.
52
+ */
53
+ declare function configureRealtime(config: RealtimeConfig): void;
54
+ /**
55
+ * Whether `configureRealtime` ran.
56
+ *
57
+ * CONFIGURED IS NOT CONNECTED, and conflating them is a real bug this project
58
+ * has already shipped once: a screen that reads "configured" as "live" keeps
59
+ * its polling fallback switched off while the server is down, and freezes on
60
+ * whatever it loaded with. Ask `useRealtimeStatus()` for liveness.
61
+ */
62
+ declare function isRealtimeConfigured(): boolean;
63
+ /** Liveness, in this package's three words rather than the transport's six. */
64
+ declare function useRealtimeStatus(): RealtimeStatus;
65
+ /**
66
+ * Listen to one named event on one channel.
67
+ *
68
+ * `event` is the name the server broadcasts, leading dot and all — the
69
+ * transport's convention for "this is our own event, not a framework one".
70
+ */
71
+ declare function useChannelEvent<T = unknown>(channel: string, event: string, handler: (payload: T) => void, deps?: unknown[]): void;
72
+ /**
73
+ * Listen to a user's notification channel.
74
+ *
75
+ * SEPARATE FROM `useChannelEvent` ON PURPOSE. Laravel broadcasts every
76
+ * notification under one framework event name, so subscribing by a custom name
77
+ * succeeds and then never fires — a failure that presents as "connected but
78
+ * nothing happens". Naming the two cases apart is what stops the next person
79
+ * reaching for the wrong one.
80
+ */
81
+ declare function useUserNotification<T = unknown>(channel: string, handler: (payload: T) => void): void;
82
+
83
+ export { type RealtimeConfig, type RealtimeStatus, configureRealtime, isRealtimeConfigured, toRealtimeStatus, useChannelEvent, useRealtimeStatus, useUserNotification };
@@ -0,0 +1,41 @@
1
+ import { configureEcho, echoIsConfigured, useConnectionStatus, useEcho, useEchoNotification } from '@laravel/echo-react';
2
+
3
+ // src/realtime/echo-adapter.ts
4
+
5
+ // src/realtime/types.ts
6
+ function toRealtimeStatus(raw) {
7
+ if (raw === "connected") {
8
+ return "connected";
9
+ }
10
+ if (raw === "connecting" || raw === "initialized" || raw == null) {
11
+ return "connecting";
12
+ }
13
+ return "unavailable";
14
+ }
15
+
16
+ // src/realtime/echo-adapter.ts
17
+ function configureRealtime(config) {
18
+ configureEcho({
19
+ broadcaster: "reverb",
20
+ key: config.key,
21
+ wsHost: config.host,
22
+ wsPort: config.port,
23
+ wssPort: config.port,
24
+ forceTLS: config.scheme === "https",
25
+ enabledTransports: ["ws", "wss"]
26
+ });
27
+ }
28
+ function isRealtimeConfigured() {
29
+ return echoIsConfigured();
30
+ }
31
+ function useRealtimeStatus() {
32
+ return toRealtimeStatus(useConnectionStatus());
33
+ }
34
+ function useChannelEvent(channel, event, handler, deps = []) {
35
+ useEcho(channel, event, handler, deps);
36
+ }
37
+ function useUserNotification(channel, handler) {
38
+ useEchoNotification(channel, handler);
39
+ }
40
+
41
+ export { configureRealtime, isRealtimeConfigured, toRealtimeStatus, useChannelEvent, useRealtimeStatus, useUserNotification };
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@godxjp/sdk",
3
+ "version": "0.1.0",
4
+ "description": "GoDX JavaScript SDK — shared frontend infrastructure for GoDX products.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "dist",
10
+ "LICENSE",
11
+ "README.md"
12
+ ],
13
+ "exports": {
14
+ "./laravel": {
15
+ "types": "./dist/laravel/index.d.ts",
16
+ "import": "./dist/laravel/index.js"
17
+ },
18
+ "./package.json": "./package.json",
19
+ "./realtime": {
20
+ "types": "./dist/realtime/index.d.ts",
21
+ "import": "./dist/realtime/index.js"
22
+ }
23
+ },
24
+ "scripts": {
25
+ "build": "tsup",
26
+ "types:check": "tsc --noEmit",
27
+ "test": "vitest run"
28
+ },
29
+ "devDependencies": {
30
+ "@laravel/echo-react": "^2.5.0",
31
+ "@types/node": "^22.10.2",
32
+ "@types/react": "^19.3.0",
33
+ "jsdom": "^25.0.1",
34
+ "laravel-echo": "^2.5.0",
35
+ "pusher-js": "^8.6.0",
36
+ "react": "^19.3.0",
37
+ "tsup": "^8.5.1",
38
+ "typescript": "^5.7.2",
39
+ "vitest": "^2.1.8"
40
+ },
41
+ "peerDependencies": {
42
+ "@laravel/echo-react": "^2.5.0",
43
+ "react": "^19.3.0"
44
+ },
45
+ "peerDependenciesMeta": {
46
+ "@laravel/echo-react": {
47
+ "optional": true
48
+ },
49
+ "react": {
50
+ "optional": true
51
+ }
52
+ }
53
+ }