@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/LICENSE ADDED
@@ -0,0 +1,17 @@
1
+ Copyright (c) 2026 Nuwah. All rights reserved.
2
+
3
+ This software and its source code are proprietary and confidential.
4
+
5
+ No part of this repository may be copied, modified, distributed, published,
6
+ sublicensed, or used to create derivative works, in whole or in part, by any
7
+ means, without the prior written permission of the copyright holder.
8
+
9
+ Access to this repository does not grant any licence, express or implied, to any
10
+ patent, copyright, trademark, or other intellectual property right.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
14
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
15
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
16
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
17
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,230 @@
1
- # Temporary Holding Version
1
+ # @nuwah/vertical-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A typed, **stack-agnostic** TypeScript client a *vertical* (its frontend or a
4
+ thin backend) uses to consume **nuwah-core**'s modular-monolith module APIs
5
+ with a bearer token.
6
+
7
+ Your app holds a Nuwah (IAM) bearer token and calls the platform API over HTTP. This SDK is that
8
+ client: typed methods over the published routes, in namespaces (`nuwah.crm`, `nuwah.bookings`,
9
+ `nuwah.accounting`, `nuwah.personData`, …), matching the API's real JSON shapes. It runs in browsers
10
+ and in Node 18.17 or later. Its one dependency is `jose`, which verifies tokens on a server; a
11
+ browser bundle that does not use it drops it.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ npm install @nuwah/vertical-sdk
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ```ts
22
+ import { createNuwahClient, NuwahApiError } from '@nuwah/vertical-sdk';
23
+
24
+ const nuwah = createNuwahClient({
25
+ // The API's address, no trailing slash.
26
+ baseUrl: 'https://app.nuwah.com',
27
+ // The vertical injects its SSO/IAM bearer token. Sync OR async.
28
+ getToken: () => authStore.accessToken,
29
+ // Optional: extra headers on every request (e.g. multi-org selection).
30
+ // defaultHeaders: () => ({ 'X-Active-Org': activeOrgId() }),
31
+ });
32
+
33
+ // Paginated list — parses core's `{ data, meta }` envelope.
34
+ const { data: contacts, meta } = await nuwah.crm.contacts.list({ search: 'ali' });
35
+
36
+ // Create (typed request body).
37
+ const contact = await nuwah.crm.contacts.create({
38
+ first_name: { en: 'Ali', ar: 'علي' },
39
+ last_name: { en: 'Haddad' },
40
+ email: 'ali@example.com',
41
+ });
42
+
43
+ // Bookings.
44
+ const types = await nuwah.bookings.sessionTypes.list({ active_only: true });
45
+ const session = await nuwah.bookings.sessions.create({
46
+ client_id, practitioner_id, session_type_id, starts_at: '2026-07-10T09:00:00Z',
47
+ });
48
+ await nuwah.bookings.sessions.confirm(session.id);
49
+
50
+ // Accounting (all money amounts are bcmath STRINGS).
51
+ const draft = await nuwah.accounting.invoices.create({ invoice_date: '2026-07-01' });
52
+ await nuwah.accounting.invoices.addLine(draft.id, { quantity: 1, unit_price: '1000.00' });
53
+ const invoice = await nuwah.accounting.invoices.confirm(draft.id);
54
+
55
+ // HR.
56
+ const employees = await nuwah.hr.employees.list(); // Laravel resource-collection envelope
57
+ const me = await nuwah.hr.me.employee();
58
+
59
+ // Errors.
60
+ try {
61
+ await nuwah.accounting.invoices.create({ invoice_date: '' });
62
+ } catch (e) {
63
+ if (e instanceof NuwahApiError) {
64
+ console.error(e.status, e.body); // e.g. 422, { message, errors }
65
+ }
66
+ }
67
+ ```
68
+
69
+ ### The `getToken` contract
70
+
71
+ `getToken: () => string | Promise<string>` — the caller owns auth. The SDK calls
72
+ it before every request and attaches `Authorization: Bearer <token>`. Return an
73
+ empty string to send no `Authorization` header. Token acquisition / refresh /
74
+ storage all live in the vertical; the SDK is stateless.
75
+
76
+ ### Response envelopes
77
+
78
+ - **Most core lists** return `{ data: T[], meta: { current_page, last_page, per_page, total } }` — typed as `Paginated<T>`.
79
+ - **`bookings.sessionTypes.list`** returns `{ data: T[] }` (no `meta`).
80
+ - **`hr.employees.list`** uses Laravel's default resource-collection envelope
81
+ (`{ data, links, meta }` with richer `meta`) — typed as `LaravelResourceCollection<T>`.
82
+ - **Single-resource** reads/writes return the bare object.
83
+ - **Translatable fields** (`first_name`, `name`, …): core expects `{ en, ar }`
84
+ on WRITE and serialises to the active-locale **string** on READ (driven by
85
+ `Accept-Language`). Accounting counterparty `name` is the raw `{ en, ar }` map.
86
+
87
+ ## Namespaces & methods
88
+
89
+ - **`crm.contacts`** — `list` `get` `create` `update` `remove`
90
+ - **`crm.companies`** — `list` `get` `create` `update` `remove`
91
+ - **`crm.leadSources`** — `list` `create` `remove`
92
+ - **`crm.tags`** — `list`
93
+ - **`crm.pipelines`** — `list` `get` `create` `update` `remove` `addStage` `reorderStages`
94
+ - **`crm.deals`** — `list` `get` `create` `update` `remove` `moveStage` `win` `lose`
95
+ - **`crm.quotes`** — `list` `get` `create` `update` `remove` `send` `accept` `reject`
96
+ - **`crm.activities`** — `list` `get` `create` `remove`
97
+ - **`crm.tasks`** — `list` `get` `create` `update` `remove` `complete`
98
+ - **`bookings.clients`** — `list` `get` `create` `update` `sessions`
99
+ - **`bookings.practitioners`** — `list` `get`
100
+ - **`bookings.sessionTypes`** — `list` `create` `update` `remove`
101
+ - **`bookings.locations`** — `list` `get` `create` `update` `remove` (plain `{data}` collection, no `meta`)
102
+ - **`bookings.spaces`** — `list` (filters: `location_id` `type` `is_active`) `get` `create` `update` `remove`; `SPACE_TYPES` const for the UI
103
+ - **`bookings.sessions`** — `list` (also filters by `space_id` / `location_id`) `get` `create` `update` `confirm` `cancel` `complete` `start` `noShow` `reschedule` `checkConflict` — sessions carry a nested `space` (with its `location`)
104
+ - **`bookings.availability`** — `(query: { date, start, duration })` → bulk slot availability (`SlotAvailability`): free/busy/full/off `status` per practitioner AND active space, with an ISO `next_free_at`. Returned **bare** (no `{data}` wrapper).
105
+ - **`bookings.insurance.insurers`** — `list` `get` `create` `update` `remove`
106
+ - **`bookings.insurance.plans`** — `list` `get` `create` `update` `remove`
107
+ - **`bookings.insurance.policies`** — `list` `get` `create` `update`
108
+ - **`bookings.clinicProfile`** — `get` `update` — authed admin CRUD for the clinic landing marketing profile (`GET/PUT /api/bookings/clinic-profile`, upserts one row/tenant). Both verbs return `{ data: ClinicProfile }`; `update` is a partial patch (`ClinicProfileInput`). Bilingual fields (`display_name`/`tagline`/`about`) are raw `{en,ar}` JSON maps (`LocalizedText`), NOT active-locale strings.
109
+ - **`bookings.bookingSettings`** — `get` `update` — authed admin CRUD for public-booking config (`GET/PUT /api/bookings/booking-settings`). Both verbs return `{ data: BookingSettings }`; `update` is a partial patch (`BookingSettingsInput`).
110
+
111
+ ### Public booking client (unauthenticated)
112
+
113
+ The clinic landing page + public booking widget hit the slug-scoped
114
+ `/api/public/{slug}/*` routes, which carry **no login and no tenant header** (tenancy is
115
+ resolved server-side from the `{slug}`). Use the dedicated **`createPublicBookingClient`**
116
+ — a token-less fetch client that **never attaches an `Authorization` header**:
117
+
118
+ ```ts
119
+ import { createPublicBookingClient } from '@nuwah/vertical-sdk';
120
+
121
+ const pub = createPublicBookingClient({ baseUrl: 'https://app.nuwah.com' });
122
+
123
+ const clinic = await pub.clinic('glow-clinic'); // PublicClinic
124
+ const { slots } = await pub.availability('glow-clinic', { // PublicAvailability
125
+ session_type_id: 'st-1',
126
+ date: '2026-07-10',
127
+ });
128
+ const confirmation = await pub.book('glow-clinic', { // BookingConfirmation
129
+ patient: { name: 'Ali', phone: '+9715…' },
130
+ session_type_id: 'st-1',
131
+ starts_at: slots[0].starts_at,
132
+ });
133
+ ```
134
+
135
+ - **`clinic(slug)`** → `PublicClinic` `{ profile, clinic, booking, services, practitioners }` (`profile` is `null` when the clinic hasn't published its marketing content).
136
+ - **`availability(slug, { session_type_id, practitioner_id?, date })`** → `PublicAvailability` `{ date, slots: PublicSlot[] }` (free slot times + free bookable practitioner ids).
137
+ - **`book(slug, input)`** → `BookingConfirmation` `{ reference, status, starts_at }` (201; deliberately minimal — leaks nothing about the patient or schedule).
138
+ - **`accounting.invoices`** — `list` `get` `create` `addLine` `removeLine` `confirm` `void`
139
+ - **`accounting.paymentsReceived`** — `list` `create`
140
+ - **`accounting.counterparties`** — `list` `get` `create` `update` `remove`
141
+ - **`accounting.accounts`** — `list` `tree` `count` `activity` `create` `update` `deactivate`
142
+ - **`accounting.journalEntries`** — `list` `get` `void` `fire`
143
+ - **`accounting.reports`** — `trialBalance` `balanceSheet` `incomeStatement` `generalLedger` `cashFlow` `accountBalances` `counterpartyLedger`
144
+ - **`accounting.arAging`** / **`accounting.apAging`** — receivables / payables aging buckets + detail
145
+ - **`accounting.claims`** — `list` `get` `create` `submit` `adjudicate` `pay` `reject` `void` `eobBatch`
146
+ - **`accounting.bills`** — `list` `get` `create` `setLines` `confirm` `void`
147
+ - **`accounting.bankAccounts`** — `list` `get` `create` `update`
148
+ - **`accounting.bankReconciliations`** — `list` `create` `complete`
149
+ - **`hr.employees`** — `list` `get` `create` `update` `startProbation` `completeProbation` `activate` `deactivate` `terminate` `transfer` `contracts` `addContract`
150
+ - **`hr.me`** — `employee`
151
+ - **`hr.attendance`** — `list` `create`
152
+ - **`hr.leaveRequests`** — `list` `get` `create` `approve` `reject` `cancel`
153
+ - **`hr.leaveTypes`** — `list` `create`
154
+ - **`hr.departments`** — `list` `get` `create` `update` `remove`
155
+ - **`hr.positions`** — `list` `get` `create` `update` `remove`
156
+ - **`pos.sales`** — `list` `get` `create` `addLine` `updateLine` `removeLine` `discount` `tender` `complete` `void` `refund` `receipt`
157
+ - **`pos.shifts`** — `list` `get` `open` `close` `cashMovement` `xReport`
158
+ - **`pos.catalog`** — `list` `get` `lookupBarcode`
159
+ - **`pos.stores`** — `list` `get` `create` `update` `registers` `createRegister`
160
+ - **`pos.registers`** — `list` `update`
161
+ - **`inventory.items`** — `list` `get` `create` `update` `archive` `restore` `variants`
162
+ - **`inventory.stock`** — `levels` `movements`
163
+ - **`inventory.warehouses`** — `list` `get` `create` `update` `locations` `createLocation` `updateLocation`
164
+ - **`inventory.categories`** — `list` `create` `update`
165
+ - **`inventory.adjustments`** — `list` `get` `create` `update` `remove` `startCounting` `submitForReview` `sendBackToCounting` `approve` `post` `cancel`
166
+ - **`inventory.purchaseOrders`** — `list` `get` `create` `update` `remove` `submit` `approve` `cancel`
167
+ - **`fixedAssets.assets`** — `list` `get` `create` `update` `dispose`
168
+ - **`fixedAssets.runDepreciation`** — `(periodDate)`
169
+ - **`fixedAssets.categories`** — `list` `create` `update`
170
+ - **`payroll.runs`** — `list` `get` `create` `run` `submit` `approve` `post` `returnToDraft` `void`
171
+ - **`payroll.payslips`** — `list` `get`
172
+ - **`files`** — `list` `upload` `uploadForm` `remove` (no GET-single route; find a file via `list`)
173
+
174
+ > **Envelope note:** shapes vary by module. Most Accounting/POS/Inventory lists
175
+ > use `{ data, meta }` (`Paginated<T>`). **Fixed Assets, Payroll, HR attendance,
176
+ > and Bookings-insurance lists return the RAW Laravel paginator** (pagination
177
+ > fields are siblings of `data`, no `meta`) — typed as `LaravelPaginator<T>`.
178
+ > `hr.leaveRequests.list` uses the resource-collection envelope
179
+ > (`LaravelResourceCollection<T>`). Chart-of-accounts, HR departments/positions,
180
+ > and inventory categories/locations return **bare arrays**. Several POS
181
+ > mutating actions and Payroll/Bills/Adjustment creates return trimmed/raw
182
+ > objects (documented per method in the source) — re-fetch via `get` for the
183
+ > full shape.
184
+
185
+ ## Endpoints without a method
186
+
187
+ For a one-off endpoint you don't want to wrap yet, use the escape hatch:
188
+
189
+ ```ts
190
+ await nuwah.http.get('/api/inventory/items', { params: { search: 'foo' } });
191
+ ```
192
+
193
+ ## API version and the SDK's version policy
194
+
195
+ **Every call names API v1.** The transport sends `Accept: application/vnd.nuwah.v1+json`
196
+ (`NUWAH_API_VERSION` / `NUWAH_API_MEDIA_TYPE` in `src/http.ts`). Core answers a plain
197
+ `application/json` caller with its *current* version, so a client that names none would move the
198
+ day core's current version moves; this SDK never does. A header passed in
199
+ `defaultHeaders` or a request's `headers` still wins, for a deliberate experiment against another
200
+ version.
201
+
202
+ **Deprecations reach you before removals do.** When core marks an operation deprecated it answers
203
+ with `Deprecation: @<unix seconds>` (RFC 9745), `Sunset: <HTTP-date>` (RFC 8594) and a `Link` to the
204
+ successor. The SDK passes each such response to `onDeprecation`:
205
+
206
+ ```ts
207
+ createNuwahClient({
208
+ baseUrl, getToken,
209
+ onDeprecation: (notice) => logger.warn('nuwah deprecation', notice), // method, path, sunsetAt, successor…
210
+ });
211
+ ```
212
+
213
+ Without a handler it warns once per operation on the console outside production builds
214
+ (`process.env.NODE_ENV !== 'production'`) and is silent in production. A deprecation is never an
215
+ error: the call still resolves normally.
216
+
217
+ **How SDK versions relate to API versions** (semver, released through Changesets):
218
+
219
+ | SDK change | Bump |
220
+ |---|---|
221
+ | A new namespace, method, optional parameter or response field | minor |
222
+ | A fix that keeps every signature | patch |
223
+ | A method or type removed or narrowed, or a parameter made required | major |
224
+ | Moving to a new API major (`NUWAH_API_VERSION`) | major, always |
225
+
226
+ So an SDK major is the only thing that changes the API version you speak, and the API's own
227
+ promises (what v1 guarantees, the deprecation window, how breaking changes are announced) are on
228
+ the developer portal's *Versioning and stability* page. An SDK method whose core operation is
229
+ deprecated is marked `@deprecated` in its JSDoc in the next minor and removed no earlier than the
230
+ operation's sunset, in a major.
@@ -0,0 +1,41 @@
1
+ // Types for nuwah-contract-check-rules.mjs (kept in JavaScript so CI runs it without a build).
2
+
3
+ export interface ContractViolation {
4
+ rule: string;
5
+ file: string;
6
+ line: number;
7
+ message: string;
8
+ }
9
+
10
+ export interface ContractCheckOptions {
11
+ /** Allowed operations, `"METHOD /api/path/{param}"`. */
12
+ operations: string[];
13
+ /** Libraries allowed besides `@nuwah/*` and relative files; defaults to {@link DEFAULT_ALLOWED_IMPORTS}. */
14
+ allowedImports?: readonly string[];
15
+ }
16
+
17
+ export declare const RULES: Readonly<{
18
+ importNotAllowed: 'import-not-allowed';
19
+ httpOutsideSdk: 'http-outside-sdk';
20
+ dynamicCode: 'dynamic-code';
21
+ unknownOperation: 'unknown-operation';
22
+ adapterNeedsCoreGap: 'adapter-needs-core-gap';
23
+ registerInvalid: 'register-invalid';
24
+ }>;
25
+
26
+ export declare const DEFAULT_ALLOWED_IMPORTS: readonly string[];
27
+
28
+ export declare function operationsFrom(document: unknown): string[];
29
+
30
+ export declare function stripComments(source: string, blankStrings?: boolean): string;
31
+
32
+ export declare function checkSource(file: string, text: string, options: ContractCheckOptions): ContractViolation[];
33
+
34
+ export declare function checkAdapters(
35
+ adapterDirectories: string[],
36
+ register: unknown,
37
+ ): { violations: ContractViolation[]; warnings: string[] };
38
+
39
+ export declare function checkRepository(
40
+ options: ContractCheckOptions & { root: string },
41
+ ): { violations: ContractViolation[]; warnings: string[]; scannedFiles: number };
@@ -0,0 +1,333 @@
1
+ // nuwah-contract-check: the rules.
2
+ //
3
+ // A level-3 vertical repository may talk to the platform only the way the platform publishes:
4
+ //
5
+ // import-not-allowed imports only from `@nuwah/*`, relative files and the allowlist
6
+ // http-outside-sdk no HTTP except through `@nuwah/vertical-sdk` (no fetch, XMLHttpRequest,
7
+ // WebSocket, EventSource, sendBeacon, HTTP libraries or node:http/https/net)
8
+ // dynamic-code no eval / new Function / import() or require() of a computed name:
9
+ // they would walk around every rule above
10
+ // unknown-operation every `/api/...` path named in code exists in the pinned operation list
11
+ // (`contract/operations.json`, from core's `openapi:snapshot`), with its
12
+ // HTTP method when the call site shows one
13
+ // adapter-needs-core-gap every directory under `extensions/adapters/` is registered in
14
+ // `register.json` → `adapters[]` with the id of the core gap it works around
15
+ //
16
+ // Plain JavaScript with no dependencies, so CI can run it straight after `npm ci`, before any build.
17
+ // Tests (`tests/`, `*.test.*`, `*.spec.*`) and root tooling configs are not scanned: the rules
18
+ // guard what runs in production.
19
+
20
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
21
+ import { join, relative, sep } from 'node:path';
22
+
23
+ export const RULES = Object.freeze({
24
+ importNotAllowed: 'import-not-allowed',
25
+ httpOutsideSdk: 'http-outside-sdk',
26
+ dynamicCode: 'dynamic-code',
27
+ unknownOperation: 'unknown-operation',
28
+ adapterNeedsCoreGap: 'adapter-needs-core-gap',
29
+ registerInvalid: 'register-invalid',
30
+ });
31
+
32
+ /** Libraries an extension may import besides `@nuwah/*` and relative files. */
33
+ export const DEFAULT_ALLOWED_IMPORTS = Object.freeze([
34
+ 'solid-js',
35
+ 'solid-js/*',
36
+ '@solidjs/router',
37
+ '@solidjs/meta',
38
+ 'hono',
39
+ 'hono/*',
40
+ 'zod',
41
+ 'node:path',
42
+ 'node:url',
43
+ 'node:crypto',
44
+ 'node:util',
45
+ 'node:buffer',
46
+ 'node:events',
47
+ 'node:assert',
48
+ ]);
49
+
50
+ /** Modules that ARE an HTTP client or a raw socket: named specifically, whatever the allowlist says. */
51
+ const HTTP_MODULES = new Set([
52
+ 'axios', 'node-fetch', 'cross-fetch', 'isomorphic-fetch', 'undici', 'got', 'ky', 'superagent',
53
+ 'request', 'needle', 'phin', 'ofetch', 'ws', 'socket.io-client', 'http', 'https', 'net', 'tls',
54
+ 'dgram', 'http2', 'node:http', 'node:https', 'node:net', 'node:tls', 'node:dgram', 'node:http2',
55
+ ]);
56
+
57
+ const HTTP_CALLS = [
58
+ // The bare global (called or passed around), not an SDK method named `.fetch` or an object key.
59
+ { pattern: /(?<![\w$.'"`])fetch\b(?!\s*:)(?!['"`])/g, what: 'fetch' },
60
+ { pattern: /\b(?:window|globalThis|self|global)\s*\.\s*fetch\b/g, what: 'fetch' },
61
+ { pattern: /\bXMLHttpRequest\b/g, what: 'XMLHttpRequest' },
62
+ { pattern: /\bnew\s+WebSocket\s*\(/g, what: 'new WebSocket()' },
63
+ { pattern: /\bnew\s+EventSource\s*\(/g, what: 'new EventSource()' },
64
+ { pattern: /\bsendBeacon\s*\(/g, what: 'navigator.sendBeacon()' },
65
+ { pattern: /\bimportScripts\s*\(/g, what: 'importScripts()' },
66
+ ];
67
+
68
+ const DYNAMIC_CODE = [
69
+ { pattern: /(?<![\w$.])eval\s*\(/g, what: 'eval()' },
70
+ { pattern: /\bnew\s+Function\s*\(/g, what: 'new Function()' },
71
+ { pattern: /(?<![\w$.])(?:import|require)\s*\(\s*(?!['"][^'"`]*['"]\s*\))/g, what: 'import()/require() of a computed name' },
72
+ ];
73
+
74
+ const SOURCE_EXTENSIONS = /\.(?:[cm]?[jt]s|[jt]sx)$/;
75
+ const SKIPPED_DIRECTORIES = new Set(['node_modules', 'dist', 'build', 'coverage', '.git', '.github', '.semgrep', 'tests', 'test', '__tests__', '.output', '.vite']);
76
+ const TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/;
77
+ const ROOT_TOOLING_CONFIG = /^(?!vertical\.config\.)[\w.-]+\.config\.[cm]?[jt]s$/;
78
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
79
+ const METHODS = ['get', 'post', 'put', 'patch', 'delete'];
80
+
81
+ /**
82
+ * Read an operation list: the slim `contract/operations.json` ({operations: ["GET /api/x"]}) or a
83
+ * whole OpenAPI document ({paths: {...}}).
84
+ *
85
+ * @param {unknown} document
86
+ * @returns {string[]}
87
+ */
88
+ export function operationsFrom(document) {
89
+ if (document && typeof document === 'object' && Array.isArray(document.operations)) {
90
+ return document.operations.filter((operation) => typeof operation === 'string');
91
+ }
92
+ const operations = [];
93
+ const paths = document && typeof document === 'object' ? document.paths : null;
94
+ if (paths && typeof paths === 'object') {
95
+ for (const [path, item] of Object.entries(paths)) {
96
+ for (const method of METHODS) {
97
+ if (item && typeof item === 'object' && method in item) operations.push(`${method.toUpperCase()} ${path}`);
98
+ }
99
+ }
100
+ }
101
+ return operations;
102
+ }
103
+
104
+ /**
105
+ * Blank out comments, keeping strings, template literals and every newline (so line numbers hold).
106
+ *
107
+ * With `blankStrings`, the inside of every string is blanked too, so words in messages
108
+ * ("could not fetch") are not read as code.
109
+ *
110
+ * @param {string} source
111
+ * @param {boolean} [blankStrings]
112
+ */
113
+ export function stripComments(source, blankStrings = false) {
114
+ let output = '';
115
+ let index = 0;
116
+ let quote = null;
117
+ const keep = (text) => (blankStrings ? text.replace(/[^\n]/g, ' ') : text);
118
+ while (index < source.length) {
119
+ const character = source[index];
120
+ const next = source[index + 1];
121
+ if (quote) {
122
+ if (character === '\\') {
123
+ output += keep(character + (next ?? ''));
124
+ index += 2;
125
+ continue;
126
+ }
127
+ output += character === quote ? character : keep(character);
128
+ if (character === quote) quote = null;
129
+ index++;
130
+ continue;
131
+ }
132
+ if (character === '"' || character === "'" || character === '`') {
133
+ quote = character;
134
+ output += character;
135
+ index++;
136
+ continue;
137
+ }
138
+ if (character === '/' && next === '/') {
139
+ while (index < source.length && source[index] !== '\n') {
140
+ output += ' ';
141
+ index++;
142
+ }
143
+ continue;
144
+ }
145
+ if (character === '/' && next === '*') {
146
+ const end = source.indexOf('*/', index + 2);
147
+ const stop = end === -1 ? source.length : end + 2;
148
+ output += source.slice(index, stop).replace(/[^\n]/g, ' ');
149
+ index = stop;
150
+ continue;
151
+ }
152
+ output += character;
153
+ index++;
154
+ }
155
+ return output;
156
+ }
157
+
158
+ function lineOf(source, offset) {
159
+ let line = 1;
160
+ for (let index = 0; index < offset && index < source.length; index++) if (source[index] === '\n') line++;
161
+ return line;
162
+ }
163
+
164
+ function isAllowedImport(specifier, allowed) {
165
+ if (specifier.startsWith('.') || specifier.startsWith('/')) return true;
166
+ if (specifier.startsWith('@nuwah/')) return true;
167
+ for (const entry of allowed) {
168
+ if (entry.endsWith('/*') ? specifier === entry.slice(0, -2) || specifier.startsWith(entry.slice(0, -1)) : specifier === entry) return true;
169
+ }
170
+ return false;
171
+ }
172
+
173
+ /** @returns {{specifier: string, offset: number, typeOnly: boolean}[]} */
174
+ function importsIn(source) {
175
+ const found = [];
176
+ const patterns = [
177
+ /\b(import|export)\s+(type\s+)?(?:[\w$*{}\s,]+?\s+from\s+)?(['"])([^'"]+)\3/g,
178
+ /(?<![\w$.])(?:require|import)\s*\(\s*(['"])([^'"]+)\1\s*\)/g,
179
+ ];
180
+ for (const match of source.matchAll(patterns[0])) {
181
+ found.push({ specifier: match[4], offset: match.index, typeOnly: Boolean(match[2]) });
182
+ }
183
+ for (const match of source.matchAll(patterns[1])) {
184
+ found.push({ specifier: match[2], offset: match.index, typeOnly: false });
185
+ }
186
+ return found;
187
+ }
188
+
189
+ /** `/api/x/${id}/y` → ['api', 'x', '{}', 'y'] — a computed segment becomes a wildcard. */
190
+ function segmentsOf(path) {
191
+ return path
192
+ .replace(/\$\{[^}]*\}/g, '{}')
193
+ .split('?')[0]
194
+ .split('#')[0]
195
+ .replace(/\/+$/, '')
196
+ .split('/')
197
+ .filter((segment) => segment !== '');
198
+ }
199
+
200
+ function matchesOperation(segments, operationSegments) {
201
+ if (segments.length !== operationSegments.length) return false;
202
+ return segments.every((segment, index) => {
203
+ const declared = operationSegments[index];
204
+ return segment === declared || /^\{[^}]+\}$/.test(declared) || segment === '{}' || segment.includes('{}');
205
+ });
206
+ }
207
+
208
+ /** Paths named in code: string and template literals starting with `/api/`. */
209
+ function apiPathsIn(source) {
210
+ const found = [];
211
+ for (const match of source.matchAll(/(['"`])(\/api\/(?:[^'"`\\\s]|\$\{[^}]*\})*)\1/g)) {
212
+ const before = source.slice(Math.max(0, match.index - 60), match.index);
213
+ const call = before.match(/\.(get|post|put|patch|delete)\s*(?:<[^>]*>)?\s*\(\s*$/);
214
+ found.push({ path: match[2], method: call ? call[1].toUpperCase() : null, offset: match.index });
215
+ }
216
+ return found;
217
+ }
218
+
219
+ function walk(root, directory, files, adapterDirectories) {
220
+ for (const entry of readdirSync(directory)) {
221
+ const full = join(directory, entry);
222
+ const stats = statSync(full);
223
+ if (stats.isDirectory()) {
224
+ if (SKIPPED_DIRECTORIES.has(entry)) continue;
225
+ const parts = relative(root, full).split(sep);
226
+ if (parts.length >= 3 && parts[parts.length - 2] === 'adapters' && parts[parts.length - 3] === 'extensions') {
227
+ adapterDirectories.push(parts.join('/'));
228
+ }
229
+ walk(root, full, files, adapterDirectories);
230
+ continue;
231
+ }
232
+ if (!SOURCE_EXTENSIONS.test(entry) || TEST_FILE.test(entry) || entry.endsWith('.d.ts')) continue;
233
+ if (directory === root && ROOT_TOOLING_CONFIG.test(entry)) continue;
234
+ files.push(full);
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Check one source text. Exposed so the rules can be tested without a repository on disk.
240
+ *
241
+ * @param {string} file the path reported in violations
242
+ * @param {string} text the file's source
243
+ * @param {{operations: string[], allowedImports?: readonly string[]}} options
244
+ */
245
+ export function checkSource(file, text, options) {
246
+ const violations = [];
247
+ const source = stripComments(text);
248
+ const allowed = options.allowedImports ?? DEFAULT_ALLOWED_IMPORTS;
249
+ const operations = options.operations.map((operation) => {
250
+ const [method, path] = operation.split(' ', 2);
251
+ return { method, segments: segmentsOf(path ?? '') };
252
+ });
253
+ const report = (rule, offset, message) => violations.push({ rule, file, line: lineOf(source, offset), message });
254
+
255
+ for (const { specifier, offset, typeOnly } of importsIn(source)) {
256
+ if (HTTP_MODULES.has(specifier) && !typeOnly) {
257
+ report(RULES.httpOutsideSdk, offset, `"${specifier}" is an HTTP client. Call the platform through @nuwah/vertical-sdk.`);
258
+ } else if (!typeOnly && !isAllowedImport(specifier, allowed)) {
259
+ report(RULES.importNotAllowed, offset, `"${specifier}" is not an allowed import (only @nuwah/*, relative files and the allowlist).`);
260
+ }
261
+ }
262
+ const code = stripComments(text, true);
263
+ for (const { pattern, what } of HTTP_CALLS) {
264
+ for (const match of code.matchAll(pattern)) report(RULES.httpOutsideSdk, match.index, `${what} is HTTP outside the SDK. Call the platform through @nuwah/vertical-sdk.`);
265
+ }
266
+ for (const { pattern, what } of DYNAMIC_CODE) {
267
+ for (const match of code.matchAll(pattern)) report(RULES.dynamicCode, match.index, `${what} cannot be checked. Use static imports and code.`);
268
+ }
269
+ for (const { path, method, offset } of apiPathsIn(source)) {
270
+ const segments = segmentsOf(path);
271
+ const known = operations.some((operation) => (method === null || operation.method === method) && matchesOperation(segments, operation.segments));
272
+ if (!known) {
273
+ report(RULES.unknownOperation, offset, `${method ?? 'Any method on'} ${path} is not an operation the platform publishes (contract/operations.json).`);
274
+ }
275
+ }
276
+ return violations;
277
+ }
278
+
279
+ /**
280
+ * Check adapter directories against `register.json`.
281
+ *
282
+ * @param {string[]} adapterDirectories relative, forward-slashed
283
+ * @param {unknown} register the parsed register.json, or undefined when it is missing
284
+ */
285
+ export function checkAdapters(adapterDirectories, register) {
286
+ const violations = [];
287
+ const warnings = [];
288
+ const entries = register && typeof register === 'object' && Array.isArray(register.adapters) ? register.adapters : [];
289
+ if (adapterDirectories.length > 0 && (register === undefined || !Array.isArray(register?.adapters))) {
290
+ violations.push({ rule: RULES.registerInvalid, file: 'register.json', line: 1, message: 'register.json must list "adapters": [{"directory", "core_gap_id"}] for every adapter directory.' });
291
+ }
292
+ for (const directory of adapterDirectories) {
293
+ const entry = entries.find((candidate) => candidate && typeof candidate === 'object' && String(candidate.directory ?? '').replace(/\/+$/, '') === directory);
294
+ if (!entry) {
295
+ violations.push({ rule: RULES.adapterNeedsCoreGap, file: directory, line: 1, message: `Adapter directory ${directory} is not registered to a core gap in register.json → adapters.` });
296
+ } else if (typeof entry.core_gap_id !== 'string' || !UUID.test(entry.core_gap_id)) {
297
+ violations.push({ rule: RULES.adapterNeedsCoreGap, file: directory, line: 1, message: `Adapter directory ${directory} needs a core_gap_id (the id of the recorded core gap).` });
298
+ }
299
+ }
300
+ for (const entry of entries) {
301
+ const directory = String(entry?.directory ?? '').replace(/\/+$/, '');
302
+ if (directory !== '' && !adapterDirectories.includes(directory)) warnings.push(`register.json lists adapter ${directory}, which does not exist.`);
303
+ }
304
+ return { violations, warnings };
305
+ }
306
+
307
+ /**
308
+ * Check a repository on disk.
309
+ *
310
+ * @param {{root: string, operations: string[], allowedImports?: readonly string[]}} options
311
+ * @returns {{violations: {rule: string, file: string, line: number, message: string}[], warnings: string[], scannedFiles: number}}
312
+ */
313
+ export function checkRepository(options) {
314
+ const files = [];
315
+ const adapterDirectories = [];
316
+ walk(options.root, options.root, files, adapterDirectories);
317
+ const violations = [];
318
+ for (const file of files) {
319
+ violations.push(...checkSource(relative(options.root, file).split(sep).join('/'), readFileSync(file, 'utf8'), options));
320
+ }
321
+ const registerPath = join(options.root, 'register.json');
322
+ let register;
323
+ if (existsSync(registerPath)) {
324
+ try {
325
+ register = JSON.parse(readFileSync(registerPath, 'utf8'));
326
+ } catch {
327
+ violations.push({ rule: RULES.registerInvalid, file: 'register.json', line: 1, message: 'register.json is not valid JSON.' });
328
+ }
329
+ }
330
+ const adapters = checkAdapters(adapterDirectories, register);
331
+ violations.push(...adapters.violations);
332
+ return { violations, warnings: adapters.warnings, scannedFiles: files.length };
333
+ }