@sixb/client 0.0.1

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 (155) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +193 -0
  3. package/dist/actions.d.ts +61 -0
  4. package/dist/actions.d.ts.map +1 -0
  5. package/dist/agent-streams.d.ts +72 -0
  6. package/dist/agent-streams.d.ts.map +1 -0
  7. package/dist/api.d.ts +54 -0
  8. package/dist/api.d.ts.map +1 -0
  9. package/dist/browser.d.ts +41 -0
  10. package/dist/browser.d.ts.map +1 -0
  11. package/dist/browser.js +174 -0
  12. package/dist/browser.js.map +10 -0
  13. package/dist/chunk-05yz32g0.js +240 -0
  14. package/dist/chunk-05yz32g0.js.map +10 -0
  15. package/dist/chunk-2d7239yx.js +1181 -0
  16. package/dist/chunk-2d7239yx.js.map +17 -0
  17. package/dist/chunk-3g6ad4jc.js +147 -0
  18. package/dist/chunk-3g6ad4jc.js.map +10 -0
  19. package/dist/chunk-aw8rcsq3.js +145 -0
  20. package/dist/chunk-aw8rcsq3.js.map +10 -0
  21. package/dist/chunk-ctsdm59b.js +1477 -0
  22. package/dist/chunk-ctsdm59b.js.map +19 -0
  23. package/dist/chunk-fxrh83wy.js +180 -0
  24. package/dist/chunk-fxrh83wy.js.map +12 -0
  25. package/dist/chunk-pey7nh0d.js +123 -0
  26. package/dist/chunk-pey7nh0d.js.map +10 -0
  27. package/dist/chunk-trpg18dp.js +3 -0
  28. package/dist/chunk-trpg18dp.js.map +9 -0
  29. package/dist/events-builder.d.ts +218 -0
  30. package/dist/events-builder.d.ts.map +1 -0
  31. package/dist/events-hooks.d.ts +50 -0
  32. package/dist/events-hooks.d.ts.map +1 -0
  33. package/dist/events-model.d.ts +12 -0
  34. package/dist/events-model.d.ts.map +1 -0
  35. package/dist/events-provider.d.ts +56 -0
  36. package/dist/events-provider.d.ts.map +1 -0
  37. package/dist/events-transport.d.ts +62 -0
  38. package/dist/events-transport.d.ts.map +1 -0
  39. package/dist/events.d.ts +5 -0
  40. package/dist/events.d.ts.map +1 -0
  41. package/dist/file.d.ts +27 -0
  42. package/dist/file.d.ts.map +1 -0
  43. package/dist/generated/@tanstack/react-query.gen.d.ts +17064 -0
  44. package/dist/generated/@tanstack/react-query.gen.d.ts.map +1 -0
  45. package/dist/generated/client/client.gen.d.ts +3 -0
  46. package/dist/generated/client/client.gen.d.ts.map +1 -0
  47. package/dist/generated/client/index.d.ts +9 -0
  48. package/dist/generated/client/index.d.ts.map +1 -0
  49. package/dist/generated/client/types.gen.d.ts +118 -0
  50. package/dist/generated/client/types.gen.d.ts.map +1 -0
  51. package/dist/generated/client/utils.gen.d.ts +34 -0
  52. package/dist/generated/client/utils.gen.d.ts.map +1 -0
  53. package/dist/generated/client.gen.d.ts +13 -0
  54. package/dist/generated/client.gen.d.ts.map +1 -0
  55. package/dist/generated/core/auth.gen.d.ts +19 -0
  56. package/dist/generated/core/auth.gen.d.ts.map +1 -0
  57. package/dist/generated/core/bodySerializer.gen.d.ts +26 -0
  58. package/dist/generated/core/bodySerializer.gen.d.ts.map +1 -0
  59. package/dist/generated/core/params.gen.d.ts +44 -0
  60. package/dist/generated/core/params.gen.d.ts.map +1 -0
  61. package/dist/generated/core/pathSerializer.gen.d.ts +34 -0
  62. package/dist/generated/core/pathSerializer.gen.d.ts.map +1 -0
  63. package/dist/generated/core/queryKeySerializer.gen.d.ts +19 -0
  64. package/dist/generated/core/queryKeySerializer.gen.d.ts.map +1 -0
  65. package/dist/generated/core/serverSentEvents.gen.d.ts +72 -0
  66. package/dist/generated/core/serverSentEvents.gen.d.ts.map +1 -0
  67. package/dist/generated/core/types.gen.d.ts +79 -0
  68. package/dist/generated/core/types.gen.d.ts.map +1 -0
  69. package/dist/generated/core/utils.gen.d.ts +20 -0
  70. package/dist/generated/core/utils.gen.d.ts.map +1 -0
  71. package/dist/generated/index.d.ts +3 -0
  72. package/dist/generated/index.d.ts.map +1 -0
  73. package/dist/generated/sdk.gen.d.ts +464 -0
  74. package/dist/generated/sdk.gen.d.ts.map +1 -0
  75. package/dist/generated/types.gen.d.ts +7672 -0
  76. package/dist/generated/types.gen.d.ts.map +1 -0
  77. package/dist/hooks.d.ts +123 -0
  78. package/dist/hooks.d.ts.map +1 -0
  79. package/dist/hooks.js +3179 -0
  80. package/dist/hooks.js.map +16 -0
  81. package/dist/index.d.ts +11 -0
  82. package/dist/index.d.ts.map +1 -0
  83. package/dist/index.js +329 -0
  84. package/dist/index.js.map +9 -0
  85. package/dist/logs-builder.d.ts +59 -0
  86. package/dist/logs-builder.d.ts.map +1 -0
  87. package/dist/logs-hooks.d.ts +30 -0
  88. package/dist/logs-hooks.d.ts.map +1 -0
  89. package/dist/logs-transport.d.ts +38 -0
  90. package/dist/logs-transport.d.ts.map +1 -0
  91. package/dist/logs.d.ts +7 -0
  92. package/dist/logs.d.ts.map +1 -0
  93. package/dist/logs.js +22 -0
  94. package/dist/logs.js.map +9 -0
  95. package/dist/models.d.ts +126 -0
  96. package/dist/models.d.ts.map +1 -0
  97. package/dist/models.js +252 -0
  98. package/dist/models.js.map +9 -0
  99. package/dist/query-hooks.d.ts +365 -0
  100. package/dist/query-hooks.d.ts.map +1 -0
  101. package/dist/query.d.ts +27 -0
  102. package/dist/query.d.ts.map +1 -0
  103. package/dist/query.js +15 -0
  104. package/dist/query.js.map +9 -0
  105. package/dist/sha256.d.ts +15 -0
  106. package/dist/sha256.d.ts.map +1 -0
  107. package/dist/telemetry-events.d.ts +25 -0
  108. package/dist/telemetry-events.d.ts.map +1 -0
  109. package/dist/tsconfig.json +5 -0
  110. package/dist/useAgentRunStream.d.ts +21 -0
  111. package/dist/useAgentRunStream.d.ts.map +1 -0
  112. package/dist/ws-socket.d.ts +45 -0
  113. package/dist/ws-socket.d.ts.map +1 -0
  114. package/package.json +105 -0
  115. package/src/actions.ts +310 -0
  116. package/src/agent-streams.ts +275 -0
  117. package/src/api.ts +229 -0
  118. package/src/browser.ts +267 -0
  119. package/src/events-builder.ts +735 -0
  120. package/src/events-hooks.ts +233 -0
  121. package/src/events-model.ts +40 -0
  122. package/src/events-provider.ts +161 -0
  123. package/src/events-transport.ts +193 -0
  124. package/src/events.ts +6 -0
  125. package/src/file.ts +367 -0
  126. package/src/generated/@tanstack/react-query.gen.ts +3876 -0
  127. package/src/generated/client/client.gen.ts +288 -0
  128. package/src/generated/client/index.ts +25 -0
  129. package/src/generated/client/types.gen.ts +209 -0
  130. package/src/generated/client/utils.gen.ts +316 -0
  131. package/src/generated/client.gen.ts +18 -0
  132. package/src/generated/core/auth.gen.ts +41 -0
  133. package/src/generated/core/bodySerializer.gen.ts +84 -0
  134. package/src/generated/core/params.gen.ts +169 -0
  135. package/src/generated/core/pathSerializer.gen.ts +171 -0
  136. package/src/generated/core/queryKeySerializer.gen.ts +117 -0
  137. package/src/generated/core/serverSentEvents.gen.ts +243 -0
  138. package/src/generated/core/types.gen.ts +104 -0
  139. package/src/generated/core/utils.gen.ts +140 -0
  140. package/src/generated/index.ts +672 -0
  141. package/src/generated/sdk.gen.ts +1984 -0
  142. package/src/generated/types.gen.ts +9049 -0
  143. package/src/hooks.ts +404 -0
  144. package/src/index.ts +18 -0
  145. package/src/logs-builder.ts +171 -0
  146. package/src/logs-hooks.ts +112 -0
  147. package/src/logs-transport.ts +112 -0
  148. package/src/logs.ts +15 -0
  149. package/src/models.ts +420 -0
  150. package/src/query-hooks.ts +1021 -0
  151. package/src/query.ts +175 -0
  152. package/src/sha256.ts +159 -0
  153. package/src/telemetry-events.ts +71 -0
  154. package/src/useAgentRunStream.ts +62 -0
  155. package/src/ws-socket.ts +202 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sixb contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,193 @@
