@nuwah/vertical-sdk 0.0.0-stage → 0.2.0-rc.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 (239) hide show
  1. package/LICENSE +17 -0
  2. package/README.md +229 -2
  3. package/bin/nuwah-contract-check-rules.d.mts +41 -0
  4. package/bin/nuwah-contract-check-rules.mjs +333 -0
  5. package/bin/nuwah-contract-check.mjs +64 -0
  6. package/dist/accounting.d.ts +1417 -0
  7. package/dist/accounting.js +274 -0
  8. package/dist/active-org.d.ts +13 -0
  9. package/dist/active-org.js +59 -0
  10. package/dist/actors.d.ts +448 -0
  11. package/dist/actors.js +143 -0
  12. package/dist/ai.d.ts +359 -0
  13. package/dist/ai.js +229 -0
  14. package/dist/analytics.d.ts +37 -0
  15. package/dist/analytics.js +8 -0
  16. package/dist/atlas.d.ts +291 -0
  17. package/dist/atlas.js +78 -0
  18. package/dist/audit.d.ts +193 -0
  19. package/dist/audit.js +26 -0
  20. package/dist/authentication.d.ts +119 -0
  21. package/dist/authentication.js +83 -0
  22. package/dist/awards.d.ts +38 -0
  23. package/dist/awards.js +10 -0
  24. package/dist/blueprint/document.d.ts +178 -0
  25. package/dist/blueprint/document.js +17 -0
  26. package/dist/blueprint/index.d.ts +3 -0
  27. package/dist/blueprint/index.js +5 -0
  28. package/dist/blueprint/manifest.d.ts +105 -0
  29. package/dist/blueprint/manifest.js +11 -0
  30. package/dist/blueprint/validate.d.ts +14 -0
  31. package/dist/blueprint/validate.js +416 -0
  32. package/dist/bookings-directory.d.ts +118 -0
  33. package/dist/bookings-directory.js +289 -0
  34. package/dist/bookings-extra.d.ts +1448 -0
  35. package/dist/bookings-extra.js +582 -0
  36. package/dist/bookings.d.ts +1365 -0
  37. package/dist/bookings.js +305 -0
  38. package/dist/builder-code.d.ts +164 -0
  39. package/dist/builder-code.js +12 -0
  40. package/dist/builder-core-gaps.d.ts +83 -0
  41. package/dist/builder-core-gaps.js +8 -0
  42. package/dist/builder-repos.d.ts +73 -0
  43. package/dist/builder-repos.js +37 -0
  44. package/dist/builder.d.ts +730 -0
  45. package/dist/builder.js +105 -0
  46. package/dist/campaigns.d.ts +105 -0
  47. package/dist/campaigns.js +25 -0
  48. package/dist/catalogs.d.ts +188 -0
  49. package/dist/catalogs.js +36 -0
  50. package/dist/commerce-ai.d.ts +182 -0
  51. package/dist/commerce-ai.js +27 -0
  52. package/dist/connections.d.ts +278 -0
  53. package/dist/connections.js +96 -0
  54. package/dist/content-control.d.ts +121 -0
  55. package/dist/content-control.js +23 -0
  56. package/dist/contributions.d.ts +560 -0
  57. package/dist/contributions.js +140 -0
  58. package/dist/conversation-assist.d.ts +154 -0
  59. package/dist/conversation-assist.js +51 -0
  60. package/dist/conversation-info.d.ts +219 -0
  61. package/dist/conversation-info.js +43 -0
  62. package/dist/crm.d.ts +533 -0
  63. package/dist/crm.js +142 -0
  64. package/dist/dashboards.d.ts +119 -0
  65. package/dist/dashboards.js +22 -0
  66. package/dist/delegations.d.ts +161 -0
  67. package/dist/delegations.js +39 -0
  68. package/dist/docs.d.ts +289 -0
  69. package/dist/docs.js +49 -0
  70. package/dist/documents.d.ts +317 -0
  71. package/dist/documents.js +84 -0
  72. package/dist/drafts.d.ts +132 -0
  73. package/dist/drafts.js +56 -0
  74. package/dist/engagements.d.ts +133 -0
  75. package/dist/engagements.js +15 -0
  76. package/dist/event-stream.d.ts +54 -0
  77. package/dist/event-stream.js +228 -0
  78. package/dist/exchanges.d.ts +447 -0
  79. package/dist/exchanges.js +145 -0
  80. package/dist/exports.d.ts +113 -0
  81. package/dist/exports.js +81 -0
  82. package/dist/feeds.d.ts +228 -0
  83. package/dist/feeds.js +52 -0
  84. package/dist/files.d.ts +56 -0
  85. package/dist/files.js +55 -0
  86. package/dist/finance-insights.d.ts +41 -0
  87. package/dist/finance-insights.js +61 -0
  88. package/dist/fixed-assets.d.ts +155 -0
  89. package/dist/fixed-assets.js +28 -0
  90. package/dist/fulfilment-jobs.d.ts +405 -0
  91. package/dist/fulfilment-jobs.js +76 -0
  92. package/dist/fulfilment.d.ts +205 -0
  93. package/dist/fulfilment.js +39 -0
  94. package/dist/hr.d.ts +350 -0
  95. package/dist/hr.js +94 -0
  96. package/dist/http.d.ts +124 -0
  97. package/dist/http.js +392 -0
  98. package/dist/inbox.d.ts +206 -0
  99. package/dist/inbox.js +36 -0
  100. package/dist/index.d.ts +384 -0
  101. package/dist/index.js +294 -0
  102. package/dist/insights.d.ts +176 -0
  103. package/dist/insights.js +52 -0
  104. package/dist/inventory.d.ts +797 -0
  105. package/dist/inventory.js +120 -0
  106. package/dist/list-query.d.ts +211 -0
  107. package/dist/list-query.js +158 -0
  108. package/dist/listings.d.ts +381 -0
  109. package/dist/listings.js +173 -0
  110. package/dist/location-sharing.d.ts +83 -0
  111. package/dist/location-sharing.js +20 -0
  112. package/dist/marketplace.d.ts +268 -0
  113. package/dist/marketplace.js +59 -0
  114. package/dist/matching.d.ts +103 -0
  115. package/dist/matching.js +22 -0
  116. package/dist/media.d.ts +221 -0
  117. package/dist/media.js +239 -0
  118. package/dist/metrics.d.ts +125 -0
  119. package/dist/metrics.js +45 -0
  120. package/dist/moderation.d.ts +240 -0
  121. package/dist/moderation.js +40 -0
  122. package/dist/money.d.ts +41 -0
  123. package/dist/money.js +79 -0
  124. package/dist/my-data.d.ts +266 -0
  125. package/dist/my-data.js +32 -0
  126. package/dist/names.d.ts +14 -0
  127. package/dist/names.js +17 -0
  128. package/dist/occasions.d.ts +256 -0
  129. package/dist/occasions.js +40 -0
  130. package/dist/onboarding.d.ts +88 -0
  131. package/dist/onboarding.js +38 -0
  132. package/dist/pagination.d.ts +204 -0
  133. package/dist/pagination.js +141 -0
  134. package/dist/party-baseline-attributes.d.ts +245 -0
  135. package/dist/party-baseline-attributes.js +36 -0
  136. package/dist/party.d.ts +401 -0
  137. package/dist/party.js +56 -0
  138. package/dist/patient.d.ts +161 -0
  139. package/dist/patient.js +45 -0
  140. package/dist/payroll.d.ts +378 -0
  141. package/dist/payroll.js +60 -0
  142. package/dist/person-addresses.d.ts +88 -0
  143. package/dist/person-addresses.js +18 -0
  144. package/dist/person-cart.d.ts +250 -0
  145. package/dist/person-cart.js +63 -0
  146. package/dist/person-chat-assist.d.ts +47 -0
  147. package/dist/person-chat-assist.js +13 -0
  148. package/dist/person-data-webhooks.d.ts +72 -0
  149. package/dist/person-data-webhooks.js +86 -0
  150. package/dist/person-data.d.ts +212 -0
  151. package/dist/person-data.js +162 -0
  152. package/dist/person-locations.d.ts +54 -0
  153. package/dist/person-locations.js +6 -0
  154. package/dist/person-messaging.d.ts +405 -0
  155. package/dist/person-messaging.js +112 -0
  156. package/dist/person-notifications.d.ts +319 -0
  157. package/dist/person-notifications.js +164 -0
  158. package/dist/personalisation.d.ts +21 -0
  159. package/dist/personalisation.js +8 -0
  160. package/dist/platform.d.ts +63 -0
  161. package/dist/platform.js +45 -0
  162. package/dist/portfolio.d.ts +163 -0
  163. package/dist/portfolio.js +28 -0
  164. package/dist/pos.d.ts +743 -0
  165. package/dist/pos.js +129 -0
  166. package/dist/procurement.d.ts +664 -0
  167. package/dist/procurement.js +157 -0
  168. package/dist/promotions.d.ts +169 -0
  169. package/dist/promotions.js +39 -0
  170. package/dist/publications.d.ts +583 -0
  171. package/dist/publications.js +164 -0
  172. package/dist/ranking.d.ts +43 -0
  173. package/dist/ranking.js +34 -0
  174. package/dist/ratings.d.ts +293 -0
  175. package/dist/ratings.js +109 -0
  176. package/dist/reactions.d.ts +123 -0
  177. package/dist/reactions.js +41 -0
  178. package/dist/recipient-orders.d.ts +294 -0
  179. package/dist/recipient-orders.js +73 -0
  180. package/dist/relationships.d.ts +18 -0
  181. package/dist/relationships.js +8 -0
  182. package/dist/reporting.d.ts +107 -0
  183. package/dist/reporting.js +56 -0
  184. package/dist/sales.d.ts +270 -0
  185. package/dist/sales.js +66 -0
  186. package/dist/shares.d.ts +105 -0
  187. package/dist/shares.js +27 -0
  188. package/dist/shop.d.ts +993 -0
  189. package/dist/shop.js +215 -0
  190. package/dist/shopping-assistant.d.ts +65 -0
  191. package/dist/shopping-assistant.js +14 -0
  192. package/dist/spaces.d.ts +422 -0
  193. package/dist/spaces.js +118 -0
  194. package/dist/stored-value.d.ts +754 -0
  195. package/dist/stored-value.js +177 -0
  196. package/dist/types.d.ts +83 -0
  197. package/dist/types.js +2 -0
  198. package/dist/vault.d.ts +290 -0
  199. package/dist/vault.js +55 -0
  200. package/dist/vertical-runtime.d.ts +17 -0
  201. package/dist/vertical-runtime.js +8 -0
  202. package/dist/vite/build-manifest-plugin.d.ts +42 -0
  203. package/dist/vite/build-manifest-plugin.js +42 -0
  204. package/dist/vite/first-paint-plugin.d.ts +26 -0
  205. package/dist/vite/first-paint-plugin.js +57 -0
  206. package/dist/wishlists.d.ts +591 -0
  207. package/dist/wishlists.js +188 -0
  208. package/dist/workbench.d.ts +114 -0
  209. package/dist/workbench.js +22 -0
  210. package/dist/workspace.d.ts +190 -0
  211. package/dist/workspace.js +41 -0
  212. package/package.json +52 -4
  213. package/templates/extension-image.Dockerfile +38 -0
  214. package/templates/nuwah-vertical.yml +102 -0
  215. package/templates/vertical-app/.env.example +34 -0
  216. package/templates/vertical-app/README.md +108 -0
  217. package/templates/vertical-app/github/workflows/ci.yml +51 -0
  218. package/templates/vertical-app/gitignore +5 -0
  219. package/templates/vertical-app/index.html +12 -0
  220. package/templates/vertical-app/package.json +28 -0
  221. package/templates/vertical-app/src/App.tsx +64 -0
  222. package/templates/vertical-app/src/blueprint/blueprint.ts +45 -0
  223. package/templates/vertical-app/src/blueprint/screens.ts +15 -0
  224. package/templates/vertical-app/src/env.d.ts +18 -0
  225. package/templates/vertical-app/src/index.css +139 -0
  226. package/templates/vertical-app/src/lib/i18n.ts +5 -0
  227. package/templates/vertical-app/src/lib/iam.ts +19 -0
  228. package/templates/vertical-app/src/lib/operations.ts +93 -0
  229. package/templates/vertical-app/src/lib/router.ts +24 -0
  230. package/templates/vertical-app/src/lib/sdk.ts +21 -0
  231. package/templates/vertical-app/src/lib/theme.ts +18 -0
  232. package/templates/vertical-app/src/lib/words.ts +39 -0
  233. package/templates/vertical-app/src/main.tsx +25 -0
  234. package/templates/vertical-app/src/pages/AppScreens.tsx +71 -0
  235. package/templates/vertical-app/src/pages/AuthCallback.tsx +44 -0
  236. package/templates/vertical-app/src/pages/Home.tsx +36 -0
  237. package/templates/vertical-app/tsconfig.json +24 -0
  238. package/templates/vertical-app/vite.config.ts +23 -0
  239. package/templates/vertical-ci.yml +192 -0