1
+ # @sixb/client
2
+
3
+ Type-safe API client for Sixb, auto-generated from the server's OpenAPI spec. Provides a fetch-based SDK for all REST endpoints, TanStack Query hooks, and a core-typed real-time domain event hook.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ bun add @sixb/client
9
+ ```
10
+
11
+ For React hooks, also install the peer dependencies:
12
+
13
+ ```bash
14
+ bun add @tanstack/react-query react
15
+ ```
16
+
17
+ ## Regenerating
18
+
19
+ The SDK is generated from the server's OpenAPI spec using `@hey-api/openapi-ts`. After modifying server routes, regenerate from the repository root:
20
+
21
+ ```bash
22
+ bun generate:client
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ### SDK (direct fetch)
28
+
29
+ ```typescript
30
+ import { client, listObjects, getObject, getTelemetryHistory, listObjectTypes } from "@sixb/client"
31
+
32
+ // Configure the base URL
33
+ client.setConfig({ baseUrl: "http://localhost:3002" })
34
+
35
+ // List all object types
36
+ const { data: types } = await listObjectTypes()
37
+
38
+ // List objects with filtering
39
+ const { data: objects } = await listObjects({
40
+ query: { objectTypeId: "thermostat", limit: "100" },
41
+ })
42
+
43
+ // Get a single object
44
+ const { data: object } = await getObject({
45
+ path: { objectTypeId: "thermostat", objectId: "living-room" },
46
+ })
47
+
48
+ // Fetch telemetry history
49
+ const { data: history } = await getTelemetryHistory({
50
+ path: { objectTypeId: "thermostat", objectId: "living-room", propertyId: "temperature" },
51
+ query: { from: "2025-01-01T00:00:00Z", to: "2025-01-02T00:00:00Z", order: "asc" },
52
+ })
53
+
54
+ // Request an action on an object, then wait for terminal success/failure
55
+ import { requestActionAndWait } from "@sixb/client"
56
+
57
+ const run = await requestActionAndWait({
58
+ path: { actionId: "setTemperature" },
59
+ body: {
60
+ subject: { kind: "object", objectTypeId: "thermostat", primaryId: "living-room" },
61
+ params: { target: 72 },
62
+ },
63
+ timeoutMs: 30_000,
64
+ })
65
+ ```
66
+
67
+ ### React Query hooks
68
+
69
+ ```tsx
70
+ import { useQuery } from "@tanstack/react-query"
71
+ import {
72
+ listObjectsOptions,
73
+ getObjectOptions,
74
+ getTelemetryHistoryOptions,
75
+ telemetryHistoryQueryOptions,
76
+ useActionRunMutation,
77
+ useTelemetryHistoryQuery,
78
+ } from "@sixb/client/hooks"
79
+ import { Thermostat } from "./ontology/Thermostat"
80
+
81
+ // List objects with automatic caching and refetching
82
+ const { data: objects } = useQuery(listObjectsOptions())
83
+
84
+ // Get a single object (uses encoded objectId = "objectTypeId~objectKey")
85
+ const { data: object } = useQuery(
86
+ getObjectOptions({ path: { objectId: "thermostat~living-room" } })
87
+ )
88
+
89
+ // Get telemetry history with a time range
90
+ const { data: history } = useQuery(
91
+ getTelemetryHistoryOptions({
92
+ path: { objectId: "thermostat~living-room", propertyId: "temperature" },
93
+ query: { range: "5m" },
94
+ })
95
+ )
96
+
97
+ // Typed telemetry history with ontology tokens
98
+ const { data: temperatureHistory } = useTelemetryHistoryQuery({
99
+ objectType: Thermostat,
100
+ objectId: "living-room",
101
+ property: Thermostat.p.temperature,
102
+ from: new Date("2025-01-01T00:00:00Z"),
103
+ to: new Date("2025-01-02T00:00:00Z"),
104
+ })
105
+
106
+ // The same token-based shape is available as a query options factory.
107
+ const temperatureHistoryOptions = telemetryHistoryQueryOptions({
108
+ objectType: Thermostat,
109
+ objectId: "living-room",
110
+ property: Thermostat.p.temperature,
111
+ })
112
+
113
+ // Action mutation whose success means the action run reached terminal success.
114
+ function SetTemperatureButton() {
115
+ const setTemperature = useActionRunMutation<{ target: number }>({
116
+ actionId: "setTemperature",
117
+ subject: { objectType: Thermostat, primaryId: "living-room" },
118
+ invalidateOnCommit: true,
119
+ })
120
+
121
+ return (
122
+ <button
123
+ type="button"
124
+ disabled={setTemperature.isPending}
125
+ onClick={() => setTemperature.mutate({ target: 72 })}
126
+ >
127
+ {setTemperature.isPending ? "Setting..." : "Set to 72"}
128
+ </button>
129
+ )
130
+ }
131
+ ```
132
+
133
+ Use `useActionRunMutation()` for app buttons where loading, success, and error states should
134
+ reflect the final action run. Keep the generated `requestActionMutation()` or root
135
+ `requestAction()` for enqueue-only flows where accepting the request is enough, such as long
136
+ background work or screens that immediately navigate to a run detail view.
137
+
138
+ ### Domain events
139
+
140
+ Subscribe with the fluent `events.object(Type)` builder (mirrors `objects(Type)`):
141
+ channels narrow the event and type the payload, `.byId(key)` scopes to one
142
+ instance, and the hooks take a built builder as their first argument.
143
+
144
+ ```tsx
145
+ import { events, useEvents, useLatest } from "@sixb/client/hooks"
146
+ import { Thermostat } from "./ontology/Thermostat"
147
+
148
+ function LiveDashboard() {
149
+ // Typed telemetry value for one property.
150
+ const { connected } = useEvents(
151
+ events.object(Thermostat).telemetry(Thermostat.p.temperature),
152
+ (event) => console.log(event.payload.value)
153
+ )
154
+
155
+ // Latest value per property for a single object.
156
+ const { values } = useLatest(events.object(Thermostat).byId("living-room").telemetry())
157
+
158
+ return <div>{connected ? "Connected" : "Disconnected"}</div>
159
+ }
160
+ ```
161
+
162
+ Action events can be scoped by run, action id, or object subject when a screen needs custom
163
+ coordination:
164
+
165
+ ```typescript
166
+ useEvents(events.actions().run("run_123").terminal(), (event) => {
167
+ console.log("action finished", event.payload.runId)
168
+ })
169
+
170
+ useEvents(events.actions().subject(Thermostat).byId("living-room").completed(), () => {
171
+ console.log("thermostat action succeeded")
172
+ })
173
+ ```
174
+
175
+ Use `useInvalidateOnEvent(builder, resolveKeys)` to invalidate TanStack Query keys on
176
+ matching events. See `docs/client/events.md` for the full event builder and hook guide.
177
+
178
+ ### UI models
179
+
180
+ ```typescript
181
+ import type { ObjectSummary, ObjectDetail, TelemetryHistory } from "@sixb/client/models"
182
+ import { toObjectSummary, toObjectDetail, executeAction } from "@sixb/client/models"
183
+ ```
184
+
185
+ The models module provides normalized types and adapter functions that transform raw API responses into UI-friendly shapes with merged telemetry properties, parsed actions, and computed fields.
186
+
187
+ ## Exports
188
+
189
+ | Entry point | What it provides |
190
+ |---|---|
191
+ | `@sixb/client` | `client`, all generated SDK functions (`listObjects`, `getObject`, `upsertObject`, `requestAction`, `getActionRun`, `getTelemetryHistory`, etc.), terminal action wait helpers (`requestActionAndWait`, `waitForActionRun`), all generated types, and UI model types/adapters |
192
+ | `@sixb/client/hooks` | TanStack Query `queryOptions` factories (`listObjectsOptions`, `getObjectOptions`, `getTelemetryHistoryOptions`, `telemetryHistoryQueryOptions`, `listRelationshipsOptions`), typed hooks (`useTelemetryHistoryQuery`, object query hooks, `useActionRunMutation`), object-query key/invalidation helpers, the `events.object(Type)` builder, and event hooks (`useEvents`, `useLatest`, `useLatestByObject`, `useInvalidateOnEvent`, `SixbEventsProvider`) |
193
+ | `@sixb/client/models` | UI model types (`ObjectSummary`, `ObjectDetail`, `TelemetryHistory`, `RelationshipEdge`, etc.) and adapters (`toObjectSummary`, `toObjectDetail`, `toTelemetryHistoryWithRange`, `executeAction`) |
@@ -0,0 +1,61 @@
1
+ import type { Client } from "./generated/client";
2
+ import { type Options } from "./generated/sdk.gen";
3
+ import type { GetActionRunResponse, RequestActionData, RequestActionResponse } from "./generated/types.gen";
4
+ export type ActionRunDetail = GetActionRunResponse;
5
+ export type ActionRunTerminalFailureStatus = Extract<ActionRunDetail["status"], "failed" | "cancelled">;
6
+ export interface ActionWaitOptions {
7
+ readonly timeoutMs?: number;
8
+ /** Slow safety check while the event socket is healthy. */
9
+ readonly fallbackPollIntervalMs?: number;
10
+ /** Faster storage check while the event socket is disconnected or reconnecting. */
11
+ readonly disconnectedPollIntervalMs?: number;
12
+ readonly signal?: AbortSignal;
13
+ /**
14
+ * When true, failed and cancelled terminal runs reject the promise. This is
15
+ * the default because it maps naturally to mutation error states.
16
+ */
17
+ readonly rejectOnTerminalFailure?: boolean;
18
+ }
19
+ export interface WaitForActionRunInput extends ActionWaitOptions {
20
+ readonly runId: string;
21
+ readonly client?: Client;
22
+ }
23
+ export type RequestActionAndWaitInput = Options<RequestActionData> & ActionWaitOptions & {
24
+ readonly onRequested?: (response: RequestActionResponse) => void | Promise<void>;
25
+ };
26
+ export declare class ActionRunFailedError extends Error {
27
+ readonly name = "ActionRunFailedError";
28
+ readonly run: ActionRunDetail;
29
+ readonly runId: string;
30
+ readonly actionId: string;
31
+ readonly status: ActionRunTerminalFailureStatus;
32
+ readonly subject: ActionRunDetail["subject"];
33
+ readonly error: ActionRunDetail["error"];
34
+ constructor(run: ActionRunDetail & {
35
+ readonly status: ActionRunTerminalFailureStatus;
36
+ });
37
+ }
38
+ export declare class ActionRunTimeoutError extends Error {
39
+ readonly name = "ActionRunTimeoutError";
40
+ readonly runId: string;
41
+ readonly timeoutMs: number;
42
+ constructor(params: {
43
+ readonly runId: string;
44
+ readonly timeoutMs: number;
45
+ });
46
+ }
47
+ export declare function requestActionAndWait(input: RequestActionAndWaitInput): Promise<ActionRunDetail>;
48
+ /**
49
+ * Wait for a durable action run to reach a terminal status.
50
+ *
51
+ * Flow:
52
+ * 1. Fetch the run detail immediately, so very fast actions that finished
53
+ * before the event socket opened are still observed.
54
+ * 2. Treat action terminal events as wakeups, then fetch the run detail again;
55
+ * the detail endpoint is the source of truth and carries commit diff data.
56
+ * 3. Keep a slow safety poll while the socket is healthy, and use a faster
57
+ * fallback poll only while the socket is disconnected or reconnecting.
58
+ */
59
+ export declare function waitForActionRun(input: WaitForActionRunInput): Promise<ActionRunDetail>;
60
+ export declare function isTerminalActionRun(run: Pick<ActionRunDetail, "status">): boolean;
61
+ //# sourceMappingURL=actions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../src/actions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAChD,OAAO,EAAgB,KAAK,OAAO,EAAiB,MAAM,qBAAqB,CAAA;AAC/E,OAAO,KAAK,EACV,oBAAoB,EACpB,iBAAiB,EACjB,qBAAqB,EACtB,MAAM,uBAAuB,CAAA;AAM9B,MAAM,MAAM,eAAe,GAAG,oBAAoB,CAAA;AAClD,MAAM,MAAM,8BAA8B,GAAG,OAAO,CAClD,eAAe,CAAC,QAAQ,CAAC,EACzB,QAAQ,GAAG,WAAW,CACvB,CAAA;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAC3B,2DAA2D;IAC3D,QAAQ,CAAC,sBAAsB,CAAC,EAAE,MAAM,CAAA;IACxC,mFAAmF;IACnF,QAAQ,CAAC,0BAA0B,CAAC,EAAE,MAAM,CAAA;IAC5C,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAA;IAC7B;;;OAGG;IACH,QAAQ,CAAC,uBAAuB,CAAC,EAAE,OAAO,CAAA;CAC3C;AAED,MAAM,WAAW,qBAAsB,SAAQ,iBAAiB;IAC9D,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CACzB;AAED,MAAM,MAAM,yBAAyB,GAAG,OAAO,CAAC,iBAAiB,CAAC,GAChE,iBAAiB,GAAG;IAClB,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC,QAAQ,EAAE,qBAAqB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CACjF,CAAA;AAEH,qBAAa,oBAAqB,SAAQ,KAAK;IAC7C,QAAQ,CAAC,IAAI,0BAAyB;IACtC,QAAQ,CAAC,GAAG,EAAE,eAAe,CAAA;IAC7B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,MAAM,EAAE,8BAA8B,CAAA;IAC/C,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAC,SAAS,CAAC,CAAA;IAC5C,QAAQ,CAAC,KAAK,EAAE,eAAe,CAAC,OAAO,CAAC,CAAA;gBAE5B,GAAG,EAAE,eAAe,GAAG;QAAE,QAAQ,CAAC,MAAM,EAAE,8BAA8B,CAAA;KAAE;CASvF;AAED,qBAAa,qBAAsB,SAAQ,KAAK;IAC9C,QAAQ,CAAC,IAAI,2BAA0B;IACvC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;gBAEd,MAAM,EAAE;QAAE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;KAAE;CAK3E;AAED,wBAAsB,oBAAoB,CACxC,KAAK,EAAE,yBAAyB,GAC/B,OAAO,CAAC,eAAe,CAAC,CAyB1B;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,qBAAqB,GAAG,OAAO,CAAC,eAAe,CAAC,CAmJvF;AAED,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,IAAI,CAAC,eAAe,EAAE,QAAQ,CAAC,GAAG,OAAO,CAEjF"}
@@ -0,0 +1,72 @@
1
+ import type { AgentRunStreamEvent } from "@sixb/core/agents/streams";
2
+ import type { BrokerRecord } from "@sixb/core/broker";
3
+ import type { GetAgentRunResponses } from "./generated/types.gen";
4
+ import { type ReconnectingSocket, type ReconnectingSocketState } from "./ws-socket";
5
+ export type { AgentRunStreamEvent } from "@sixb/core/agents/streams";
6
+ export type { ReconnectingSocket, ReconnectingSocketState } from "./ws-socket";
7
+ export type AgentRunSnapshot = GetAgentRunResponses[200];
8
+ export interface AgentRunStreamRecord extends Omit<BrokerRecord, "payload"> {
9
+ readonly payload: AgentRunStreamEvent;
10
+ }
11
+ export interface AgentRunStreamSubscribeMessage {
12
+ readonly type: "subscribe";
13
+ readonly runId: string;
14
+ readonly afterCursor?: string;
15
+ }
16
+ export interface AgentRunStreamReplayMessage {
17
+ readonly type: "replay";
18
+ readonly runId: string;
19
+ readonly afterCursor?: string;
20
+ readonly limit?: number;
21
+ }
22
+ export interface AgentRunStreamUnsubscribeMessage {
23
+ readonly type: "unsubscribe";
24
+ readonly runId?: string;
25
+ }
26
+ export type AgentRunStreamClientMessage = AgentRunStreamSubscribeMessage | AgentRunStreamReplayMessage | AgentRunStreamUnsubscribeMessage;
27
+ export type AgentRunStreamServerMessage = {
28
+ readonly type: "connected";
29
+ readonly channel?: string;
30
+ } | {
31
+ readonly type: "subscribed";
32
+ readonly runId: string;
33
+ readonly afterCursor: string | null;
34
+ } | {
35
+ readonly type: "replayed";
36
+ readonly runId: string;
37
+ readonly afterCursor: string | null;
38
+ readonly count: number;
39
+ } | {
40
+ readonly type: "unsubscribed";
41
+ readonly runId?: string | null;
42
+ } | {
43
+ readonly type: "error";
44
+ readonly message: string;
45
+ } | {
46
+ readonly type: "run.snapshot";
47
+ readonly run: AgentRunSnapshot;
48
+ } | {
49
+ readonly type: "record";
50
+ readonly record: AgentRunStreamRecord;
51
+ };
52
+ export declare function createSixbAgentsWebSocketUrl(baseUrl?: string): string;
53
+ export interface AgentRunSocketOptions {
54
+ readonly runId: string;
55
+ readonly afterCursor?: string;
56
+ readonly reconnect?: boolean;
57
+ readonly reconnectDelayMs?: number;
58
+ /** Override the API base url. Defaults to the global client config. */
59
+ readonly baseUrl?: string;
60
+ readonly onEvent: (event: AgentRunStreamEvent, cursor: string) => void;
61
+ readonly onRunSnapshot?: (run: AgentRunSnapshot) => void;
62
+ readonly onError?: (message: string) => void;
63
+ readonly onStateChange?: (state: ReconnectingSocketState) => void;
64
+ }
65
+ /**
66
+ * Open a subscribing WebSocket to `/ws/agents` for one run and stream its records to `onEvent`.
67
+ * Tracks the latest cursor across reconnects so no record is replayed. React-free: the
68
+ * `useAgentRunStream` hook is a thin wrapper that mirrors the socket state into React state.
69
+ */
70
+ export declare function createAgentRunSocket(options: AgentRunSocketOptions): ReconnectingSocket;
71
+ export declare function parseAgentRunStreamServerMessage(value: unknown): AgentRunStreamServerMessage | null;
72
+ //# sourceMappingURL=agent-streams.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-streams.d.ts","sourceRoot":"","sources":["../src/agent-streams.ts"],"names":[],"mappings":"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"}
package/dist/api.d.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { type Client, type Config } from "./generated/client";
2
+ export declare const SIXB_CSRF_HEADER_NAME = "x-sixb-csrf";
3
+ export declare const SIXB_CSRF_TOKEN_RESPONSE_HEADER_NAME = "x-sixb-csrf-token";
4
+ export type SixbClient = Client;
5
+ export type SixbClientAuth = {
6
+ readonly kind: "bearer";
7
+ readonly token: string;
8
+ } | {
9
+ readonly kind: "cookie";
10
+ readonly csrfToken?: () => string | null | undefined;
11
+ } | {
12
+ readonly kind: "none";
13
+ };
14
+ export interface SixbClientOptions {
15
+ readonly baseUrl?: string;
16
+ readonly auth?: SixbClientAuth;
17
+ readonly fetch?: typeof fetch;
18
+ readonly headers?: Config["headers"];
19
+ readonly credentials?: RequestCredentials;
20
+ }
21
+ export interface SixbApiErrorInit {
22
+ readonly status: number;
23
+ readonly statusText?: string;
24
+ readonly url?: string;
25
+ readonly method?: string;
26
+ readonly body?: unknown;
27
+ }
28
+ /**
29
+ * A structured HTTP error thrown by the Sixb client. The raw generated client
30
+ * throws the bare response body (a string, or parsed JSON) with no status code
31
+ * or identity, which makes failures impossible to branch on and prints as
32
+ * cryptic quoted text in dev tooling. `SixbApiError` carries the status, the
33
+ * parsed `body`, and a readable `message`, so callers and error boundaries can
34
+ * tell a `404` apart from a `500` instead of catching a stringy blob.
35
+ */
36
+ export declare class SixbApiError extends Error {
37
+ readonly status: number;
38
+ readonly statusText: string;
39
+ readonly url: string;
40
+ readonly method: string;
41
+ readonly body: unknown;
42
+ constructor(message: string, init: SixbApiErrorInit);
43
+ }
44
+ /**
45
+ * Identifies a `SixbApiError` across bundle boundaries. The custom app and the
46
+ * client are bundled separately, so a plain `instanceof` would miss errors that
47
+ * crossed packages; the structural fallback recognizes them by shape.
48
+ */
49
+ export declare function isSixbApiError(value: unknown): value is SixbApiError;
50
+ export declare function createSixbClient(options?: SixbClientOptions): SixbClient;
51
+ export declare function configureSixbClient(client: SixbClient, options?: SixbClientOptions): SixbClient;
52
+ export declare function createSixbClientConfig(options?: SixbClientOptions): Config;
53
+ export declare function normalizeSixbApiBaseUrl(value: string): string;
54
+ //# sourceMappingURL=api.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,KAAK,MAAM,EAAE,KAAK,MAAM,EAA8B,MAAM,oBAAoB,CAAA;AAEpG,eAAO,MAAM,qBAAqB,gBAAgB,CAAA;AAClD,eAAO,MAAM,oCAAoC,sBAAsB,CAAA;AAEvE,MAAM,MAAM,UAAU,GAAG,MAAM,CAAA;AAE/B,MAAM,MAAM,cAAc,GACtB;IACE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAA;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CACvB,GACD;IACE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAA;IACvB,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,MAAM,GAAG,IAAI,GAAG,SAAS,CAAA;CACrD,GACD;IACE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CACtB,CAAA;AAEL,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,IAAI,CAAC,EAAE,cAAc,CAAA;IAC9B,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAA;IAC7B,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,SAAS,CAAC,CAAA;IACpC,QAAQ,CAAC,WAAW,CAAC,EAAE,kBAAkB,CAAA;CAC1C;AAED,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;IAC5B,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAA;CACxB;AAED;;;;;;;GAOG;AACH,qBAAa,YAAa,SAAQ,KAAK;IACrC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;gBAEV,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,gBAAgB;CASpD;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,YAAY,CAUpE;AAED,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,iBAAsB,GAAG,UAAU,CAI5E;AAED,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,UAAU,EAClB,OAAO,GAAE,iBAAsB,GAC9B,UAAU,CAIZ;AAED,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,iBAAsB,GAAG,MAAM,CAa9E;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAgB7D"}
@@ -0,0 +1,41 @@
1
+ import type { AuthSessionAudience } from "@sixb/core";
2
+ export type { SixbApiErrorInit } from "./api";
3
+ export { isSixbApiError, SixbApiError } from "./api";
4
+ import type { GetAuthSessionResponse } from "./generated/types.gen";
5
+ export interface SixbBrowserRuntimeConfig {
6
+ readonly api: {
7
+ readonly baseUrl: string;
8
+ };
9
+ readonly auth: {
10
+ readonly audience: AuthSessionAudience;
11
+ readonly enabled: boolean;
12
+ };
13
+ }
14
+ export interface SixbBrowserRuntimeDefaults {
15
+ readonly apiBaseUrl?: string;
16
+ readonly audience: AuthSessionAudience;
17
+ readonly authEnabled?: boolean;
18
+ }
19
+ export interface SixbBrowserClientController {
20
+ setCsrfToken(token: string | null): void;
21
+ getCsrfToken(): string | null;
22
+ dispose(): void;
23
+ }
24
+ export interface SixbBrowserClientOptions {
25
+ readonly getCurrentUrl?: () => string | null;
26
+ readonly redirect?: (url: string) => void;
27
+ }
28
+ declare global {
29
+ interface Window {
30
+ __SIXB_RUNTIME__?: Partial<SixbBrowserRuntimeConfig>;
31
+ }
32
+ }
33
+ export declare function renderSixbBrowserRuntimeScript(config: SixbBrowserRuntimeConfig): string;
34
+ export declare function readSixbBrowserRuntimeConfig(defaults: SixbBrowserRuntimeDefaults): SixbBrowserRuntimeConfig;
35
+ export declare function configureSixbBrowserClient(config: SixbBrowserRuntimeConfig, options?: SixbBrowserClientOptions): SixbBrowserClientController;
36
+ export declare function requireSixbBrowserAuthSession(config: SixbBrowserRuntimeConfig, controller: SixbBrowserClientController, options?: {
37
+ readonly returnTo?: string;
38
+ readonly redirect?: (url: string) => void;
39
+ }): Promise<GetAuthSessionResponse>;
40
+ export declare function createSixbSignInUrl(config: SixbBrowserRuntimeConfig, returnTo: string): string;
41
+ //# sourceMappingURL=browser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../src/browser.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AAQrD,YAAY,EAAE,gBAAgB,EAAE,MAAM,OAAO,CAAA;AAC7C,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,OAAO,CAAA;AAGpD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAA;AAQnE,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,GAAG,EAAE;QACZ,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;KACzB,CAAA;IACD,QAAQ,CAAC,IAAI,EAAE;QACb,QAAQ,CAAC,QAAQ,EAAE,mBAAmB,CAAA;QACtC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAA;KAC1B,CAAA;CACF;AAED,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;IAC5B,QAAQ,CAAC,QAAQ,EAAE,mBAAmB,CAAA;IACtC,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAA;CAC/B;AAED,MAAM,WAAW,2BAA2B;IAC1C,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAAA;IACxC,YAAY,IAAI,MAAM,GAAG,IAAI,CAAA;IAC7B,OAAO,IAAI,IAAI,CAAA;CAChB;AAED,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,MAAM,GAAG,IAAI,CAAA;IAC5C,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAA;CAC1C;AAID,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,MAAM;QACd,gBAAgB,CAAC,EAAE,OAAO,CAAC,wBAAwB,CAAC,CAAA;KACrD;CACF;AAED,wBAAgB,8BAA8B,CAAC,MAAM,EAAE,wBAAwB,GAAG,MAAM,CAGvF;AAED,wBAAgB,4BAA4B,CAC1C,QAAQ,EAAE,0BAA0B,GACnC,wBAAwB,CAiB1B;AAED,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,wBAAwB,EAChC,OAAO,GAAE,wBAA6B,GACrC,2BAA2B,CA6H7B;AA8BD,wBAAsB,6BAA6B,CACjD,MAAM,EAAE,wBAAwB,EAChC,UAAU,EAAE,2BAA2B,EACvC,OAAO,GAAE;IACP,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAA;CACrC,GACL,OAAO,CAAC,sBAAsB,CAAC,CAajC;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,wBAAwB,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAK9F"}
@@ -0,0 +1,174 @@
1
+ // @bun
2
+ import {
3
+ SIXB_CSRF_TOKEN_RESPONSE_HEADER_NAME,
4
+ SixbApiError,
5
+ configureSixbClient,
6
+ isSixbApiError,
7
+ normalizeSixbApiBaseUrl
8
+ } from "./chunk-aw8rcsq3.js";
9
+ import {
10
+ client,
11
+ getAuthSession
12
+ } from "./chunk-ctsdm59b.js";
13
+ // src/browser.ts
14
+ var SESSION_ACTIVITY_HEADER_NAME = "x-sixb-session-activity";
15
+ var SESSION_ACTIVITY_HEADER_VALUE = "1";
16
+ var SESSION_ACTIVITY_WINDOW_MS = 5 * 60000;
17
+ var SESSION_ACTIVITY_EVENT_TYPES = ["pointerdown", "keydown", "touchstart"];
18
+ var SESSION_ACTIVITY_LISTENER_OPTIONS = { capture: true, passive: true };
19
+ var activeBrowserController = null;
20
+ function renderSixbBrowserRuntimeScript(config) {
21
+ const safeConfig = JSON.stringify(config).replaceAll("<", "\\u003c");
22
+ return `<script>window.__SIXB_RUNTIME__ = ${safeConfig};</script>`;
23
+ }
24
+ function readSixbBrowserRuntimeConfig(defaults) {
25
+ const runtime = window.__SIXB_RUNTIME__;
26
+ const runtimeAuthEnabled = runtime?.auth?.enabled;
27
+ return {
28
+ api: {
29
+ baseUrl: normalizeSixbApiBaseUrl(runtime?.api?.baseUrl ?? defaults.apiBaseUrl ?? window.location.origin)
30
+ },
31
+ auth: {
32
+ audience: runtime?.auth?.audience ?? defaults.audience,
33
+ enabled: typeof runtimeAuthEnabled === "boolean" ? runtimeAuthEnabled : defaults.authEnabled ?? true
34
+ }
35
+ };
36
+ }
37
+ function configureSixbBrowserClient(config, options = {}) {
38
+ activeBrowserController?.dispose();
39
+ let csrfToken = null;
40
+ let disposed = false;
41
+ let redirectStarted = false;
42
+ const browserDocument = typeof document === "undefined" ? null : document;
43
+ let lastActivityAt = browserDocument?.visibilityState === "visible" ? Date.now() : null;
44
+ const recordVisibleActivity = () => {
45
+ if (browserDocument?.visibilityState === "visible") {
46
+ lastActivityAt = Date.now();
47
+ }
48
+ };
49
+ if (browserDocument) {
50
+ for (const type of SESSION_ACTIVITY_EVENT_TYPES) {
51
+ browserDocument.addEventListener(type, recordVisibleActivity, SESSION_ACTIVITY_LISTENER_OPTIONS);
52
+ }
53
+ browserDocument.addEventListener("visibilitychange", recordVisibleActivity);
54
+ }
55
+ configureSixbClient(client, {
56
+ baseUrl: config.api.baseUrl,
57
+ auth: {
58
+ kind: "cookie",
59
+ csrfToken: () => csrfToken
60
+ }
61
+ });
62
+ const activityInterceptorId = client.interceptors.request.use((request) => {
63
+ const activityAge = lastActivityAt === null ? Number.POSITIVE_INFINITY : Date.now() - lastActivityAt;
64
+ const hasRecentVisibleActivity = browserDocument?.visibilityState === "visible" && activityAge >= 0 && activityAge < SESSION_ACTIVITY_WINDOW_MS;
65
+ if (hasRecentVisibleActivity) {
66
+ request.headers.set(SESSION_ACTIVITY_HEADER_NAME, SESSION_ACTIVITY_HEADER_VALUE);
67
+ } else {
68
+ request.headers.delete(SESSION_ACTIVITY_HEADER_NAME);
69
+ }
70
+ return request;
71
+ });
72
+ const authResponseInterceptorId = client.interceptors.response.use((response, request) => {
73
+ const responseCsrfToken = response.headers.get(SIXB_CSRF_TOKEN_RESPONSE_HEADER_NAME);
74
+ if (responseCsrfToken) {
75
+ csrfToken = responseCsrfToken;
76
+ }
77
+ if (!config.auth.enabled || response.status !== 401 || isAuthRedirectExcludedRequest(config, request) || request.headers.has("authorization")) {
78
+ return response;
79
+ }
80
+ csrfToken = null;
81
+ if (redirectStarted) {
82
+ return response;
83
+ }
84
+ try {
85
+ const currentUrl = options.getCurrentUrl ? options.getCurrentUrl() : typeof window === "undefined" ? null : window.location.href;
86
+ if (!currentUrl || isSixbAuthPage(config, currentUrl)) {
87
+ return response;
88
+ }
89
+ redirectStarted = true;
90
+ const redirect = options.redirect ?? ((url) => {
91
+ if (typeof window !== "undefined")
92
+ window.location.assign(url);
93
+ });
94
+ redirect(createSixbSignInUrl(config, currentUrl));
95
+ } catch {
96
+ redirectStarted = false;
97
+ }
98
+ return response;
99
+ });
100
+ const controller = {
101
+ setCsrfToken(token) {
102
+ csrfToken = token;
103
+ },
104
+ getCsrfToken() {
105
+ return csrfToken;
106
+ },
107
+ dispose() {
108
+ if (disposed)
109
+ return;
110
+ disposed = true;
111
+ csrfToken = null;
112
+ lastActivityAt = null;
113
+ client.interceptors.request.eject(activityInterceptorId);
114
+ client.interceptors.response.eject(authResponseInterceptorId);
115
+ if (browserDocument) {
116
+ for (const type of SESSION_ACTIVITY_EVENT_TYPES) {
117
+ browserDocument.removeEventListener(type, recordVisibleActivity, SESSION_ACTIVITY_LISTENER_OPTIONS);
118
+ }
119
+ browserDocument.removeEventListener("visibilitychange", recordVisibleActivity);
120
+ }
121
+ if (activeBrowserController === controller) {
122
+ activeBrowserController = null;
123
+ client.setConfig({ auth: undefined, credentials: undefined });
124
+ }
125
+ }
126
+ };
127
+ activeBrowserController = controller;
128
+ return controller;
129
+ }
130
+ function isAuthRedirectExcludedRequest(config, request) {
131
+ const requestUrl = new URL(request.url);
132
+ const apiUrl = new URL(normalizeSixbApiBaseUrl(config.api.baseUrl), requestUrl);
133
+ const apiPath = apiUrl.pathname.replace(/\/+$/, "");
134
+ const method = request.method.toUpperCase();
135
+ return requestUrl.origin === apiUrl.origin && (method === "GET" && requestUrl.pathname === `${apiPath}/api/auth/session` || method === "POST" && requestUrl.pathname === `${apiPath}/api/auth/sign-out`);
136
+ }
137
+ function isSixbAuthPage(config, currentUrl) {
138
+ try {
139
+ const current = new URL(currentUrl);
140
+ const api = new URL(normalizeSixbApiBaseUrl(config.api.baseUrl), current);
141
+ return current.origin === api.origin && (current.pathname === "/auth" || current.pathname.startsWith("/auth/"));
142
+ } catch {
143
+ return false;
144
+ }
145
+ }
146
+ async function requireSixbBrowserAuthSession(config, controller, options = {}) {
147
+ const { data } = await getAuthSession({ throwOnError: true });
148
+ if (data.authenticated) {
149
+ controller.setCsrfToken(data.csrfToken);
150
+ return data;
151
+ }
152
+ controller.setCsrfToken(null);
153
+ const returnTo = options.returnTo ?? window.location.href;
154
+ const redirect = options.redirect ?? ((url) => window.location.assign(url));
155
+ redirect(createSixbSignInUrl(config, returnTo));
156
+ return data;
157
+ }
158
+ function createSixbSignInUrl(config, returnTo) {
159
+ const url = new URL("/auth/sign-in", normalizeSixbApiBaseUrl(config.api.baseUrl));
160
+ url.searchParams.set("audience", config.auth.audience);
161
+ url.searchParams.set("returnTo", returnTo);
162
+ return url.toString();
163
+ }
164
+ export {
165
+ requireSixbBrowserAuthSession,
166
+ renderSixbBrowserRuntimeScript,
167
+ readSixbBrowserRuntimeConfig,
168
+ isSixbApiError,
169
+ createSixbSignInUrl,
170
+ configureSixbBrowserClient,
171
+ SixbApiError
172
+ };
173
+
174
+ //# debugId=893FC89655D661E364756E2164756E21