package/dist/hr.js ADDED
@@ -0,0 +1,94 @@
1
+ export function createHrNamespace(http) {
2
+ return {
3
+ employees: {
4
+
5
+ list: (query) => http.get('/api/hr/employees', { params: query }),
6
+
7
+ get: (id) => http.get(`/api/hr/employees/${id}`),
8
+
9
+ create: (input) => http.post('/api/hr/employees', input),
10
+
11
+ update: (id, input) => http.put(`/api/hr/employees/${id}`, input),
12
+
13
+ startProbation: (id) => http.post(`/api/hr/employees/${id}/start-probation`),
14
+
15
+ completeProbation: (id) => http.post(`/api/hr/employees/${id}/complete-probation`),
16
+
17
+ activate: (id) => http.post(`/api/hr/employees/${id}/activate`),
18
+
19
+ deactivate: (id) => http.post(`/api/hr/employees/${id}/deactivate`),
20
+
21
+ terminate: (id, input) => http.post(`/api/hr/employees/${id}/terminate`, input),
22
+
23
+ transfer: (id, input) => http.post(`/api/hr/employees/${id}/transfer`, input),
24
+
25
+ contracts: (id) => http.get(`/api/hr/employees/${id}/contracts`),
26
+
27
+ addContract: (id, input) => http.post(`/api/hr/employees/${id}/contracts`, input),
28
+
29
+ salaryStructures: (id) => http.get(`/api/hr/employees/${id}/salary-structures`),
30
+
31
+ addSalaryStructure: (id, input) => http.post(`/api/hr/employees/${id}/salary-structures`, input),
32
+ },
33
+ me: {
34
+
35
+ employee: () => http.get('/api/hr/me/employee'),
36
+ },
37
+ attendance: {
38
+
39
+ list: (query) => http.get('/api/hr/attendance', {
40
+ params: query,
41
+ }),
42
+
43
+ create: (input) => http.post('/api/hr/attendance', input),
44
+ },
45
+ leaveRequests: {
46
+
47
+ list: (query) => http.get('/api/hr/leave-requests', {
48
+ params: query,
49
+ }),
50
+
51
+ get: (id) => http.get(`/api/hr/leave-requests/${id}`),
52
+
53
+ create: (input) => http.post('/api/hr/leave-requests', input),
54
+
55
+ approve: (id, approvedByEmployeeId) => http.post(`/api/hr/leave-requests/${id}/approve`, approvedByEmployeeId === undefined ? {} : { approved_by_employee_id: approvedByEmployeeId }),
56
+
57
+ reject: (id, rejectionReason) => http.post(`/api/hr/leave-requests/${id}/reject`, {
58
+ rejection_reason: rejectionReason,
59
+ }),
60
+
61
+ cancel: (id) => http.post(`/api/hr/leave-requests/${id}/cancel`),
62
+ },
63
+ leaveTypes: {
64
+
65
+ list: () => http.get('/api/hr/leave-types'),
66
+
67
+ create: (input) => http.post('/api/hr/leave-types', input),
68
+ },
69
+ departments: {
70
+
71
+ list: () => http.get('/api/hr/departments'),
72
+
73
+ get: (id) => http.get(`/api/hr/departments/${id}`),
74
+
75
+ create: (input) => http.post('/api/hr/departments', input),
76
+
77
+ update: (id, input) => http.put(`/api/hr/departments/${id}`, input),
78
+
79
+ remove: (id) => http.delete(`/api/hr/departments/${id}`),
80
+ },
81
+ positions: {
82
+
83
+ list: () => http.get('/api/hr/positions'),
84
+
85
+ get: (id) => http.get(`/api/hr/positions/${id}`),
86
+
87
+ create: (input) => http.post('/api/hr/positions', input),
88
+
89
+ update: (id, input) => http.put(`/api/hr/positions/${id}`, input),
90
+
91
+ remove: (id) => http.delete(`/api/hr/positions/${id}`),
92
+ },
93
+ };
94
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,124 @@
1
+ /** The API major this SDK speaks. Changing it is an SDK major release (see the README). */
2
+ export declare const NUWAH_API_VERSION = 1;
3
+ export declare const NUWAH_API_MEDIA_TYPE = "application/vnd.nuwah.v1+json";
4
+ /** What the SDK reports when core says an operation is deprecated. */
5
+ export interface DeprecationNotice {
6
+ method: string;
7
+ /** The path as the caller wrote it, without the query string. */
8
+ path: string;
9
+ /** The raw `Deprecation` value: `@<unix seconds>` (RFC 9745), or `true` from a sunset version. */
10
+ deprecation: string;
11
+ /** When the operation was (or will be) deprecated, when the header carried a date. */
12
+ deprecatedAt: Date | null;
13
+ /** The raw `Sunset` HTTP-date (RFC 8594), when one was sent. */
14
+ sunset: string | null;
15
+ /** After this moment the operation may stop answering. */
16
+ sunsetAt: Date | null;
17
+ /** The `rel="successor-version"` target from `Link`, when one was sent. */
18
+ successor: string | null;
19
+ /** The `rel="deprecation"` documentation target from `Link`, when one was sent. */
20
+ documentation: string | null;
21
+ }
22
+ /** Read the deprecation headers of one response, or null when it carries none. */
23
+ export declare function deprecationNoticeFrom(method: string, path: string, headers: Record<string, string>): DeprecationNotice | null;
24
+ /** A single query-string value. Arrays repeat the key (`?status[]=a&status[]=b`). */
25
+ export type QueryValue = string | number | boolean | null | undefined | Array<string | number>;
26
+ /** Query parameters for a GET/list call. Nullish values are omitted. */
27
+ export type QueryParams = Record<string, QueryValue>;
28
+ export interface NuwahClientConfig {
29
+ /** Base URL of the core monolith, e.g. `http://localhost:8090`. No trailing slash. */
30
+ baseUrl: string;
31
+ /**
32
+ * Yields the bearer token the SDK attaches to every request. Sync or async so
33
+ * the caller can source it from an in-memory store, a refresh flow, etc. Return
34
+ * an empty string to send no `Authorization` header (e.g. public probes).
35
+ */
36
+ getToken: () => string | Promise<string>;
37
+ /** Injectable fetch (tests / Node < 18 / custom agents). Defaults to global `fetch`. */
38
+ fetch?: typeof fetch;
39
+ /** Extra headers merged into every request (e.g. `X-Active-Org` for multi-org users). */
40
+ defaultHeaders?: Record<string, string> | (() => Record<string, string>);
41
+ traceparent?: () => string | null;
42
+ /**
43
+ * Called for every response that carries a `Deprecation` header. When omitted, the SDK warns
44
+ * once per operation on the console outside production builds and stays silent in production.
45
+ * Pass a function to route notices into your own logging (it is called in every environment).
46
+ */
47
+ onDeprecation?: (notice: DeprecationNotice) => void;
48
+ onUnauthorized?: (presentedToken: string) => Promise<boolean>;
49
+ }
50
+ /**
51
+ * What the SDK reports about one finished outbound call.
52
+ *
53
+ * Note what is NOT here: no request body, no response body, no headers. This
54
+ * crosses into an observability tool, and the verticals front clinic data.
55
+ */
56
+ export interface HttpCallRecord {
57
+ method: string;
58
+ /** The path as the caller wrote it, e.g. `/api/academy/cohorts`. No query string. */
59
+ path: string;
60
+ /** The query string actually sent, without the leading `?`. Empty when there is none. */
61
+ query: string;
62
+ /** The HTTP status, or `null` when the call never got one (transport failure). */
63
+ status: number | null;
64
+ ok: boolean;
65
+ durationMs: number;
66
+ /**
67
+ * The headers this SDK sent, verbatim. Reported RAW and unredacted on purpose:
68
+ * the SDK cannot know a host's redaction policy, so it hands over what it sent
69
+ * and the observer decides what may be retained. Nothing here is stored by the
70
+ * SDK itself.
71
+ */
72
+ requestHeaders: Record<string, string>;
73
+ /** The request body BEFORE serialisation, or undefined. Raw bodies are omitted. */
74
+ requestBody?: unknown;
75
+ /** Response headers, when a response arrived. */
76
+ responseHeaders?: Record<string, string>;
77
+ /** The parsed response body, when one arrived and parsed as JSON; else the raw text. */
78
+ responseBody?: unknown;
79
+ /** Present when the call threw — a transport error or a non-2xx `NuwahApiError`. */
80
+ error?: unknown;
81
+ }
82
+ export type HttpObserver = (record: HttpCallRecord) => void;
83
+ export declare function setHttpObserver(observer: HttpObserver | null): void;
84
+ /**
85
+ * Thrown on any non-2xx response. Carries the HTTP `status` and the parsed
86
+ * response `body` (core's error envelope — typically `{ message, errors? }`).
87
+ */
88
+ export declare class NuwahApiError extends Error {
89
+ readonly status: number;
90
+ readonly body: unknown;
91
+ readonly traceId: string | null;
92
+ constructor(status: number, body: unknown, message?: string, traceId?: string | null);
93
+ }
94
+ /**
95
+ * The code core's global idempotency middleware answers (422, `{message, code}`) when one
96
+ * `Idempotency-Key` arrives with a DIFFERENT request than the one it first answered.
97
+ */
98
+ export declare const IDEMPOTENCY_KEY_REUSED = "idempotency_key_reused";
99
+ export declare function refusalReason(error: unknown): string | null;
100
+ /**
101
+ * True when core refused because this `Idempotency-Key` already answered a different request:
102
+ * the global middleware's `idempotency_key_reused` (`code`), or a module's own prefixed reason
103
+ * (`exchange_idempotency_key_reused`), which a caller that reaches the module without the
104
+ * middleware's stored answer can still meet. Either way: mint a NEW key for a new intent.
105
+ */
106
+ export declare function isIdempotencyKeyReused(error: unknown): boolean;
107
+ export interface RequestOptions {
108
+ params?: QueryParams;
109
+ /** Per-request header overrides. */
110
+ headers?: Record<string, string>;
111
+ /** AbortSignal for cancellation / timeouts. */
112
+ signal?: AbortSignal;
113
+ keepalive?: boolean;
114
+ onUploadProgress?: (sentBytes: number, totalBytes: number) => void;
115
+ }
116
+ /** The low-level verb surface every namespace is built on. */
117
+ export interface Http {
118
+ get<T>(path: string, options?: RequestOptions): Promise<T>;
119
+ post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
120
+ put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
121
+ patch<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
122
+ delete<T>(path: string, options?: RequestOptions): Promise<T>;
123
+ }
124
+ export declare function createHttp(config: NuwahClientConfig): Http;
package/dist/http.js ADDED
@@ -0,0 +1,392 @@
1
+
2
+
3
+ export const NUWAH_API_VERSION = 1;
4
+
5
+ export const NUWAH_API_MEDIA_TYPE = `application/vnd.nuwah.v${NUWAH_API_VERSION}+json`;
6
+ function isProductionBuild() {
7
+ try {
8
+ return process.env.NODE_ENV === 'production';
9
+ }
10
+ catch {
11
+ return false;
12
+ }
13
+ }
14
+
15
+ function linkTarget(link, relation) {
16
+ if (!link)
17
+ return null;
18
+ for (const entry of link.split(/,(?=\s*<)/)) {
19
+ const match = /^\s*<([^>]*)>(.*)$/.exec(entry);
20
+ if (!match)
21
+ continue;
22
+ const rel = /;\s*rel\s*=\s*"?([^";]*)"?/i.exec(match[2]);
23
+
24
+ if (rel && rel[1].toLowerCase().split(/\s+/).includes(relation))
25
+ return match[1];
26
+ }
27
+ return null;
28
+ }
29
+
30
+ export function deprecationNoticeFrom(method, path, headers) {
31
+ const deprecation = headers['deprecation'];
32
+ if (!deprecation)
33
+ return null;
34
+ const seconds = /^@(-?\d+)$/.exec(deprecation.trim());
35
+ const sunset = headers['sunset'] ?? null;
36
+ const sunsetAt = sunset ? new Date(sunset) : null;
37
+ return {
38
+ method,
39
+ path,
40
+ deprecation,
41
+ deprecatedAt: seconds ? new Date(Number(seconds[1]) * 1000) : null,
42
+ sunset,
43
+ sunsetAt: sunsetAt && !Number.isNaN(sunsetAt.getTime()) ? sunsetAt : null,
44
+ successor: linkTarget(headers['link'], 'successor-version'),
45
+ documentation: linkTarget(headers['link'], 'deprecation'),
46
+ };
47
+ }
48
+
49
+ const warnedDeprecations = new Set();
50
+ function reportDeprecation(config, notice) {
51
+
52
+ try {
53
+ if (typeof config.onDeprecation === 'function') {
54
+ config.onDeprecation(notice);
55
+ return;
56
+ }
57
+ if (isProductionBuild())
58
+ return;
59
+ const key = `${notice.method} ${notice.path}`;
60
+ if (warnedDeprecations.has(key))
61
+ return;
62
+ warnedDeprecations.add(key);
63
+ console.warn(`[@nuwah/vertical-sdk] ${key} is deprecated by core` +
64
+ (notice.sunset ? `; it may stop answering after ${notice.sunset}` : '') +
65
+ (notice.successor ? `. Use ${notice.successor} instead.` : '.') +
66
+ (notice.documentation ? ` See ${notice.documentation}` : ''));
67
+ }
68
+ catch {
69
+
70
+ }
71
+ }
72
+
73
+ let httpObserver = null;
74
+ export function setHttpObserver(observer) {
75
+ httpObserver = typeof observer === 'function' ? observer : null;
76
+ }
77
+
78
+ function headersToObject(headers) {
79
+ const out = {};
80
+ try {
81
+ const iterable = headers;
82
+ if (typeof iterable?.forEach === 'function') {
83
+ iterable.forEach((value, key) => { out[String(key).toLowerCase()] = String(value); });
84
+ }
85
+ }
86
+ catch {
87
+
88
+ }
89
+ return out;
90
+ }
91
+
92
+ function observe(record) {
93
+ if (!httpObserver)
94
+ return;
95
+ try {
96
+ httpObserver(record);
97
+ }
98
+ catch {
99
+
100
+ }
101
+ }
102
+
103
+ export class NuwahApiError extends Error {
104
+ status;
105
+ body;
106
+
107
+ traceId;
108
+ constructor(status, body, message, traceId = null) {
109
+ super(message ?? extractMessage(body) ?? `Request failed with status ${status}`);
110
+ this.name = 'NuwahApiError';
111
+ this.status = status;
112
+ this.body = body;
113
+ this.traceId = traceId;
114
+
115
+ Object.setPrototypeOf(this, NuwahApiError.prototype);
116
+ }
117
+ }
118
+
119
+ export const IDEMPOTENCY_KEY_REUSED = 'idempotency_key_reused';
120
+
121
+ export function refusalReason(error) {
122
+ const body = error?.body;
123
+ if (!body || typeof body !== 'object')
124
+ return null;
125
+ for (const field of ['reason', 'code']) {
126
+ const value = body[field];
127
+ if (typeof value === 'string' && value !== '')
128
+ return value;
129
+ }
130
+ return null;
131
+ }
132
+
133
+ export function isIdempotencyKeyReused(error) {
134
+ const reason = refusalReason(error);
135
+ return reason !== null && (reason === IDEMPOTENCY_KEY_REUSED || reason.endsWith(`_${IDEMPOTENCY_KEY_REUSED}`));
136
+ }
137
+
138
+ function markReplayed(parsed) {
139
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
140
+ return;
141
+ const envelope = parsed;
142
+ if ('replayed' in envelope)
143
+ envelope.replayed = true;
144
+ const data = envelope.data;
145
+ if (data && typeof data === 'object' && !Array.isArray(data) && 'replayed' in data) {
146
+ data.replayed = true;
147
+ }
148
+ }
149
+ function extractMessage(body) {
150
+ if (body && typeof body === 'object' && 'message' in body) {
151
+ const message = body.message;
152
+ if (typeof message === 'string')
153
+ return message;
154
+ }
155
+ return undefined;
156
+ }
157
+
158
+ function queryValueText(value) {
159
+ if (typeof value === 'boolean')
160
+ return value ? '1' : '0';
161
+ return String(value);
162
+ }
163
+ function buildQuery(params) {
164
+ if (!params)
165
+ return '';
166
+ const search = new URLSearchParams();
167
+ for (const [key, value] of Object.entries(params)) {
168
+ if (value === null || value === undefined)
169
+ continue;
170
+ if (Array.isArray(value)) {
171
+ for (const item of value)
172
+ search.append(`${key}[]`, queryValueText(item));
173
+ }
174
+ else {
175
+ search.append(key, queryValueText(value));
176
+ }
177
+ }
178
+ const query = search.toString();
179
+ return query ? `?${query}` : '';
180
+ }
181
+
182
+ function parseRawHeaders(raw) {
183
+ const headers = {};
184
+ for (const line of raw.trim().split(/[\r\n]+/)) {
185
+ const separator = line.indexOf(':');
186
+ if (separator <= 0)
187
+ continue;
188
+ headers[line.slice(0, separator).trim().toLowerCase()] = line.slice(separator + 1).trim();
189
+ }
190
+ return headers;
191
+ }
192
+ function progressRequestConstructor() {
193
+ const candidate = globalThis.XMLHttpRequest;
194
+ return typeof candidate === 'function' ? candidate : null;
195
+ }
196
+
197
+ function sendWithProgress(Request, method, url, headers, body, signal, onProgress) {
198
+ return new Promise((resolve, reject) => {
199
+ const abortError = () => {
200
+ const error = new Error('The upload was cancelled.');
201
+ error.name = 'AbortError';
202
+ return error;
203
+ };
204
+ if (signal?.aborted) {
205
+ reject(abortError());
206
+ return;
207
+ }
208
+ const xhr = new Request();
209
+ xhr.open(method, url);
210
+ for (const [name, value] of Object.entries(headers))
211
+ xhr.setRequestHeader(name, value);
212
+ xhr.upload.onprogress = (event) => {
213
+ if (event.lengthComputable)
214
+ onProgress(event.loaded, event.total);
215
+ };
216
+ const onAbort = () => xhr.abort();
217
+ signal?.addEventListener('abort', onAbort, { once: true });
218
+ const done = () => signal?.removeEventListener('abort', onAbort);
219
+ xhr.onload = () => {
220
+ done();
221
+ resolve({ status: xhr.status, headers: parseRawHeaders(xhr.getAllResponseHeaders()), text: xhr.responseText ?? '' });
222
+ };
223
+ xhr.onerror = () => {
224
+ done();
225
+ reject(new TypeError('Network request failed'));
226
+ };
227
+ xhr.onabort = () => {
228
+ done();
229
+ reject(abortError());
230
+ };
231
+ xhr.send(body);
232
+ });
233
+ }
234
+
235
+ function now() {
236
+ return typeof performance !== 'undefined' && typeof performance.now === 'function'
237
+ ? performance.now()
238
+ : Date.now();
239
+ }
240
+
241
+ function currentTraceparent(config) {
242
+ if (typeof config.traceparent !== 'function')
243
+ return undefined;
244
+ try {
245
+ const value = config.traceparent();
246
+ return typeof value === 'string' && value !== '' ? value : undefined;
247
+ }
248
+ catch {
249
+ return undefined;
250
+ }
251
+ }
252
+ function safeJson(text) {
253
+ try {
254
+ return JSON.parse(text);
255
+ }
256
+ catch {
257
+ return text;
258
+ }
259
+ }
260
+ export function createHttp(config) {
261
+ const baseUrl = config.baseUrl.replace(/\/$/, '');
262
+
263
+ async function request(method, path, body, options = {}) {
264
+ if (!config.onUnauthorized)
265
+ return requestOnce(method, path, body, options);
266
+ const presentedToken = await config.getToken();
267
+ try {
268
+ return await requestOnce(method, path, body, options);
269
+ }
270
+ catch (error) {
271
+ if (!(error instanceof NuwahApiError) || error.status !== 401 || options.signal?.aborted)
272
+ throw error;
273
+ let renewed = false;
274
+ try {
275
+ renewed = await config.onUnauthorized(presentedToken);
276
+ }
277
+ catch {
278
+ renewed = false;
279
+ }
280
+ if (!renewed)
281
+ throw error;
282
+ return requestOnce(method, path, body, options);
283
+ }
284
+ }
285
+ async function requestOnce(method, path, body, options = {}) {
286
+ const fetchImpl = config.fetch ?? globalThis.fetch;
287
+ if (typeof fetchImpl !== 'function') {
288
+ throw new Error('No fetch implementation available. Pass `fetch` in the client config on runtimes without a global fetch.');
289
+ }
290
+ const token = await config.getToken();
291
+ const hasBody = body !== undefined && body !== null;
292
+
293
+ const isRawBody = (typeof FormData !== 'undefined' && body instanceof FormData) ||
294
+ (typeof Blob !== 'undefined' && body instanceof Blob) ||
295
+ body instanceof ArrayBuffer ||
296
+ (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams);
297
+ const extraHeaders = typeof config.defaultHeaders === 'function' ? config.defaultHeaders() : config.defaultHeaders;
298
+ const trace = currentTraceparent(config);
299
+
300
+ const startedAt = now();
301
+ let status = null;
302
+ let failure;
303
+ let responseHeaders;
304
+ let responseBody;
305
+
306
+ const requestHeaders = {
307
+ Accept: NUWAH_API_MEDIA_TYPE,
308
+ 'X-Requested-With': 'XMLHttpRequest',
309
+ ...(hasBody && !isRawBody ? { 'Content-Type': 'application/json' } : {}),
310
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
311
+
312
+ ...(trace ? { traceparent: trace } : {}),
313
+ ...extraHeaders,
314
+ ...options.headers,
315
+ };
316
+ const query = buildQuery(options.params);
317
+ try {
318
+ const url = `${baseUrl}${path}${query}`;
319
+ const wireBody = hasBody
320
+ ? isRawBody
321
+ ? body
322
+ : JSON.stringify(body)
323
+ : undefined;
324
+ let answer;
325
+ const ProgressCapable = options.onUploadProgress && !config.fetch ? progressRequestConstructor() : null;
326
+ if (ProgressCapable && options.onUploadProgress) {
327
+ answer = await sendWithProgress(ProgressCapable, method, url, requestHeaders, wireBody ?? null, options.signal, options.onUploadProgress);
328
+ }
329
+ else {
330
+ const response = await fetchImpl(url, {
331
+ method,
332
+ signal: options.signal,
333
+
334
+ ...(options.keepalive === true ? { keepalive: true } : {}),
335
+ headers: requestHeaders,
336
+
337
+ body: wireBody,
338
+ });
339
+ answer = {
340
+ status: response.status,
341
+ headers: headersToObject(response.headers),
342
+ text: response.status === 204 ? '' : await response.text(),
343
+ };
344
+ }
345
+ status = answer.status;
346
+ responseHeaders = answer.headers;
347
+ const deprecation = deprecationNoticeFrom(method, path, responseHeaders);
348
+ if (deprecation)
349
+ reportDeprecation(config, deprecation);
350
+ if (answer.status === 204)
351
+ return undefined;
352
+ const text = answer.text;
353
+ const parsed = text ? safeJson(text) : null;
354
+
355
+ responseBody = parsed !== null ? parsed : text;
356
+ if (answer.status < 200 || answer.status >= 300) {
357
+
358
+ throw new NuwahApiError(answer.status, parsed, undefined, responseHeaders['x-trace-id'] ?? null);
359
+ }
360
+ if (responseHeaders['idempotency-replay'] === 'true')
361
+ markReplayed(parsed);
362
+ return parsed;
363
+ }
364
+ catch (error) {
365
+ failure = error;
366
+ throw error;
367
+ }
368
+ finally {
369
+ observe({
370
+ method,
371
+ path,
372
+ query: query.startsWith('?') ? query.slice(1) : query,
373
+ status,
374
+ ok: status !== null && status >= 200 && status < 300,
375
+ durationMs: Math.round((now() - startedAt) * 100) / 100,
376
+ requestHeaders,
377
+
378
+ ...(hasBody && !isRawBody ? { requestBody: body } : {}),
379
+ ...(responseHeaders ? { responseHeaders } : {}),
380
+ ...(responseBody !== undefined ? { responseBody } : {}),
381
+ ...(failure !== undefined ? { error: failure } : {}),
382
+ });
383
+ }
384
+ }
385
+ return {
386
+ get: (path, options) => request('GET', path, undefined, options),
387
+ post: (path, body, options) => request('POST', path, body, options),
388
+ put: (path, body, options) => request('PUT', path, body, options),
389
+ patch: (path, body, options) => request('PATCH', path, body, options),
390
+ delete: (path, options) => request('DELETE', path, undefined, options),
391
+ };
392
+ }